code stringlengths 2 1.05M |
|---|
/*
* jQuery edSlider plugin v.1.0
* @author Eduardo Carneiro Moreno
* Code under MIT License
*/
(function ($) {
$.fn.edslider = function (settings) {
var defaults = {
width:960,
height:400,
position:1,
interval:3000,
speed:700,
paginator:true,
navigator:true,
progress:true,
skin:'edslider'
};
var options = $.extend({}, defaults, settings);
return this.each(function () {
//Building (wrapping, validating, setting up)
var slider = $(this),
sliderLi = slider.find('li');
if (sliderLi.length == 0) {
alert('ERROR!\n\nEmpty slider!');
return false;
}
var sliderImg = sliderLi.find('img'),
wrapper = slider.wrap('<div class="' + options.skin + '"/>').parent().css('width', options.width),
startPosition = options.position;
if (options.position == 0 || options.position > sliderLi.length) {
alert('ERROR!\n\nStart position value must be between 1 and ' + sliderLi.length + '!');
startPosition = 1;
}
slider.hover(
function () {
slider.addClass('hover');
hoverControl();
},
function () {
slider.removeClass('hover');
hoverControl();
}
).add(sliderLi).css('height', options.height);
sliderLi.filter(':nth-child(' + startPosition + ')').addClass('current');
//Controls (navigation, pagination and progress bar)
var position, controls, paginator, paginatorLi, progress, progressWidth, progressWidthLeft, interact = false;
if ((options.navigator || options.paginator) && sliderLi.length > 1) {
controls = wrapper.append('<div class="controls" />').find('.controls');
if (options.paginator) {
paginator = controls.prepend('<ul class="paginator"/>').find('.paginator');
sliderLi.each(function () {
paginator.append('<li> </li>');
});
paginatorLi = paginator.find('li').on('click', function () {
if (interact) {
position = $(this).index();
sliderLi.removeClass('current').filter(':nth-child(' + ++position + ')').addClass('current');
play();
}
});
}
if (options.navigator) {
controls.append('<div class="navigator prev"/><div class="navigator next"/>').find('.navigator').on('click', function () {
var btn = $(this);
btn.hasClass('next') && interact && next();
btn.hasClass('prev') && interact && prev();
});
}
}
if (options.progress) {
progress = wrapper.prepend('<div class="progress"/>').find('.progress');
progressWidth = options.width;
}
//Functions (init, play, next, prev, pause, resume)
var time, timeLeft, current, index;
function init() {
sliderLi.length > 1 ? play() : sliderLi.fadeIn(options.speed);
}
function play() {
clearTimeout(time);
interact = false;
options.progress && progress.stop().fadeOut('fast');
current = sliderLi.filter('.current').siblings().fadeOut(options.speed).end().fadeIn(options.speed, function () {
interact = true;
options.progress && progress.stop().show().width(0).animate({
width:progressWidth
}, options.interval, function () {
$(this).fadeOut('fast');
});
time = setTimeout(next, options.interval);
hoverControl();
});
index = sliderLi.index(current) + 1;
options.paginator && paginatorLi.removeClass('current').filter(':nth-child(' + index + ')').addClass('current');
}
function next() {
sliderLi.removeClass('current');
++index <= sliderLi.length ? current.next().addClass('current') : sliderLi.filter(':first-child').addClass('current');
play();
}
function prev() {
sliderLi.removeClass('current');
--index >= 1 ? current.prev().addClass('current') : sliderLi.filter(':last-child').addClass('current');
play();
}
function pause() {
clearTimeout(time);
progress.stop();
progressWidthLeft = progressWidth - progress.width();
timeLeft = progressWidthLeft * (Math.ceil(options.interval / progressWidth));
}
function resume() {
progress.stop().animate({
width:'+=' + progressWidthLeft
}, timeLeft, function () {
timeLeft = options.interval;
progressWidthLeft = progressWidth;
next();
});
}
function hoverControl() {
interact && options.progress && (slider.hasClass('hover') ? pause() : (timeLeft && resume()));
}
//Preloading and init
var preloadedImgs = 0,
totalImgs = sliderImg.length;
if (totalImgs > 0) {
slider.css({
'background-image':'url("images/load.gif")',
'background-repeat':'no-repeat',
'background-position':'center'
});
sliderImg.each(function () {
$('<img/>').attr('src', this.src + '?random=' + (new Date()).getTime()).on('load', function () {
if (++preloadedImgs == totalImgs) {
slider.css('background-image', 'none');
init();
}
});
});
} else {
init();
}
});
}
})(jQuery); |
/** @jsx React.DOM */
var React = require('react');
var jQuery = require('jquery2');
var Router = require('react-router');
var Route = Router.Route;
var Routes = Router.Routes;
var NotFoundRoute = Router.NotFoundRoute;
var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var BranchStore = require('./lib/stores/BranchStore');
var App = React.createClass({
render: function() {
return (
<div id={"layout"}>
<a href="#menu" id="menuLink" class="menu-link">
{/* <!-- Hamburger icon --> */}
<span></span>
</a>
<div id={'menu'}>
<div className={'pure-menu pure-menu-open'}>
<a className="pure-menu-heading" href="#">Trogdor</a>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li className="menu-item-divided pure-menu-selected">
<a href="#">Services</a>
</li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
<div id="main">
{/* this is the important part */}
<this.props.activeRouteHandler/>
</div>
</div>
);
}
});
var Dashboard = React.createClass({
render: function() {
return (
<div className="header">
<h1>Trogdor Status: </h1>
<h2>A subtitle for your page goes here</h2>
</div>
);
}
});
var routes = (
<Routes location="history">
<Route name="app" path="/" handler={App}>
{/* <Route name="inbox" handler={Inbox}/>
<Route name="calendar" handler={Calendar}/> */}
<DefaultRoute handler={Dashboard}/>
</Route>
</Routes>
);
jQuery(document).ready(function(){
React.render(routes, document.getElementById('app'));
/* Load Data */
console.log("Calling BRanch Store");
BranchStore.loadAllBranches();
});
|
var fs = require('fs')
function File() {
function open(path, document) {
fs.readFile(path, 'utf-8', function (error, contents) {
document.getElementById('editor').value = contentsM
});
}
function save(path, document) {
var text = document.getElementById('editor').value;
fs.writeFile(path, text);
}
this.open = open;
this.save = save;
}
module.exports = new File; |
const argv = require('yargs').argv;
const webpack = require('webpack');
const cssnano = require('cssnano');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('./project.config');
const debug = require('debug')('app:config:webpack');
const __DEV__ = project.globals.__DEV__;
const __PROD__ = project.globals.__PROD__;
const __TEST__ = project.globals.__TEST__;
debug('Creating configuration.');
const webpackConfig = {
name : 'client',
target : 'web',
devtool : project.compiler_devtool,
resolve : {
root : project.paths.client(),
extensions : ['', '.js', '.jsx', '.json'],
},
module : {},
};
// ------------------------------------
// Entry Points
// ------------------------------------
const APP_ENTRY = project.paths.client('main.js');
webpackConfig.entry = {
app : __DEV__
? [APP_ENTRY].concat(`webpack-hot-middleware/client?path=${project.compiler_public_path}__webpack_hmr`)
: [APP_ENTRY],
vendor : project.compiler_vendors,
};
// ------------------------------------
// Bundle Output
// ------------------------------------
webpackConfig.output = {
filename : `[name].[${project.compiler_hash_type}].js`,
path : project.paths.dist(),
publicPath : project.compiler_public_path,
};
// ------------------------------------
// Externals
// ------------------------------------
webpackConfig.externals = {};
webpackConfig.externals['react/lib/ExecutionEnvironment'] = true;
webpackConfig.externals['react/lib/ReactContext'] = true;
webpackConfig.externals['react/addons'] = true;
// ------------------------------------
// Plugins
// ------------------------------------
webpackConfig.plugins = [
new webpack.DefinePlugin(project.globals),
new HtmlWebpackPlugin({
template : project.paths.client('index.html'),
hash : false,
favicon : project.paths.public('favicon.ico'),
filename : 'index.html',
inject : 'body',
minify : {
collapseWhitespace : true,
},
}),
];
// Ensure that the compiler exits on errors during testing so that
// they do not get skipped and misreported.
if (__TEST__ && !argv.watch) {
webpackConfig.plugins.push(function () {
this.plugin('done', (stats) => {
if (stats.compilation.errors.length) {
// Pretend no assets were generated. This prevents the tests
// from running making it clear that there were warnings.
throw new Error(
stats.compilation.errors.map(err => err.message || err)
);
}
});
});
}
if (__DEV__) {
debug('Enabling plugins for live development (HMR, NoErrors).');
webpackConfig.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
} else if (__PROD__) {
debug('Enabling plugins for production (OccurenceOrder, Dedupe & UglifyJS).');
webpackConfig.plugins.push(
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
compress : {
unused : true,
dead_code : true,
warnings : false,
},
})
);
}
// Don't split bundles during testing, since we only want import one bundle
if (!__TEST__) {
webpackConfig.plugins.push(
new webpack.optimize.CommonsChunkPlugin({
names : ['vendor'],
})
);
}
// ------------------------------------
// Loaders
// ------------------------------------
// JavaScript / JSON
webpackConfig.module.loaders = [{
test : /\.(js|jsx)$/,
exclude : /node_modules/,
loader : 'babel',
query : project.compiler_babel,
}, {
test : /\.json$/,
loader : 'json',
}];
// ------------------------------------
// Style Loaders
// ------------------------------------
// We use cssnano with the postcss loader, so we tell
// css-loader not to duplicate minimization.
const BASE_CSS_LOADER = 'css?sourceMap&-minimize';
webpackConfig.module.loaders.push({
test : /\.scss$/,
exclude : null,
loaders : [
'style',
BASE_CSS_LOADER,
'postcss',
'sass?sourceMap',
],
});
webpackConfig.module.loaders.push({
test : /\.css$/,
exclude : null,
loaders : [
'style',
BASE_CSS_LOADER,
'postcss',
],
});
webpackConfig.sassLoader = {
includePaths : project.paths.client('styles'),
};
webpackConfig.postcss = [
cssnano({
autoprefixer : {
add : true,
remove : true,
browsers : ['last 2 versions'],
},
discardComments : {
removeAll : true,
},
discardUnused : false,
mergeIdents : false,
reduceIdents : false,
safe : true,
sourcemap : true,
}),
];
// File loaders
/* eslint-disable */
webpackConfig.module.loaders.push(
{ test: /\.woff(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff' },
{ test: /\.woff2(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/font-woff2' },
{ test: /\.otf(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=font/opentype' },
{ test: /\.ttf(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=application/octet-stream' },
{ test: /\.eot(\?.*)?$/, loader: 'file?prefix=fonts/&name=[path][name].[ext]' },
{ test: /\.svg(\?.*)?$/, loader: 'url?prefix=fonts/&name=[path][name].[ext]&limit=10000&mimetype=image/svg+xml' },
{ test: /\.(png|jpg)$/, loader: 'url?limit=8192' }
)
/* eslint-enable */
// ------------------------------------
// Finalize Configuration
// ------------------------------------
// when we don't know the public path (we know it only when HMR is enabled [in development]) we
// need to use the extractTextPlugin to fix this issue:
// http://stackoverflow.com/questions/34133808/webpack-ots-parsing-error-loading-fonts/34133809#34133809
if (!__DEV__) {
debug('Applying ExtractTextPlugin to CSS loaders.');
webpackConfig.module.loaders.filter(loader =>
loader.loaders && loader.loaders.find(name => /css/.test(name.split('?')[0]))
).forEach((loader) => {
const first = loader.loaders[0];
const rest = loader.loaders.slice(1);
loader.loader = ExtractTextPlugin.extract(first, rest.join('!'));
delete loader.loaders;
});
webpackConfig.plugins.push(
new ExtractTextPlugin('[name].[contenthash].css', {
allChunks : true,
})
);
}
module.exports = webpackConfig;
|
const initState={
list:[],
pageObj:{count:0,page:0},
detailId:-1,
detailList:[]
}
const key='addItem';
function addItem(state=initState,action){
switch(action.type){
case key+'setTypeList':{
return Object.assign({},state,{
list:action.data
})
}
case key+'_detail':{
return Object.assign({},state,{
detailId:action.detailId,
detailList:action.detailList
})
}
default:return state
}
}
export default addItem |
#!/usr/bin/env node
//
// lib/utils.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxbreak: true*/
// (a, b) -> a + b
//
// Params:
// a: The instance to be written on
// b: The instance to write onto a
//
// Returns:
// The returned object is `a` with the contents of `b` written ontop of it.
// This is very unsafe, and it will most likely injur your dog.
//
// Desc:
// A simple and unsafe merge of objects a and b.
exports.merge = function (a, b) {
for (var key in b)
a[key] = b[key]
}
// (a, b) -> a + b
//
// Params:
// a: The instance to be written on
// b: The instance to write onto a
//
// Returns:
// The returned object is `a` with the contents of `b` written ontop of it.
// This is very unsafe, and it will most likely injur your dog.
//
// Raises:
// Error('fail_merge found the same key in both object a and b. '+
// 'The offending key:'+ key)
//
// Desc:
// A simple merge of objects a and b. The difference with `merge` is that
// this will throw an exception if any overlap between a and b is found.
exports.fail_merge = function (a, b) {
for (var key in b) {
if (key in a) {
throw new Error('fail_merge found the same key in both object a and b. '+
'The offending key:'+ key)
} else {
a[key] = b[key]
}
}
}
// (pattern) -> RegExp()
//
// Params:
// pattern: A regexy string or a RegExp object.
//
// Returns:
// A RegExp object.
//
// Desc:
// Format the given pattern with some basics things like enforcing start
// matching, end match, and end slash ignoring.
exports.format_route_pattern = function (pattern) {
// Stringify our pattern so we can work with it, if it's not already a string
if (pattern.source)
pattern = pattern.source
// Check for the start op, so that the regex only matches from the start.
if (pattern.indexOf('^') !== 0)
pattern = '^'+ pattern
// Replace the * character to any number of accepted characters.
pattern = pattern.replace(/\*/g, '[a-zA-Z0-9\\-_]*')
// Escape any usage of the dot character, so foo.html works.
pattern = pattern.replace(/\./g, '\\.')
// Check for the end op, and if it exists remove it.
// This will allow us to work on it, without having to offset the end op.
if (pattern.lastIndexOf('$') === pattern.length - 1)
pattern = pattern.substring(0, pattern.length - 1)
if (pattern.lastIndexOf('[\\/]?') !== pattern.length - 5) {
// Check for the optional ending slash pattern. If it
// already exists, we can safely ignore this step.
if (pattern.lastIndexOf('\\/') === pattern.length - 2) {
// Check for the ending slash on domains. If it exists, replace it
// with an optional end slash.
pattern = pattern.substring(0, pattern.length - 2) +'[\\/]?'
}
else {
// Since we have not found the user trying to add in an ending slash,
// add our own.
pattern = pattern +'[\\/]?'
}
}
// Return our RegExp object. Make sure to append our ending op.
return RegExp(pattern + '$')
} |
/* @flow */
'use strict'
import React from 'react'
import {
Animated,
Image,
Platform,
StyleSheet,
TouchableHighlight,
View
} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import ProgressBar from '../../ProgressBar'
import colors from '../../colors'
class NavigationBar extends React.Component {
static propTypes = {
leftButtonIconRotated: React.PropTypes.bool.isRequired,
rightButtonIconColor: React.PropTypes.string.isRequired,
onDidPressRightButton: React.PropTypes.func.isRequired,
onDidPressLeftButton: React.PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.state = {
rotationValue: new Animated.Value(props.leftButtonIconRotated ? 1 : 0)
}
}
shouldComponentUpdate(nextProps, nextState) {
return nextProps.leftButtonIconRotated !== this.props.leftButtonIconRotated ||
nextProps.progress !== this.props.progress
}
componentWillReceiveProps(props) {
if (this.props.leftButtonIconRotated !== props.leftButtonIconRotated) {
Animated.spring(
this.state.rotationValue, {
toValue: props.leftButtonIconRotated ? 1 : 0,
duration: 50
}
).start()
}
}
render() {
return (
<View style={styles.container}>
<ProgressBar progress={this.props.progress} />
<View style={styles.leftContainer}>
<TouchableHighlight
underlayColor={'white'}
style={[styles.button]}
onPress={this.props.onDidPressLeftButton}>
<AnimatedIcon
name="plus"
color={colors.grayUI}
size={20}
style={[
styles.animatedIcon,
{transform: [{
rotate: this.state.rotationValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '225deg']
})
}]}
]}
/>
</TouchableHighlight>
</View>
<View style={styles.titleContainer}>
<Image style={styles.icon} source={require('../../../img/nav-icon-gray.png')} />
</View>
<View style={styles.rightContainer}>
<TouchableHighlight
underlayColor={'white'}
style={styles.button}
onPress={this.props.onDidPressRightButton}>
<Icon name={'bell'} color={this.props.rightButtonIconColor} size={20} />
</TouchableHighlight>
</View>
<View style={styles.separator} />
</View>
)
}
}
const AnimatedIcon = Animated.createAnimatedComponent(Icon)
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
flexDirection: 'row',
height: Platform.OS === 'ios' ? 64 : 55,
paddingTop: Platform.OS === 'ios' ? 20 : 0
},
leftContainer: {
flex: 1
},
rightContainer: {
alignItems: 'flex-end',
flex: 1
},
titleContainer: {
alignItems: 'center',
flex: 1,
justifyContent: 'center'
},
separator: {
backgroundColor: colors.grayBackground,
bottom: 0,
height: 1,
left: 0,
position: 'absolute',
right: 0
},
animatedIcon: {
backgroundColor: 'transparent',
},
button: {
width: Platform.OS === 'ios' ? 44 : 55,
height: Platform.OS === 'ios' ? 44 : 55,
justifyContent: 'center',
alignItems: 'center'
}
})
export default NavigationBar
|
var del = require('del'),
gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
runSequence = require('run-sequence'),
gulpNSP = require('gulp-nsp'),
mocha = require('gulp-mocha'),
install = require('gulp-install'),
lambda = require('gulp-awslambda'),
zip = require('gulp-zip'),
lambdaenv = require('./lambdaenv.json'),
package = require('./package.json'),
/* Configurations. Note that most of the configuration is stored in
the task context. These are mainly for repeating configuration items */
buildname = (package.name + '_' + package.version).replace(/[^A-Za-z0-9_-]/g, '_');
/* Bump version number for package.json */
// TODO Provide means for appending a patch id based on git commit id or md5 hash
gulp.task('bump', function() {
// Fetch whether we're bumping major, minor or patch; default to minor
var env = $.util.env,
type = (env.major) ? 'major' : (env.patch) ? 'patch' : 'minor';
gulp.src(['./package.json'])
.pipe($.bump({ type: type }))
.pipe(gulp.dest('./node_modules'));
});
gulp.task('build-cleantmp', function() {
return del('temp');
});
gulp.task('build-copysrcfiles', function() {
return gulp.src(['src/*.js*'])
.pipe(gulp.dest('temp'));
});
gulp.task('build-copynodemodules', function() {
return gulp.src('./package.json')
.pipe(gulp.dest('temp'))
.pipe(install({production: true}));
});
gulp.task('build-ziptemp', function() {
return gulp.src('temp/**/*')
.pipe(zip(buildname + '.zip'))
.pipe(gulp.dest('dist/'));
});
gulp.task('buildzip', function() {
return runSequence('build-copysrcfiles', 'build-copynodemodules', 'build-ziptemp');
});
gulp.task('deployzip', function() {
var lambdaparams = {
FunctionName: buildname,
Description: package.description,
Role: lambdaenv.Role
}, lambdaoptions = {
region: lambdaenv.Region
};
return gulp.src('dist/' + buildname + '.zip')
.pipe(lambda(lambdaparams, lambdaoptions));
});
gulp.task('deploy', function() {
return runSequence(
'build-copysrcfiles',
'build-copynodemodules',
'build-ziptemp',
'deployzip',
'build-cleantmp'
);
});
gulp.task('test-run', function() {
process.env.NODE_ENV = 'test';
$.util.log('Running tests (mocha)');
gulp.src(['tests/test*.js'])
.pipe(mocha());
});
//To check your package.json
gulp.task('test-nsp', function(cb) {
gulpNSP('./package.json', cb);
});
gulp.task('clean', function(cb) {
return del([
'dist',
// here we use a globbing pattern to match everything inside the `mobile` folder
'temp'
], cb);
});
// NOTE: Running also build to avoid running against old code
gulp.task('test', function() {
return runSequence('check', 'test-nsp');
});
// NOTE: Running also build to avoid running against old code
gulp.task('check', function() {
return runSequence('test-run');
});
gulp.task('default', ['build', 'test']);
gulp.task('default', ['build', 'test']);
|
'use strict'
const Emulation = require('./emulation/webDriver')
const Capabilities = require('./capabilities')
const LoaderHelpers = require('./loaderHelper')
class Patata {
constructor () {
this._hasStarted = false
this._suites = []
this._servers = []
this._provider = null
this._emulator = null
}
get suites () { return this._suites }
get currentSuite () { return this._currentSuite }
get loaderHelper () {
if (!this._loaderHelper) {
this._loaderHelper = new LoaderHelpers.LoaderHelper()
}
return this._loaderHelper
}
get capabilityFactory () {
if (!this._capabilityFactory) {
this._capabilityFactory = new Capabilities.CapabilityFactory()
}
return this._capabilityFactory
}
get capability () { return this._capability }
get servers () { return this._servers }
get provider () { return this._provider }
get emulator () { return this._emulator }
get config () { return this._config || {} }
init (suiteConfigurationArg) {
this._currentSuite = this.getSuite(suiteConfigurationArg)
this._capability = this.obtainCapability(this.currentSuite)
this._provider = this.obtainProvider(this.currentSuite)
this._servers = this.obtainServers(this.currentSuite)
this._emulator = new Emulation.WebDriver(this)
this._config = this.obtainConfig(this.currentSuite)
return this
}
getSuite (suiteConfigurationArg) {
var suiteConfiguration
if (typeof suiteConfigurationArg === 'string') {
suiteConfiguration = this._suites[suiteConfigurationArg]
} else {
suiteConfiguration = suiteConfigurationArg
}
return suiteConfiguration
}
start (hook, scenario, implicitWait) {
return new Promise((resolve, reject) => {
if (this._hasStarted) {
resolve(this)
return
}
if (this._provider === null) {
throw new Error('You need to attach a provider in order to obtain the file to test.')
}
this._provider.getBin().then((uri) => {
this.emulator.start(uri).then(() => {
resolve(this)
}).catch((error) => {
reject(error)
})
}).catch((error) => {
reject(error)
})
this._hasStarted = true
})
}
quit () {
this.emulator.quit()
return this
}
component (name, fn) {
if (!name || !fn) {
return this
}
if (fn.length === 0) {
Object.defineProperty(Object.prototype, name, { get: fn }) // eslint-disable-line no-extend-native
} else {
this.component(name, () => fn)
}
return this
}
components (components) {
for (var attr in components) {
this.component(attr, components[attr])
}
return this
}
suite (name, suite) {
this._suites[name] = this.loaderHelper.loadAsFunctionModuleOrObject(suite)
return this
}
registerProvider (provider, options) {
if (!provider || provider === 'default') {
provider = './defaults/defaultProvider.js'
}
var Plugin = this.loaderHelper.obtainPlugin(provider)
return new Plugin(this, options)
}
obtainCapability (suiteConfiguration) {
var result = this.capabilityFactory.getByName(suiteConfiguration.capability)
return result
}
obtainProvider (suiteConfiguration) {
suiteConfiguration.provider.package = suiteConfiguration.provider.package || 'default'
return this.registerProvider(suiteConfiguration.provider.package, suiteConfiguration.provider)
}
obtainServers (suiteConfiguration) {
return suiteConfiguration.servers
}
obtainConfig (suiteConfiguration) {
var config = suiteConfiguration.config
return this.loaderHelper.loadAsFunctionModuleOrObject(config)
}
}
exports.Patata = Patata
|
var types = [];
var element = '<div class="contentitem"><div class="panel panel-default"><div class="panel-heading"><i class="fa fa-align-justify fa-fw"></i>ContentItem</div><div class="panel-body"><div class="item" contenteditable="True"></div></div></div></div>';
function createElement(){
var dropdown = '<div class="pull-right"><select >'
for(var i = 0; i < types.length; i++){
dropdown += '<option value="'+types[i]['id']+'">'+types[i]['name']+'</option>'
}
dropdown += "</select><a onclick='Delete(this);' class='delete'>X</a></div>"
element = '<div class="contentitem"><div class="panel panel-default"><div onmousedown="sort(this);" onmouseup="removesort(this);" class="panel-heading"><i class="fa fa-align-justify fa-fw"></i>ContentItem'+dropdown+'</div><div class="panel-body"><div class="item" contenteditable="True"></div></div></div></div>';
}
$("#addunder").click(function(){
$(this).before(element);
});
$("#addabove").click(function(){
$(this).next().after(element);
});
$("#publish").click(function(){
var data = [];
var items = $('.contentitem');
for(var i = 0; i < items.length; i++){
var elem = $(items[i]);
var child = elem.children();
var header = child.children()[0];
var panel = child.children()[1]
var text = $(panel).children()[0];
var inheader = $(header).children()[1];
var select = $(inheader).children()[0];
tempar = {};
tempar['content'] = $(text).html();
tempar['type'] = $(select).val();
data.push(tempar);
}
var content = $('#settings').serializeArray();
var newar = {};
for(var i =0; i < content.length; i++){
if(content[i]['name'] == 'index'){
newar[content[i]['name']] = 1;
}else
newar[content[i]['name']] = content[i]['value'];
}
tempar = [newar,data]
$.ajax({
type: "POST",
url: "/admin/publish",
data: {content: tempar},
dataType: "JSON",
success: function (response) {
if(response == true){
alert("published!!");
}else{
alert("Error please try again!!");
}
}
});
});
function Delete(element){
console.log($(element).parent().parent().parent().parent().remove());
}
function sort(element){
$('#contentpanel').sortable({
items : 'div.contentitem:not(#addunder, #addabove)'
});
$('#contentpanel').sortable("option", "disabled", false);
$('.sortable').disableSelection();
}
function removesort(element){
$("#contentpanel").sortable( "disable" ); //call widget-function destroy
}
$("#save").click(function(){
var data = [];
var items = $('.contentitem');
for(var i = 0; i < items.length; i++){
var elem = $(items[i]);
var child = elem.children();
var header = child.children()[0];
var panel = child.children()[1]
var text = $(panel).children()[0];
var inheader = $(header).children()[1];
var select = $(inheader).children()[0];
tempar = {};
tempar['content'] = $(text).html();
tempar['type'] = $(select).val();
data.push(tempar);
}
var content = $('#settings').serializeArray();
var newar = {};
for(var i =0; i < content.length; i++){
if(content[i]['name'] == 'index'){
newar[content[i]['name']] = true;
}else
newar[content[i]['name']] = content[i]['value'];
}
tempar = [newar,data]
$.ajax({
type: "POST",
url: "/admin/saveToDraft",
data: {content: tempar},
dataType: "JSON",
success: function (response) {
// console.log(response);
if(response == true){
alert("Saved to draft!!");
}else{
alert("Error please try again!!");
}
}
});
});
$(document).ready(function(){
$.ajax({
type: "POST",
url: "/admin/getTypes",
dataType: "JSON",
success: function (response) {
types = response;
createElement();
}
});
$.ajax({
type: "POST",
url: "/admin/getContent",
dataType: "JSON",
success: function (response) {
if(response == null){
}else{
for(var i =0; i < response.length; i++){
var item = response[i];
$("#addunder").before(element);
var elem = $('#addunder').prev();
var child = elem.children();
var header = child.children()[0];
var panel = child.children()[1]
var text = $(panel).children()[0];
var inheader = $(header).children()[1];
var select = $(inheader).children()[0];
$(select).val(item['type']);
$(text ).html(item['content']);
}
}
}
});
}); |
var searchData=
[
['newgamemenu',['NewGameMenu',['../class_symp_1_1_new_game_menu.html',1,'Symp']]]
];
|
angular.module('auth')
.factory('AuthenticationService', AuthenticationService);
function AuthenticationService($http, $window, $q, $rootScope, MessageManager) {
var authservice = {};
authservice.auth_token = undefined;
authservice.user_info = undefined;
authservice.loadPromise = $q.defer();
authservice.waitForLoad = function () {
"use strict";
return authservice.loadPromise.promise.then(function () {
return authservice;
});
};
var login_ok = false;
authservice.login_without_token = function () {
$http.get('/auth/me/').then(
function (data) {
authservice.user_info = {
'id': data.data.id,
'username': data.data.username,
'email': data.data.email,
'created_at': 0
};
login_ok = true;
$rootScope.$emit('login', authservice.user_info);
authservice.loadPromise.resolve(data);
},
function () {
$window.location.href = '/accounts/login/';
//authservice.logout_with_token();
// Note: We don't reject the promise here! A failed login just means waitForLoad() keeps waiting
}
);
};
/*
authservice.login_with_token = function (auth_token) {
authservice.auth_token = auth_token;
$http.defaults.headers.common.Authorization = 'Token ' + authservice.auth_token;
$http.get('/auth/me/').then(
function (data) {
authservice.user_info = {
'id': data.data.id,
'username': data.data.username,
'email': data.data.email,
'created_at': 0
};
$rootScope.$emit('login', authservice.user_info);
authservice.loadPromise.resolve(data);
},
function () {
console.log('Logout with token');
//authservice.logout_with_token();
// Note: We don't reject the promise here! A failed login just means waitForLoad() keeps waiting
}
);
return authservice.loadPromise.promise;
};
*/
authservice.logout_with_token = function () {
authservice.auth_token = undefined;
authservice.user_info = undefined;
authservice.loadPromise = $q.defer(); // Reset the loadPromise
$http.defaults.headers.common.Authorization = undefined;
$window.localStorage.setItem('auth_token', null);
$window.location.reload();
};
/*
authservice.login = function (username, password) {
return $http.post(
'/auth/login/',
{'username': username, 'password': password},
{headers: { 'Authorization': undefined }}
).then(
function (data) {
return authservice.login_with_token(data.data.auth_token).then(
function () {
$window.localStorage.setItem('auth_token', data.data.auth_token);
}
);
},
function (data) {
return $q.reject(data);
}
);
};
authservice.register = function (data) {
return $http.post(
'/auth/register/',
{'username': data.username, 'password': data.password, 'email': data.email}
).then(function (res) {
MessageManager.toggleMessage('newAccount');
return authservice.login(res.data.username, data.password);
},
function (error) {
return $q.reject(error);
});
};
authservice.changePassword = function (data) {
return $http.post(
'/auth/password/',
{new_password: data.new_password1, re_new_password: data.new_password2, current_password: data.old_password}
).then(
function (data) {
MessageManager.toggleMessage('changePasswordSuccess');
},
function (error) {
// djoser and django are using the same name, mapping need to be done manually
var _data = _.cloneDeep(error.data);
if (angular.isDefined(error.data.new_password)) {
_data.new_password1 = error.data.new_password;
}
if (angular.isDefined(error.data.re_new_password)) {
_data.new_password2 = error.data.re_new_password;
}
if (angular.isDefined(error.data.current_password)) {
_data.old_password = error.data.current_password;
}
error.data = _data;
return $q.reject(error);
}
);
};
authservice.forgotPassword = function (data) {
return $http.post(
'/auth/password/reset/',
{email: data.email}
).then(
function (rep) {
MessageManager.vars.emailSentResetPassword = data.email;
MessageManager.toggleMessage('emailSentResetPassword');
},
function (error) {
return $q.reject(error);
}
);
};
authservice.validate_token = function (token) {
return authservice.login_with_token(token);
};
*/
authservice.logout = function () {
$window.location.href = '/accounts/logout/';
};
function auth_token_is_valid(auth_token) {
return (angular.isDefined(auth_token) && auth_token !== null && auth_token !== 'null');
}
authservice.is_logged_in = function () {
return login_ok;
};
/*
Try to restore the auth token and user_info from localStorage
*/
/*
var stored_token = $window.localStorage.getItem('auth_token');
if (auth_token_is_valid(stored_token)) {
authservice.login_with_token(stored_token);
} */
authservice.login_without_token();
return authservice;
}
AuthenticationService.$inject = ['$http', '$window', '$q', '$rootScope', 'MessageManager'];
|
import React from "react";
import PropTypes from "prop-types";
import classNames from "classnames";
import { Field } from "redux-form";
const renderInput = field => {
const className = classNames([
"form-group",
{ "has-error": field.meta.touched && field.meta.error }
]);
return (
<div className={className}>
<label className="control-label" htmlFor={"field-" + field.input.name}>
{field.label}
</label>
<textarea
{...field.input}
className="form-control"
id={"field-" + field.input.name}
required={field.required}
placeholder={field.placeholder}
/>
{field.meta.touched &&
field.meta.error && (
<span className="help-block">{field.meta.error}</span>
)}
{field.description && (
<span className="help-block">{field.description}</span>
)}
</div>
);
};
const TextareaWidget = props => {
return (
<Field
component={renderInput}
label={props.label}
name={props.fieldName}
required={props.required}
id={"field-" + props.fieldName}
placeholder={props.schema.default}
description={props.schema.description}
/>
);
};
TextareaWidget.propTypes = {
schema: PropTypes.object.isRequired,
fieldName: PropTypes.string,
label: PropTypes.string,
theme: PropTypes.object,
multiple: PropTypes.bool,
required: PropTypes.bool
};
export default TextareaWidget;
|
'use strict';
var analytics = require('./analytics');
var find = require('./find-parent-form');
var uuid = require('@braintree/uuid');
var DropinError = require('./dropin-error');
var kebabCaseToCamelCase = require('./kebab-case-to-camel-case');
var WHITELISTED_DATA_ATTRIBUTES = [
'locale',
'payment-option-priority',
'data-collector.kount',
'data-collector.paypal',
// camelcase version was accidentally used initially.
// we add the kebab case version to match the docs, but
// we retain the camelcase version for backwards compatibility
'card.cardholderName',
'card.cardholderName.required',
'card.cardholder-name',
'card.cardholder-name.required',
'paypal.amount',
'paypal.currency',
'paypal.flow',
'paypal.landing-page-type',
'paypal-credit.amount',
'paypal-credit.currency',
'paypal-credit.flow',
'paypal-credit.landing-page-type'
];
function injectHiddenInput(name, value, form) {
var input = form.querySelector('[name="' + name + '"]');
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = name;
form.appendChild(input);
}
input.value = value;
}
function addCompositeKeyValuePairToObject(obj, key, value) {
var decomposedKeys = key.split('.');
var topLevelKey = kebabCaseToCamelCase(decomposedKeys[0]);
if (decomposedKeys.length === 1) {
obj[topLevelKey] = deserialize(value);
} else {
obj[topLevelKey] = obj[topLevelKey] || {};
addCompositeKeyValuePairToObject(obj[topLevelKey], decomposedKeys.slice(1).join('.'), value);
}
}
function deserialize(value) {
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
function createFromScriptTag(createFunction, scriptTag) {
var authorization, container, createOptions, form;
if (!scriptTag) {
return;
}
authorization = scriptTag.getAttribute('data-braintree-dropin-authorization');
if (!authorization) {
throw new DropinError('Authorization not found in data-braintree-dropin-authorization attribute');
}
container = document.createElement('div');
container.id = 'braintree-dropin-' + uuid();
form = find.findParentForm(scriptTag);
if (!form) {
throw new DropinError('No form found for script tag integration.');
}
form.addEventListener('submit', function (event) {
event.preventDefault();
});
scriptTag.parentNode.insertBefore(container, scriptTag);
createOptions = {
authorization: authorization,
container: container
};
WHITELISTED_DATA_ATTRIBUTES.forEach(function (compositeKey) {
var value = scriptTag.getAttribute('data-' + compositeKey);
if (value == null) {
return;
}
addCompositeKeyValuePairToObject(createOptions, compositeKey, value);
});
createFunction(createOptions).then(function (instance) {
analytics.sendEvent(instance._client, 'integration-type.script-tag');
form.addEventListener('submit', function () {
instance.requestPaymentMethod(function (requestPaymentError, payload) {
if (requestPaymentError) {
return;
}
injectHiddenInput('payment_method_nonce', payload.nonce, form);
if (payload.deviceData) {
injectHiddenInput('device_data', payload.deviceData, form);
}
form.submit();
});
});
});
}
module.exports = createFromScriptTag;
|
var renderRequired = false
function requireRender() {
if (renderRequired) return
renderRequired = true
window.requestAnimationFrame(render)
}
function render() {
renderRequired = false
slider.draw()
}
var Slider = function(element) {
this.$element = $(element)
this.$root = this.$element.parent()
this.anchorY = null
this.touchY = null
this.value = null
this.options = {
minPos: 0,
maxPos: this.$root.height() - this.$element.height()
}
this.position = this.options.maxPos / 2
this.init()
}
Slider.prototype.init = function() {
this.$element.on('touchstart', $.proxy(this.onTouchStart, this))
this.$element.on('touchend', $.proxy(this.onTouchEnd, this))
this.$root.on('touchstart', $.proxy(this.onTouchStartRoot, this))
this.$element.on('touchmove', $.proxy(this.onTouchMove, this))
$(window).on('resize', $.proxy(this.onResize, this))
this.draw()
}
Slider.prototype.reset = function(){
this.position = this.options.maxPos / 2
this.value = null
this.init()
}
Slider.prototype.onResize = function() {
var ratio = this.position / this.options.maxPos
this.options.maxPos = this.$root.height() - this.$element.height()
this.position = this.options.maxPos * ratio
requireRender()
}
Slider.prototype.onTouchStart = function(e) {
var firstTouch = e.originalEvent.touches[0]
this.anchorY = this.touchY = firstTouch.clientY
e.stopPropagation()
e.preventDefault()
}
Slider.prototype.onTouchEnd = function(e) {
this.anchorY = this.touchY = null
requireRender()
}
Slider.prototype.onTouchStartRoot = function(e) {
this.$element.addClass('shake')
setTimeout($.proxy(function(){
this.$element.removeClass('shake')
}, this), 1000)
e.stopPropagation()
e.preventDefault()
}
Slider.prototype.onTouchMove = function(e) {
var firstTouch = e.originalEvent.touches[0]
this.touchY = firstTouch.clientY
requireRender()
e.preventDefault()
}
Slider.prototype.update = function() {
var diff, height, delta, value, stickZone, target, speed
if (this.touchY) { // dragging
speed = 0.75
diff = this.touchY - this.anchorY
}
else {// free
speed = 0.2
stickZone = 0.2
// proche du haut
if (this.position <= stickZone * this.options.maxPos)
target = this.options.minPos
// proche du bas
else if (this.position >= (1 - stickZone) * this.options.maxPos)
target = this.options.maxPos
// milieu
else
target = this.options.maxPos / 2
diff = target - this.position
}
if (Math.abs(diff) >= 1)
delta = diff * speed
else
delta = diff
if (diff === 0)
return false
this.anchorY = this.anchorY + delta
position = this.position
position += delta
position = position > this.options.maxPos ? this.options.maxPos : position
position = position < this.options.minPos ? this.options.minPos : position
this.position = position
if (this.position === this.options.maxPos && this.value != 'a') {
value = 'a'
}
if (this.position === this.options.minPos && this.value != 'b') {
value = 'b'
}
if (value) {
this.value = value
this.$root.trigger('change', this.value);
}
}
Slider.prototype.draw = function() {
var x = this.update()
this.$element.css({ top: this.position })
$('.b').height(this.options.maxPos - this.position)
$('.a').height(this.position)
if (x !== false) requireRender()
}
|
var mongoose = require('mongoose');
var BaseModel = require("./base_model");
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var BoardSchema = new Schema({
user_id: { type: ObjectId, ref: 'User' },
title: { type: String },
create_at: { type: Date, default: Date.now },
type: {type: String, default: 'public', enum: ['private', 'public']},
topic_count: {type: Number, default: 0},
collect_count: {type: Number, default: 0},
cover: {type: String}, // 封面
content: {type: String},
deleted: {type: Boolean, default: false}
});
BoardSchema.plugin(BaseModel);
BoardSchema.index({create_at: -1});
BoardSchema.index({user_id: 1, create_at: -1});
mongoose.model('Board', BoardSchema); |
YUI.add("inputex-url",function(Y){
var lang = Y.Lang;
var inputEx = Y.inputEx;
/**
* Adds an url regexp, and display the favicon at this url
* @class inputEx.UrlField
* @extends inputEx.StringField
* @constructor
* @param {Object} options inputEx.Field options object
* <ul>
* <li>favicon: boolean whether the domain favicon.ico should be displayed or not (default is true, except for https)</li>
* </ul>
*/
inputEx.UrlField = function(options) {
inputEx.UrlField.superclass.constructor.call(this,options);
};
Y.extend(inputEx.UrlField, inputEx.StringField, {
/**
* Adds the invalid Url message
* @param {Object} options Options object as passed to the constructor
*/
setOptions: function(options) {
inputEx.UrlField.superclass.setOptions.call(this, options);
this.options.className = options.className ? options.className : "inputEx-Field inputEx-UrlField";
this.options.messages.invalid = inputEx.messages.invalidUrl;
this.options.favicon = lang.isUndefined(options.favicon) ? (("https:" == document.location.protocol) ? false : true) : options.favicon;
this.options.size = options.size || 50;
// validate with url regexp
this.options.regexp = inputEx.regexps.url;
},
/**
* Adds a img tag before the field to display the favicon
*/
render: function() {
inputEx.UrlField.superclass.render.call(this);
this.el.size = this.options.size;
if(!this.options.favicon) {
Y.one(this.el).addClass( 'nofavicon');
}
// Create the favicon image tag
if(this.options.favicon) {
this.favicon = inputEx.cn('img', {src: inputEx.spacerUrl});
this.fieldContainer.insertBefore(this.favicon,this.fieldContainer.childNodes[0]);
// focus field when clicking on favicon
Y.on("click",function(){this.focus();},this.favicon,this)
}
},
setClassFromState: function() {
inputEx.UrlField.superclass.setClassFromState.call(this);
if(this.options.favicon) {
// try to update with url only if valid url (else pass null to display inputEx.spacerUrl)
this.updateFavicon((this.previousState == inputEx.stateValid) ? this.getValue() : null);
}
},
updateFavicon: function(url) {
var newSrc = url ? url.match(/https?:\/\/[^\/]*/)+'/favicon.ico' : inputEx.spacerUrl;
if(newSrc != this.favicon.src) {
// Hide the favicon
inputEx.sn(this.favicon, null, {visibility: 'hidden'});
// Change the src
this.favicon.src = newSrc;
// Set the timer to launch displayFavicon in 1s
if(this.timer) { clearTimeout(this.timer); }
var that = this;
this.timer = setTimeout(function(){that.displayFavicon();}, 1000);
}
},
/**
* Display the favicon if the icon was found (use of the naturalWidth property)
*/
displayFavicon: function() {
inputEx.sn(this.favicon, null, {visibility: (this.favicon.naturalWidth!=0) ? 'visible' : 'hidden'});
}
});
inputEx.messages.invalidUrl = "Invalid URL, ex: http://www.test.com";
// Register this class as "url" type
inputEx.registerType("url", inputEx.UrlField, [
{ type: 'boolean', label: 'Display favicon', name:'favicon', value: true}
]);
},'0.1.1',{
requires: ["inputex-string"]
});
|
/* eslint-env mocha */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
User Selector - Test
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
import chai, { expect } from 'chai';
import chaiImmutable from 'chai-immutable';
import { fromJS } from 'immutable';
import { getUser, getUserData } from '../../../src/selectors/user';
chai.use(chaiImmutable);
/**
* User Selector - Test
*/
describe('User Selector', () => {
it('should get user object from state', () => {
const state = {
user: fromJS({
isAuthenticating: false,
isAuthenticated: false,
data: {},
}),
};
const expectedState = state.user.toJS();
const newState = getUser(state);
expect(newState).to.deep.equal(expectedState);
});
it('should get user data object from state', () => {
const state = {
user: fromJS({
isAuthenticating: false,
isAuthenticated: false,
data: {
email: 'bulicmatko@gmail.com',
displayName: 'Matko Bulic',
},
}),
};
const expectedState = state.user.toJS().data;
const newState = getUserData(state);
expect(newState).to.deep.equal(expectedState);
});
});
|
var currentSearch = 0;
var pageCount = 1;
var currentTerm = "";
var intv;
//old loading src https://promotions.coca-cola.com/etc/designs/promotions/img/loading.gif
var loadingsrc = "https://media.giphy.com/media/hQgJCEdGOEHa8/giphy.gif";
$(document).on("ready", function () {
$("#psearchbox").keydown(function(){
$("#searchbox").focus();
$(".plane").animate({opacity:0},200);
$(".plane").addClass("noTouch");
$(".plane").empty();
});
$('#searchbox').keyup(function () {
var dInput = $(this).val();
console.log(dInput);
if (dInput.length >= 1) {
getRequest(dInput);
}
else {
$(".resu").empty();
}
});
var xChecker = setInterval(function(){
if ($(".stayPanel .title").text() == "Title"){
$(".stayPanel").css("opacity",0);
}
checkWiki();
},100);
$(document).on('mouseenter', '.resultblock', function (event) {
var link = $(this).find(".title").attr("href");
intv = setInterval(function () {
pollImageReady(getHost(link).replace(/.*?:\/\//g, ""));
}, 2000);
$(".stay").animate({ opacity: 1 }, 700);
$(".stayPanel").css("opacity",0);
}).on('mouseleave', '.resultblock', function () {
clearInterval(intv);
$(".stay").animate({ opacity: 0 }, 400);
checkWiki();
$(".stay").find("img").attr("src", loadingsrc)
});
if (document.location.search.length) {
$("#searchbox").val(document.location.search.split("q=")[1]);
var terms = $("#searchbox").val();
$(".resultBox").empty();
pageCount = 1;
$(".stayPanel .title").empty();
$(".stayPanel .panelPeek").attr("src","");
$(".stayPanel .desc").empty();
parseResultsXML(terms, 0);
} else {
// no query string exists
}
});
function pollImageReady(url) {
var site = "http://free.pagepeeker.com/v2/thumbs_ready.php?size=m&url=" + url;
$.getJSON(site, function (data) {
var obj = JSON.parse(JSON.stringify(data));
var val = obj.IsReady;
if (val == 1) {
clearInterval(intv);
$(".stay").find("img").attr("src", "http://api3.pagepeeker.com/v2/thumbs.php?size=x&url=" + url);
}
else {
console.log(val);
$(".stay").find("img").attr("src", "https://promotions.coca-cola.com/etc/designs/promotions/img/loading.gif")
}
});
}
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 20) {
if (currentTerm != "") {
$(".resultBox").append("<b style='text-align:center'> ~~~ Page " + pageCount + " ~~~ </b>")
pageCount += 1;
parseResultsXML(currentTerm, currentSearch + 10);
}
}
});
function getRequest(query) {
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?",
{
"hl": "en", // Language
"jsonp": "suggestCallBack", // jsonp callback function name
"q": query, // query term
"client": "youtube" // force youtube style response, i.e. jsonp
}
);
}
function suggestCallBack(data) {
var suggestions = [];
$(".resu").empty();
$.each(data[1], function (key, val) {
suggestions.push({ "value": val[0] });
var li = document.createElement("li");
li.innerText = val[0];
li.onclick = function () {
$("#searchbox").val(val[0]);
$(".resu").empty();
var terms = $("#searchbox").val();
$(".resultBox").empty();
parseResultsXML(terms, 0);
};
$(".resu").append(li);
});
}
function filterKeyPress(e) {
var key = e.keyCode;
if (key == 13) {
var terms = $("#searchbox").val();
$(".resultBox").empty();
pageCount = 1;
setTimeout(function(){
$(".resu").empty();
},1000);
$(".stayPanel .title").empty();
$(".stayPanel .panelPeek").attr("src","");
$(".stayPanel .desc").empty();
parseResultsXML(terms, 0);
}
}
function parseResultsXML(term, startAt) {
currentTerm = term;
var query = "https://www.googleapis.com/customsearch/v1?key=AIzaSyAdAxmhj88AcMJ82-RL61UJ-3cdqmyEhtU&cx=012139983785816136535:ljxdm-trvww&q=" + term + "&alt=atom&start=" + startAt;
$.ajax({
url: query,
type: 'GET',
dataType: 'xml',
success: function (s) {
formResults(xmlToString(s))
},
error: function (e) { parseResultsJSON(term, startAt) }
});
}
function parseResultsJSON(term, startAt) {
currentTerm = term;
var query = "https://www.googleapis.com/customsearch/v1element?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY&num=10&prettyPrint=false&source=gcsc&gss=.com&sig=ee93f9aae9c9e9dba5eea831d506e69a&cx=partner-pub-8993703457585266%3A4862972284&start=" + startAt + "&googlehost=www.google.com&q=" + term + "&callback=called";
$.ajax({
url: query,
type: 'REST',
dataType: 'jsonp'
});
}
function called(itm) {
formJResults(JSON.stringify(itm));
}
function checkWiki() {
var firstResult = $(document).find(".resultblock");
var firstAddress = firstResult.find(".root").html();
var firstheading = firstResult.find(".title").html();
var firstImage = firstResult.find(".hidden").text();
var firstdesc = firstResult.find(".desc").text().replace(/\n/gm, '');
if (firstAddress.toLowerCase().indexOf("wikipedia.org") >= 0) {
var imgLoc = firstImage.replace('"','').split('""')[0].replace('"','');
showPanel(imgLoc,firstdesc,firstheading,firstAddress);
}
else
{
$(".stayPanel").css("opacity",0);
$(".stayPanel .title").empty();
$(".stayPanel .panelPeek").attr("src","");
$(".stayPanel .desc").empty();
}
}
String.prototype.trunc =
function( n, useWordBoundary ){
var isTooLong = this.length > n,
s_ = isTooLong ? this.substr(0,n-1) : this;
s_ = (useWordBoundary && isTooLong) ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
return isTooLong ? s_ + '...' : s_;
};
function showPanel(imgLoc, desc, heading, link){
var panel_image = $(".stayPanel").find(".panelPeek");
var panel_title = $(".stayPanel").find(".title");
var panel_description = $(".stayPanel").find(".desc");
panel_image.attr("src",imgLoc);
panel_title.html(heading);
panel_description.html(desc.trunc(435,true)+ " <a href=" + link+ "> Learn more </a>");
$(".stayPanel").css("opacity",1);
}
function formJResults(jsonS) {
var $json = $.parseJSON(jsonS);
$.each($json.results, function (idx, obj) {
var linc = JSON.stringify($json.results[idx].unescapedUrl);
var titl = JSON.stringify($json.results[idx].title);
var desc = JSON.stringify($json.results[idx].content);
var cseImage = "";
if (linc.toLowerCase().indexOf("wikipedia.org") >= 0) {
cseImage = JSON.stringify($json.results[idx].richSnippet.cseImage.src);
}
createJResultBlock(titl, linc, desc, cseImage);
});
checkWiki();
}
function createJResultBlock(xtitle, path, desc, zimg) {
path = path.replace(/^"(.+(?="$))"$/, '$1');
xtitle = xtitle.replace(/^"(.+(?="$))"$/, '$1');
desc = desc.replace(/^"(.+(?="$))"$/, '$1');
var isWiki = (path.toLowerCase().indexOf("wikipedia.org") >= 0);
var resBlock = document.createElement("div");
resBlock.className = "resultblock";
$(".resultBox").append(resBlock);
var title = document.createElement("a");
title.className = "title";
title.innerHTML = xtitle;
title.href = path;
resBlock.appendChild(title);
var xroot = document.createElement("p");
xroot.className = "root";
xroot.innerHTML = path;
resBlock.appendChild(xroot);
var xdesc = document.createElement("p");
xdesc.className = "desc";
xdesc.innerHTML = desc;
resBlock.appendChild(xdesc);
if (isWiki == true) {
zimg = zimg || "";
var zimage = document.createElement("p")
zimage.className = "hidden";
zimage.innerText = String(zimg).replace('""','');
resBlock.appendChild(zimage);
}
var mimg = document.createElement("img");
mimg.src = "http://www.google.com/s2/favicons?domain=" + getHost(path);
resBlock.appendChild(mimg);
}
function formResults(xmlS) {
var xmlDoc = $.parseXML(xmlS);
var $xml = $(xmlDoc);
var $results = $xml.find("entry");
$.each($results, function (i, item) {
var soort = $(this).attr('gd:kind');
if (soort == "customsearch#result") {
var addr = $(this).find("id").text();
var titl = $(this).find("title").text();
var desc = $(this).find("summary").text();
var cseImage = "";
createJResultBlock(titl, addr, desc, cseImage);
}
});
checkWiki();
}
// function createResultBlock(xtitle, path, desc) {
// var resBlock = document.createElement("div");
// resBlock.className = "resultblock";
// $(".resultBox").append(resBlock);
// var title = document.createElement("a");
// title.className = "title";
// title.innerHTML = xtitle;
// title.href = path;
// resBlock.appendChild(title);
// var xroot = document.createElement("p");
// xroot.className = "root";
// xroot.innerHTML = getHost(path);
// resBlock.appendChild(xroot);
// var xdesc = document.createElement("p");
// xdesc.className = "desc";
// xdesc.innerHTML = desc;
// resBlock.appendChild(xdesc);
// var mimg = document.createElement("img");
// mimg.src = "http://www.google.com/s2/favicons?domain=" + getHost(path);
// resBlock.appendChild(mimg);
// }
function getHost(address) {
var att = document.createElement('a');
att.href = address;
return att.hostname; // => "example.com"
}
function xmlToString(xmlData) {
var xmlString;
//IE
if (window.ActiveXObject) {
xmlString = xmlData.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else {
xmlString = (new XMLSerializer()).serializeToString(xmlData);
}
return xmlString;
} |
import test from 'ava';
import VK from '../';
var app = {
clientId: 'CLIENT_ID',
clientSecret: 'CLIENT_SECRET',
redirectUri: 'REDIRECT_URI',
scope: ['wall', 'friends']
};
test('checking method reachability', t => {
var vk = new VK(app);
t.ok(vk.hasInScope('wall.post'), 'sees scoped method in scope');
t.ok(vk.hasInScope('users.get'), 'sees open method in scope');
t.notOk(vk.hasInScope('photos.save'), 'doesn\'t see unscoped method in scope');
t.end();
});
|
// Copyright (c) 2006-2009 by Martin Stubenschrott <stubenschrott@vimperator.org>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const DEFAULT_FAVICON = "chrome://mozapps/skin/places/defaultFavicon.png";
// also includes methods for dealing with keywords and search engines
const Bookmarks = Module("bookmarks", {
requires: ["autocommands", "config", "liberator", "storage", "services"],
init: function () {
const faviconService = services.get("favicon");
const bookmarksService = services.get("bookmarks");
const historyService = services.get("history");
const tagging = PlacesUtils.tagging;
function getFavicon (uri) {
if (typeof uri === "string")
uri = util.newURI(uri);
var url = null;
faviconService.getFaviconDataForPage(uri, function (iconURI) {
url = iconURI ? iconURI.spec : "";
});
while (url === null)
liberator.threadYield(false, true);
return url;
}
this.getFavicon = getFavicon;
// Fix for strange Firefox bug:
// Error: [Exception... "Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIObserverService.addObserver]"
// nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)"
// location: "JS frame :: file://~firefox/components/nsTaggingService.js :: anonymous :: line 89"
// data: no]
// Source file: file://~firefox/components/nsTaggingService.js
tagging.getTagsForURI(window.makeURI("http://mysterious.bug"), {});
const Bookmark = Struct("url", "title", "icon", "keyword", "tags", "id");
const Keyword = Struct("keyword", "title", "icon", "url");
Bookmark.defaultValue("icon", function () getFavicon(this.url));
Bookmark.prototype.__defineGetter__("extra", function () [
["keyword", this.keyword, "Keyword"],
["tags", this.tags.join(", "), "Tag"]
].filter(function (item) item[1]));
const storage = modules.storage;
function Cache(name, store) {
const rootFolders = [bookmarksService.toolbarFolder, bookmarksService.bookmarksMenuFolder, bookmarksService.unfiledBookmarksFolder];
const sleep = liberator.sleep; // Storage objects are global to all windows, 'liberator' isn't.
let bookmarks = [];
let self = this;
this.__defineGetter__("name", function () name);
this.__defineGetter__("store", function () store);
this.__defineGetter__("bookmarks", function () this.load());
this.__defineGetter__("keywords", function () {
return self.bookmarks.filter(k => k.keyword)
.map(k => Keyword(k.keyword, k.title, k.icon, k.url));
});
this.__iterator__ = function () iter(self.bookmarks);
function loadBookmark(node) {
if (node.uri == null) // How does this happen?
return false;
let uri = util.newURI(node.uri);
let keyword = bookmarksService.getKeywordForBookmark(node.itemId);
let tags = tagging.getTagsForURI(uri, {}) || [];
let bmark = Bookmark(node.uri, node.title, node.icon, keyword, tags, node.itemId);
bookmarks.push(bmark);
return bmark;
}
function readBookmark(id) {
return {
itemId: id,
uri: bookmarksService.getBookmarkURI(id).spec,
title: bookmarksService.getItemTitle(id)
};
}
function deleteBookmark(id) {
let length = bookmarks.length;
bookmarks = bookmarks.filter(function (item) item.id != id);
return bookmarks.length < length;
}
this.findRoot = function findRoot(id) {
do {
var root = id;
id = bookmarksService.getFolderIdForItem(id);
} while (id != bookmarksService.placesRoot && id != root);
return root;
};
this.isBookmark = function (id) rootFolders.indexOf(self.findRoot(id)) >= 0;
// since we don't use a threaded bookmark loading (by set preload)
// anymore, is this loading synchronization still needed? --mst
let loading = false;
this.load = function load() {
if (loading) {
while (loading)
sleep(10);
return bookmarks;
}
// update our bookmark cache
bookmarks = [];
loading = true;
let folders = rootFolders.slice();
let query = historyService.getNewQuery();
let options = historyService.getNewQueryOptions();
while (folders.length > 0) {
query.setFolders(folders, 1);
folders.shift();
let result = historyService.executeQuery(query, options);
let folder = result.root;
folder.containerOpen = true;
// iterate over the immediate children of this folder
for (let i = 0; i < folder.childCount; i++) {
let node = folder.getChild(i);
if (node.type == node.RESULT_TYPE_FOLDER) // folder
folders.push(node.itemId);
else if (node.type == node.RESULT_TYPE_URI) // bookmark
loadBookmark(node);
}
// close a container after using it!
folder.containerOpen = false;
}
this.__defineGetter__("bookmarks", function () bookmarks);
loading = false;
return bookmarks;
};
var observer = {
onBeginUpdateBatch: function onBeginUpdateBatch() {},
onEndUpdateBatch: function onEndUpdateBatch() {},
onItemVisited: function onItemVisited() {},
onItemMoved: function onItemMoved() {},
onItemAdded: function onItemAdded(itemId, folder, index) {
if (bookmarksService.getItemType(itemId) == bookmarksService.TYPE_BOOKMARK) {
if (self.isBookmark(itemId)) {
let bmark = loadBookmark(readBookmark(itemId));
storage.fireEvent(name, "add", bmark);
statusline.updateField("bookmark");
}
}
},
onItemRemoved: function onItemRemoved(itemId, folder, index) {
if (deleteBookmark(itemId)) {
storage.fireEvent(name, "remove", itemId);
statusline.updateField("bookmark");
}
},
onItemChanged: function onItemChanged(itemId, property, isAnnotation, value) {
if (isAnnotation)
return;
let bookmark = bookmarks.filter(function (item) item.id == itemId)[0];
if (bookmark) {
if (property == "tags")
value = tagging.getTagsForURI(util.newURI(bookmark.url), {});
if (property in bookmark)
bookmark[property] = value;
storage.fireEvent(name, "change", itemId);
}
},
QueryInterface: function QueryInterface(iid) {
if (iid.equals(Ci.nsINavBookmarkObserver) || iid.equals(Ci.nsISupports))
return this;
throw Cr.NS_ERROR_NO_INTERFACE;
}
};
bookmarksService.addObserver(observer, false);
}
let bookmarkObserver = function (key, event, arg) {
if (event == "add")
autocommands.trigger("BookmarkAdd", arg);
};
this._cache = storage.newObject("bookmark-cache", Cache, { store: false });
storage.addObserver("bookmark-cache", bookmarkObserver, window);
},
get format() ({
anchored: false,
title: ["URL", "Info"],
keys: { text: "url", description: "title", icon: function(item) item.icon || DEFAULT_FAVICON,
extra: "extra", tags: "tags", keyword: "keyword" },
process: [template.icon, template.bookmarkDescription]
}),
// TODO: why is this a filter? --djk
get: function get(filter, tags, maxItems, extra) {
return completion.runCompleter("bookmark", filter, maxItems, tags, extra);
},
// if starOnly = true it is saved in the unfiledBookmarksFolder, otherwise in the bookmarksMenuFolder
add: function add(starOnly, title, url, keyword, tags, folder, force) {
var bs = services.get("bookmarks");
try {
let uri = util.createURI(url);
if (!force) {
for (let bmark in this._cache) {
if (bmark[0] == uri.spec) {
var id = bmark[5];
if (title)
bs.setItemTitle(id, title);
break;
}
}
}
let folderId = bs[starOnly ? "unfiledBookmarksFolder" : "bookmarksMenuFolder"];
if (folder) {
let folders = folder.split("/");
if (!folders[folders.length - 1])
folders.pop();
let rootFolderId = folderId;
if (folders[0] === "TOOLBAR") {
rootFolderId = bs.toolbarFolder;
folders.shift();
}
let node = Bookmarks.getBookmarkFolder(folders, rootFolderId);
if (node)
folderId = node.itemId;
else {
liberator.echoerr("Bookmark folder is not found: `" + folder + "'");
return false;
}
}
if (id == undefined)
id = bs.insertBookmark(folderId, uri, -1, title || url);
if (!id)
return false;
if (keyword)
bs.setKeywordForBookmark(id, keyword);
if (tags) {
PlacesUtils.tagging.untagURI(uri, null);
PlacesUtils.tagging.tagURI(uri, tags);
}
}
catch (e) {
liberator.echoerr(e);
return false;
}
return true;
},
toggle: function toggle(url) {
if (!url)
return;
let count = this.remove(url);
if (count > 0)
liberator.echomsg("Removed bookmark: " + url);
else {
let title = buffer.title || url;
let extra = "";
if (title != url)
extra = " (" + title + ")";
this.add(true, title, url);
liberator.echomsg("Added bookmark: " + url);
}
},
isBookmarked: function isBookmarked(url) services.get("bookmarks").isBookmarked(util.newURI(url)),
// returns number of deleted bookmarks
remove: function remove(url) {
try {
let uri = util.newURI(url);
let bmarks = services.get("bookmarks").getBookmarkIdsForURI(uri, {});
bmarks.forEach(services.get("bookmarks").removeItem);
return bmarks.length;
}
catch (e) {
liberator.echoerr(e);
return 0;
}
},
// TODO: add filtering
// also ensures that each search engine has a Liberator-friendly alias
getSearchEngines: function getSearchEngines() {
let searchEngines = [];
for (let [, engine] in Iterator(services.get("search").getVisibleEngines({}))) {
let alias = engine.alias;
if (!alias || !/^[a-z0-9_-]+$/.test(alias))
alias = engine.name.replace(/^\W*([a-zA-Z_-]+).*/, "$1").toLowerCase();
if (!alias)
alias = "search"; // for search engines which we can't find a suitable alias
// make sure we can use search engines which would have the same alias (add numbers at the end)
let newAlias = alias;
for (let j = 1; j <= 10; j++) { // <=10 is intentional
if (!searchEngines.some(function (item) item[0] == newAlias))
break;
newAlias = alias + j;
}
// only write when it changed, writes are really slow
if (engine.alias != newAlias)
engine.alias = newAlias;
searchEngines.push([engine.alias, engine.description, engine.iconURI && engine.iconURI.spec]);
}
return searchEngines;
},
getSuggestions: function getSuggestions(engineName, query, callback) {
const responseType = "application/x-suggestions+json";
let engine = services.get("search").getEngineByAlias(engineName);
if (engine && engine.supportsResponseType(responseType))
var queryURI = engine.getSubmission(query, responseType).uri.spec;
if (!queryURI)
return [];
function process(resp) {
let results = [];
try {
results = JSON.parse(resp.responseText)[1];
results = results.filter((item, k) => typeof item == "string")
.map((item, k) => [item, ""]);
}
catch (e) {}
if (!callback)
return results;
return callback(results);
}
let resp = util.httpGet(queryURI, callback && process);
if (!callback)
return process(resp);
return null;
},
// TODO: add filtering
// format of returned array:
// [keyword, helptext, url]
getKeywords: function getKeywords() {
return this._cache.keywords;
},
// full search string including engine name as first word in @param text
// if @param useDefSearch is true, it uses the default search engine
// @returns the url for the search string
// if the search also requires a postData, [url, postData] is returned
getSearchURL: function getSearchURL(text, useDefsearch) {
let searchString = (useDefsearch ? options["defsearch"] + " " : "") + text;
// we need to make sure our custom alias have been set, even if the user
// did not :open <tab> once before
this.getSearchEngines();
// ripped from Firefox
function getShortcutOrURI(url) {
var keyword = url;
var param = "";
var offset = url.indexOf(" ");
if (offset > 0) {
keyword = url.substr(0, offset);
param = url.substr(offset + 1);
}
var engine = services.get("search").getEngineByAlias(keyword);
if (engine) {
var submission = engine.getSubmission(param, null);
return [submission.uri.spec, submission.postData];
}
let [shortcutURL, postData] = PlacesUtils.getURLAndPostDataForKeyword(keyword);
if (!shortcutURL)
return [url, null];
let data = window.unescape(postData || "");
if (/%s/i.test(shortcutURL) || /%s/i.test(data)) {
var charset = "";
var matches = shortcutURL.match(/^(.*)\&mozcharset=([a-zA-Z][_\-a-zA-Z0-9]+)\s*$/);
if (matches)
[, shortcutURL, charset] = matches;
else {
try {
charset = services.get("history").getCharsetForURI(window.makeURI(shortcutURL));
}
catch (e) {}
}
var encodedParam;
if (charset)
encodedParam = escape(window.convertFromUnicode(charset, param));
else
encodedParam = encodeURIComponent(param);
shortcutURL = shortcutURL.replace(/%s/g, encodedParam).replace(/%S/g, param);
if (/%s/i.test(data))
postData = window.getPostDataStream(data, param, encodedParam, "application/x-www-form-urlencoded");
}
else if (param)
return [shortcutURL, null];
return [shortcutURL, postData];
}
let [url, postData] = getShortcutOrURI(searchString);
if (url == searchString)
return null;
if (postData)
return [url, postData];
return url; // can be null
},
// if openItems is true, open the matching bookmarks items in tabs rather than display
list: function list(filter, tags, openItems, maxItems, keyword) {
// FIXME: returning here doesn't make sense
// Why the hell doesn't it make sense? --Kris
// Because it unconditionally bypasses the final error message
// block and does so only when listing items, not opening them. In
// short it breaks the :bmarks command which doesn't make much
// sense to me but I'm old-fashioned. --djk
let kw = (keyword == "") ? undefined : {keyword:keyword};
if (!openItems)
return completion.listCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription);
let items = completion.runCompleter("bookmark", filter, maxItems, tags, kw, CompletionContext.Filter.textAndDescription);
if (items.length)
return liberator.open(items.map(function (i) i.url), liberator.NEW_TAB);
if (filter.length > 0 && tags.length > 0)
liberator.echoerr("No bookmarks matching tags: \"" + tags + "\" and string: \"" + filter + "\"");
else if (filter.length > 0)
liberator.echoerr("No bookmarks matching string: \"" + filter + "\"");
else if (tags.length > 0)
liberator.echoerr("No bookmarks matching tags: \"" + tags + "\"");
else
liberator.echoerr("No bookmarks set");
return null;
}
}, {
getBookmarkFolder: function (folders, rootFolderId) {
var q = PlacesUtils.history.getNewQuery(),
o = PlacesUtils.history.getNewQueryOptions();
if (rootFolderId == PlacesUtils.tagsFolderId)
o.resultType = o.RESULTS_AS_TAG_QUERY;
else {
q.setFolders([rootFolderId], 1);
o.expandQueries = false;
}
var res = PlacesUtils.history.executeQuery(q, o);
var node = res.root;
for (let folder of folders) {
node = getFolderFromNode(node, folder);
if (!node)
break;
}
return node;
function getFolderFromNode (node, title) {
for (let child in Bookmarks.iterateFolderChildren(node)) {
if (child.title == title && child instanceof Ci.nsINavHistoryContainerResultNode) {
node.containerOpen = false;
return child;
}
}
return null;
}
},
iterateFolderChildren: function (node, onlyFolder, onlyWritable) {
if (!node.containerOpen)
node.containerOpen = true;
for (let i = 0, len = node.childCount; i < len; i++) {
let child = node.getChild(i);
if (PlacesUtils.nodeIsContainer(child))
child.QueryInterface(Ci.nsINavHistoryContainerResultNode);
if (PlacesUtils.nodeIsFolder(child)) {
if (onlyWritable && child.childrenReadOnly)
continue;
}
else if (onlyFolder)
continue;
yield child;
}
},
}, {
commands: function () {
commands.add(["ju[mps]"],
"Show jumplist",
function () {
let sh = history.session;
let jumps = Array.from(iter(sh))
.map(([idx, val]) => [
idx == sh.index ? ">" : "",
Math.abs(idx - sh.index),
val.title,
xml`<a highlight="URL" href=${val.URI.spec}>${val.URI.spec}</a>`
]);
let list = template.tabular([{ header: "Jump", style: "color: red", colspan: 2 },
{ header: "", style: "text-align: right", highlight: "Number" },
{ header: "Title", style: "width: 250px; max-width: 500px; overflow: hidden" },
{ header: "URL", highlight: "URL jump-list" }],
jumps);
commandline.echo(list, commandline.HL_NORMAL, commandline.FORCE_MULTILINE);
},
{ argCount: "0" });
// TODO: Clean this up.
function tags(context, args) {
let filter = context.filter;
let have = filter.split(",");
args.completeFilter = have.pop();
let prefix = filter.substr(0, filter.length - args.completeFilter.length);
let tags = util.Array.uniq(
util.Array.flatten(bookmarks._cache.bookmarks.map(b => b.tags))
);
return tags.filter(tag => have.indexOf(tag) < 0)
.map(tag => [prefix + tag, tag]);
}
function title(context, args) {
if (!args.bang)
return [[content.document.title, "Current Page Title"]];
context.keys.text = "title";
context.keys.description = "url";
return bookmarks.get(args.join(" "), args["-tags"], null, { keyword: args["-keyword"], title: context.filter });
}
function keyword(context, args) {
let keywords = util.Array.uniq(
util.Array.flatten(bookmarks._cache.keywords.map(b => b.keyword))
);
return keywords.map(kw => [kw, kw]);
}
commands.add(["bma[rk]"],
"Add a bookmark",
function (args) {
let url = args.length == 0 ? buffer.URL : args[0];
let title = args["-title"] || (args.length == 0 ? buffer.title : null);
let keyword = args["-keyword"] || null;
let tags = args["-tags"] || [];
let folder = args["-folder"] || "";
if (bookmarks.add(false, title, url, keyword, tags, folder, args.bang)) {
let extra = (title == url) ? "" : " (" + title + ")";
liberator.echomsg("Added bookmark: " + url + extra);
}
else
liberator.echoerr("Could not add bookmark: " + title);
}, {
argCount: "?",
bang: true,
completer: function (context, args) {
if (!args.bang) {
context.completions = [[content.document.documentURI, "Current Location"]];
return;
}
completion.bookmark(context, args["-tags"], { keyword: args["-keyword"], title: args["-title"] });
},
options: [[["-title", "-t"], commands.OPTION_STRING, null, title],
[["-tags", "-T"], commands.OPTION_LIST, null, tags],
[["-keyword", "-k"], commands.OPTION_STRING, function (arg) /\w/.test(arg)],
[["-folder", "-f"], commands.OPTION_STRING, null, function (context, args) {
return completion.bookmarkFolder(context, args, PlacesUtils.bookmarksMenuFolderId, true, true);
}]],
});
commands.add(["bmarks"],
"List or open multiple bookmarks",
function (args) {
bookmarks.list(args.join(" "), args["-tags"] || [], args.bang, args["-max"], args["-keyword"] || []);
},
{
bang: true,
completer: function completer(context, args) {
context.quote = null;
context.filter = args.join(" ");
context.filters = [CompletionContext.Filter.textAndDescription];
let kw = (args["-keyword"]) ? {keyword: args["-keyword"]} : undefined;
completion.bookmark(context, args["-tags"], kw);
},
options: [[["-tags", "-T"], commands.OPTION_LIST, null, tags],
[["-max", "-m"], commands.OPTION_INT],
[["-keyword", "-k"], commands.OPTION_STRING, null, keyword]]
});
commands.add(["delbm[arks]"],
"Delete a bookmark",
function (args) {
if (args.bang) {
function deleteAll() {
bookmarks._cache.bookmarks.forEach(function (bmark) { services.get("bookmarks").removeItem(bmark.id); });
liberator.echomsg("All bookmarks deleted");
}
if (commandline.silent)
deleteAll();
else {
commandline.input("This will delete all bookmarks. Would you like to continue? (yes/[no]) ",
function (resp) {
if (resp && resp.match(/^y(es)?$/i)) {
deleteAll();
}
});
}
}
else {
let url = args.string || buffer.URL;
let deletedCount = bookmarks.remove(url);
liberator.echomsg("Deleted " + deletedCount + " bookmark(s) with url: " + JSON.stringify(url));
}
},
{
argCount: "?",
bang: true,
completer: function completer(context) completion.bookmark(context),
literal: 0
});
},
mappings: function () {
var myModes = config.browserModes;
mappings.add(myModes, ["a"],
"Open a prompt to bookmark the current URL",
function () {
let options = {};
let bmarks = bookmarks.get(buffer.URL).filter(function (bmark) bmark.url == buffer.URL);
if (bmarks.length == 1) {
let bmark = bmarks[0];
options["-title"] = bmark.title;
if (bmark.keyword)
options["-keyword"] = bmark.keyword;
if (bmark.tags.length > 0)
options["-tags"] = bmark.tags.join(", ");
}
else {
if (buffer.title != buffer.URL)
options["-title"] = buffer.title;
}
commandline.open("",
commands.commandToString({ command: "bmark", options: options, arguments: [buffer.URL], bang: bmarks.length > 1 }),
modes.EX);
});
mappings.add(myModes, ["A"],
"Toggle bookmarked state of current URL",
function () { bookmarks.toggle(buffer.URL); });
},
options: function () {
options.add(["defsearch", "ds"],
"Set the default search engine",
"string", "google",
{
completer: function completer(context) {
completion.search(context, true);
context.completions = [["", "Don't perform searches by default"]].concat(context.completions);
}
});
var browserSearch = services.get("search");
browserSearch.init(function() {
var alias = browserSearch.defaultEngine.alias;
if (alias) {
let defsearch = options.get("defsearch");
// when already changed, it means the user had been changed in RC file
if (defsearch.value === defsearch.defaultValue)
defsearch.value = alias
defsearch.defaultValue = alias;
}
});
},
completion: function () {
completion.bookmark = function bookmark(context, tags, extra) {
context.title = ["Bookmark", "Title"];
context.format = bookmarks.format;
for (let val in Iterator(extra || [])) {
let [k, v] = val; // Need block scope here for the closure
if (v)
context.filters.push(function (item) this._match(v, item[k] || ""));
}
// Need to make a copy because set completions() checks instanceof Array,
// and this may be an Array from another window.
context.completions = Array.slice(storage["bookmark-cache"].bookmarks);
completion.urls(context, tags);
};
completion.search = function search(context, noSuggest) {
let [, keyword, space, args] = context.filter.match(/^\s*(\S*)(\s*)(.*)$/);
let keywords = bookmarks.getKeywords();
let engines = bookmarks.getSearchEngines();
context.title = ["Search Keywords"];
context.completions = keywords.concat(engines);
context.keys = { text: 0, description: 1, icon: function(item) item[2] || DEFAULT_FAVICON };
if (!space || noSuggest)
return;
context.fork("suggest", keyword.length + space.length, this, "searchEngineSuggest",
keyword, true);
let item = keywords.filter(function (k) k.keyword == keyword)[0];
if (item && item.url.indexOf("%s") > -1) {
context.fork("keyword/" + keyword, keyword.length + space.length, null, function (context) {
context.format = history.format;
context.title = [keyword + " Quick Search"];
// context.background = true;
context.compare = CompletionContext.Sort.unsorted;
context.generate = function () {
let [begin, end] = item.url.split("%s");
return history.get({ uri: window.makeURI(begin), uriIsPrefix: true }).map(function (item) {
let rest = item.url.length - end.length;
let query = item.url.substring(begin.length, rest);
if (item.url.substr(rest) == end && query.indexOf("&") == -1) {
query = query.replace(/#.*/, "");
// Countermeasure for "Error: malformed URI sequence".
try {
item.url = decodeURIComponent(query);
}
catch (e) {
item.url = query;
}
return item;
}
return null;
}).filter(util.identity);
};
});
}
};
completion.searchEngineSuggest = function searchEngineSuggest(context, engineAliases, kludge) {
if (!context.filter)
return;
let engineList = (engineAliases || options["suggestengines"] || "google").split(",");
engineList.forEach(function (name) {
let engine = services.get("search").getEngineByAlias(name);
if (!engine)
return;
let [, word] = /^\s*(\S+)/.exec(context.filter) || [];
if (!kludge && word == name) // FIXME: Check for matching keywords
return;
let ctxt = context.fork(name, 0);
ctxt.title = [engine.description + " Suggestions"];
ctxt.compare = CompletionContext.Sort.unsorted;
ctxt.incomplete = true;
ctxt.match = function (str) str.toLowerCase().indexOf(this.filter.toLowerCase()) === 0;
bookmarks.getSuggestions(name, ctxt.filter, function (compl) {
ctxt.incomplete = false;
ctxt.completions = compl;
});
});
};
completion.bookmarkFolder = function bookmarkFolder (context, args, rootFolderId, onlyFolder, onlyWritable) {
let filter = context.filter,
folders = filter.split("/"),
item = folders.pop();
if (!rootFolderId)
rootFolderId = PlacesUtils.bookmarksMenuFolderId;
let folderPath = folders.length ? folders.join("/") + "/" : "";
if (folders[0] === "TOOLBAR") {
rootFolderId = PlacesUtils.toolbarFolderId;
folders.shift();
}
let folder = Bookmarks.getBookmarkFolder(folders, rootFolderId);
context.title = ["Bookmarks", folders.join("/") + "/"];
context._match = function (filter, str) str.toLowerCase().startsWith(filter.toLowerCase());
let results = [];
if (folders.length === 0) {
results.push(["TOOLBAR", "Bookmarks Toolbar"]);
}
if (folder) {
for (let child in Bookmarks.iterateFolderChildren(folder, onlyFolder, onlyWritable)) {
if (PlacesUtils.nodeIsSeparator(child))
continue;
results.push([folderPath + PlacesUIUtils.getBestTitle(child), child.uri]);
}
folder.containerOpen = false;
}
return context.completions = results;
};
completion.addUrlCompleter("S", "Suggest engines", completion.searchEngineSuggest);
completion.addUrlCompleter("b", "Bookmarks", completion.bookmark);
completion.addUrlCompleter("s", "Search engines and keyword URLs", completion.search);
}
});
// vim: set fdm=marker sw=4 ts=4 et:
|
var fs = require('fs');
module.exports = function($stateProvider, $locationProvider, $urlRouterProvider) {
$stateProvider
.state('app.player', {
views: {
'body': {
template: fs.readFileSync(__dirname + '/../templates/player.html'),
controller: 'playerCtrl'
}
}
});
}
|
const PropTypes = require('prop-types');
const StyleConstants = require('./Style');
const shapeForObject = (obj, propType) =>
PropTypes.shape(
Object.keys(obj).reduce((shape, key) => {
shape[key] = propType;
return shape;
}, {})
);
module.exports = {
buttonTypes: [
'base',
'disabled',
'neutral',
'primary',
'primaryOutline',
'primaryInverse',
'secondary'
],
Icons: [
{
value: 'accounts',
displayValue: 'Accounts'
},
{
value: 'adCampaign',
displayValue: 'Ad Campaign'
},
{
value: 'add',
displayValue: 'Add'
},
{
value: 'add-solid',
displayValue: 'Add Solid'
},
{
value: 'android',
displayValue: 'Android'
},
{
value: 'apple',
displayValue: 'Apple'
},
{
value: 'appliances',
displayValue: 'Appliances'
},
{
value: 'arrow-down',
displayValue: 'Arrow Down'
},
{
value: 'arrow-down-fat',
displayValue: 'Arrow Down Fat'
},
{
value: 'arrow-left',
displayValue: 'Arrow Left'
},
{
value: 'arrow-right',
displayValue: 'Arrow Right'
},
{
value: 'arrow-up',
displayValue: 'Arrow Up'
},
{
value: 'arrow-up-fat',
displayValue: 'Arrow Up Fat'
},
{
value: 'art',
displayValue: 'Art'
},
{
value: 'attention',
displayValue: 'Attention'
},
{
value: 'attention-solid',
displayValue: 'Attention Solid'
},
{
value: 'auto',
displayValue: 'Auto'
},
{
value: 'backspace',
displayValue: 'Backspace'
},
{
value: 'bell',
displayValue: 'bell'
},
{
value: 'bike',
displayValue: 'Bike'
},
{
value: 'bill-pay',
displayValue: 'Bill Pay'
},
{
value: 'bubbles',
displayValue: 'Bubbles'
},
{
value: 'business',
displayValue: 'Business'
},
{
value: 'calendar',
displayValue: 'Calendar'
},
{
value: 'calendar-plus',
displayValue: 'Calendar Plus'
},
{
value: 'camera',
displayValue: 'Camera'
},
{
value: 'campaigns',
displayValue: 'Campaigns'
},
{
value: 'caret-down',
displayValue: 'Caret Down'
},
{
value: 'caret-left',
displayValue: 'Caret Left'
},
{
value: 'caret-right',
displayValue: 'Caret Right'
},
{
value: 'caret-up',
displayValue: 'Caret Up'
},
{
value: 'cash',
displayValue: 'Cash'
},
{
value: 'chart',
displayValue: 'Chart'
},
{
value: 'check',
displayValue: 'Check'
},
{
value: 'check-skinny',
displayValue: 'Check Skinny'
},
{
value: 'check-solid',
displayValue: 'Check Solid'
},
{
value: 'checkbox',
displayValue: 'Checkbox'
},
{
value: 'checkbox-selected',
displayValue: 'Checkbox Selected'
},
{
value: 'checkbox-solid',
displayValue: 'Checkbox Solid'
},
{
value: 'checking',
displayValue: 'Checking'
},
{
value: 'checkmark',
displayValue: 'Checkmark'
},
{
value: 'clock',
displayValue: 'Clock'
},
{
value: 'close',
displayValue: 'Close'
},
{
value: 'close-skinny',
displayValue: 'Close Skinny'
},
{
value: 'close-solid',
displayValue: 'Close Solid'
},
{
value: 'close-box',
displayValue: 'Close Box'
},
{
value: 'comparisons',
displayValue: 'Comparisons'
},
{
value: 'credit-card',
displayValue: 'Credit Card'
},
{
value: 'debts',
displayValue: 'Debts'
},
{
value: 'delete',
displayValue: 'Delete'
},
{
value: 'desktop',
displayValue: 'Desktop'
},
{
value: 'document',
displayValue: 'Document'
},
{
value: 'dollar',
displayValue: 'Dollar'
},
{
value: 'download',
displayValue: 'Download'
},
{
value: 'duplicate',
displayValue: 'Duplicate'
},
{
value: 'edit',
displayValue: 'Edit'
},
{
value: 'education',
displayValue: 'Education'
},
{
value: 'entertainment',
displayValue: 'Entertainment'
},
{
value: 'envelope',
displayValue: 'Envelope'
},
{
value: 'filter',
displayValue: 'Filter'
},
{
value: 'flag',
displayValue: 'Flag'
},
{
value: 'folder',
displayValue: 'Folder'
},
{
value: 'food',
displayValue: 'Food'
},
{
value: 'furniture',
displayValue: 'Furniture'
},
{
value: 'gallery',
displayValue: 'Gallery'
},
{
value: 'gear',
displayValue: 'Gear'
},
{
value: 'gifts',
displayValue: 'Gifts'
},
{
value: 'go-back',
displayValue: 'Go back'
},
{
value: 'hamburger',
displayValue: 'Hamburger'
},
{
value: 'health',
displayValue: 'Health'
},
{
value: 'help',
displayValue: 'Help'
},
{
value: 'home',
displayValue: 'Home'
},
{
value: 'import',
displayValue: 'Import'
},
{
value: 'info',
displayValue: 'Info'
},
{
value: 'info-solid',
displayValue: 'Info-solid'
},
{
value: 'investment',
displayValue: 'Investment'
},
{
value: 'jewlery',
displayValue: 'Jewlery'
},
{
value: 'kabob_horizontal',
displayValue: 'Kabob Horizontal'
},
{
value: 'key',
displayValue: 'Key'
},
{
value: 'kids',
displayValue: 'Kids'
},
{
value: 'line-of-credit',
displayValue: 'Line Of Credit'
},
{
value: 'link',
displayValue: 'Link'
},
{
value: 'list-view',
displayValue: 'List View'
},
{
value: 'loans',
displayValue: 'Loans'
},
{
value: 'lock',
displayValue: 'Lock'
},
{
value: 'map',
displayValue: 'Map'
},
{
value: 'map-2',
displayValue: 'Map 2'
},
{
value: 'mobile-phone',
displayValue: 'Mobile Phone'
},
{
value: 'money-banknote',
displayValue: 'Money Banknote'
},
{
value: 'mx',
displayValue: 'MX'
},
{
value: 'needle',
displayValue: 'Needle'
},
{
value: 'net-worth',
displayValue: 'Net Worth'
},
{
value: 'net-worth2',
displayValue: 'Net Worth 2'
},
{
value: 'no',
displayValue: 'NO'
},
{
value: 'pause',
displayValue: 'Pause'
},
{
value: 'percent',
displayValue: 'Percent'
},
{
value: 'personal-care',
displayValue: 'Personal Care'
},
{
value: 'pets',
displayValue: 'Pets'
},
{
value: 'phone',
displayValue: 'Phone'
},
{
value: 'pig',
displayValue: 'Pig'
},
{
value: 'play',
displayValue: 'Play'
},
{
value: 'play-solid',
displayValue: 'Play Solid'
},
{
value: 'plus',
displayValue: 'Plus'
},
{
value: 'plus-box',
displayValue: 'Plus Box'
},
{
value: 'pointer',
displayValue: 'pointer'
},
{
value: 'property',
displayValue: 'Property'
},
{
value: 'radio-empty',
displayValue: 'Radio Empty'
},
{
value: 'radio-filled',
displayValue: 'Radio Filled'
},
{
value: 'real-estate',
displayValue: 'Real Estate'
},
{
value: 'remarketing',
displayValue: 'Remarketing'
},
{
value: 'retirement',
displayValue: 'Retirement'
},
{
value: 'rocket',
displayValue: 'Rocket'
},
{
value: 'savings',
displayValue: 'Savings'
},
{
value: 'search',
displayValue: 'Search'
},
{
value: 'shopping',
displayValue: 'Shopping'
},
{
value: 'segments',
displayValue: 'Segments'
},
{
value: 'spending',
displayValue: 'Spending'
},
{
value: 'spinner',
displayValue: 'Spinner'
},
{
value: 'split',
displayValue: 'Split'
},
{
value: 'sports',
displayValue: 'Sports'
},
{
value: 'submit-feedback',
displayValue: 'Submit Feedback'
},
{
value: 'subtract',
displayValue: 'Subtract'
},
{
value: 'sync',
displayValue: 'Sync'
},
{
value: 'taxes',
displayValue: 'Taxes'
},
{
value: 'temple',
displayValue: 'Temple'
},
{
value: 'transfer',
displayValue: 'Transfer'
},
{
value: 'transactions',
displayValue: 'Transactions'
},
{
value: 'travel',
displayValue: 'Travel'
},
{
value: 'user',
displayValue: 'User'
},
{
value: 'utilities',
displayValue: 'Utilities'
},
{
value: 'view',
displayValue: 'View'
},
{
value: 'visit',
displayValue: 'Visit'
},
{
value: 'waffle',
displayValue: 'Waffle'
},
{
value: 'wallet',
displayValue: 'Wallet'
},
{
value: 'windows',
displayValue: 'Windows'
},
{
value: 'x-axis',
displayValue: 'X Axis'
},
{
value: 'y-axis',
displayValue: 'Y Axis'
}
],
themeShape: PropTypes.shape({
Colors: shapeForObject(StyleConstants.Colors, PropTypes.string)
})
};
|
/*
// Desired interface for NP in Phaser:
game.neutrino.init({
effects: "export_js/", // "" by default
textures: "textures/" // "" by default
});
game.neutrino.generateTurbulance(); // to generate turbulance texture
game.neturino.loadTurbulance("path_to_noise_texture"); // to load turbulance texture
model = game.neutrino.loadModel("path_to_effect_file");
effect = game.add.neutrino(model, {
position: [400, 300, 0], // [0, 0, 0] by default
rotation: 45, // 0 by default
scale: [1, 1] // [1, 1] by default
});
*/
class PhaserNeutrino {
constructor(){
}
init(config){
const effects = (config && config.effects) || "export_js/";
const textures = (config && config.textures) || "textures/";
//TODO instantiate a PhaserNeutrinoContext
this.neutrinoContext = new PhaserNeutrinoContext(game.renderer, effects, textures);
return this.neutrinoContext;
}
generateTurbulance(){
if(!this.neutrinoContext) {
console.warn('PhaserNeutrino - call init first');
return;
}
const noiseGenerator = new this.neutrinoContext.neutrino.NoiseGenerator();
while (!noiseGenerator.step()) { // approx. 5,000 steps
// you can use 'noiseGenerator.progress' to get generating progress from 0.0 to 1.0
}
}
loadTurbulance(path){
//TODO -
}
/**
*
* @param effectScript
* @returns {*}
*/
loadModel(effectScript){
if(!this.neutrinoContext) {
console.warn('PhaserNeutrino - call init first');
return;
}
return new PhaserNeutrinoEffectModel(this.neutrinoContext, effectScript)
}
/**
*
* @param model
* @param props
* @param game
* @returns {PhaserNeutrinoEffect}
*/
createEffect(model, props, game){
let {position, scale, rotation} = props;
if(!position) position = [0, 0, 0];
if(!scale) scale = [1, 1, 1];
if(!rotation) rotation = 0;
//(effectModel, position, game, rotation, scale)
return new PhaserNeutrinoEffect(
model,
position,
game,
rotation,
scale
);
}
}
Phaser.Game.prototype.neutrino = new PhaserNeutrino();
//game.add.neutrino();
Phaser.GameObjectFactory.prototype.neutrino = function (model, props) {
const effect = Phaser.Game.prototype.neutrino.createEffect(model, props, this.game);
game.stage.addChild(effect);
return effect;
};
//game.make.neutrino();
Phaser.GameObjectCreator.prototype.neutrino = function (model, props) {
return Phaser.Game.prototype.neutrino.createEffect(model, props, this.game);
}; |
/**
* Range object.
*/
export default class Range
{
/**
* Creates a Range.
* @param {Position} first - First position.
* @param {Position} last - Last position.
*/
constructor(first, last)
{
this.first = first;
this.last = last;
}
/**
* Returns correct range, even if last column or row is smaller than first.
* @return {Range} Correct range.
*/
correct()
{
const first = this.first;
const last = this.last;
if (first.column > last.column)
{
const oldCol = first.column;
first.column = last.column;
last.column = oldCol;
}
if (first.row > last.row)
{
const oldRow = first.row;
first.row = last.row;
last.row = oldRow;
}
return new Range(first, last);
}
}
|
import React, { useState, useEffect } from "react"
import { useLocation } from "@reach/router"
import { UpArrowAlt as Arrow } from "@styled-icons/boxicons-regular/UpArrowAlt"
import { LightBulb as Light } from "@styled-icons/entypo/LightBulb"
import { GridHorizontal as Grid } from "@styled-icons/boxicons-regular/GridHorizontal"
import { ListUl as List } from "@styled-icons/boxicons-regular/ListUl"
import { Menu } from "@styled-icons/boxicons-regular/Menu"
import * as Styled from "./styled"
import * as GA from "./trackers"
const MenuBar = ({ setIsMenuOpen, isMenuOpen }) => {
const [theme, setTheme] = useState(null)
const [display, setDisplay] = useState(null)
const location = useLocation()
const isDarkMode = theme === "dark"
const isListMode = display === "list"
if (theme !== null) {
GA.themeTracker(theme)
}
useEffect(() => {
setTheme(window.__theme)
setDisplay(window.__display)
window.__onThemeChange = () => setTheme(window.__theme)
window.__onDisplayChange = () => setDisplay(window.__display)
}, [])
const openMenu = () => {
GA.menuTracker()
setIsMenuOpen(!isMenuOpen)
}
return (
<Styled.MenuBarWrapper>
<Styled.MenuBarGroupMobile>
<Styled.MenuBarGroup>
<Styled.MenuBarItem title="Open Menu" onClick={openMenu}>
<Menu />
</Styled.MenuBarItem>
</Styled.MenuBarGroup>
</Styled.MenuBarGroupMobile>
<Styled.MenuBarGroup>
<Styled.MenuBarItem
title="Change theme"
onClick={() => {
window.__setPreferredTheme(isDarkMode ? "light" : "dark")
if (window.DISQUS !== undefined) {
window.setTimeout(() => {
window.DISQUS.reset({
reload: true,
})
}, 300)
}
}}
className={theme}
isDarkMode={isDarkMode}
>
<Light />
</Styled.MenuBarItem>
{location.pathname === "/" && (
<Styled.MenuBarItem
title="Change visualization"
onClick={() => {
window.__setPreferredDisplay(isListMode ? "grid" : "list")
}}
className="display"
>
{isListMode ? <Grid /> : <List />}
</Styled.MenuBarItem>
)}
<Styled.MenuBarItem
title="Go to top"
onClick={() => {
window.scroll({ top: 0, behavior: "smooth" })
}}
>
<Arrow />
</Styled.MenuBarItem>
</Styled.MenuBarGroup>
</Styled.MenuBarWrapper>
)
}
export default MenuBar
|
'use babel'
import { File, CompositeDisposable, Emitter } from 'atom'
import LibraryCol from './col-library'
import path from 'path'
export default class DictionaryWatch extends Watch {
constructor () {
}
parseFile(filename, data) {
}
}
|
var Router = Ember.Router.extend(); // ensure we don't share routes between all Router instances
Router.map(function() {
this.route('component-test');
this.route('helper-test');
// this.resource('posts', function() {
// this.route('new');
// });
this.resource('station', { path: '/stations/:station' });
});
export default Router;
|
// Note: we use AVA here because it makes setting up the
// conditions for each test relatively simple. The same
// can be done with Tape using a bit more code.
var test = require('ava')
var configureDatabase = require('./helpers/database-config')
configureDatabase(test)
var db = require('../db')
test('getUsers gets all users', function (t) {
// One for each letter of the alphabet!
var expected = 26
return db.getUsers(t.context.connection)
.then(function (result) {
var actual = result.length
t.is(expected, actual)
})
})
test('getUsers gets a single user', function (t) {
var expected = 'Ambitious Aardvark'
return db.getUser(99901, t.context.connection)
.then(function (result) {
var actual = result[0].name
t.is(expected, actual)
})
})
|
"use strict";
var path = require('path'),
expect = require('chai').expect;
require('string.prototype.startswith');
describe('bcrypt argv', function () {
var bcrypt = require(path.join(__dirname, '..', 'index.js'));
it('should handle null value', function (done) {
bcrypt(null, function (err, hash) {
expect(err).to.exist;
expect(err).not.to.be.undefined;
done();
});
});
it('should handle undefined value', function (done) {
bcrypt(undefined, function (err, hash) {
expect(err).to.exist;
expect(err).not.to.be.undefined;
done();
});
});
it('should handle invalid type', function (done) {
bcrypt("this is a string", function (err, hash) {
expect(err).to.exist;
expect(err).not.to.be.undefined;
done();
});
});
it('should handle empty array', function (done) {
bcrypt([], function (err, hash) {
expect(err).to.exist;
expect(err).not.to.be.undefined;
done();
});
});
it('should return usage/help with no arguments', function (done) {
var stdout_write = global.process.stdout.write;
var stderr_write = global.process.stderr.write;
var strings = [];
var errStrings = [];
global.process.stdout.write = function (string) {
strings.push(string);
};
global.process.stderr.write = function (string) {
errStrings.push(string);
};
bcrypt(['node', 'bcrypt'], function (err, hash) {
global.process.stdout.write = stdout_write;
global.process.stderr.write = stderr_write;
expect(err).to.exist;
expect(strings.length).to.be.greaterThan(0);
expect(strings[0].startsWith('usage')).to.be.true;
done();
});
});
it('should return a valid hash with only one argument', function (done) {
bcrypt(['node', 'bcrypt', 'test_string'], function (err, hash) {
expect(err).to.not.exist;
expect(hash).to.exist;
expect(hash).to.be.a('string');
expect(hash.startsWith('$2a$')).to.be.true;
done();
});
});
it('should return a hash with two arguments', function (done) {
bcrypt(['node', 'bcrypt', 'test_string_2', '4'], function (err, hash) {
expect(err).to.not.exist;
expect(hash).to.exist;
expect(hash).to.be.a('string');
expect(hash.startsWith('$2a$04$')).to.be.true;
done();
});
});
it('should replace hash salt rounds < 4 with 4', function (done) {
bcrypt(['node', 'bcrypt', 'test_string_2', '1'], function (err, hash) {
expect(err).to.not.exist;
expect(hash).to.exist;
expect(hash).to.be.a('string');
expect(hash.startsWith('$2a$04$')).to.be.true;
done();
});
});
it('should change hash salt rounds', function (done) {
bcrypt(['node', 'bcrypt', 'test_string_3', '7'], function (err, hash) {
expect(err).to.not.exist;
expect(hash).to.exist;
expect(hash).to.be.a('string');
expect(hash.startsWith('$2a$07$')).to.be.true;
done();
});
});
}); |
"use strict";
var DocumentNode = require('../node/node');
var ContainerNode = function(node, document) {
DocumentNode.call(this, node, document);
};
ContainerNode.type = {
"id": "container",
"properties": {
"nodes": ["array", "content"]
}
};
ContainerNode.Prototype = function() {};
ContainerNode.Prototype.prototype = DocumentNode.prototype;
ContainerNode.prototype = new ContainerNode.Prototype();
ContainerNode.prototype.constructor = ContainerNode;
ContainerNode.prototype.defineProperties();
module.exports = ContainerNode;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M12 4c-4.41 0-8 3.59-8 8s3.59 8 8 8 8-3.59 8-8-3.59-8-8-8zm1 13h-2v-6h2v6zm0-8h-2V7h2v2z" opacity=".3" /><path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /></React.Fragment>
, 'InfoTwoTone');
|
import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
import Card from '../src/components/Card';
import CardBody from '../src/components/CardBody';
import ContentWrap from '../src/components/ContentWrap';
storiesOf('ContentWrap', module)
.add('default', () => (
<ContentWrap>
<Card>
<CardBody>
This Card is ContentWrapped
</CardBody>
</Card>
</ContentWrap>
));
|
/**
* Created by pomy on 4/25/16.
*/
'use strict';
let $ = require('cheerio');
//let coRequest = require('co-request');
let lib = require('../../lib');
let toutiaoLib = require('./toutiaoLib');
function* toutiao() {
//this.response.set("Content-Type", "application/json;charset=utf-8");
let resBody = yield lib.parseBody('http://toutiao.io/').then((body) => {
return body;
});
let postList = $(resBody).find('.posts');
let curDate = $(resBody).find('.daily:first-child').find('.date').children('small').text();
let lists = postList.first().children('.post');
let toutiaoLists = toutiaoLib.parseList(lists);
let arr = lib.listToArr(toutiaoLists);
this.response.body = {
postLists:arr,
curDate: curDate
};
}
function* toutiaoArticle() {
//this.response.set("Content-Type", "application/json;charset=utf-8");
let origin = this.request.get('x-custom-header');
/**
* 异步请求同步: Generator 和 Promise
* 用 request 请求时,没法同步,但可以用 Promise封装了,见 requestPromise
* 另外就是利用 co-request 看了源码后 也是用 Promise 进行 polyfill
* let result = yield coRequest(origin);
url = result.client._httpMessage._headers.host + result.client._httpMessage.path;
* 另一个点是 yield 后只能跟 promise/generator等 跟普通的Object会报错
*/
// let result = yield coRequest(origin);
// url = result.client._httpMessage._headers.host + result.client._httpMessage.path;
let url = yield lib.parseUrl(origin).then((path) => {
return path;
});
this.body = JSON.stringify({
url: url
});
}
function* toutiaotPrev () {
//this.response.set("Content-Type", "application/json;charset=utf-8");
let prevUrl = this.request.get('x-custom-header');
let resBody = yield lib.parseBody(prevUrl).then((body) => {
return body;
},(err) => {
console.log('reject',err);
return 404;
});
let arr = [];
let hasNext = 0;
let curDate = '';
if(resBody !== 404){
let lists = $(resBody).find('.post');
hasNext = 1;
curDate = $(resBody).find('.date').children('small').text();
let toutiaoPrevLists = toutiaoLib.parseList(lists);
arr = lib.listToArr(toutiaoPrevLists);
}
this.response.body = {
postLists:arr,
hasNext: hasNext,
curDate: curDate
};
}
module.exports.register = (router) => {
router.get('/toutiao', toutiao);
router.get('/toutiao/article', toutiaoArticle);
router.get('/toutiao/prev', toutiaotPrev)
}; |
import gmJs from 'gm';
/**
* Converts images and replaces HTML for image integration.
* @constructor
* @param {Object} config [description]
* @return {Object} [description]
*/
const imageStyles = function(config) {
const external = {};
const internal = {};
const gm = gmJs.subClass({imageMagick: true});
internal.jpgQuality = 85;
/**
* Improve image without changing its dimensions.
* @param {String} sourceFilename [description]
* @param {String} targetFilename [description]
* @return {Promise} [description]
*/
external.generateNoStyleImage = function(sourceFilename, targetFilename) {
if (!targetFilename) {
throw new Error('No target filename given for conversion');
}
return new Promise(
function(resolve, reject) {
//console.log(sourceFilename);
gm(sourceFilename)
.strip() //noProfile()
.colorspace('sRGB')
.samplingFactor(1, 1) // @see https://developers.google.com/speed/docs/insights/OptimizeImages
.interlace('Plane')
.quality(internal.jpgQuality)
.write(targetFilename, function(err) {
if (err) {
reject(err);
}
resolve( 1 );
})
;
}
);
};
/**
* Convert image to all different images sizes for a given style.
* @param {String} sourceFilename [description]
* @param {String} targetFilename [description]
* @param {String} style [description]
* @return {Promise} [description]
*/
external.generateImagesFromStyle = function(sourceFilename, targetFilename, style) {
if (!targetFilename) {
throw new Error('No target filename given for conversion');
}
let styleData = internal.getStyle(style);
let processed = 0;
let maxProcessed = styleData.srcset.length;
return new Promise(
function(resolve, reject) {
let checkProcessed = function(err) {
if (err) {
reject(err);
}
if (++processed === maxProcessed) {
resolve( processed );
}
};
styleData.srcset.forEach(function(currentSrcSet) {
//console.log(sourceFilename);
gm(sourceFilename)
.strip() //noProfile()
.colorspace('sRGB')
.samplingFactor(1, 1) // @see https://developers.google.com/speed/docs/insights/OptimizeImages
.geometry(currentSrcSet[0], currentSrcSet[1], "^")
.gravity('Center')
.crop(currentSrcSet[0], currentSrcSet[1])
.unsharp(2, 0.5, 0.5, 0)
.interlace('Plane')
.quality(internal.jpgQuality)
.write(external.getFilenameSrcset(targetFilename, currentSrcSet), checkProcessed)
;
});
}
);
};
/**
* Cycle through all styles, generate all sizes for the given image, including
* a conversion of the original file to an optimized copy of itself.
* @param {String} sourceFilename [description]
* @param {String} targetFilename [description]
* @param {Array} styles Optional, defaults to all styles
* @return {Promise} [description]
*/
external.generateImagesWithStyles = function(sourceFilename, targetFilename, styles) {
if (!targetFilename) {
throw new Error('No target filename given for conversion');
}
styles = styles || Object.keys(config.themeConf.imageStyles);
let processed = 0;
return new Promise(
function(resolve, reject) {
let promises = styles.map(function(style) {
return external.generateImagesFromStyle(sourceFilename, targetFilename, style);
});
Promise
.all(promises)
.then(function(generatedImages) {
if (promises.length > 0) {
processed = generatedImages.reduce(function(accumulatedValue, generatedImage) {
return accumulatedValue + generatedImage;
});
}
return external.generateNoStyleImage(sourceFilename, targetFilename);
})
.then(function() {
processed++;
resolve(processed);
})
.catch(reject)
;
}
);
};
/**
* Replace IMG-tags in HTML with HTML for their current style.
* @param {String} html [description]
* @return {String} [description]
*/
external.replaceImgHtml = function(html) {
return html.replace(/(?:<img src=")([^"]+)#([^"]+)(?:")/g, internal.parseImagesReplace);
};
/**
* Returns HTML for a given filename and image style.
* Used by `external.replaceImgHtml()`.
* @see https://caniuse.com/#search=webp
* @param {String} all Will be ignored (as it comes from a `.replace` operation)
* @param {String} filename Filename of image
* @param {String} style Style for image
* @return {String} HTML for IMG-tag
*/
internal.parseImagesReplace = function(all, filename, style) {
style = style || "default";
let html;
if (style.match(/^\d+x\d+$/)) {
html = '<img src="' + filename + '" ' + style.replace(/^(\d+)x(\d+)$/, function(all, width, height) {
return 'width="' + width +'" height="' + height + '" style="--aspect-ratio: ' + internal.getAspectRatio(width, height) + ';"'
});
} else if (filename.match(/\.(svg)/)) {
let currentStyle = internal.getStyle(style);
let dominantIndex = (currentStyle.srcset.length - 1);
html = '<img src="' + filename + '" class="' + style + '"';
html += ' width="' + currentStyle.srcset[dominantIndex][0] + '" height="' + currentStyle.srcset[dominantIndex][1] + '"';
html += ' style="--aspect-ratio: ' + internal.getAspectRatio(currentStyle.srcset[dominantIndex][0], currentStyle.srcset[dominantIndex][1]) + ';"';
} else {
let currentStyle = internal.getStyle(style);
let dominantIndex = (currentStyle.srcset.length - 1);
let srcset = [];
let i;
html = '<img data-src="' + filename + '" src="' + external.getFilenameSrcset(filename, currentStyle.srcset[dominantIndex]) + '" class="' + style + '"';
html += ' width="' + currentStyle.srcset[dominantIndex][0] + '" height="' + currentStyle.srcset[dominantIndex][1] + '"';
html += ' style="--aspect-ratio: ' + internal.getAspectRatio(currentStyle.srcset[dominantIndex][0], currentStyle.srcset[dominantIndex][1]) + ';"';
if (currentStyle.srcset.length > 1) {
for (i = 0; i < currentStyle.srcset.length; i++) {
srcset.push(external.getFilenameSrcset(filename, currentStyle.srcset[i]) + ' ' + currentStyle.srcset[i][0] + 'w');
}
html += ' srcset="' + srcset.join(', ') + '"';
if (currentStyle.sizes.length) {
html += ' sizes="' + currentStyle.sizes.join(', ') + '"';
}
}
}
return html;
};
/**
* Get computed filename of image, given its style and index.
* @param {String} filename Original filename.
* @param {String} style like `default`, `quad`
* @param {Integer} index Index of style, defaults to `0`.
* @return {String} Converted filename for given style.
*/
external.getFilename = function(filename, style, index) {
let currentStyle = internal.getStyle(style);
index = index || 0;
if (!currentStyle.srcset[index]) {
throw new Error("Wrong image index in style: " + style + ', ' + index);
}
return external.getFilenameSrcset(filename, currentStyle.srcset[index]);
};
/**
* Get computed filename of image, given its srcset.
* @param {String} filename Original filename.
* @param {Array} srcset with [width,height]
* @return {String} Converted filename for given style.
*/
external.getFilenameSrcset = function(filename, srcset) {
return filename.replace(/^(.+)(\.[^.]+)$/, '$1-' + Number(srcset[0]) + 'x' + Number(srcset[1]) + '$2');
};
/**
* Get style properties.
* @param {String} style [description]
* @return {Object} [description]
*/
internal.getStyle = function(style) {
style = style || "default";
if (config.themeConf && config.themeConf.imageStyles && config.themeConf.imageStyles[style] !== undefined) {
return config.themeConf.imageStyles[style];
} else if (style.match(/^\d+x\d+$/)) {
return {};
}
throw new Error("Wrong image style: " + style);
};
/**
* Normalize aspect ratio
* @param {Integer} width
* @param {Integer} height
* @return {String}
*/
internal.getAspectRatio = function(width, height) {
switch (Number(width) / Number(height)) {
case 21/9: return '21/9';
case 16/9: return '16/9';
case 16/10: return '16/10';
case 4/3: return '4/3';
case 3/2: return '3/2';
case 1/2: return '1/2';
case 1/1: return '1/1';
case 2/1: return '2/1';
case 2/3: return '2/3';
case 3/4: return '3/4';
case 10/16: return '10/16';
case 9/16: return '9/16';
case 9/21: return '9/21';
}
return String(width) + '/' + String(height);
};
return external;
};
export default imageStyles;
|
import Page from "./page"
const PAGE_URL = "/people/new"
const INVISIBLE_CUSTOM_FIELDS = {
textArea: "formCustomFields.textareaFieldName",
number: "formCustomFields.numberFieldName"
}
const SENSITIVE_CUSTOM_FIELDS = {
birthday: "formSensitiveFields.birthday",
politicalPosition: "formSensitiveFields.politicalPosition"
}
export class CreatePerson extends Page {
get form() {
return browser.$("form.form-horizontal")
}
get alertSuccess() {
return browser.$(".alert-success")
}
get lastName() {
return this.form.$("#lastName")
}
get firstName() {
return browser.$("#firstName")
}
get duplicatesButton() {
return browser.$('//button[text()="Possible Duplicates"]')
}
get modalContent() {
return browser.$("div.modal-content")
}
get modalCloseButton() {
return this.modalContent.$("button.btn-close")
}
get similarPerson() {
return this.modalContent.$("tbody tr:first-child td:first-child a")
}
get rolePrincipalButton() {
return browser.$('label[for="role_PRINCIPAL"]')
}
get roleAdvisorButton() {
return browser.$('label[for="role_ADVISOR"]')
}
get emailAddress() {
return browser.$("#emailAddress")
}
get phoneNumber() {
return browser.$("#phoneNumber")
}
get rank() {
return browser.$('select[name="rank"]')
}
get gender() {
return browser.$('select[name="gender"]')
}
get country() {
return browser.$('select[name="country"]')
}
get endOfTourDate() {
return browser.$("#endOfTourDate")
}
get biography() {
return browser.$(".biography .editable")
}
get submitButton() {
return browser.$("#formBottomSubmit")
}
get endOfTourToday() {
return browser.$(".bp3-datepicker-footer button.bp3-button:first-child")
}
get customFieldsContainer() {
return browser.$("#custom-fields")
}
get numberCustomFieldContainer() {
return this.getCustomFieldContainerByName(INVISIBLE_CUSTOM_FIELDS.number)
}
get numberCustomField() {
return this.numberCustomFieldContainer.$('input[type="number"]')
}
get numberCustomFieldHelpText() {
return this.numberCustomFieldContainer.$(
'//div[contains(text(), "greater than")]'
)
}
get defaultInvisibleCustomFields() {
return Object.keys(INVISIBLE_CUSTOM_FIELDS).map(field =>
this.getCustomFieldContainerByName(INVISIBLE_CUSTOM_FIELDS[field])
)
}
get greenButton() {
return this.customFieldsContainer.$(
'label[for="formCustomFields.colourOptions_GREEN"]'
)
}
get amberButton() {
return this.customFieldsContainer.$(
'label[for="formCustomFields.colourOptions_AMBER"]'
)
}
get addArrayObjectButton() {
return this.customFieldsContainer.$(
'button[id="add-formCustomFields.arrayFieldName"]'
)
}
get objectDateField() {
return this.customFieldsContainer.$(
'input[id="formCustomFields.arrayFieldName.0.dateF"]'
)
}
get sensitiveFieldsContainer() {
return browser.$("#sensitive-fields")
}
get birthdaySensitiveFieldContainer() {
return this.getSensitiveFieldContainerByName(
SENSITIVE_CUSTOM_FIELDS.birthday
)
}
get politicalPositionSensitiveFieldContainer() {
return this.getSensitiveFieldContainerByName(
SENSITIVE_CUSTOM_FIELDS.politicalPosition
)
}
get birthday() {
return this.sensitiveFieldsContainer.$(
'input[id="formSensitiveFields.birthday'
)
}
get leftButton() {
return this.sensitiveFieldsContainer.$(
'label[for="formSensitiveFields.politicalPosition_LEFT"]'
)
}
get middleButton() {
return this.sensitiveFieldsContainer.$(
'label[for="formSensitiveFields.politicalPosition_MIDDLE"]'
)
}
getCustomFieldContainerByName(name) {
return this.customFieldsContainer.$(`div[id="fg-${name}"]`)
}
getSensitiveFieldContainerByName(name) {
return this.sensitiveFieldsContainer.$(`div[id="fg-${name}"]`)
}
openAsSuperUser() {
super.openAsSuperUser(PAGE_URL)
}
openAsAdmin() {
super.openAsAdminUser(PAGE_URL)
}
submitForm() {
this.submitButton.scrollIntoView()
this.submitButton.click()
}
}
export default new CreatePerson()
|
/**
* Hydro configuration
*
* @param {Hydro} hydro
*/
module.exports = function(hydro) {
hydro.set({
suite: 'event-to-stream',
timeout: 500,
plugins: [
require('hydro-bdd'),
require('hydro-co')
],
globals: {
assert: require('assert/')
}
})
}
|
smalltalk.addPackage('Helios-KeyBindings');
smalltalk.addClass('HLBinding', smalltalk.Object, ['key', 'label'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "applyOn:",
category: 'actions',
fn: function (aKeyBinder){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"applyOn:",{aKeyBinder:aKeyBinder},smalltalk.HLBinding)})},
args: ["aKeyBinder"],
source: "applyOn: aKeyBinder",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "atKey:",
category: 'accessing',
fn: function (aKey){
var self=this;
return smalltalk.withContext(function($ctx1) {
return nil;
}, function($ctx1) {$ctx1.fill(self,"atKey:",{aKey:aKey},smalltalk.HLBinding)})},
args: ["aKey"],
source: "atKey: aKey\x0a\x09^ nil",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "displayLabel",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._label();
return $1;
}, function($ctx1) {$ctx1.fill(self,"displayLabel",{},smalltalk.HLBinding)})},
args: [],
source: "displayLabel\x0a\x09^ self label",
messageSends: ["label"],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "isActive",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._subclassResponsibility();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isActive",{},smalltalk.HLBinding)})},
args: [],
source: "isActive\x0a\x09^ self subclassResponsibility",
messageSends: ["subclassResponsibility"],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "isFinal",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return false;
}, function($ctx1) {$ctx1.fill(self,"isFinal",{},smalltalk.HLBinding)})},
args: [],
source: "isFinal\x0a\x09\x22 Answer true if the receiver is the final binding of a sequence \x22\x0a\x09\x0a\x09^ false",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "key",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@key"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"key",{},smalltalk.HLBinding)})},
args: [],
source: "key\x0a\x09^ key",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "key:",
category: 'accessing',
fn: function (anInteger){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@key"]=anInteger;
return self}, function($ctx1) {$ctx1.fill(self,"key:",{anInteger:anInteger},smalltalk.HLBinding)})},
args: ["anInteger"],
source: "key: anInteger\x0a\x09key := anInteger",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "label",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@label"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"label",{},smalltalk.HLBinding)})},
args: [],
source: "label\x0a\x09^ label",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "label:",
category: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@label"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"label:",{aString:aString},smalltalk.HLBinding)})},
args: ["aString"],
source: "label: aString\x0a\x09label := aString",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "release",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"release",{},smalltalk.HLBinding)})},
args: [],
source: "release",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "renderActionFor:html:",
category: 'rendering',
fn: function (aBinder,html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$3,$4,$5,$6,$2;
$1=_st(html)._span();
_st($1)._class_("command");
$2=_st($1)._with_((function(){
return smalltalk.withContext(function($ctx2) {
$3=_st(html)._span();
_st($3)._class_("label");
$4=_st($3)._with_(_st(self._shortcut())._asLowercase());
$4;
$5=_st(html)._a();
_st($5)._class_("action");
_st($5)._with_(self._displayLabel());
$6=_st($5)._onClick_((function(){
return smalltalk.withContext(function($ctx3) {
return _st(aBinder)._applyBinding_(self);
}, function($ctx3) {$ctx3.fillBlock({},$ctx2)})}));
return $6;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"renderActionFor:html:",{aBinder:aBinder,html:html},smalltalk.HLBinding)})},
args: ["aBinder", "html"],
source: "renderActionFor: aBinder html: html\x0a\x09html span class: 'command'; with: [\x0a\x09\x09html span \x0a\x09\x09\x09class: 'label'; \x0a\x09\x09\x09with: self shortcut asLowercase.\x0a \x09\x09html a \x0a \x09class: 'action'; \x0a with: self displayLabel;\x0a \x09\x09\x09onClick: [ aBinder applyBinding: self ] ]",
messageSends: ["class:", "span", "with:", "asLowercase", "shortcut", "a", "displayLabel", "onClick:", "applyBinding:"],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "renderOn:html:",
category: 'rendering',
fn: function (aBindingHelper,html){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"renderOn:html:",{aBindingHelper:aBindingHelper,html:html},smalltalk.HLBinding)})},
args: ["aBindingHelper", "html"],
source: "renderOn: aBindingHelper html: html",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "shortcut",
category: 'accessing',
fn: function (){
var self=this;
function $String(){return smalltalk.String||(typeof String=="undefined"?nil:String)}
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st($String())._fromCharCode_(self._key());
return $1;
}, function($ctx1) {$ctx1.fill(self,"shortcut",{},smalltalk.HLBinding)})},
args: [],
source: "shortcut\x0a\x09^ String fromCharCode: self key",
messageSends: ["fromCharCode:", "key"],
referencedClasses: ["String"]
}),
smalltalk.HLBinding);
smalltalk.addMethod(
smalltalk.method({
selector: "on:labelled:",
category: 'instance creation',
fn: function (anInteger,aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._key_(anInteger);
_st($2)._label_(aString);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:labelled:",{anInteger:anInteger,aString:aString},smalltalk.HLBinding.klass)})},
args: ["anInteger", "aString"],
source: "on: anInteger labelled: aString\x0a\x09^ self new\x0a \x09key: anInteger;\x0a label: aString;\x0a yourself",
messageSends: ["key:", "new", "label:", "yourself"],
referencedClasses: []
}),
smalltalk.HLBinding.klass);
smalltalk.addClass('HLBindingAction', smalltalk.HLBinding, ['command'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "applyOn:",
category: 'actions',
fn: function (aKeyBinder){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._command())._isInputRequired();
if(smalltalk.assert($1)){
_st(aKeyBinder)._selectBinding_(self._inputBinding());
} else {
_st(self._command())._execute();
};
return self}, function($ctx1) {$ctx1.fill(self,"applyOn:",{aKeyBinder:aKeyBinder},smalltalk.HLBindingAction)})},
args: ["aKeyBinder"],
source: "applyOn: aKeyBinder\x0a\x09self command isInputRequired\x0a\x09\x09ifTrue: [ aKeyBinder selectBinding: self inputBinding ]\x0a\x09\x09ifFalse: [ self command execute ]",
messageSends: ["ifTrue:ifFalse:", "selectBinding:", "inputBinding", "execute", "command", "isInputRequired"],
referencedClasses: []
}),
smalltalk.HLBindingAction);
smalltalk.addMethod(
smalltalk.method({
selector: "command",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@command"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"command",{},smalltalk.HLBindingAction)})},
args: [],
source: "command\x0a\x09^ command",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingAction);
smalltalk.addMethod(
smalltalk.method({
selector: "command:",
category: 'accessing',
fn: function (aCommand){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@command"]=aCommand;
return self}, function($ctx1) {$ctx1.fill(self,"command:",{aCommand:aCommand},smalltalk.HLBindingAction)})},
args: ["aCommand"],
source: "command: aCommand\x0a\x09command := aCommand",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingAction);
smalltalk.addMethod(
smalltalk.method({
selector: "inputBinding",
category: 'accessing',
fn: function (){
var self=this;
function $HLBindingInput(){return smalltalk.HLBindingInput||(typeof HLBindingInput=="undefined"?nil:HLBindingInput)}
return smalltalk.withContext(function($ctx1) {
var $2,$3,$4,$5,$1;
$2=_st($HLBindingInput())._new();
_st($2)._label_(_st(self._command())._inputLabel());
_st($2)._ghostText_(_st(self._command())._displayLabel());
_st($2)._defaultValue_(_st(self._command())._defaultInput());
_st($2)._inputCompletion_(_st(self._command())._inputCompletion());
_st($2)._callback_((function(val){
return smalltalk.withContext(function($ctx2) {
$3=self._command();
_st($3)._input_(val);
$4=_st($3)._execute();
return $4;
}, function($ctx2) {$ctx2.fillBlock({val:val},$ctx1)})}));
$5=_st($2)._yourself();
$1=$5;
return $1;
}, function($ctx1) {$ctx1.fill(self,"inputBinding",{},smalltalk.HLBindingAction)})},
args: [],
source: "inputBinding\x0a\x09^ HLBindingInput new\x0a\x09\x09label: self command inputLabel;\x0a\x09\x09ghostText: self command displayLabel;\x0a\x09\x09defaultValue: self command defaultInput;\x0a\x09\x09inputCompletion: self command inputCompletion;\x0a\x09\x09callback: [ :val | \x0a\x09\x09\x09self command \x0a\x09\x09\x09\x09input: val;\x0a\x09\x09\x09\x09execute ];\x0a\x09\x09yourself",
messageSends: ["label:", "inputLabel", "command", "new", "ghostText:", "displayLabel", "defaultValue:", "defaultInput", "inputCompletion:", "inputCompletion", "callback:", "input:", "execute", "yourself"],
referencedClasses: ["HLBindingInput"]
}),
smalltalk.HLBindingAction);
smalltalk.addMethod(
smalltalk.method({
selector: "isActive",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._command())._isActive();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isActive",{},smalltalk.HLBindingAction)})},
args: [],
source: "isActive\x0a\x09^ self command isActive",
messageSends: ["isActive", "command"],
referencedClasses: []
}),
smalltalk.HLBindingAction);
smalltalk.addMethod(
smalltalk.method({
selector: "isFinal",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(self._command())._isInputRequired())._not();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isFinal",{},smalltalk.HLBindingAction)})},
args: [],
source: "isFinal\x0a\x09^ self command isInputRequired not",
messageSends: ["not", "isInputRequired", "command"],
referencedClasses: []
}),
smalltalk.HLBindingAction);
smalltalk.addClass('HLBindingGroup', smalltalk.HLBinding, ['bindings'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "activeBindings",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._bindings())._select_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(each)._isActive();
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"activeBindings",{},smalltalk.HLBindingGroup)})},
args: [],
source: "activeBindings\x0a\x09^ self bindings select: [ :each | each isActive ]",
messageSends: ["select:", "isActive", "bindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "add:",
category: 'accessing',
fn: function (aBinding){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._bindings())._add_(aBinding);
return $1;
}, function($ctx1) {$ctx1.fill(self,"add:",{aBinding:aBinding},smalltalk.HLBindingGroup)})},
args: ["aBinding"],
source: "add: aBinding\x0a\x09^ self bindings add: aBinding",
messageSends: ["add:", "bindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "addActionKey:labelled:callback:",
category: 'accessing',
fn: function (anInteger,aString,aBlock){
var self=this;
function $HLBindingAction(){return smalltalk.HLBindingAction||(typeof HLBindingAction=="undefined"?nil:HLBindingAction)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st($HLBindingAction())._on_labelled_(anInteger,aString);
_st($1)._callback_(aBlock);
$2=_st($1)._yourself();
self._add_($2);
return self}, function($ctx1) {$ctx1.fill(self,"addActionKey:labelled:callback:",{anInteger:anInteger,aString:aString,aBlock:aBlock},smalltalk.HLBindingGroup)})},
args: ["anInteger", "aString", "aBlock"],
source: "addActionKey: anInteger labelled: aString callback: aBlock\x0a\x09self add: ((HLBindingAction on: anInteger labelled: aString)\x0a \x09callback: aBlock;\x0a yourself)",
messageSends: ["add:", "callback:", "on:labelled:", "yourself"],
referencedClasses: ["HLBindingAction"]
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "addGroupKey:labelled:",
category: 'accessing',
fn: function (anInteger,aString){
var self=this;
function $HLBindingGroup(){return smalltalk.HLBindingGroup||(typeof HLBindingGroup=="undefined"?nil:HLBindingGroup)}
return smalltalk.withContext(function($ctx1) {
self._add_(_st($HLBindingGroup())._on_labelled_(anInteger,aString));
return self}, function($ctx1) {$ctx1.fill(self,"addGroupKey:labelled:",{anInteger:anInteger,aString:aString},smalltalk.HLBindingGroup)})},
args: ["anInteger", "aString"],
source: "addGroupKey: anInteger labelled: aString\x0a\x09self add: (HLBindingGroup on: anInteger labelled: aString)",
messageSends: ["add:", "on:labelled:"],
referencedClasses: ["HLBindingGroup"]
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "at:",
category: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._bindings())._detect_ifNone_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(_st(each)._label()).__eq(aString);
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}),(function(){
return smalltalk.withContext(function($ctx2) {
return nil;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"at:",{aString:aString},smalltalk.HLBindingGroup)})},
args: ["aString"],
source: "at: aString\x0a\x09^ self bindings \x0a \x09detect: [ :each | each label = aString ]\x0a \x09ifNone: [ nil ]",
messageSends: ["detect:ifNone:", "=", "label", "bindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "at:add:",
category: 'accessing',
fn: function (aString,aBinding){
var self=this;
var binding;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
binding=self._at_(aString);
$1=binding;
if(($receiver = $1) == nil || $receiver == undefined){
$2=self;
return $2;
} else {
$1;
};
_st(binding)._add_(aBinding);
return self}, function($ctx1) {$ctx1.fill(self,"at:add:",{aString:aString,aBinding:aBinding,binding:binding},smalltalk.HLBindingGroup)})},
args: ["aString", "aBinding"],
source: "at: aString add: aBinding\x0a\x09| binding |\x0a\x09\x0a\x09binding := self at: aString.\x0a\x09binding ifNil: [ ^ self ].\x0a\x09\x09\x0a\x09binding add: aBinding",
messageSends: ["at:", "ifNil:", "add:"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "atKey:",
category: 'accessing',
fn: function (anInteger){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._bindings())._detect_ifNone_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(_st(each)._key()).__eq(anInteger);
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}),(function(){
return smalltalk.withContext(function($ctx2) {
return nil;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return $1;
}, function($ctx1) {$ctx1.fill(self,"atKey:",{anInteger:anInteger},smalltalk.HLBindingGroup)})},
args: ["anInteger"],
source: "atKey: anInteger\x0a\x09^ self bindings \x0a \x09detect: [ :each | each key = anInteger ]\x0a \x09ifNone: [ nil ]",
messageSends: ["detect:ifNone:", "=", "key", "bindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "bindings",
category: 'accessing',
fn: function (){
var self=this;
function $OrderedCollection(){return smalltalk.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)}
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@bindings"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@bindings"]=_st($OrderedCollection())._new();
$1=self["@bindings"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"bindings",{},smalltalk.HLBindingGroup)})},
args: [],
source: "bindings\x0a\x09^ bindings ifNil: [ bindings := OrderedCollection new ]",
messageSends: ["ifNil:", "new"],
referencedClasses: ["OrderedCollection"]
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "displayLabel",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(smalltalk.HLBinding.fn.prototype._displayLabel.apply(_st(self), [])).__comma("...");
return $1;
}, function($ctx1) {$ctx1.fill(self,"displayLabel",{},smalltalk.HLBindingGroup)})},
args: [],
source: "displayLabel\x0a\x09^ super displayLabel, '...'",
messageSends: [",", "displayLabel"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "isActive",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._activeBindings())._notEmpty();
return $1;
}, function($ctx1) {$ctx1.fill(self,"isActive",{},smalltalk.HLBindingGroup)})},
args: [],
source: "isActive\x0a\x09^ self activeBindings notEmpty",
messageSends: ["notEmpty", "activeBindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "release",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._bindings())._do_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(each)._release();
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"release",{},smalltalk.HLBindingGroup)})},
args: [],
source: "release\x0a\x09self bindings do: [ :each | each release ]",
messageSends: ["do:", "release", "bindings"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addMethod(
smalltalk.method({
selector: "renderOn:html:",
category: 'rendering',
fn: function (aBindingHelper,html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self._isActive();
if(smalltalk.assert($1)){
_st(aBindingHelper)._renderBindingGroup_on_(self,html);
};
return self}, function($ctx1) {$ctx1.fill(self,"renderOn:html:",{aBindingHelper:aBindingHelper,html:html},smalltalk.HLBindingGroup)})},
args: ["aBindingHelper", "html"],
source: "renderOn: aBindingHelper html: html\x0a\x09self isActive ifTrue: [\x0a\x09\x09aBindingHelper renderBindingGroup: self on: html ]",
messageSends: ["ifTrue:", "renderBindingGroup:on:", "isActive"],
referencedClasses: []
}),
smalltalk.HLBindingGroup);
smalltalk.addClass('HLBindingInput', smalltalk.HLBinding, ['input', 'callback', 'status', 'wrapper', 'binder', 'ghostText', 'isFinal', 'message', 'messageTag', 'inputCompletion', 'defaultValue'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "applyOn:",
category: 'actions',
fn: function (aKeyBinder){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._isFinal_(true);
self._evaluate_(_st(_st(self._input())._asJQuery())._val());
return self}, function($ctx1) {$ctx1.fill(self,"applyOn:",{aKeyBinder:aKeyBinder},smalltalk.HLBindingInput)})},
args: ["aKeyBinder"],
source: "applyOn: aKeyBinder\x0a\x09self isFinal: true.\x0a\x09self evaluate: self input asJQuery val",
messageSends: ["isFinal:", "evaluate:", "val", "asJQuery", "input"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "atKey:",
category: 'accessing',
fn: function (aKey){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(aKey).__eq((13));
if(! smalltalk.assert($1)){
return nil;
};
return self}, function($ctx1) {$ctx1.fill(self,"atKey:",{aKey:aKey},smalltalk.HLBindingInput)})},
args: ["aKey"],
source: "atKey: aKey\x0a\x09aKey = 13 ifFalse: [ ^ nil ]",
messageSends: ["ifFalse:", "="],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "callback",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@callback"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@callback"]=(function(value){
return smalltalk.withContext(function($ctx2) {
}, function($ctx2) {$ctx2.fillBlock({value:value},$ctx1)})});
$1=self["@callback"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"callback",{},smalltalk.HLBindingInput)})},
args: [],
source: "callback\x0a\x09^ callback ifNil: [ callback := [ :value | ] ]",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "callback:",
category: 'accessing',
fn: function (aBlock){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@callback"]=aBlock;
return self}, function($ctx1) {$ctx1.fill(self,"callback:",{aBlock:aBlock},smalltalk.HLBindingInput)})},
args: ["aBlock"],
source: "callback: aBlock\x0a\x09callback := aBlock",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "clearStatus",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._status_("info");
self._message_("");
self._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"clearStatus",{},smalltalk.HLBindingInput)})},
args: [],
source: "clearStatus\x0a\x09self status: 'info'.\x0a\x09self message: ''.\x0a\x09self refresh",
messageSends: ["status:", "message:", "refresh"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "defaultValue",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@defaultValue"];
if(($receiver = $2) == nil || $receiver == undefined){
$1="";
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"defaultValue",{},smalltalk.HLBindingInput)})},
args: [],
source: "defaultValue\x0a\x09^ defaultValue ifNil: [ '' ]",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "defaultValue:",
category: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@defaultValue"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"defaultValue:",{aString:aString},smalltalk.HLBindingInput)})},
args: ["aString"],
source: "defaultValue: aString\x0a\x09defaultValue := aString",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "errorStatus",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._status_("error");
self._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"errorStatus",{},smalltalk.HLBindingInput)})},
args: [],
source: "errorStatus\x0a\x09self status: 'error'.\x0a\x09self refresh",
messageSends: ["status:", "refresh"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "evaluate:",
category: 'actions',
fn: function (aString){
var self=this;
function $Error(){return smalltalk.Error||(typeof Error=="undefined"?nil:Error)}
return smalltalk.withContext(function($ctx1) {
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self._callback())._value_(aString);
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}))._on_do_($Error(),(function(ex){
return smalltalk.withContext(function($ctx2) {
_st(_st(self._input())._asJQuery())._one_do_("keydown",(function(){
return smalltalk.withContext(function($ctx3) {
return self._clearStatus();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2)})}));
self._message_(_st(ex)._messageText());
self._errorStatus();
return self._isFinal_(false);
}, function($ctx2) {$ctx2.fillBlock({ex:ex},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"evaluate:",{aString:aString},smalltalk.HLBindingInput)})},
args: ["aString"],
source: "evaluate: aString\x0a\x09\x0a\x09[ self callback value: aString ]\x0a\x09on: Error\x0a\x09do: [:ex |\x0a\x09\x09self input asJQuery \x0a\x09\x09\x09one: 'keydown' \x0a\x09\x09\x09do: [ self clearStatus ].\x0a\x09\x09self message: ex messageText.\x0a\x09\x09self errorStatus.\x0a\x09\x09self isFinal: false ].",
messageSends: ["on:do:", "one:do:", "clearStatus", "asJQuery", "input", "message:", "messageText", "errorStatus", "isFinal:", "value:", "callback"],
referencedClasses: ["Error"]
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "ghostText",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@ghostText"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"ghostText",{},smalltalk.HLBindingInput)})},
args: [],
source: "ghostText\x0a\x09^ ghostText",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "ghostText:",
category: 'accessing',
fn: function (aText){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@ghostText"]=aText;
return self}, function($ctx1) {$ctx1.fill(self,"ghostText:",{aText:aText},smalltalk.HLBindingInput)})},
args: ["aText"],
source: "ghostText: aText\x0a\x09ghostText := aText",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "input",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@input"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"input",{},smalltalk.HLBindingInput)})},
args: [],
source: "input\x0a\x09^ input",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "inputCompletion",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@inputCompletion"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=[];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"inputCompletion",{},smalltalk.HLBindingInput)})},
args: [],
source: "inputCompletion\x0a\x09^ inputCompletion ifNil: [ #() ]",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "inputCompletion:",
category: 'accessing',
fn: function (aCollection){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@inputCompletion"]=aCollection;
return self}, function($ctx1) {$ctx1.fill(self,"inputCompletion:",{aCollection:aCollection},smalltalk.HLBindingInput)})},
args: ["aCollection"],
source: "inputCompletion: aCollection\x0a\x09inputCompletion := aCollection",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "isActive",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return true;
}, function($ctx1) {$ctx1.fill(self,"isActive",{},smalltalk.HLBindingInput)})},
args: [],
source: "isActive\x0a\x09^ true",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "isFinal",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@isFinal"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@isFinal"]=smalltalk.HLBinding.fn.prototype._isFinal.apply(_st(self), []);
$1=self["@isFinal"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"isFinal",{},smalltalk.HLBindingInput)})},
args: [],
source: "isFinal\x0a\x09^ isFinal ifNil: [ isFinal := super isFinal ]",
messageSends: ["ifNil:", "isFinal"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "isFinal:",
category: 'testing',
fn: function (aBoolean){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@isFinal"]=aBoolean;
return self}, function($ctx1) {$ctx1.fill(self,"isFinal:",{aBoolean:aBoolean},smalltalk.HLBindingInput)})},
args: ["aBoolean"],
source: "isFinal: aBoolean\x0a\x09isFinal := aBoolean",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "message",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@message"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@message"]="";
$1=self["@message"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"message",{},smalltalk.HLBindingInput)})},
args: [],
source: "message\x0a\x09^ message ifNil: [ message := '' ]",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "message:",
category: 'accessing',
fn: function (aString){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@message"]=aString;
return self}, function($ctx1) {$ctx1.fill(self,"message:",{aString:aString},smalltalk.HLBindingInput)})},
args: ["aString"],
source: "message: aString\x0a\x09message := aString",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "refresh",
category: 'rendering',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=self["@wrapper"];
if(($receiver = $1) == nil || $receiver == undefined){
$2=self;
return $2;
} else {
$1;
};
_st(self["@wrapper"])._class_(self._status());
_st(self["@messageTag"])._contents_(self._message());
return self}, function($ctx1) {$ctx1.fill(self,"refresh",{},smalltalk.HLBindingInput)})},
args: [],
source: "refresh\x0a\x09wrapper ifNil: [ ^ self ].\x0a \x0a\x09wrapper class: self status.\x0a\x09messageTag contents: self message",
messageSends: ["ifNil:", "class:", "status", "contents:", "message"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "release",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@status"]=nil;
self["@wrapper"]=nil;
self["@binder"]=nil;
return self}, function($ctx1) {$ctx1.fill(self,"release",{},smalltalk.HLBindingInput)})},
args: [],
source: "release\x0a\x09status := nil.\x0a\x09wrapper := nil.\x0a\x09binder := nil",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "renderOn:html:",
category: 'rendering',
fn: function (aBinder,html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2,$4,$5,$6,$7,$3;
self["@binder"]=aBinder;
$1=self["@wrapper"];
if(($receiver = $1) == nil || $receiver == undefined){
self["@wrapper"]=_st(html)._span();
self["@wrapper"];
} else {
$1;
};
$2=self["@wrapper"];
_st($2)._class_(self._status());
$3=_st($2)._with_((function(){
return smalltalk.withContext(function($ctx2) {
$4=_st(html)._input();
_st($4)._placeholder_(self._ghostText());
_st($4)._value_(self._defaultValue());
$5=_st($4)._yourself();
self["@input"]=$5;
self["@input"];
_st(_st(self["@input"])._asJQuery())._typeahead_(smalltalk.HashedCollection._fromPairs_(["source".__minus_gt(self._inputCompletion())]));
$6=_st(html)._span();
_st($6)._class_("help-inline");
_st($6)._with_(self._message());
$7=_st($6)._yourself();
self["@messageTag"]=$7;
return self["@messageTag"];
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(self["@input"])._asJQuery())._focus();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}))._valueWithTimeout_((10));
return self}, function($ctx1) {$ctx1.fill(self,"renderOn:html:",{aBinder:aBinder,html:html},smalltalk.HLBindingInput)})},
args: ["aBinder", "html"],
source: "renderOn: aBinder html: html\x0a\x09binder := aBinder.\x0a\x09wrapper ifNil: [ wrapper := html span ].\x0a\x0a\x09wrapper \x0a\x09\x09class: self status;\x0a\x09\x09with: [\x0a\x09\x09\x09input := html input\x0a\x09\x09\x09\x09placeholder: self ghostText;\x0a\x09\x09\x09\x09value: self defaultValue;\x0a\x09\x09\x09\x09yourself.\x0a\x09\x09\x09input asJQuery \x0a\x09\x09\x09\x09typeahead: #{ 'source' -> self inputCompletion }.\x0a\x09\x09\x09messageTag := (html span\x0a\x09\x09\x09\x09class: 'help-inline';\x0a\x09\x09\x09\x09with: self message;\x0a\x09\x09\x09\x09yourself) ].\x0a\x09\x0a\x09\x22Evaluate with a timeout to ensure focus.\x0a\x09Commands can be executed from a menu, clicking on the menu to\x0a\x09evaluate the command would give it the focus otherwise\x22\x0a\x09\x0a\x09[ input asJQuery focus ] valueWithTimeout: 10",
messageSends: ["ifNil:", "span", "class:", "status", "with:", "placeholder:", "ghostText", "input", "value:", "defaultValue", "yourself", "typeahead:", "->", "inputCompletion", "asJQuery", "message", "valueWithTimeout:", "focus"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "status",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@status"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@status"]="info";
$1=self["@status"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"status",{},smalltalk.HLBindingInput)})},
args: [],
source: "status\x0a\x09^ status ifNil: [ status := 'info' ]",
messageSends: ["ifNil:"],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addMethod(
smalltalk.method({
selector: "status:",
category: 'accessing',
fn: function (aStatus){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@status"]=aStatus;
return self}, function($ctx1) {$ctx1.fill(self,"status:",{aStatus:aStatus},smalltalk.HLBindingInput)})},
args: ["aStatus"],
source: "status: aStatus\x0a\x09status := aStatus",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLBindingInput);
smalltalk.addClass('HLKeyBinder', smalltalk.Object, ['modifierKey', 'helper', 'bindings', 'selectedBinding'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "activate",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._helper())._show();
return self}, function($ctx1) {$ctx1.fill(self,"activate",{},smalltalk.HLKeyBinder)})},
args: [],
source: "activate\x0a\x09self helper show",
messageSends: ["show", "helper"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "activationKey",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return (32);
}, function($ctx1) {$ctx1.fill(self,"activationKey",{},smalltalk.HLKeyBinder)})},
args: [],
source: "activationKey\x0a\x09\x22SPACE\x22\x0a\x09^ 32",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "activationKeyLabel",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "ctrl + space";
}, function($ctx1) {$ctx1.fill(self,"activationKeyLabel",{},smalltalk.HLKeyBinder)})},
args: [],
source: "activationKeyLabel\x0a\x09^ 'ctrl + space'",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "applyBinding:",
category: 'actions',
fn: function (aBinding){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2,$3;
$1=_st(aBinding)._isActive();
if(! smalltalk.assert($1)){
$2=self;
return $2;
};
self._selectBinding_(aBinding);
_st(aBinding)._applyOn_(self);
$3=_st(aBinding)._isFinal();
if(smalltalk.assert($3)){
self._deactivate();
};
return self}, function($ctx1) {$ctx1.fill(self,"applyBinding:",{aBinding:aBinding},smalltalk.HLKeyBinder)})},
args: ["aBinding"],
source: "applyBinding: aBinding\x0a\x09aBinding isActive ifFalse: [ ^ self ].\x0a\x09\x0a\x09self selectBinding: aBinding.\x0a aBinding applyOn: self.\x0a\x09\x0a\x09aBinding isFinal ifTrue: [ self deactivate ]",
messageSends: ["ifFalse:", "isActive", "selectBinding:", "applyOn:", "ifTrue:", "deactivate", "isFinal"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "bindings",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@bindings"];
if(($receiver = $2) == nil || $receiver == undefined){
self["@bindings"]=self._defaultBindings();
$1=self["@bindings"];
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"bindings",{},smalltalk.HLKeyBinder)})},
args: [],
source: "bindings\x0a\x09^ bindings ifNil: [ bindings := self defaultBindings ]",
messageSends: ["ifNil:", "defaultBindings"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "deactivate",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@selectedBinding"];
if(($receiver = $1) == nil || $receiver == undefined){
$1;
} else {
_st(self["@selectedBinding"])._release();
};
self["@selectedBinding"]=nil;
_st(self._helper())._hide();
return self}, function($ctx1) {$ctx1.fill(self,"deactivate",{},smalltalk.HLKeyBinder)})},
args: [],
source: "deactivate\x0a\x09selectedBinding ifNotNil: [ selectedBinding release ].\x0a selectedBinding := nil.\x0a\x09self helper hide",
messageSends: ["ifNotNil:", "release", "hide", "helper"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "defaultBindings",
category: 'defaults',
fn: function (){
var self=this;
var group;
function $HLBindingGroup(){return smalltalk.HLBindingGroup||(typeof HLBindingGroup=="undefined"?nil:HLBindingGroup)}
function $HLCloseTabCommand(){return smalltalk.HLCloseTabCommand||(typeof HLCloseTabCommand=="undefined"?nil:HLCloseTabCommand)}
function $HLOpenCommand(){return smalltalk.HLOpenCommand||(typeof HLOpenCommand=="undefined"?nil:HLOpenCommand)}
return smalltalk.withContext(function($ctx1) {
var $1,$2,$3;
$1=_st($HLBindingGroup())._new();
_st($1)._addGroupKey_labelled_((86),"View");
_st($1)._add_(_st(_st($HLCloseTabCommand())._new())._asBinding());
$2=_st($1)._yourself();
group=$2;
_st($HLOpenCommand())._registerConcreteClassesOn_(group);
$3=group;
return $3;
}, function($ctx1) {$ctx1.fill(self,"defaultBindings",{group:group},smalltalk.HLKeyBinder)})},
args: [],
source: "defaultBindings\x0a\x09| group |\x0a\x09\x0a\x09group := HLBindingGroup new\x0a\x09\x09addGroupKey: 86 labelled: 'View';\x0a\x09\x09add: HLCloseTabCommand new asBinding;\x0a\x09\x09yourself.\x0a\x09\x09\x0a\x09HLOpenCommand registerConcreteClassesOn: group.\x0a\x09\x09\x09\x09\x0a\x09^ group",
messageSends: ["addGroupKey:labelled:", "new", "add:", "asBinding", "yourself", "registerConcreteClassesOn:"],
referencedClasses: ["HLBindingGroup", "HLCloseTabCommand", "HLOpenCommand"]
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "escapeKey",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return (27);
}, function($ctx1) {$ctx1.fill(self,"escapeKey",{},smalltalk.HLKeyBinder)})},
args: [],
source: "escapeKey\x0a\x09\x22ESC\x22\x0a\x09^ 27",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "flushBindings",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@bindings"]=nil;
return self}, function($ctx1) {$ctx1.fill(self,"flushBindings",{},smalltalk.HLKeyBinder)})},
args: [],
source: "flushBindings\x0a\x09bindings := nil",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "handleActiveKeyDown:",
category: 'events',
fn: function (event){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(_st(_st(event)._which()).__eq(self._escapeKey()))._or_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(_st(event)._which()).__eq((71)))._and_((function(){
return smalltalk.withContext(function($ctx3) {
return _st(event)._ctrlKey();
}, function($ctx3) {$ctx3.fillBlock({},$ctx2)})}));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
if(smalltalk.assert($1)){
self._deactivate();
_st(event)._preventDefault();
return false;
};
$2=self._handleBindingFor_(event);
return $2;
}, function($ctx1) {$ctx1.fill(self,"handleActiveKeyDown:",{event:event},smalltalk.HLKeyBinder)})},
args: ["event"],
source: "handleActiveKeyDown: event\x0a\x0a\x09\x22ESC or ctrl+g deactivate the keyBinder\x22\x0a\x09(event which = self escapeKey or: [\x0a\x09\x09event which = 71 and: [ event ctrlKey ] ])\x0a \x09ifTrue: [ \x0a \x09self deactivate.\x0a\x09\x09\x09\x09event preventDefault.\x0a\x09\x09\x09\x09^ false ].\x0a \x0a \x22Handle the keybinding\x22\x0a ^ self handleBindingFor: event",
messageSends: ["ifTrue:", "deactivate", "preventDefault", "or:", "and:", "ctrlKey", "=", "which", "escapeKey", "handleBindingFor:"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "handleBindingFor:",
category: 'events',
fn: function (anEvent){
var self=this;
var binding;
return smalltalk.withContext(function($ctx1) {
var $1;
binding=_st(self._selectedBinding())._atKey_(_st(anEvent)._which());
$1=binding;
if(($receiver = $1) == nil || $receiver == undefined){
$1;
} else {
self._applyBinding_(binding);
_st(anEvent)._preventDefault();
return false;
};
return self}, function($ctx1) {$ctx1.fill(self,"handleBindingFor:",{anEvent:anEvent,binding:binding},smalltalk.HLKeyBinder)})},
args: ["anEvent"],
source: "handleBindingFor: anEvent\x0a\x09| binding |\x0a binding := self selectedBinding atKey: anEvent which.\x0a \x0a binding ifNotNil: [ \x0a \x09self applyBinding: binding.\x0a\x09\x09anEvent preventDefault.\x0a\x09\x09^ false ]",
messageSends: ["atKey:", "which", "selectedBinding", "ifNotNil:", "applyBinding:", "preventDefault"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "handleInactiveKeyDown:",
category: 'events',
fn: function (event){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(_st(event)._which()).__eq(self._activationKey());
if(smalltalk.assert($1)){
$2=_st(event)._ctrlKey();
if(smalltalk.assert($2)){
self._activate();
_st(event)._preventDefault();
return false;
};
};
return self}, function($ctx1) {$ctx1.fill(self,"handleInactiveKeyDown:",{event:event},smalltalk.HLKeyBinder)})},
args: ["event"],
source: "handleInactiveKeyDown: event\x0a\x09event which = self activationKey ifTrue: [\x0a \x09event ctrlKey ifTrue: [\x0a\x09\x09\x09self activate. \x0a event preventDefault. \x0a ^ false ] ]",
messageSends: ["ifTrue:", "activate", "preventDefault", "ctrlKey", "=", "activationKey", "which"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "handleKeyDown:",
category: 'events',
fn: function (event){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self._isActive();
if(smalltalk.assert($2)){
$1=self._handleActiveKeyDown_(event);
} else {
$1=self._handleInactiveKeyDown_(event);
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"handleKeyDown:",{event:event},smalltalk.HLKeyBinder)})},
args: ["event"],
source: "handleKeyDown: event\x0a\x09^ self isActive\x0a \x09ifTrue: [ self handleActiveKeyDown: event ]\x0a \x09ifFalse: [ self handleInactiveKeyDown: event ]",
messageSends: ["ifTrue:ifFalse:", "handleActiveKeyDown:", "handleInactiveKeyDown:", "isActive"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "helper",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@helper"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"helper",{},smalltalk.HLKeyBinder)})},
args: [],
source: "helper\x0a\x09^ helper",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "initialize",
category: 'initialization',
fn: function (){
var self=this;
function $HLKeyBinderHelper(){return smalltalk.HLKeyBinderHelper||(typeof HLKeyBinderHelper=="undefined"?nil:HLKeyBinderHelper)}
return smalltalk.withContext(function($ctx1) {
var $1,$2;
smalltalk.Object.fn.prototype._initialize.apply(_st(self), []);
self["@helper"]=_st($HLKeyBinderHelper())._on_(self);
$1=self["@helper"];
_st($1)._renderStart();
$2=_st($1)._renderCog();
return self}, function($ctx1) {$ctx1.fill(self,"initialize",{},smalltalk.HLKeyBinder)})},
args: [],
source: "initialize\x0a\x09super initialize.\x0a\x09helper := HLKeyBinderHelper on: self.\x0a\x09helper \x09\x0a\x09\x09renderStart;\x0a\x09\x09renderCog",
messageSends: ["initialize", "on:", "renderStart", "renderCog"],
referencedClasses: ["HLKeyBinderHelper"]
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "isActive",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(".".__comma(_st(self._helper())._cssClass()))._asJQuery())._is_(":visible");
return $1;
}, function($ctx1) {$ctx1.fill(self,"isActive",{},smalltalk.HLKeyBinder)})},
args: [],
source: "isActive\x0a\x09^ ('.', self helper cssClass) asJQuery is: ':visible'",
messageSends: ["is:", "asJQuery", ",", "cssClass", "helper"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "selectBinding:",
category: 'actions',
fn: function (aBinding){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(aBinding).__eq(self["@selectedBinding"]);
if(smalltalk.assert($1)){
$2=self;
return $2;
};
self["@selectedBinding"]=aBinding;
_st(self._helper())._refresh();
return self}, function($ctx1) {$ctx1.fill(self,"selectBinding:",{aBinding:aBinding},smalltalk.HLKeyBinder)})},
args: ["aBinding"],
source: "selectBinding: aBinding\x0a\x09aBinding = selectedBinding ifTrue: [ ^ self ].\x0a\x09\x0a\x09selectedBinding := aBinding.\x0a\x09self helper refresh",
messageSends: ["ifTrue:", "=", "refresh", "helper"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "selectedBinding",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$1;
$2=self["@selectedBinding"];
if(($receiver = $2) == nil || $receiver == undefined){
$1=self._bindings();
} else {
$1=$2;
};
return $1;
}, function($ctx1) {$ctx1.fill(self,"selectedBinding",{},smalltalk.HLKeyBinder)})},
args: [],
source: "selectedBinding\x0a\x09^ selectedBinding ifNil: [ self bindings ]",
messageSends: ["ifNil:", "bindings"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "setupEvents",
category: 'events',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(window)._jQuery_("body"))._keydown_((function(event){
return smalltalk.withContext(function($ctx2) {
return self._handleKeyDown_(event);
}, function($ctx2) {$ctx2.fillBlock({event:event},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"setupEvents",{},smalltalk.HLKeyBinder)})},
args: [],
source: "setupEvents\x0a\x09(window jQuery: 'body') keydown: [ :event | self handleKeyDown: event ]",
messageSends: ["keydown:", "handleKeyDown:", "jQuery:"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addMethod(
smalltalk.method({
selector: "systemIsMac",
category: 'testing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(_st(navigator)._platform())._match_("Mac");
return $1;
}, function($ctx1) {$ctx1.fill(self,"systemIsMac",{},smalltalk.HLKeyBinder)})},
args: [],
source: "systemIsMac\x0a\x09^ navigator platform match: 'Mac'",
messageSends: ["match:", "platform"],
referencedClasses: []
}),
smalltalk.HLKeyBinder);
smalltalk.addClass('HLKeyBinderHelper', smalltalk.HLWidget, ['keyBinder'], 'Helios-KeyBindings');
smalltalk.addMethod(
smalltalk.method({
selector: "cssClass",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return "key_helper";
}, function($ctx1) {$ctx1.fill(self,"cssClass",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "cssClass\x0a\x09^ 'key_helper'",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "hide",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(".".__comma(self._cssClass()))._asJQuery())._remove();
self._showCog();
return self}, function($ctx1) {$ctx1.fill(self,"hide",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "hide\x0a\x09('.', self cssClass) asJQuery remove.\x0a\x09self showCog",
messageSends: ["remove", "asJQuery", ",", "cssClass", "showCog"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "hideCog",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st("#cog-helper"._asJQuery())._hide();
return self}, function($ctx1) {$ctx1.fill(self,"hideCog",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "hideCog\x0a\x09'#cog-helper' asJQuery hide",
messageSends: ["hide", "asJQuery"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "keyBinder",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=self["@keyBinder"];
return $1;
}, function($ctx1) {$ctx1.fill(self,"keyBinder",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "keyBinder\x0a\x09^ keyBinder",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "keyBinder:",
category: 'accessing',
fn: function (aKeyBinder){
var self=this;
return smalltalk.withContext(function($ctx1) {
self["@keyBinder"]=aKeyBinder;
return self}, function($ctx1) {$ctx1.fill(self,"keyBinder:",{aKeyBinder:aKeyBinder},smalltalk.HLKeyBinderHelper)})},
args: ["aKeyBinder"],
source: "keyBinder: aKeyBinder\x0a\x09keyBinder := aKeyBinder",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "registerBindings",
category: 'keyBindings',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
return self}, function($ctx1) {$ctx1.fill(self,"registerBindings",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "registerBindings\x0a\x09\x22Do nothing\x22",
messageSends: [],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderBindingGroup:on:",
category: 'rendering',
fn: function (aBindingGroup,html){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(_st(_st(aBindingGroup)._activeBindings())._sorted_((function(a,b){
return smalltalk.withContext(function($ctx2) {
return _st(_st(a)._key()).__lt(_st(b)._key());
}, function($ctx2) {$ctx2.fillBlock({a:a,b:b},$ctx1)})})))._do_((function(each){
return smalltalk.withContext(function($ctx2) {
return _st(each)._renderActionFor_html_(self._keyBinder(),html);
}, function($ctx2) {$ctx2.fillBlock({each:each},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"renderBindingGroup:on:",{aBindingGroup:aBindingGroup,html:html},smalltalk.HLKeyBinderHelper)})},
args: ["aBindingGroup", "html"],
source: "renderBindingGroup: aBindingGroup on: html\x0a\x09(aBindingGroup activeBindings \x0a \x09sorted: [ :a :b | a key < b key ])\x0a do: [ :each | each renderActionFor: self keyBinder html: html ]",
messageSends: ["do:", "renderActionFor:html:", "keyBinder", "sorted:", "<", "key", "activeBindings"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderBindingOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st(self._selectedBinding())._renderOn_html_(self,html);
return self}, function($ctx1) {$ctx1.fill(self,"renderBindingOn:",{html:html},smalltalk.HLKeyBinderHelper)})},
args: ["html"],
source: "renderBindingOn: html\x0a\x09self selectedBinding renderOn: self html: html",
messageSends: ["renderOn:html:", "selectedBinding"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderCloseOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
$1=_st(html)._a();
_st($1)._class_("close");
_st($1)._with_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(html)._tag_("i"))._class_("icon-remove");
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
$2=_st($1)._onClick_((function(){
return smalltalk.withContext(function($ctx2) {
return _st(self._keyBinder())._deactivate();
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"renderCloseOn:",{html:html},smalltalk.HLKeyBinderHelper)})},
args: ["html"],
source: "renderCloseOn: html\x0a\x09html a\x0a\x09\x09class: 'close';\x0a\x09\x09with: [ (html tag: 'i') class: 'icon-remove' ];\x0a\x09\x09onClick: [ self keyBinder deactivate ]",
messageSends: ["class:", "a", "with:", "tag:", "onClick:", "deactivate", "keyBinder"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderCog",
category: 'rendering',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$3,$4,$2;
_st((function(html){
return smalltalk.withContext(function($ctx2) {
$1=_st(html)._div();
_st($1)._id_("cog-helper");
$2=_st($1)._with_((function(){
return smalltalk.withContext(function($ctx3) {
$3=_st(html)._a();
_st($3)._with_((function(){
return smalltalk.withContext(function($ctx4) {
return _st(_st(html)._tag_("i"))._class_("icon-cog");
}, function($ctx4) {$ctx4.fillBlock({},$ctx3)})}));
$4=_st($3)._onClick_((function(){
return smalltalk.withContext(function($ctx4) {
return _st(self._keyBinder())._activate();
}, function($ctx4) {$ctx4.fillBlock({},$ctx3)})}));
return $4;
}, function($ctx3) {$ctx3.fillBlock({},$ctx2)})}));
return $2;
}, function($ctx2) {$ctx2.fillBlock({html:html},$ctx1)})}))._appendToJQuery_("body"._asJQuery());
return self}, function($ctx1) {$ctx1.fill(self,"renderCog",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "renderCog\x0a\x09[ :html |\x0a\x09\x09html \x0a\x09\x09\x09div id: 'cog-helper'; \x0a\x09\x09\x09with: [\x0a\x09\x09\x09\x09html a \x0a\x09\x09\x09\x09\x09with: [ (html tag: 'i') class: 'icon-cog' ];\x0a\x09\x09\x09\x09\x09onClick: [ self keyBinder activate ] ] ]\x0a\x09\x09appendToJQuery: 'body' asJQuery",
messageSends: ["appendToJQuery:", "asJQuery", "id:", "div", "with:", "class:", "tag:", "a", "onClick:", "activate", "keyBinder"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderContentOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$3,$4,$2;
$1=_st(html)._div();
_st($1)._class_(self._cssClass());
$2=_st($1)._with_((function(){
return smalltalk.withContext(function($ctx2) {
$3=self;
_st($3)._renderSelectionOn_(html);
_st($3)._renderBindingOn_(html);
$4=_st($3)._renderCloseOn_(html);
return $4;
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}));
return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},smalltalk.HLKeyBinderHelper)})},
args: ["html"],
source: "renderContentOn: html\x0a\x09html div class: self cssClass; with: [\x0a \x09self \x0a \x09renderSelectionOn:html;\x0a \x09renderBindingOn: html;\x0a\x09\x09\x09renderCloseOn: html ]",
messageSends: ["class:", "cssClass", "div", "with:", "renderSelectionOn:", "renderBindingOn:", "renderCloseOn:"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderSelectionOn:",
category: 'rendering',
fn: function (html){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$3,$5,$4,$2;
$1=_st(html)._span();
_st($1)._class_("selected");
$3=$1;
$5=_st(self._selectedBinding())._label();
if(($receiver = $5) == nil || $receiver == undefined){
$4="Action";
} else {
$4=$5;
};
$2=_st($3)._with_($4);
return self}, function($ctx1) {$ctx1.fill(self,"renderSelectionOn:",{html:html},smalltalk.HLKeyBinderHelper)})},
args: ["html"],
source: "renderSelectionOn: html\x0a\x09\x09html span \x0a \x09class: 'selected'; \x0a with: (self selectedBinding label ifNil: [ 'Action' ])",
messageSends: ["class:", "span", "with:", "ifNil:", "label", "selectedBinding"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "renderStart",
category: 'rendering',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1,$2;
_st(_st(window)._jQuery_("#helper"))._remove();
_st((function(html){
return smalltalk.withContext(function($ctx2) {
$1=_st(html)._div();
_st($1)._id_("helper");
$2=_st($1)._with_(_st("Press ".__comma(_st(self._keyBinder())._activationKeyLabel())).__comma(" to start"));
return $2;
}, function($ctx2) {$ctx2.fillBlock({html:html},$ctx1)})}))._appendToJQuery_("body"._asJQuery());
_st((function(){
return smalltalk.withContext(function($ctx2) {
return _st(_st(window)._jQuery_("#helper"))._fadeOut_((1000));
}, function($ctx2) {$ctx2.fillBlock({},$ctx1)})}))._valueWithTimeout_((2000));
return self}, function($ctx1) {$ctx1.fill(self,"renderStart",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "renderStart\x0a\x09(window jQuery: '#helper') remove.\x0a\x0a\x09[ :html |\x0a\x09\x09html div \x0a\x09\x09\x09id: 'helper';\x0a\x09\x09\x09with: 'Press ', self keyBinder activationKeyLabel, ' to start' ] appendToJQuery: 'body' asJQuery.\x0a\x09\x0a\x09[ (window jQuery: '#helper') fadeOut: 1000 ] \x0a\x09\x09valueWithTimeout: 2000",
messageSends: ["remove", "jQuery:", "appendToJQuery:", "asJQuery", "id:", "div", "with:", ",", "activationKeyLabel", "keyBinder", "valueWithTimeout:", "fadeOut:"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "selectedBinding",
category: 'accessing',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $1;
$1=_st(self._keyBinder())._selectedBinding();
return $1;
}, function($ctx1) {$ctx1.fill(self,"selectedBinding",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "selectedBinding\x0a\x09^ self keyBinder selectedBinding",
messageSends: ["selectedBinding", "keyBinder"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "show",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
self._hideCog();
self._appendToJQuery_("body"._asJQuery());
return self}, function($ctx1) {$ctx1.fill(self,"show",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "show\x0a\x09self hideCog.\x0a\x09self appendToJQuery: 'body' asJQuery",
messageSends: ["hideCog", "appendToJQuery:", "asJQuery"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "showCog",
category: 'actions',
fn: function (){
var self=this;
return smalltalk.withContext(function($ctx1) {
_st("#cog-helper"._asJQuery())._show();
return self}, function($ctx1) {$ctx1.fill(self,"showCog",{},smalltalk.HLKeyBinderHelper)})},
args: [],
source: "showCog\x0a\x09'#cog-helper' asJQuery show",
messageSends: ["show", "asJQuery"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper);
smalltalk.addMethod(
smalltalk.method({
selector: "on:",
category: 'instance creation',
fn: function (aKeyBinder){
var self=this;
return smalltalk.withContext(function($ctx1) {
var $2,$3,$1;
$2=self._new();
_st($2)._keyBinder_(aKeyBinder);
$3=_st($2)._yourself();
$1=$3;
return $1;
}, function($ctx1) {$ctx1.fill(self,"on:",{aKeyBinder:aKeyBinder},smalltalk.HLKeyBinderHelper.klass)})},
args: ["aKeyBinder"],
source: "on: aKeyBinder\x0a\x09^ self new\x0a \x09keyBinder: aKeyBinder;\x0a yourself",
messageSends: ["keyBinder:", "new", "yourself"],
referencedClasses: []
}),
smalltalk.HLKeyBinderHelper.klass);
|
'use strict';
require('./components/grid');
require('./components/tile');
require('./components/tiled_map');
function loadMap(context, callback) {
return function workerListener(e) {
var result = e.data;
if (result.error)
return callback(new Error('Error on loading map: ' + result.error));
callback(null, result.json);
};
}
function CraftyTiledMap(jsonPath, options) {
if (!(this instanceof CraftyTiledMap))
return new CraftyTiledMap(jsonPath, options);
this.jsonPath = jsonPath;
this.workerPath =
('/bower_components/crafty-tiled-map/download_json_worker.js' ||
options.workerPath);
this.worker = new Worker(this.workerPath);
}
CraftyTiledMap.prototype.downloaded = function craftyTiledMapDownloaded(fn) {
this.worker.addEventListener('message', loadMap(this, fn), false);
this.worker.postMessage({command: 'download', data: this.jsonPath});
};
module.exports = CraftyTiledMap;
Crafty.TiledMap = CraftyTiledMap;
|
import Section from './section';
describe('Section', () => {
test('props', () => {
const section = new Section('hoge', {
data: {
title: 'foo',
description: 'bar',
style: {
height: '10px',
},
},
});
expect(section.name).toEqual('hoge');
expect(section.title).toEqual('foo');
expect(section.description).toEqual('bar');
expect(section.style).toMatchObject({
height: '10px',
});
});
test('.export', () => {
const section = new Section('hoge', {data: {}});
const exported = section.export();
expect(exported).toHaveProperty('name');
expect(exported).toHaveProperty('title');
expect(exported).toHaveProperty('description');
expect(exported).toHaveProperty('style');
expect(exported).toHaveProperty('html');
expect(exported).toHaveProperty('css');
expect(exported).toHaveProperty('items');
});
});
|
'use strict';
var angular = require('angular').mock;
var moduleName = require('./view2.js');
describe('View2 controller', function() {
beforeEach(function(){
angular.module(moduleName);
angular.inject(function($controller, $rootScope){
this.$controller = $controller;
this.$rootScope = $rootScope;
});
var scope = this.$rootScope.$new();
this.ctrl = this.$controller('View2Ctrl', {
$scope: scope
});
});
it('has the right title', function() {
expect(this.ctrl.title).toEqual('foo');
});
});
|
describe("Utilities", function() {
beforeEach(function() {
var div = $("<div id='cmd-resume'></div>");
$("body").append(div);
jasmine.Ajax.install();
});
afterEach(function() {
$("#cmd-resume").remove();
jasmine.Ajax.uninstall();
});
describe("Invalid commands", function() {
beforeEach(function() {
$("#cmd-resume").CMDResume("details.json");
});
it("Empty message", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("");
var output = getSingleOutput();
expect(output).toEqual("No command entered.");
});
it("Spaces", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand(" ");
var output = getSingleOutput();
expect(output).toEqual("No command entered.");
});
it("Tab", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand(" ");
var output = getSingleOutput();
expect(output).toEqual("No command entered.");
});
});
describe("clear command", function() {
beforeEach(function() {
$("#cmd-resume").CMDResume("man.json");
});
it("Empty results", function() {
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("clear");
expect(getClearOutput()).toEqual(0);
});
});
describe("pdf command", function() {
beforeEach(function() {
$("#cmd-resume").CMDResume("man.json");
});
it("Empty results", function() {
jasmine.Ajax.requests.mostRecent().respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("pdf");
var output = pdf.fullCommandOutput();
expect(output.command).toEqual("Résumé PDF");
expect(output.values[0]).toEqual("https://en.wikipedia.org/wiki/R%C3%A9sum%C3%A9");
});
});
describe("man command", function() {
beforeEach(function() {
$("#cmd-resume").CMDResume("man.json");
});
it("Valid command", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("man man");
var output = manCommandOutput();
expect(output.command).toEqual("man");
expect(output.message).toEqual(" - describes what each command does");
});
it("No command", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("man");
var output = manCommandOutput();
expect(output.command).toEqual("man:");
expect(output.message).toEqual(" No command entered.");
});
it("Invalid command", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("details"))
});
enterCommand("man notacommand");
var output = manFailedCommandOutput();
expect(output.man).toEqual("man: ");
expect(output.command).toEqual("notacommand");
expect(output.message).toEqual(" is an unknown command.");
});
it("Data is empty", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
var data = loadJSON("details");
data.basics.name = "";
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(data)
});
enterCommand("man name");
var output = manFailedCommandOutput();
expect(output.man).toEqual("man: ");
expect(output.command).toEqual("name");
expect(output.message).toEqual(" is an unknown command.");
});
it("Data is not provided", function() {
var mostRecentRequest = jasmine.Ajax.requests.mostRecent();
mostRecentRequest.respondWith({
status: 200,
responseText: JSON.stringify(loadJSON("empty"))
});
enterCommand("man name");
var output = manFailedCommandOutput();
expect(output.man).toEqual("man: ");
expect(output.command).toEqual("name");
expect(output.message).toEqual(" is an unknown command.");
});
});
});
|
module.exports = {
port: process.env.PORT || 3000,
files: ['./**/*.{html,htm,css,js}'],
server:{
baseDir: "./"
}
};
|
import React from 'react';
import { QueryRenderer, graphql } from 'react-relay';
import relay from '../../relay.js';
// https://github.com/facebook/relay/issues/1851
export default function ShortCountSpeedTableDescription(props) {
const q = graphql`
query ShortCountSpeedTableDescriptionQuery {
__type(name: "ShortCountSpeed") {
name
description
fields {
name
description
}
}
}
`;
return (
<div>
<h1>Short Count Speeds Table Description</h1>
<QueryRenderer
environment={relay}
query={q}
render={({ error, props }) => {
if (error) {
return <div>{error.message}</div>;
} else if (props) {
return <pre>{JSON.stringify(props, null, 4)}</pre>;
}
return <div>Loading</div>;
}}
/>
</div>
);
}
|
var config = require(__dirname + '/lib/config');
var logger = require(__dirname + '/lib/logger');
var fs = require('fs');
if (config.https) {
var https = require('https');
var keyFileName = __dirname + '/ssl/server.key';
var certFileName = __dirname + '/ssl/server.crt';
if (!fs.existsSync(keyFileName)) {
throw new Error('Key file does not exist' + keyFileName);
}
if (!fs.existsSync(certFileName)) {
throw new Error('Key file does not exist' + certFileName);
}
var options = {
key: fs.readFileSync(keyFileName),
cert: fs.readFileSync(certFileName)
};
var app = https.createServer(options);
} else {
var app = require('http').createServer(handler);
}
var io = require('socket.io')(app);
var db = require(__dirname + '/lib/db');
var log = require(__dirname + '/lib/log');
app.listen(config.port);
function handler (req, res) {
res.writeHead(404);
}
var dbNamespaceMeta = io.of('/db/meta');
dbNamespaceMeta.on('connection', function (socket) {
logger.verbose('New db meta connection', socket.id);
db.getTables(true, socket);
socket.on('table_details', function (data) {
if (!data.name) {
logger.warn("Missing parameter name for table_details");
return;
}
db.getTableDetails(true, data.name, socket);
});
socket.on('table_rows', function (data) {
if (!data.name || !data.page) {
logger.warn("Missing parameter name or page for table_rows", data.name, data.page);
return;
}
db.getRows(true, data.name, data.page, socket);
});
});
var dbNamespaceMeta = io.of('/db/game');
dbNamespaceMeta.on('connection', function (socket) {
logger.verbose('New db game connection', socket.id);
db.getTables(false, socket);
socket.on('table_details', function (data) {
if (!data.name) {
logger.warn("Missing parameter name for table_details");
return;
}
db.getTableDetails(false, data.name, socket);
});
socket.on('table_rows', function (data) {
if (!data.name || !data.page) {
logger.warn("Missing parameter name or page for table_rows", data.name, data.page);
return;
}
db.getRows(false, data.name, data.page, socket);
});
});
var logNamespaceMeta = io.of('/log/meta');
logNamespaceMeta.on('connection', function (socket) {
logger.verbose('New log meta connection', socket.id);
log.getContents(true, socket);
});
fs.watch(config.log.pathMeta, function(event, filename) {
if (event == 'rename') {
logger.error("Log file renamed to", filename);
return;
}
log.getChanges(true, logNamespaceMeta);
});
var logNamespaceGame = io.of('/log/game');
logNamespaceGame.on('connection', function (socket) {
logger.verbose('New log game connection', socket.id);
log.getContents(false, socket);
});
fs.watch(config.log.pathGame, function(event, filename) {
if (event == 'rename') {
logger.error("Log file renamed to", filename);
return;
}
log.getChanges(false, logNamespaceGame);
});
logger.info('Listening on port', config.port, (config.https) ? 'SSL' : '');
|
(function($){
$.fn.auto_assemble = function(listing, error_list, permalink) {
var assembler = new Assembler();
var change_handler = function() {
var errors = assembler.assemble($(this).val());
if (errors) {
$(error_list).empty();
for (var i = 0; i < errors.length; ++i) {
$(error_list).append('<li>' + errors[i] + '</li>');
}
}
if (listing) {
$(listing).set_listing(assembler.get_listing());
}
if (permalink) {
var code = encodeURIComponent($(this).val());
$(permalink).attr('href', '?code=' + code);
}
};
$(this).change(change_handler);
var timer = null;
$(this).keyup(function() {
var me = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function() {
change_handler.apply(me, args);
timer = null;
}, 500);
});
};
})(jQuery);
|
require('../app').directive('fileInput', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var parent = element.parent();
var fInput = angular.element('<input type="file" accept="image/*" style="display: none"/>');
var imgEl = angular.element('<img style="display: none"/>');
parent.append(fInput);
//parent.append(imgEl);
fInput.change(function(){
element.text($(this).val());
var input = this;
if ( input.files && input.files[0] ) {
var FR = new FileReader();
FR.onload = function(e) {
//imgEl.attr( "src", e.target.result );
var callback = scope.$eval(attrs.onFile);
callback(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
});
element.click(function(){
fInput.click();
});
}
}
}); |
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/layout/App.js';
ReactDOM.render(<App />, document.getElementById('root'));
|
class Parent {
constructor(a) {
this.filed1 = a;
}
func1() {
console.log(`原型方法1`);
}
static bar = "静态属性 1"; //静态方式只能自身访问
static bar2 = function () {
console.log("静态方法 1");
};
}
class Child extends Parent {
constructor() {
super(); // 修改this原型指向实现继承 采用函数+对象混合继承
this.filed3 = 111;
}
static bar3() {
super.bar2(); //相当与父类调用 static不影响
}
filed4 = 4;
func2 = function () {
console.log("fun2");
};
}
console.log(Parent.bar); // 类可以调用静态属性
Parent.bar2(); //类可以直接调用静态方法
let a = new Parent(111); // 实例化
console.log(a.filed1); // 实例可以访问原型属性
a.func1(); // 实例可以访问原型方法
Child.bar3(); // 直接调用继承类对象
let b = new Child(); // 实例化
console.log(11111);
console.log(b.filed4);
|
import React from 'react';
import { Link } from 'react-router-dom';
import moment from 'moment';
import messages from 'lib/text';
import * as helper from 'lib/helper';
import style from './style.css';
import SummaryForm from './summaryForm.js';
import Paper from 'material-ui/Paper';
import Divider from 'material-ui/Divider';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import SelectField from 'material-ui/SelectField';
import Dialog from 'material-ui/Dialog';
export default class CustomerSummary extends React.Component {
constructor(props) {
super(props);
this.state = {
openSummaryEdit: false
};
}
showSummaryEdit = () => {
this.setState({ openSummaryEdit: true });
};
hideSummaryEdit = () => {
this.setState({ openSummaryEdit: false });
};
saveSummaryEdit = customer => {
this.props.onCustomerSummaryUpdate(customer);
this.hideSummaryEdit();
};
render() {
const { customer, settings } = this.props;
const totalSpent = helper.formatCurrency(customer.total_spent, settings);
return (
<Paper className="paper-box" zDepth={1}>
<div className={style.innerBox}>
<div
className={style.customerName}
style={{ paddingBottom: 26, paddingTop: 0 }}
>
{customer.full_name}
<div>
<small>{customer.group_name}</small>
</div>
</div>
<div className={style.summaryRow + ' row'}>
<div className="col-xs-5">
<span>{messages.email}</span>
</div>
<div className="col-xs-7">
<a href={'MailTo:' + customer.email} className={style.link}>
{customer.email}
</a>
</div>
</div>
<div className={style.summaryRow + ' row'}>
<div className="col-xs-5">
<span>{messages.mobile}</span>
</div>
<div className="col-xs-7">{customer.mobile}</div>
</div>
<div className={style.summaryRow + ' row'}>
<div className="col-xs-5">
<span>{messages.customers_totalSpent}</span>
</div>
<div className="col-xs-7">{totalSpent}</div>
</div>
<div className={style.summaryRow + ' row'}>
<div className="col-xs-5">
<span>{messages.note}</span>
</div>
<div className="col-xs-7">{customer.note}</div>
</div>
<div style={{ marginTop: 20 }}>
<RaisedButton
label="Edit"
style={{ marginRight: 15 }}
onClick={this.showSummaryEdit}
/>
</div>
<Dialog
title={messages.customers_titleEdit}
modal={false}
open={this.state.openSummaryEdit}
onRequestClose={this.hideSummaryEdit}
contentStyle={{ width: 600 }}
>
<SummaryForm
initialValues={customer}
onCancel={this.hideSummaryEdit}
onSubmit={this.saveSummaryEdit}
/>
</Dialog>
</div>
</Paper>
);
}
}
|
'use strict';
var _app = angular.module('main');
_app.controller('TodosCtrl', ['$scope', 'TodosStorage', 'Todo', 'underscore', function ( $scope, todosStorage, Todo, _ ) {
// defaults
(function(){
$scope.todos = todosStorage.get();
$scope.formTodoNewTitle = '';
$scope.formTodoNewDescription = '';
$scope.hideComplete = false;
$scope.availableTodos = 0;
})();
// clear add form
$scope.clearForm = function(){
$scope.formTodoNewTitle = '';
$scope.formTodoNewDescription = '';
};
// watch todos property
$scope.$watch('todos',function(newVal,oldVal){
if(newVal !== oldVal){
todosStorage.put($scope.todos);
}
},true);
// add todo
$scope.addTodo = function(){
if($scope.formTodoNewTitle.trim() !== ''){
$scope.todos.push(new Todo({
title: $scope.formTodoNewTitle,
description: $scope.formTodoNewDescription,
}));
$scope.clearForm();
}
};
// edit todo
$scope.editTodo = function(current,fields){
var _new = _.extend(current,fields);
var _todos = _.filter($scope.todos,function(_item){
if(_item.$$hashKey === _new.$$hashKey) {
_item = _new.$$hashKey;
}
return _item;
});
$scope.todos = _todos;
todosStorage.put($scope.todos);
$scope.$digest();
};
// delete all complete items
$scope.deleteComplete = function(){
var _todos = _.filter($scope.todos, function(_item){
if(_item.done !== true){
return _item;
}
});
$scope.todos = _todos;
todosStorage.put($scope.todos);
};
// get todos total
$scope.getTodosTotal = function(){
if($scope.hideComplete !== true){
return $scope.todos.length;
}else{
return (_.filter($scope.todos,function(todo){
return !todo.done;
})).length;
}
};
// delete todo
$scope.deleteThis = function(_scope){
var _todos = _.filter($scope.todos,function(_item){
if(_scope.$$hashKey !== _item.$$hashKey){
return _item;
}
});
$scope.todos = _todos;
todosStorage.put($scope.todos);
};
}]);
|
import puppeteer from '../puppeteer';
describe('puppeteer helpers', () => {
describe('.launch()', () => {
test('should return a truthy Chromium instance without any param', async () => {
const browser = await puppeteer.launch();
expect(browser).toBeTruthy();
await browser.close();
});
});
}); |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><circle cx="12" cy="16" r="1" /><path d="M12 13c.55 0 1-.45 1-1V8c0-.55-.45-1-1-1s-1 .45-1 1v4c0 .55.45 1 1 1z" /><path d="M17 1H7c-1.1 0-1.99.9-1.99 2v18c0 1.1.89 2 1.99 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 17H7V6h10v12z" /></React.Fragment>
, 'SecurityUpdateWarningRounded');
|
(function(){
var shortUrl = require(__dirname + "/src/url");
module.exports = function (url) {
return shortUrl.process(url);
};
})();
|
//--------------------------------------------------------------------------
//
// Server app
//
//--------------------------------------------------------------------------
var env = process.env.NODE_ENV || 'development',
config = require('./config')[env],
path = require('path'),
express = require('express'),
server = express(),
http = require('http'),
https = require('https'),
bodyParser = require('body-parser'),
compression = require('compression'),
logger = require('winston'),
loggerHttp = require('morgan'),
bunyan = require('bunyan'),
log = bunyan.createLogger({name: config.id}),
indexController = require('./controllers/index');
//--------------------------------------------------------------------------
//
// SSL support
//
//--------------------------------------------------------------------------
if ( config.features.ssl.enabled ) {
server.set( 'port', process.env.PORT || config.features.ssl.port );
} else {
server.set( 'port', process.env.PORT || config.port );
}
//--------------------------------------------------------------------------
//
// Database support (MongoDB)
//
//--------------------------------------------------------------------------
if ( config.features.db.enabled ) {
var mongoose = require('mongoose');
mongoose.connect( config.features.db.host + config.features.db.name );
}
//--------------------------------------------------------------------------
//
// Templating support (Handlebars)
//
//--------------------------------------------------------------------------
if ( config.features.templating.enabled ) {
var expressHbs = require('express-handlebars');
server.engine( 'hbs', expressHbs( {extname:'hbs'} ) );
server.set( 'view engine', 'hbs' );
server.set( 'views', path.join( __dirname, '/views' ) );
}
//--------------------------------------------------------------------------
//
// Reverse proxy support (NGINX)
//
//--------------------------------------------------------------------------
if ( config.features.reverse_proxy.enabled ) {
server.enable( 'trust proxy' );
}
//--------------------------------------------------------------------------
//
// Middleware configuration
//
//--------------------------------------------------------------------------
server.use( loggerHttp( 'short' ) );
server.use( bodyParser.json() );
server.use( bodyParser.urlencoded({
extended: true
}) );
//--------------------------------------------------------------------------
//
// Router
//
//--------------------------------------------------------------------------
server.get( '/', indexController.default );
//--------------------------------------------------------------------------
//
// Start server
//
//--------------------------------------------------------------------------
if ( config.features.ssl.enabled ) {
var fs = require('fs');
var sslOptions = {
key: fs.readFileSync( config.features.ssl.key ),
cert: fs.readFileSync( config.features.ssl.cert )
};
https.createServer(sslOptions, server).listen(server.get('port'), function() {
log.info('Express server listening on port %d', server.get('port'));
});
} else {
http.createServer(server).listen(server.get('port'), function() {
log.info('Express server listening on port %d', server.get('port'));
});
}
|
'use strict'
const mongoose = require('mongoose')
const MONGODB_URL = process.env.MONGODB_URL || 'mongodb://localhost:27017/battleship'
mongoose.Promise = Promise
module.exports.connect = () => mongoose.connect(MONGODB_URL)
module.exports.disconnect = () => mongoose.disconnect()
|
import test from 'ava';
import avaRuleTester from 'eslint-ava-rule-tester';
import rule from '../rules/consistent-compose';
import {code} from './helpers';
const ruleTester = avaRuleTester(test, {
env: {
es6: true
},
parserOptions: {
sourceType: 'module'
}
});
const error = {
ruleId: 'consistent-compose'
};
ruleTester.run('consistent-compose', rule, {
valid: [
{
code: code(`flow(fn1, fn2)(x);`, ['flow']),
options: ['flow']
},
{
code: code(`pipe(fn1, fn2)(x);`, ['pipe']),
options: ['pipe']
},
{
code: code(`compose(fn1, fn2)(x);`, ['compose']),
options: ['compose']
},
{
code: code(`flowRight(fn1, fn2)(x);`, ['flowRight']),
options: ['flowRight']
},
{
code: code(`_.flow(fn1, fn2)(x);`),
options: ['flow']
},
{
code: code(`compose(fn1, fn2)(x);`, false),
options: ['flow']
},
// Check assignments created via composition
{
code: code(`var composed = flow(fn1, fn2); var b = composed(x);`, ['flow']),
options: ['flow']
},
{
code: code(`var composed = _.pipe(fn1, fn2); var b = composed(x);`),
options: ['pipe']
},
// Make sure there are no false positives on non-compose functions
{
code: code(`_.partial(fn1, args)(x);`),
options: ['flow']
},
{
code: code(`partial(fn1, args)(x);`, ['partial']),
options: ['flow']
},
{
code: code(`_.map(fn1, iterable);`),
options: ['flow']
},
{
code: code(`map(fn1, iterable);`, ['map']),
options: ['flow']
},
{
code: code(`var fn = map(fn2);`, ['map']),
options: ['flow']
},
{
code: code(`var fn = _.map(fn2);`),
options: ['flow']
},
// Should not warn on ambiguously renamed imports
{
code: code(`import {map as flow} from 'lodash/fp'; flow(fn1, iterable);`, false),
options: ['compose']
},
// Should not warn if no compose function is specified
{
code: code(`compose(fn1, fn2); pipe(fn1, fn2);`, ['compose', 'pipe']),
options: []
},
{
code: code(`_.compose(fn1, fn2); _.pipe(fn1, fn2);`),
options: []
}
],
invalid: [
{
code: code(`compose(fn1, fn2)(x);`, ['compose']),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
{
code: code(`pipe(fn1, fn2)(x);`, ['pipe']),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `pipe`. Use `flow` instead'
}]
},
{
code: code(`flowRight(fn1, fn2)(x);`, ['flowRight']),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `flowRight`. Use `flow` instead'
}]
},
{
code: code(`flow(fn1, fn2)(x);`, ['flow']),
options: ['compose'],
errors: [{
...error, message: 'Forbidden use of `flow`. Use `compose` instead'
}]
},
{
code: code(`_.compose(fn1, fn2)(x);`),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
{
code: code(`import {compose} from 'lodash'; compose(fn1, fn2)(x);`, false),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
{
code: code(`var {compose} = require('lodash/fp'); compose(fn1, fn2)(x);`, false),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
{
code: code(`import {compose as c} from 'lodash/fp'; c(fn1, fn2)(x);`, false),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
{
code: code(`var {c: compose} = require('lodash/fp'); c(fn1, fn2)(x);`, false),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
},
// Should still warn on ambiguously renamed imports
{
code: code(`import {compose as flow} from 'lodash/fp'; flow(fn1, fn2)(x);`, false),
options: ['flow'],
errors: [{
...error, message: 'Forbidden use of `compose`. Use `flow` instead'
}]
}
]
});
|
// Enable strict syntax mode
'use strict';
// Base class
var BudaLineAgent = require( '../../buda_agent_line' );
// Custom requirements
var util = require( 'util' );
// Constructor method
function BudaJSONLAgent( conf, handlers ) {
BudaLineAgent.call( this, conf, handlers );
}
util.inherits( BudaJSONLAgent, BudaLineAgent );
// Parse each line as a JSON object
BudaJSONLAgent.prototype.transform = function( line ) {
var res;
try {
res = JSON.parse( line );
return res;
} catch( e ) {
this.emit( 'error', line );
return false;
}
};
module.exports = BudaJSONLAgent;
|
//Register babel to transpile before our tests run
require('babel-register')();
// disable webpack features that Mocha does not understand
require.extensions['.css'] = function () {};
|
'use strict';
angular.module('pokedex')
.controller('MainCtrl', function () {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
exports.level = {
"goalTreeString": "{\"branches\":{\"master\":{\"target\":\"C7\",\"id\":\"master\"},\"bugWork\":{\"target\":\"C2\",\"id\":\"bugWork\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"},\"C2\":{\"parents\":[\"C1\"],\"id\":\"C2\"},\"C3\":{\"parents\":[\"C1\"],\"id\":\"C3\"},\"C4\":{\"parents\":[\"C3\"],\"id\":\"C4\"},\"C5\":{\"parents\":[\"C2\"],\"id\":\"C5\"},\"C6\":{\"parents\":[\"C4\",\"C5\"],\"id\":\"C6\"},\"C7\":{\"parents\":[\"C6\"],\"id\":\"C7\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"solutionCommand": "git branch bugWork master^^2^",
"startTree": "{\"branches\":{\"master\":{\"target\":\"C7\",\"id\":\"master\"}},\"commits\":{\"C0\":{\"parents\":[],\"id\":\"C0\",\"rootCommit\":true},\"C1\":{\"parents\":[\"C0\"],\"id\":\"C1\"},\"C2\":{\"parents\":[\"C1\"],\"id\":\"C2\"},\"C3\":{\"parents\":[\"C1\"],\"id\":\"C3\"},\"C4\":{\"parents\":[\"C3\"],\"id\":\"C4\"},\"C5\":{\"parents\":[\"C2\"],\"id\":\"C5\"},\"C6\":{\"parents\":[\"C4\",\"C5\"],\"id\":\"C6\"},\"C7\":{\"parents\":[\"C6\"],\"id\":\"C7\"}},\"HEAD\":{\"target\":\"master\",\"id\":\"HEAD\"}}",
"name": {
"en_US": "Multiple parents",
"zh_CN": "多个父提交记录",
'fr_FR': 'Parents multiples',
"de_DE": "Mehrere Vorgänger",
"ja" : "複数の親",
"es_AR": "Múltiples padres",
"pt_BR": "Múltiplos pais",
"zh_TW": "多個 parent commit",
"ru_RU": "Здоровая семья, или несколько родителей",
"ko" : "다수의 부모",
'uk': 'Декілька батьків'
},
"hint": {
"en_US": "Use `git branch bugWork` with a target commit to create the missing reference.",
"de_DE": "Nutze `git branch bugWork` mit einem Ziel-Commit um die fehlende Referenz zu erstellen.",
"ja" : "`git branch bugWork`を対象のコミットと組み合わせて使い、欠如しているリファレンスを作成しましょう",
'fr_FR': 'Utilisez "git branch bugWork" avec un commit pour créer une référence manquante',
"zh_CN": "使用 `git branch bugWork` 加上一个目标提交记录来创建消失的引用。",
"es_AR": "Usá `git branch bugWork` sobre algún commit para crear la referencia faltante",
"pt_BR": "Use `git branch bugWork` com um commit alvo para criar a referência que falta",
"zh_TW": "在一個指定的 commit 上面使用 `git branch bugWork`。",
"ru_RU": "`git branch bugWork` на нужном коммите поможет создать нужную ссылку.",
"ko" : "`git branch bugWork`를 대상 커밋과 함께 사용해서 부족한 참조를 만드세요",
'uk': 'Використай "git branch bugWork" на потрібному коміті щоб створити потрібне посилання'
},
"startDialog": {
"en_US": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Specifying Parents",
"",
"Like the `~` modifier, the `^` modifier also accepts an optional number after it.",
"",
"Rather than specifying the number of generations to go back (what `~` takes), the modifier on `^` specifies which parent reference to follow from a merge commit. Remember that merge commits have multiple parents, so the path to choose is ambiguous.",
"",
"Git will normally follow the \"first\" parent upwards from a merge commit, but specifying a number with `^` changes this default behavior.",
"",
"Enough talking, let's see it in action.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Here we have a merge commit. If we checkout `master^` without the modifier, we will follow the first parent after the merge commit. ",
"",
"(*In our visuals, the first parent is positioned directly above the merge commit.*)"
],
"afterMarkdowns": [
"Easy -- this is what we are all used to."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Now let's try specifying the second parent instead..."
],
"afterMarkdowns": [
"See? We followed the other parent upwards."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"The `^` and `~` modifiers can make moving around a commit tree very powerful:"
],
"afterMarkdowns": [
"Lightning fast!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Even crazier, these modifiers can be chained together! Check this out:"
],
"afterMarkdowns": [
"The same movement as before, but all in one command."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Put it to practice",
"",
"To complete this level, create a new branch at the specified destination.",
"",
"Obviously it would be easy to specify the commit directly (with something like `C6`), but I challenge you to use the modifiers we talked about instead!"
]
}
}
]
},
"de_DE": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Vorgänger ansteuern",
"",
"Wie der Operator `~` akzeptiert auch der Operator `^` eine optionale Anzahl.",
"",
"Anstatt der Anzahl von Schritten, die zurückgegangen werden soll (das ist das, was man bei `~` angibt), bezeichnet die Anzahl nach `^` welchem Vorgänger bei einem Merge-Commit gefolgt werden soll. Du erinnerst dich, dass ein Merge-Commit mehrere Vorgänger hat; es gilt also aus diesen auszuwählen.",
"",
"Normalerweise folgt Git dem \"ersten\" Vorgänger des Merge-Commit, aber durch Angabe einer Zahl nach dem `^` lässt sich dieses Verhalten ändern.",
"",
"Aber genug gequatscht, schauen wir's uns in Aktion an.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Hier sehen wir einen Merge-Commit. Wenn wir einen Checkout von `master^` ohne Zahl machen, wird Git auf den ersten Vorgänger des Commits zurückgehen. ",
"",
"*(In unserer Darstellung befindet sich der erste Vorgänger direkt über dem Merge-Commit.)*"
],
"afterMarkdowns": [
"Simpel -- so kennen wir das."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Jetzt versuchen wir mal stattdessen den zweiten Vorgänger anzugeben ..."
],
"afterMarkdowns": [
"Gesehen? Wir gehen zu dem anderen Vorgänger zurück."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Die Operatoren `^` und `~` geben uns eine Menge Möglichkeiten für das Navigieren durch den Commit-Baum:"
],
"afterMarkdowns": [
"Bämm!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Noch abgefahrener: die beiden Operatoren können verkettet werden. Aufgepasst:"
],
"afterMarkdowns": [
"Gleicher Ablauf wie zuvor, nur alles in einem Befehl."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Setzen wir's um",
"",
"Erstelle einen neuen Branch an dem angegebenen Ziel, um diesen Level abzuschließen.",
"",
"Es ist natürlich möglich den Commit einfach direkt anzugeben (also mit sowas wie `C6`), aber ich fordere dich heraus stattdessen die relativen Operatoren zu benutzen!"
]
}
}
]
},
"fr_FR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Determine les Parents",
"",
"Comme le symbole `~`, le symbole `^` accepte un numéro après lui.",
"",
"Au lieu d'entrer le nombre de générations à remonter (ce que `~` fait), le symbole `^` détermine quel parent est à remonter. Attention, un merge commit a deux parents ce qui peut porter à confusion.",
"",
"Normalement Git suit le \"premier\" parent pour un commit/merge, mais avec un numéro suivi de `^` le comportement par défault est modifié.",
"",
"Assez de bla bla, passons à l\'action",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Nous avons un commit/merge. Si nous faisons checkout `master^` sans le symbole, on obtient le premier parent suivant ce commit. ",
"",
"(*Dans notre vue, le premier parent se situe juste au dessus du merge.*)"
],
"afterMarkdowns": [
"Facile -- C\'est ce que nous faisons tout le temps."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Nous allons spécifier le deuxième parent à la place."
],
"afterMarkdowns": [
"Vous voyez ? Nous suivons le second parent."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Les symboles `^` et `~` permettent de se déplacer de façon très efficace :"
],
"afterMarkdowns": [
"Boum, vitesse du tonnerre !"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Encore plus fou, ces symboles peuvent être enchainés ! Regardez cela :"
],
"afterMarkdowns": [
"Le même résultat, mais en une seule commande."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Un peu de pratique",
"",
"Pour réussir le niveau, créez une nouvelle branche à la destination indiquée",
"",
"Évidement ce serait plus rapide de spécifier le commit (C6 par exemple), mais faites-le plutôt avec les symboles de déplacement dont nous venons de parler !"
]
}
}
]
},
"zh_CN": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 选择父提交",
"",
"和 `~` 修改符一样,`^` 修改符之后也可以跟一个(可选的)数字。",
"",
"这不是用来指定向上返回几代(`~` 的作用),`^` 后的数字指定跟随合并提交记录的哪一个父提交。还记得一个合并提交有多个父提交吧,所有选择哪条路径不是那么清晰。",
"",
"Git 默认选择跟随合并提交的\"第一个\"父提交,使用 `^` 后跟一个数字来改变这一默认行为。",
"",
"废话不多说,举个例子。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"这里有一个合并提交。如果不加数字修改符直接切换到 `master^`,会回到第一个父提交。",
"",
"(*在我们的图示中,第一个父提交是指合并提交正上方的那个父提交。*)"
],
"afterMarkdowns": [
"OK -- 这恰好是我们想要的。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"现在来试试选择第二个父提交……"
],
"afterMarkdowns": [
"看见了吧?我们回到了第二个父提交。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"使用 `^` 和 `~` 可以自由地在提交树中移动:"
],
"afterMarkdowns": [
"快若闪电!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"再疯狂点,这些修改符支持链式操作!试一下这个:"
],
"afterMarkdowns": [
"和前面的结果一样,但只用了一条命令。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 实践一下",
"",
"要完成此关,在指定的目标位置创建一个新的分支。",
"",
"很明显可以简单地直接使用提交记录的 hash 值(比如 `C6`),但我要求你使用刚刚讲到的相对引用修饰符!"
]
}
}
]
},
"es_AR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Especificando los padres",
"",
"Como el modificador de `~`, `^` también acepta un número opcional después de él.",
"",
"En lugar de especificar cuántas generaciones hacia atrás ir (como `~`), el modificador de `^` especifica por cuál de las referencias padres seguir en un commit de merge. Recordá que un commit de merge tiene múltiples padres, por lo que el camino a seguir es ambiguo.",
"",
"Git normalmente sigue el \"primer\" padre de un commit de merge, pero especificando un número junto con `^` cambia este comportamiento predefinido.",
"",
"Demasiada charla, veámoslo en acción.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Acá tenemos un commit de merge. Si hacemos checkout de `master^`, sin modificadores, vamos a seguir al primer padre después del commit de merge. ",
"",
"(*En nuestras visualizaciones, el primer padre se ubica directamente arriba del commit de merge.*)"
],
"afterMarkdowns": [
"Fácil -- esto es a lo que estamos acostumbrados."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Ahora tratemos de especificar el segundo padre, en cambio..."
],
"afterMarkdowns": [
"¿Ves? Seguimos al otro padre hacia arriba."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Los modificadores de `^` y `~` son muy poderosos a la hora de movernos en un árbol:"
],
"afterMarkdowns": [
"¡Rapidísimo!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Más loco aún, ¡estos modificadores pueden encadenarse entre sí! Mirá esto:"
],
"afterMarkdowns": [
"El mismo movimiento que antes, pero todo en uno."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Ponelo en práctica",
"",
"Para completar este nivel, creá una nueva rama en la ubicación indicada.",
"",
"Obviamente sería muy fácil especificar el commit directamente (algo como `C6`), pero te reto a usar los modificadores de los que estuvimos hablando, mejor"
]
}
}
]
},
"pt_BR": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Especificando pais",
"",
"Assim como o modificador `~`, o modificador `^` também aceita um número opcional depois dele.",
"",
"Em vez de especificar o número de gerações a voltar (que é o que o `~` faz), o modificador no `^` especifica qual referência de pai a ser seguida a partir de um commit de merge. Lembre-se que commits de merge possuem múltiplos pais, então o caminho a seguir é ambíguo.",
"",
"O Git normalmente subirá o \"primeiro\" pai de um commit de merge, mas especificar um número após o `^` muda esse comportamento padrão.",
"",
"Basta de conversa, vejamos o operador em ação.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Aqui temos um commit de merge. Se fizermos checkout em `master^` sem especificar um número, vamos seguir o primeiro pai acima do commit de merge. ",
"",
"(*Em nossa visualização, o primeiro pai é aquele diretamente acima do commit de merge.*)"
],
"afterMarkdowns": [
"Fácil -- isso é aquilo com o que já estamos acostumados."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Agora vamos, em vez disso, especificar o segundo pai..."
],
"afterMarkdowns": [
"Viu? Subimos para o outro pai."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Os modificadores `^` e `~` podem tornar a movimentação ao redor da árvore de commits muito poderosa:"
],
"afterMarkdowns": [
"Rápido como a luz!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Ainda mais louco, esses modificadores podem ser encadeados em conjunto! Veja só:"
],
"afterMarkdowns": [
"O mesmo movimento que o anterior, mas tudo em um único comando."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Coloque em prática",
"",
"Para completar este nível, crie um novo ramo no destino especificado.",
"",
"Obviamente seria mais fácil especificar o commit diretamente (com algo como `C6`), mas em vez disso eu desafio você a usar os modificadores sobre os quais falamos!"
]
}
}
]
},
"zh_TW": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 選擇 parent commit",
"",
"和 `~` 符號一樣,`^` 符號的後面也可以接一個(可選的)數字。",
"",
"這不是用來指定往上回去幾代(`~` 的作用),`^` 後面所跟的數字表示我要選擇哪一個 parent commit。還記得一個 merge commit 可以有多個 parent commit 吧,所以當我們要選擇走到哪一個 parent commit 的時候就會比較麻煩了。",
"",
"git 預設會選擇 merge commit 的\"第一個\" parent commit,使用 `^` 後面接一個數字可以改變這個預設的行為。",
"",
"廢話不多說,舉一個例子。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"這裡有一個 merge commit。如果後面不加數字的話會直接切換到`master^`,也就是說會回到第一個 parent commit。",
"",
"(*在我們的圖示中,第一個 parent commit 是指 merge commit 正上方的那一個 parent commit。*)"
],
"afterMarkdowns": [
"簡單吧!這就是預設的情況。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"現在來試試選擇第二個 parent commit..."
],
"afterMarkdowns": [
"看到了嗎?我們回到了第二個 parent commit。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"使用`^`和`~`可以自由在 commit tree 中移動:"
],
"afterMarkdowns": [
"簡直就像是電光石火!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"再瘋狂點,這些符號可以被連在一起!試一下這個:"
],
"afterMarkdowns": [
"和前面的結果一樣,但只用了一條指令。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 練習一下",
"",
"要完成這一關,在指定的目標位置上面建立一個新的 branch。",
"",
"很明顯可以直接使用 commit 的 hash 值(比如 `C6`),但我要求你使用剛剛講到的相對引用的符號!"
]
}
}
]
},
"ru_RU": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Определение родителей",
"",
"Так же как тильда (~), каретка (^) принимает номер после себя.",
"",
"Но в отличие от количества коммитов, на которые нужно откатиться назад (как делает `~`), номер после `^` определяет, на какого из родителей мерджа надо перейти. Учитывая, что мерджевый коммит имеет двух родителей, просто указать ^ нельзя.",
"",
"Git по умолчанию перейдёт на \"первого\" родителя коммита, но указание номера после `^` изменяет это поведение.",
"",
"Посмотрим, как это работает.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Вот мерджевый коммит. Если мы перейдём на `master^` без номера, то попадём на первого родителя.",
"",
"(*На нашей визуализации первый родитель находится прямо над коммитом*)"
],
"afterMarkdowns": [
"Просто - прямо как мы любим."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Теперь попробуем перейти на второго родителя."
],
"afterMarkdowns": [
"Вот. Мы на втором родительском коммите."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Модификаторы `^` и `~` сильно помогают перемещаться по дереву коммитов:"
],
"afterMarkdowns": [
"Быстро как Флэш!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Более того, эти модификаторы можно применять вместе. Например, так:"
],
"afterMarkdowns": [
"Сделаем то же самое, что перед этим, только в одну команду."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### На практике",
"",
"Чтобы пройти этот уровень, создай ветку в указанном месте.",
"",
"Очевидно, что (в данном случае) будет проще указать коммит напрямую, но для того, чтобы закрепить пройденное, используй модификаторы, о которых мы говорили выше."
]
}
}
]
},
"ja": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 親の指定",
"",
"`~`修飾子と同じように、`^`修飾子も後に任意の番号を置くことができます。",
"",
"指定した数だけ遡る(これは`~`の場合の機能)のではなく、`^`はマージコミットからどの親を選択するかを指定できます。マージコミットは複数の親で構成されるので、選択する経路が曖昧であることを覚えておいてください。",
"",
"Gitは通常、マージコミットから「一つ目」の親、マージされた側のブランチの親を選びます。しかし、`^`で数を指定することでこのデフォルトの動作を変えることができます。",
"",
"では、実際の動作を見ていきましょう。",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"ここに、マージコミットがあります。もし、指定無しに`master^`でチェックアウトした場合、私たちは一番目の親に移動することになります。",
"",
"(*私たちのツリーでは、一番目の親はマージコミットのちょうど上に位置しています。*)"
],
"afterMarkdowns": [
"簡単ですね -- これがデフォルトの動作になります。"
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"それでは代わりに二つ目の親を指定してみます"
],
"afterMarkdowns": [
"見ましたか?私たちは他の親に移ることができました。"
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"`^`修飾子と`~`修飾子は、コミット履歴を辿るのを強力に補助してくれます:"
],
"afterMarkdowns": [
"超高速ですね!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"より素晴らしいことに、これらの修飾子は連鎖させることができます!これを見てください:"
],
"afterMarkdowns": [
"前と同じ移動ですが、なんと一つのコマンドでできています。"
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 練習課題",
"",
"このレベルをクリアするためには、まず新しいブランチを指定したように作成します。",
"",
"明らかに直接コミットを指定した方が(`C6`というように)簡単ですが、私は今まで述べたような修飾子を使う方法で挑戦してもらいたいと思います。"
]
}
}
]
},
"ko": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 부모를 선택하기",
"",
"`~` 수식처럼 `^` 수식 또한 뒤에 숫자를 추가 할 수 있습니다.",
"",
"몇개의 세대를 돌아갈지 정하는 것 대신(`~`의 기능) `^`수식은 병합이된 커밋에서 어떤 부모를 참조할지 선택할 수 있습니다. 병합된 커밋들은 다수의 부모를 가지고 있다는것을 기억하시나요? 어떤 부모를 선택할지 예측할 수가 없습니다.",
"",
"Git은 보통 병합된 커밋에서 \"첫\"부모를 따라갑니다. 하지만 `^`수식을 를 숫자와 함께 사용하면 앞의 디폴트 동작대로가 아닌 다른 결과가 나타납니다.",
"",
"이만 줄이고, 직접 확인해봅시다.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"여기 병합된 커밋이 있습니다. 우리가 `master`를 수식없이 체크아웃한다면 병합된 커밋의 첫 부모를 따라 올라갈 것입니다. ",
"",
"(*화면에서는 첫 부모는 병합된 커밋 바로 위에 위치해 있습니다.*)"
],
"afterMarkdowns": [
"간단하죠 -- 우리한테 익숙한 모습입니다."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"자 이제 두번째 부모를 선택해봅시다..."
],
"afterMarkdowns": [
"보이나요? 다른 부모를 선택해 올라갔습니다."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"`^`수식과 `~`수식을 이용해 커밋트리에서 효과적으로 움직일 수 있습니다.:"
],
"afterMarkdowns": [
"빛처럼 빠르게 말이죠!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"더 대단한것은 이 수식들은 같이 사용할 수 있다는 겁니다! 확인해봅시다:"
],
"afterMarkdowns": [
"앞과 같은 움직임이지만 하나의 명령으로 표현되었습니다."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### 직접 확인해봅시다",
"",
"이 레벨을 완료하기 위해서 정해진 목적지에 새 브랜치를 생성하세요.",
"",
"물론 커밋을 직접 특정지어주면 아주 쉽겠지만(`C6`과 같이), 수식을 익혀볼겸 배운것을 사용해 도전해 봅시다!"
]
}
}
]
},
"uk": {
"childViews": [
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Вибираємо Попередників",
"",
"Так само як і модифікатор `~`, модифікатор `^` також приймає необов’язкове число після нього.",
"",
"Замість того, щоб вказувати кількість генерацій щоб переміститись назад (те що робить `~`), число після `^` вказує на яке батьківське посилання мерджу потрібно перейти. Зауважте що так як мерджевий коміт має декілька батьків, використання '^' без числа є неоднозначним.",
"",
"Git зазвичай перейде на \"першого\" з батьків вверх з мерджевого коміту, але вказання числа після `^` змінює цю поведінку. ",
"",
"Годі ляси точити, перевірмо як це працює в дії.",
""
]
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Ось ми маємо мерджевий коміт. Якщо зробимо checkout `master^` без числа, ми потрапимо на першого з предків ",
"",
"(*В нашій візуалізації перший предок знаходиться прямо над мерджевим комітом*)"
],
"afterMarkdowns": [
"Легко -- те до чого ми всі звикли."
],
"command": "git checkout master^",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Тепер спробуймо натомість вказати другого батька..."
],
"afterMarkdowns": [
"Бачиш? Ми перейшли до другого батька вверх."
],
"command": "git checkout master^2",
"beforeCommand": "git checkout HEAD^; git commit; git checkout master; git merge C2"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Модифікатори `^` та `~` дозволяють легко пересуватися деревом комітів:"
],
"afterMarkdowns": [
"Супер швидко!"
],
"command": "git checkout HEAD~; git checkout HEAD^2; git checkout HEAD~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "GitDemonstrationView",
"options": {
"beforeMarkdowns": [
"Більше того, ці модифікатори можна використовувати разом! Заціни:"
],
"afterMarkdowns": [
"Те саме, що й перед цим, але однією командою."
],
"command": "git checkout HEAD~^2~2",
"beforeCommand": "git commit; git checkout C0; git commit; git commit; git commit; git checkout master; git merge C5; git commit"
}
},
{
"type": "ModalAlert",
"options": {
"markdowns": [
"### Практика",
"",
"Щоб завершити цей рівень, створи нову гілку на вказаному місці.",
"",
"Очевидно, що в данному випадку досить легко вказати коміт напряму (щось на зразок checkout `C6`), але для закріплення матеріалу використай модифікатори, про які ми щойно говорили!"
]
}
}
]
}
}
};
|
const chai = require('chai');
chai.should();
|
import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
location: config.locationType,
rootURL: config.rootURL
});
Router.map(function() {
this.route('l33t-components', function() {
this.route('navbar');
this.route('validated-field');
this.route('section-header');
this.route('string-question');
this.route('textarea-question');
});
this.route('models');
this.route('login');
this.route('register');
this.route('company', { path: ':company_id' }, function() {
this.route('questionnaire', { path: ':questionnaire_id'} );
});
});
export default Router;
|
const isNumber = require("../object/isNumber.js");
/**
* Evaluate if a number is the number 1.
* @param {Number} n The number to evaluate
* @returns {Boolean} True if n is 1, false otherwise
*/
function isOne(n)
{
if (isNumber(n) && n === 1)
return true;
return false;
}
module.exports = isOne; |
IntlMessageFormat.__addLocaleData({locale:"vun",pluralRuleFunction:function(e,a){return a?"other":1==e?"one":"other"}}); |
/**
* Problem: https://leetcode.com/problems/counting-bits/description/
*/
/**
* @param {number} num
* @return {number[]}
*/
var countBits = function(num) {
var result = [0], pow;
for (var i = 1; i <= num; ++i) {
if (i & (i - 1)) {
result.push(result[i - pow] + 1);
} else {
pow = i;
result.push(1);
}
}
return result;
};
module.exports = countBits;
|
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
define(["require", "exports", 'aurelia-dependency-injection', '../../all'], function (require, exports, aurelia_dependency_injection_1, all_1) {
"use strict";
var ToolboxComponent = (function (_super) {
__extends(ToolboxComponent, _super);
function ToolboxComponent(_gridOptions) {
_super.call(this);
this._gridOptions = _gridOptions;
this.buttons = [];
}
ToolboxComponent.prototype.addButton = function (button) {
if (!button.text || !button.click) {
throw new Error("Missing text or click handler.");
}
this.buttons.push(button);
};
ToolboxComponent.prototype.createOptions = function () {
if (!this._gridOptions.domBased.has('toolbox') && !this._gridOptions.codeBased.toolbox) {
return false;
}
return {};
};
ToolboxComponent = __decorate([
aurelia_dependency_injection_1.inject(all_1.GridOptions)
], ToolboxComponent);
return ToolboxComponent;
}(all_1.GridComponent));
exports.ToolboxComponent = ToolboxComponent;
});
|
define(['phaser', 'klik/core/ManagedObject'], function (Phaser, ManagedObject) {
'use strict';
return ManagedObject.extends('StarfieldBatched', {
init: function() {
this.distance = 300;
this.speed = 4;
this.max = 200;
this.xx = [];
this.yy = [];
this.zz = [];
},
methods: {
preload: function () {
this.game.load.image('star', 'assets/demos/star.png');
},
create: function () {
if (this.game.renderType === Phaser.WEBGL) {
this.max = 2000;
}
var sprites = this.game.add.spriteBatch();
this.stars = [];
for (var i = 0; i < this.max; i++) {
this.xx[i] = Math.floor(Math.random() * 800) - 400;
this.yy[i] = Math.floor(Math.random() * 600) - 300;
this.zz[i] = Math.floor(Math.random() * 1700) - 100;
var star = this.game.make.sprite(0, 0, 'star');
star.anchor.set(0.5);
sprites.addChild(star);
this.stars.push(star);
}
},
update: function () {
for (var i = 0; i < this.max; i++) {
this.stars[i].perspective = this.distance / (this.distance - this.zz[i]);
this.stars[i].x = this.game.world.centerX + this.xx[i] * this.stars[i].perspective;
this.stars[i].y = this.game.world.centerY + this.yy[i] * this.stars[i].perspective;
this.zz[i] += this.speed;
if (this.zz[i] > 290) {
this.zz[i] -= 600;
}
this.stars[i].alpha = Math.min(this.stars[i].perspective / 2, 1);
this.stars[i].scale.set(this.stars[i].perspective / 2);
this.stars[i].rotation += 0.1;
}
}
}
});
});
|
angular.module('fellowship.modules.users.services', []); // CONTRUCTOR
|
'use strict';
var expect = require('chai').expect,
Poll = require('../lib/poll');
describe('Poll', function () {
it('should be defined', function () {
expect(typeof Poll).to.eq('function');
});
describe('constructor', function () {
var args;
function newPoll() {
return new Poll(args);
}
beforeEach(function () {
args = {
id: 1,
question: 'What is the question?',
answers: [ 'Yes', 'No' ]
};
});
it('requires id', function () {
delete args.id;
expect(newPoll).to.throw(/poll id was not specified/);
});
it('requires numerical id', function () {
args.id = '1';
expect(newPoll).to.throw(/poll id must be a number/);
});
it('requires question string', function () {
delete args.question;
expect(newPoll).to.throw(/poll question must be specified/);
});
it('requires not empty string', function () {
args.question = '';
expect(newPoll).to.throw(/poll question must be specified/);
});
it('requires answers', function () {
delete args.answers;
expect(newPoll).to.throw(/poll answers must be specified/);
});
it('requires at least 2 answers', function () {
args.answers = ['Yes'];
expect(newPoll).to.throw(/poll answers count must be at least 2, but was \d+/);
});
it('is not revotable by default', function () {
expect(newPoll().revotable).to.eq(false);
});
it('accepts revotable as optional parameter', function () {
args.revotable = 'anything truthy';
expect(newPoll().revotable).to.eq(true);
});
it('uses answer values as ids if passed as an array', function () {
expect(newPoll().answers).to.eql({
'1': { key: '1', name: 'Yes' },
'2': { key: '2', name: 'No' }
});
});
it('calculates answers count', function () {
expect(newPoll().getSize()).to.eq(2);
});
it('accepts answers as object too', function () {
args.answers = [
{ key: 'A', name: 'Yes' },
{ key: 'B', name: 'No' },
{ key: 'C', name: 'Maybe' }
];
expect(newPoll().answerIds).to.eql(['A', 'B', 'C']);
});
});
describe('voting', function () {
var poll;
beforeEach(function () {
poll = new Poll({
id: 2,
question: 'Is it a question?',
answers: ['Yes', 'No', 'Yeah']
});
});
it('should be closed by default', function () {
expect(poll.opened).to.eq(false);
});
it('should have empty opening time at start', function () {
expect(poll.timeOpened).to.eq(null);
});
it('should have empty closing time at start', function () {
expect(poll.timeClosed).to.eq(null);
});
it('should be open if opened', function () {
poll.open();
expect(poll.opened).to.eq(true);
});
it('should be closed if opened and closed', function () {
poll.open();
poll.close();
expect(poll.opened).to.eq(false);
});
it('should not set close time if was not previously opened', function () {
poll.close();
expect(poll.timeClosed).to.eq(null);
});
describe('if poll is open', function () {
beforeEach(function () {
poll.open();
});
it('should ignore opening for multiple times', function () {
poll.open();
expect(poll.opened).to.eq(true);
});
it('should count vote for valid voter and existing answer', function () {
expect(poll.vote('192.168.1.100', 'Yes')).to.eq(true);
expect(poll.vote('192.168.1.101', 'No')).to.eq(true);
expect(poll.vote('192.168.1.102', 'Yeah')).to.eq(true);
});
describe('and not revotable', function () {
beforeEach(function () {
poll.revotable = false;
});
it('should not allow to vote multiple times', function () {
expect(poll.vote('192.168.1.100', 'Yes')).to.eq(true);
expect(poll.vote('192.168.1.100', 'No')).to.eq(false);
expect(poll.vote('192.168.1.100', 'Yes')).to.eq(false);
});
});
describe('and revotable', function () {
beforeEach(function () {
poll.revotable = true;
});
it('should allow to vote multiple times', function () {
expect(poll.vote('192.168.1.100', 'Yes')).to.eq(true);
expect(poll.vote('192.168.1.100', 'No')).to.eq(true);
});
});
it('should not count vote for non-existing answer', function () {
expect(poll.vote('192.168.1.100', 'XAXA')).to.eq(false);
});
it('should not count vote for invalid voter', function () {
expect(poll.vote(undefined, 'Yeah')).to.eq(false);
expect(poll.vote(null, 'Yeah')).to.eq(false);
expect(poll.vote('', 'Yeah')).to.eq(false);
expect(poll.vote(0, 'Yeah')).to.eq(false);
expect(poll.vote(123, 'Yeah')).to.eq(false);
});
it('sets its opening time', function () {
var delta = Date.now() - poll.timeOpened;
expect(delta).to.be.below(500);
});
});
describe('if poll is closed', function () {
beforeEach(function () {
poll.open();
poll.close();
});
it('should not count any votes for anything', function () {
expect(poll.vote('192.168.1.100', 'Yes')).to.eq(false);
expect(poll.vote('192.168.1.100', 'XAXA')).to.eq(false);
expect(poll.vote(null, 'Yes')).to.eq(false);
expect(poll.vote(null, 'XAXA')).to.eq(false);
});
it('should ignores closing for multiple times', function () {
poll.close();
expect(poll.opened).to.eq(false);
});
it('should set its closing time', function () {
expect(poll.timeClosed).to.not.eq(null);
});
it('should clear closing time if re-opened again', function () {
poll.open();
expect(poll.timeClosed).to.eq(null);
});
});
it('should be not count vote on closed poll', function () {
poll.close();
poll.vote('127.0.0.1', 'Yes');
expect(poll.opened).to.eq(false);
});
describe('votes', function () {
beforeEach(function () {
poll.open();
poll.vote('John', 'Yes');
poll.vote('Colin', 'No');
});
it('should be remember vote keys', function () {
expect(poll.votes.John.key).to.eq('Yes');
expect(poll.votes.Colin.key).to.eq('No');
});
it('should be remember vote time', function () {
expect(poll.votes.John.time).to.exist();
});
it('should be remember last vote time', function (done) {
poll.revotable = true;
var firstTime = poll.votes.John.time;
setTimeout(function () {
poll.vote('John', 'No');
expect(poll.votes.John.time).to.be.gt(firstTime);
done();
}, 20);
});
});
describe('statistics', function () {
beforeEach(function () {
poll.open();
poll.vote('John', 'Yes');
poll.vote('Colin', 'Yeah');
poll.vote('David', 'No');
});
it('should be right in simple case', function () {
expect(poll.countVotes()).to.eql({
'Yes': 1,
'No': 1,
'Yeah': 1
});
});
it('should stay right even someone tries to cheat', function () {
poll.revotable = false;
poll.vote('John', 'No');
expect(poll.countVotes()).to.eql({
'Yes': 1,
'No': 1,
'Yeah': 1
});
});
it('should stay right if someone has changed his mind', function () {
poll.revotable = true;
poll.vote('John', 'No');
expect(poll.countVotes()).to.eql({
'Yes': 0,
'No': 2,
'Yeah': 1
});
});
it('should be able to return voters list', function () {
expect(poll.getVoters().sort()).to.eql([
'Colin', 'David', 'John'
]);
});
});
});
});
|
import state from './entity.state'
import mutations from './entity.mutations'
import actions from './entity.actions'
import getters from './entity.getters'
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
|
//私有方法
function _filter_time(time) {
var tmptime = Math.ceil((new Date()-new Date(time))/1000); //时间差
if (tmptime >= 60) {
if (tmptime >= 3600) {
if (tmptime >= 3600*24) {
if (tmptime > 3600*24*30) { //如果时间差超过1个月
tmptime = time.split(' ')[0]; //输出年-月-天
}
else { //如果大于1天小于1个月
if (Math.floor((tmptime%(3600*24))/3600) > 0) {
tmptime = Math.floor(tmptime/3600/24)+'天'+Math.floor((tmptime%(3600*24))/3600)+'小时前'; //输出 约xx天xx小时前
}
else { //如果没有多余小时
tmptime = Math.floor(tmptime/3600/24)+'天前'; //输入 约xx天前
}
}
}
else { //如果大于1小时小于1天
if (Math.floor((tmptime%3600)/60) > 0) {
tmptime = Math.floor(tmptime/3600)+'小时'+Math.floor((tmptime%3600)/60)+'分钟前'; //输出 约xx小时xx分钟前
}
else { //如果没有多余分钟
tmptime = Math.floor(tmptime/3600)+'小时前'; //输入 约xx小时前
}
}
}
else { //如果大于1分钟小于1小时
tmptime = Math.floor(tmptime/60)+'分钟前'; //输出 约xx分钟前
}
}
else { //如果小于1分钟
tmptime = tmptime+'秒前'; //输出 约xx秒前
}
return tmptime;
}
//私有方法
function _filter_space(str) {
return str.replace(/[ \t\n\r]+/g, '');
}
//私有方法
function _md5(str) {
var crypto = require('crypto');
return crypto.createHash('md5').update(str).digest('hex');
}
//获取标准格式的当前时间
exports.getNowTime = function() {
var d = new Date();
var year = d.getYear()+1900;
var month = d.getMonth()+1;
var date = d.getDate();
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
month = month.toString().length<2 ? '0'+month : month;
date = date.toString().length<2 ? '0'+date : date;
hours = hours.toString().length<2 ? '0'+hours : hours;
minutes = minutes.toString().length<2 ? '0'+minutes : minutes;
seconds = seconds.toString().length<2 ? '0'+seconds : seconds;
return {
year: year,
month: month,
date: date,
hours: hours,
minutes: minutes,
seconds: seconds,
time: year+'/'+month+'/'+date+' '+hours+':'+minutes+':'+seconds
}
}
//去除所有空格换行符以及tab键
exports.filter_space = _filter_space;
//md5加密
exports.md5 = _md5;
//压缩文章内容
exports.compress_code = function(arr) {
arr.forEach(function(one) {
one.content = _filter_space(one.content).replace(/<[^>].*?>/g, '').substr(0, 500);
});
}
//格式化文章中的一些数据
exports.filter_static = function(arr, _uid) {
var self_blogs = [];
arr.forEach(function(one) {
//start: 过滤出当前用户博文
if (one.author_id == _uid) {
self_blogs.push(one);
}
//end: 过滤出当前用户博文
//start: 过滤文章标签
var label_arr = one.label.split(',');
var new_arr = [];
label_arr.forEach(function(label) {
var label_arr2 = label.split(',');
label_arr2.forEach(function(label2) {
var clean_elem = label2.trim();
if (clean_elem != '') {
new_arr.push(clean_elem);
}
});
});
one.label = new_arr;
//end: 过滤文章标签
//格式化文章评论时间
one.comments.forEach(function(comment) {
comment._time = _filter_time(comment._time);
});
//给文章的喜欢数据添加标志
one.loves.forEach(function(love) {
love.type = 'love';
});
//给文章的推荐数据添加标志
one.recommends.forEach(function(recommend) {
recommend.type = 'recommend';
});
//合并推荐、喜欢数组病根据时间排序
one.hots = one.loves.concat(one.recommends).sort(function(value1, value2) {
return new Date(value2['_time']) - new Date(value1['_time']);
});
//格式化排序后的文章推荐、喜欢时间
one.hots.forEach(function(hot) {
hot._time = _filter_time(hot._time);
});
//格式化文章时间
one.time = _filter_time(one.time);
});
return self_blogs;
}
//给文章的热度数据添加标志
exports.filter_loveAndRecommend = function(arr, _uid) {
var love_blogs = [];
arr.forEach(function(one) {
var isExists_love = one.loves.some(function(e) {
return e._uid == _uid;
});
var isExists_recommend = one.recommends.some(function(e) {
return e._uid == _uid;
});
if (isExists_love) {
//标识当前登录者是否喜欢了该文章
one.isLove = true;
//过滤喜欢的博文
love_blogs.push(one);
}
if (isExists_recommend) {
//标识当前登录者是否推荐了该文章
one.isRecommend = true;
}
});
//返回喜欢的博文
return love_blogs;
} |
const React = require('react');
const ReactDOM = require('react-dom');
import { QueueAnim, Icon, Button } from '../index';
import ScrollOverPack from 'rc-scroll-anim/lib/ScrollOverPack';
import ScrollLink from 'rc-scroll-anim/lib/ScrollLink';
import ScrollElement from 'rc-scroll-anim/lib/ScrollElement';
import scrollScreen from 'rc-scroll-anim/lib/ScrollScreen';
import ScrollEvent from 'rc-scroll-anim/lib/EventDispatcher';
import mapped from 'rc-scroll-anim/lib/Mapped';
import TweenOne from 'rc-tween-one';
module.exports = function() {
InstantClickChangeFns.push(function() {
if (!document.getElementById('banner')) {
// componentWillUnmount 不会触发, 手动删掉事件;
ScrollEvent._listeners = {};
mapped.unMount();
return;
}
// 导航处理
function scrollNavEvent() {
const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
const clientHeight = document.documentElement.clientHeight;
if (scrollTop >= clientHeight) {
header.className = header.className.indexOf('home-nav-bottom') >= 0 ? header.className : header.className + ' home-nav-bottom';
} else {
header.className = header.className.replace(/home-nav-bottom/ig, '');
}
}
$(window).off('scroll.scrollNavEvent');
$(window).on('scroll.scrollNavEvent', scrollNavEvent);
// list point
class Link extends React.Component {
componentDidMount() {
// 整屏滚动;
scrollScreen.init({docHeight: 4746});
}
render() {
return (
<div>
<ScrollLink className="list-point" location="banner"/>
<ScrollLink className="list-point" location="page1"/>
<ScrollLink className="list-point" location="page2"/>
<ScrollLink className="list-point" location="page3"/>
<ScrollLink className="list-point" location="page4"/>
</div>
);
}
}
ReactDOM.render(<Link />, document.getElementById('list'));
// banner
class Banner extends React.Component {
constructor() {
super(...arguments);
}
typeFunc(a) {
if (a.key === 'line') {
return 'right';
} else if (a.key === 'button') {
return 'bottom';
}
return 'left';
}
render() {
return (
<ScrollElement scrollName="banner" style={{height: '100%'}}>
<QueueAnim className="banner-text-wrapper" type={this.typeFunc} delay={300}>
<h2 key="h2">ANT <p>DESIGN</p></h2>
<p key="content">一个 UI 设计语言</p>
<span className="line" key="line"/>
<div className="start-button" key="button">
<a href="/docs/spec/introduce"><Icon type="smile-circle"/>开始探索</a>
</div>
<iframe key="github-btn" src="https://ghbtns.com/github-btn.html?user=ant-design&repo=ant-design&type=star&count=true" frameBorder="0" scrolling="0" width="98px" height="20px" />
</QueueAnim>
<TweenOne className='down' vars={[{opacity: 1},{y: 10, duration: 800, yoyo: true, repeat: -1}]}>
<Icon type="down"/>
</TweenOne>
</ScrollElement>
)
}
}
ReactDOM.render(<Banner />, document.getElementById('banner'));
// page1
class Page1 extends React.Component {
render() {
return (
<ScrollOverPack scrollName="page1" className="content-wrapper" playScale={1} replay>
<TweenOne key="image" className="image1 image-wrapper" vars={{x: 0, opacity: 1, duration: 550}}
style={{transform: 'translateX(-100px)', opacity: 0}} hideProps={{type: 'reverse'}}/>
<QueueAnim className="text-wrapper" delay={300} key="text" duration={550} leaveReverse
hideProps={{child: null}}>
<h2 key="h2">最佳实践</h2>
<p key="p" style={{maxWidth: 310}}>近一年的中后台设计实践,积累了大量的优秀案例。</p>
<div key="button"><Button type="primary" size="large"
onClick={()=>{window.location.href='/docs/practice/cases'}}>了解更多<Icon
type="right"/></Button></div>
</QueueAnim>
</ScrollOverPack>
);
}
}
ReactDOM.render(<Page1 />, document.getElementById('page1'));
//page2
class Page2 extends React.Component {
render() {
return (
<ScrollOverPack scrollName="page2" className="content-wrapper" playScale={1} replay>
<QueueAnim className="text-wrapper left-text" delay={300} key="text" duration={550} type='bottom'
leaveReverse
hideProps={{child: null}}>
<h2 key="h2">设计模式</h2>
<p key="p" style={{maxWidth: 260}}>总结中后台设计中反复出现的问题,并提供相应的解决方案。</p>
<div key="button"><Button type="primary" size="large"
onClick={()=>{window.location.href='/docs/pattern/navigation'}}>了解更多<Icon
type="right"/></Button>
</div>
</QueueAnim>
<TweenOne key="image" className="image2 image-wrapper" vars={{x: 0, opacity: 1, delay: 300, duration: 550}}
style={{transform: 'translateX(100px)', opacity: 0}} hideProps={{type: 'reverse'}}/>
</ScrollOverPack>
);
}
}
ReactDOM.render(<Page2 />, document.getElementById('page2'));
// page3
class Page3 extends React.Component {
render() {
return (
<ScrollOverPack scrollName="page3" className="content-wrapper" playScale={1} replay>
<TweenOne key="image" className="image3 image-wrapper" vars={{x: 0, opacity: 1, duration: 550}}
style={{transform: 'translateX(-100px)', opacity: 0}} hideProps={{type: 'reverse'}}/>
<QueueAnim className="text-wrapper" delay={300} key="text" duration={550} leaveReverse style={{top: '40%'}}
hideProps={{child: null}}>
<h2 key="h2">丰富的基础组件</h2>
<p key="p" style={{maxWidth: 280}}>丰富、灵活、实用的基础组件,为业务产品提供强有力的设计支持。</p>
<div key="button"><Button type="primary" size="large"
onClick={()=>{window.location.href='/docs/react/introduce'}}>了解更多<Icon
type="right"/></Button></div>
</QueueAnim>
</ScrollOverPack>
);
}
}
ReactDOM.render(<Page3/>, document.getElementById('page3'));
// page4
class Page4 extends React.Component {
render(){
return (
<ScrollOverPack scrollName="page4" className="content-wrapper" playScale={1}>
<QueueAnim className="text-wrapper-bottom" delay={300} key="text" duration={550} leaveReverse type="bottom"
hideProps={{child: null}}>
<h2 key="h2">微小·确定·幸福</h2>
<p key="p">这是一套致力于提升『用户』和『设计者』使用体验的中后台设计语言。</p>
</QueueAnim>
<TweenOne key="image" className="image4 bottom-wrapper" vars={{y: 0, opacity: 1, duration: 550, delay: 550}}
style={{transform: 'translateY(50px)', opacity: 0}} hideProps={{type: 'reverse'}}/>
</ScrollOverPack>
);
}
}
ReactDOM.render(<Page4 />, document.getElementById('page4'));
});
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:5ba2ca4f8da8962fa5a82327e8aecac68ebbb4804a29f901afc25abea1f6b721
size 17136
|
var Path = require('path');
var parseHtml = require('html-flavors').parseHtml;
var DEBUG = false;
var jsParserOptions = require('./parserOptions')['.js'];
var parsers = {
'.js': function (code) {
var parser = require('acorn-jsx');
return parser.parse(code, jsParserOptions);
},
'.html': function (code) {
return parseHtml(code);
}
};
function parse(file) {
var path = file.path;
var ext = Path.extname(path);
if (parsers.hasOwnProperty(ext)) {
try {
var root = parsers[ext](file.contents + '');
} catch(e) {
if (DEBUG)
console.error(e);
return file;
}
//var body = root.program? root.program.body : root.body;
//if (!body) throw 'Couldn\'t determine AST body';
var ast = {
type: 'ast',
root: root,
//body: body
}
var clone = {path: file.path, contents: file.contents};
return Object.assign(clone, {ast: ast});
}
return file;
}
parse.jsParserOptions = jsParserOptions;
module.exports = parse;
|
/* GET login page */
exports.view = function(req, res){
res.render('login');
}; |
(function() {
'use strict';
angular.module('fallout4CoolTools.components.ui.directives.pagination', []);
})();
|
import React, { Component } from 'react';
import moment from 'moment';
import EventsContainer from '../../containers/Events';
import _ from 'lodash';
import './index.scss';
import Event from './Event';
import Calendar from './Calendar';
const sortEvents = events => {
const now = moment();
return _.chain(events)
.sortBy('dateTime')
.value();
};
const findActiveEvent = events => {
const now = moment();
return _.find(sortEvents(events), event =>
now.isSameOrBefore(moment(event.dateTime), 'day'),
);
};
class Agenda extends Component {
constructor(props) {
super(props);
let events = sortEvents(props.events);
this.state = { events, activeEvent: findActiveEvent(events) };
}
componentWillReceiveProps(nextProps) {
this.setState({ events: sortEvents(nextProps.events) });
}
get activeEventIndex() {
return _.indexOf(this.state.events, this.state.activeEvent);
}
onNext = () => {
if (this.activeEventIndex < this.state.events.length - 1)
this.setState({
activeEvent: this.state.events[this.activeEventIndex + 1],
});
};
onPrevious = () => {
if (this.activeEventIndex > 0)
this.setState({
activeEvent: this.state.events[this.activeEventIndex - 1],
});
};
onEventClick = selectedEvent => this.setState({ activeEvent: selectedEvent });
renderEvent() {
const { activeEvent } = this.state;
return (
<Event
{...this.props}
{...activeEvent}
onNext={this.onNext}
onPrevious={this.onPrevious}
/>
);
}
render() {
return (
<section className="Agenda" id="Agenda">
<h1 className="Agenda-title">{this.props.translate('agenda.title')}</h1>
<div className="Agenda-content">
<div className="Agenda-calendarContainer">
<Calendar {...this.props} onEventClick={this.onEventClick} />
</div>
<div className="Agenda-eventContainer">{this.renderEvent()}</div>
</div>
</section>
);
}
}
export default EventsContainer(Agenda);
|
import G6 from '@antv/g6';
const data = {
nodes: [{
id: '0',
label: '0'
}, {
id: '1',
label: '1'
}, {
id: '2',
label: '2'
}, {
id: '3',
label: '3'
}, {
id: '4',
label: '4'
}, {
id: '5',
label: '5'
}, {
id: '6',
label: '6'
}, {
id: '7',
label: '7'
}, {
id: '8',
label: '8'
}, {
id: '9',
label: '9'
}, {
id: '10',
label: '10'
}, {
id: '11',
label: '11'
}, {
id: '12',
label: '12'
}, {
id: '13',
label: '13'
}, {
id: '14',
label: '14'
}, {
id: '15',
label: '15'
}, {
id: '16',
label: '16'
}, {
id: '17',
label: '17'
}, {
id: '18',
label: '18'
}, {
id: '19',
label: '19'
}, {
id: '20',
label: '20'
}, {
id: '21',
label: '21'
}, {
id: '22',
label: '22'
}, {
id: '23',
label: '23'
}, {
id: '24',
label: '24'
}, {
id: '25',
label: '25'
}, {
id: '26',
label: '26'
}, {
id: '27',
label: '27'
}, {
id: '28',
label: '28'
}, {
id: '29',
label: '29'
}, {
id: '30',
label: '30'
}, {
id: '31',
label: '31'
}, {
id: '32',
label: '32'
}, {
id: '33',
label: '33'
}],
edges: [{
source: '0',
target: '1'
}, {
source: '0',
target: '2'
}, {
source: '0',
target: '3'
}, {
source: '0',
target: '4'
}, {
source: '0',
target: '5'
}, {
source: '0',
target: '7'
}, {
source: '0',
target: '8'
}, {
source: '0',
target: '9'
}, {
source: '0',
target: '10'
}, {
source: '0',
target: '11'
}, {
source: '0',
target: '13'
}, {
source: '0',
target: '14'
}, {
source: '0',
target: '15'
}, {
source: '0',
target: '16'
}, {
source: '2',
target: '3'
}, {
source: '4',
target: '5'
}, {
source: '4',
target: '6'
}, {
source: '5',
target: '6'
}, {
source: '7',
target: '13'
}, {
source: '8',
target: '14'
}, {
source: '9',
target: '10'
}, {
source: '10',
target: '22'
}, {
source: '10',
target: '14'
}, {
source: '10',
target: '12'
}, {
source: '10',
target: '24'
}, {
source: '10',
target: '21'
}, {
source: '10',
target: '20'
}, {
source: '11',
target: '24'
}, {
source: '11',
target: '22'
}, {
source: '11',
target: '14'
}, {
source: '12',
target: '13'
}, {
source: '16',
target: '17'
}, {
source: '16',
target: '18'
}, {
source: '16',
target: '21'
}, {
source: '16',
target: '22'
}, {
source: '17',
target: '18'
}, {
source: '17',
target: '20'
}, {
source: '18',
target: '19'
}, {
source: '19',
target: '20'
}, {
source: '19',
target: '33'
}, {
source: '19',
target: '22'
}, {
source: '19',
target: '23'
}, {
source: '20',
target: '21'
}, {
source: '21',
target: '22'
}, {
source: '22',
target: '24'
}, {
source: '22',
target: '25'
}, {
source: '22',
target: '26'
}, {
source: '22',
target: '23'
}, {
source: '22',
target: '28'
}, {
source: '22',
target: '30'
}, {
source: '22',
target: '31'
}, {
source: '22',
target: '32'
}, {
source: '22',
target: '33'
}, {
source: '23',
target: '28'
}, {
source: '23',
target: '27'
}, {
source: '23',
target: '29'
}, {
source: '23',
target: '30'
}, {
source: '23',
target: '31'
}, {
source: '23',
target: '33'
}, {
source: '32',
target: '33'
}]
};
const width = document.getElementById('container').scrollWidth;
const height = document.getElementById('container').scrollHeight || 500;
const graph = new G6.Graph({
container: 'container',
width,
height,
modes: {
default: [ 'drag-canvas', 'drag-node' ]
},
layout: {
type: 'radial',
unitRadius: 50,
preventOverlap: true,
maxPreventOverlapIteration: 100
},
animate: true,
defaultNode: {
style: {
lineWidth: 2,
fill: '#C6E5FF',
stroke: '#5B8FF9'
}
},
defaultEdge: {
size: 1,
color: '#e2e2e2',
style: {
endArrow: {
path: 'M 4,0 L -4,-4 L -4,4 Z',
d: 4
}
}
}
});
const nodes = data.nodes;
nodes.forEach(node => {
node.size = Math.random() * 20 + 10;
});
graph.data(data);
graph.render();
|
webApp.controller('ModelsCategoriesController', ['$rootScope', '$scope', '$http', 'modelsCategoriesService',
function($rootScope, $scope, $http, modelsCategoriesService) {
$scope.models_categories = {
inProgress: false,
new_models_category_name: '',
new_models_category_description: '',
data: [],
add: function() {
if (!$scope.models_categories.new_models_category_name) {
return;
}
$http({
method: 'post',
url: 'api/add_models_category.php',
data: {
name: $scope.models_categories.new_models_category_name,
description: $scope.models_categories.new_models_category_description
}
}).then(function(res) {
if (res && res.data && res.data.result == 'ok') {
// reset the "new" form
$scope.models_categories.new_models_category_name = '';
$scope.models_categories.new_models_category_description = '';
// reload models categories list
$scope.models_categories.load();
} else {
alert('Error adding new models category');
}
}, function() {
alert('Network error');
});
},
update: function(modelsCategoryId) {
// find the model category in the data
var name = false, description;
$scope.models_categories.data.forEach(function(modelsCategoryData) {
if (modelsCategoryData.id == modelsCategoryId) {
name = modelsCategoryData.name;
description = modelsCategoryData.description;
}
});
if (name === false) {
alert('Cannot find the model category');
return false;
}
$http({
method: 'post',
url: 'api/update_models_category.php',
data: {
id: modelsCategoryId,
name: name,
description: description
}
}).then(function(res) {
if (res && res.data && res.data.result == 'ok') {
// reload models categories list
$scope.models_categories.load();
} else {
alert('Error updating the models category');
}
}, function() {
alert('Network error');
});
},
delete: function(modelsCategoryId) {
if (!modelsCategoryId || !confirm('Delete?')) {
return;
}
$scope.models_categories.inProgress = true;
$http({
method: 'post',
url: 'api/delete_models_category.php',
data: {
id: modelsCategoryId
}
}).then(function(res) {
if (res && res.data && res.data.result == 'ok') {
// .. success
$scope.models_categories.load();
} else {
alert('Error adding new models category');
}
}, function() {
alert('Network error');
}).finally(function() {
$scope.models_categories.inProgress = false;
});
},
load: function() {
modelsCategoriesService.load(function(modelsCategories) {
$scope.models_categories.data = modelsCategories;
}, 'forceReload = true');
}
};
$rootScope.$watch('hasRestrictedAccess', function(hasRestrictedAccess) {
if (hasRestrictedAccess) {
$scope.models_categories.load();
}
});
}]);
|
'use strict';
import { REQUEST_TIMEOUT } from '../lib/constants';
import { default as baseRequest } from 'request';
import { default as moment } from 'moment-timezone';
import cheerio from 'cheerio';
import proj4 from 'proj4';
import epsg from 'proj4js-defs';
import { convertUnits, acceptableParameters } from '../lib/utils';
const request = baseRequest.defaults({timeout: REQUEST_TIMEOUT});
// Load all the EPSG definitions
epsg(proj4);
export const name = 'eea';
exports.fetchData = function (source, cb) {
// Because we're getting the data async, make a top-level timeout
// to keep things from going on forever. Default to 7 minutes
const timeoutId = setTimeout(() => {
return cb({message: 'Failure to receive data from EEA system.'});
}, (process.env.EEA_GLOBAL_TIMEOUT || 360) * 1000);
// Unsure of how date is exactly handled by the EEA system, the adapter
// applies a generous buffer to the toDate and fromDate
let fromDate = moment.utc().subtract(12, 'hour').format('YYYY-MM-DD+HH[%3A]mm');
let toDate = moment.utc().add(1, 'hour').format('YYYY-MM-DD+HH[%3A]mm');
// Only ask for the pollutants we want
let pollutants = acceptableParameters.map((p) => {
// https://github.com/openaq/openaq-fetch/issues/202
if (p === 'pm25') { p = 'PM2.5'; }
return p.toUpperCase();
});
pollutants = pollutants.join();
let finalUrl = `http://fme.discomap.eea.europa.eu/fmedatastreaming/AirQuality/AirQualityUTDExport.fmw?FromDate=${fromDate}&ToDate=${toDate}&Countrycode=${source.country}&Pollutant=${pollutants}&Format=XML&UserToken=${process.env.EEA_TOKEN}&RunAsync=True`;
request(finalUrl, function (err, res, body) {
if (err || res.statusCode !== 200) {
return cb({message: 'Failure to receive job ID from EEA.'});
}
// Since we're asking for the data asynchronously, keep checking for
// results every few seconds.
const $ = cheerio.load(body, {xmlMode: true});
let checkerId;
checkerId = setInterval(() => {
request($('ResultURL').text(), (err, res, body) => {
if (err) {
return cb({message: 'Failure to load EEA job result.'});
}
// Check to see if data is ready yet
const $ = cheerio.load(body, {xmlMode: true});
if ($('Code').text() !== 'BlobNotFound') {
// Cancel the timers
clearInterval(checkerId);
clearTimeout(timeoutId);
// Wrap everything in a try/catch in case something goes wrong
try {
// Format the data
var data = formatData(body);
} catch (e) {
return cb({message: 'Unknown adapter error.'});
}
// Make sure data is valid
if (data === undefined) {
return cb({message: 'Failure to parse data.'});
}
cb(null, data);
}
});
}, (process.env.EEA_ASYNC_RECHECK || 60) * 1000);
});
};
// Loop over measurements, adding station data and saving to database.
const formatData = (body) => {
let $ = cheerio.load(body, {xmlMode: true});
// Reproject if necessary
// EPSG:4979 is the correct projection, but not found in EPSG definition file
const parseCoordinates = function (x, y, from) {
if (from === 'EPSG:4979') {
return [x, y];
} else {
return proj4(proj4.defs(from), proj4.defs('EPSG:4326'), [x, y]);
}
};
// Return date object given local date and timezone url
const getDate = function (date, timezone) {
// For offset, we're making use of the fact that moment.js picks up first string
// like +02 in the provided url
const mo = moment.utc(date, 'YYYY-MM-DD HH:mm:ss').utcOffset(timezone, true);
return {utc: mo.toDate(), local: mo.format('YYYY-MM-DDTHH:mm:ssZ')};
};
let measurements = [];
// Loop over each <record> in the XML and store the measurement
$('record', 'records').each(function (i, elem) {
// If it's not a parameter we want, can skip the rest
const parameter = $('pollutant', this).text().replace('.', '').toLowerCase();
if (acceptableParameters.indexOf(parameter) === -1) {
return;
}
let coordinates = parseCoordinates($('samplingpoint_point', this).attr('x'), $('samplingpoint_point', this).attr('y'), $('samplingpoint_point', this).attr('coordsys'));
let m = {
date: getDate($('value_datetime_end', this).text(), $('network_timezone', this).text()),
parameter: parameter,
location: $('station_name', this).text(),
value: Number($('value_numeric', this).text()),
unit: $('value_numeric', this).attr('unit'),
city: $('network_name', this).text().replace(/"/g, ''),
averagingPeriod: {unit: 'hours', value: 1},
coordinates: {
latitude: Number(coordinates[1]),
longitude: Number(coordinates[0])
},
attribution: [{
name: 'European Environmental Agency',
url: 'http://www.eea.europa.eu/themes/air/air-quality'
}]
};
measurements.push(m);
});
// Make sure units are correct
measurements = convertUnits(measurements);
// Ship it off to be saved!
return {name: 'unused', measurements: measurements};
};
|
export {
default as PageQuestionnaire
} from './containers/page-questionnaire-container';
|
import Component from '@ember/component'
import { computed } from '@ember/object'
import hbs from 'htmlbars-inline-precompile'
/**
* Core card.
*
* ```handlebars
* {{#rad-card as |components|}}
* {{#components.block}}
* {{#components.title}}Card title{{/components.title}}
* Card body
* {{/components.block}}
* {{#components.footer}}Card footer{{/components.footer}}
* {{/rad-card}}
* ```
*
* {{#rad-card as |components|}}
* {{#components.block}}
* {{#components.title}}Party Time{{/components.title}}
* <img src="http://i.giphy.com/125RIkH7IluIpy.gif"/>
* {{/components.block}}
* {{/rad-card}}
*
* @class Component.RadCard
* @constructor
* @extends Ember.Component
*/
export default Component.extend({
// Props
// ---------------------------------------------------------------------------
/**
* Pass a brand to use to style the component and it's child components.
* @property brand
* @type {string}
* @default ''
*/
brand: '',
// Default Component References
// ---------------------------------------------------------------------------
/**
* @property blockComponent
* @type {string}
* @passed
* @optional
* @default 'rad-classnamed'
*/
blockComponent: 'rad-classnamed',
/**
* @property bodyComponent
* @deprecated
* @type {string}
* @passed
* @optional
* @default 'rad-classnamed'
*/
bodyComponent: 'rad-classnamed',
/**
* @property footerComponent
* @type {string}
* @passed
* @optional
* @default 'rad-classnamed'
*/
footerComponent: 'rad-classnamed',
/**
* @property headerComponent
* @type {string}
* @passed
* @optional
* @default 'rad-classnamed'
*/
headerComponent: 'rad-classnamed',
/**
* @property titleComponent
* @type {string}
* @passed
* @optional
* @default 'rad-classnamed'
*/
titleComponent: 'rad-classnamed',
// Properties
// ---------------------------------------------------------------------------
/**
* @property attributeBindings
* @type {Array}
* @default 'data-test'
*/
attributeBindings: ['data-test'],
/**
* Computed css class for the brand bound to the component.
* TODO: v2 remove card-default
* @property brandClass
* @type {String}
*/
brandClass: computed(function() {
return this.brand ? `card-${this.brand}` : 'card-default';
}),
/**
* @property classNames
* @type {Array}
* @default 'card rad-card'
*/
classNames: ['card', 'rad-card'],
/**
* Bind props to classes on the root component element.
* @property classNameBindings
* @type {Array}
*/
classNameBindings: ['brandClass'],
// Layout
// ---------------------------------------------------------------------------
layout: hbs`
{{! TODO: make title an h4 by default in v2, old titles should actually be
headers in v2 }}
{{yield (hash
block=(component blockComponent
_classNames='card-block'
data-test=(if data-test (concat data-test '-block')))
body=(component bodyComponent
_classNames='card-block card-body'
data-test=(if data-test (concat data-test '-body')))
footer=(component footerComponent
_classNames='card-footer'
data-test=(if data-test (concat data-test '-footer')))
header=(component headerComponent
_classNames='card-header'
data-test=(if data-test (concat data-test '-header')))
title=(component titleComponent
_classNames='card-title'
tagName='div'
data-test=(if data-test (concat data-test '-title')))
)}}
`,
})
|
// flow-typed signature: 30d9c3ac4977136c992cb91299f08b2b
// flow-typed version: <<STUB>>/node-forge_v0.7.4/flow_v0.61.0
/**
* This is an autogenerated libdef stub for:
*
* 'node-forge'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'node-forge' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'node-forge/dist/forge.all.min' {
declare module.exports: any;
}
declare module 'node-forge/dist/forge.min' {
declare module.exports: any;
}
declare module 'node-forge/dist/prime.worker.min' {
declare module.exports: any;
}
declare module 'node-forge/lib/aes' {
declare module.exports: any;
}
declare module 'node-forge/lib/aesCipherSuites' {
declare module.exports: any;
}
declare module 'node-forge/lib/asn1' {
declare module.exports: any;
}
declare module 'node-forge/lib/baseN' {
declare module.exports: any;
}
declare module 'node-forge/lib/cipher' {
declare module.exports: any;
}
declare module 'node-forge/lib/cipherModes' {
declare module.exports: any;
}
declare module 'node-forge/lib/debug' {
declare module.exports: any;
}
declare module 'node-forge/lib/des' {
declare module.exports: any;
}
declare module 'node-forge/lib/ed25519' {
declare module.exports: any;
}
declare module 'node-forge/lib/forge' {
declare module.exports: any;
}
declare module 'node-forge/lib/form' {
declare module.exports: any;
}
declare module 'node-forge/lib/hmac' {
declare module.exports: any;
}
declare module 'node-forge/lib/http' {
declare module.exports: any;
}
declare module 'node-forge/lib/index.all' {
declare module.exports: any;
}
declare module 'node-forge/lib/index' {
declare module.exports: any;
}
declare module 'node-forge/lib/jsbn' {
declare module.exports: any;
}
declare module 'node-forge/lib/kem' {
declare module.exports: any;
}
declare module 'node-forge/lib/log' {
declare module.exports: any;
}
declare module 'node-forge/lib/md.all' {
declare module.exports: any;
}
declare module 'node-forge/lib/md' {
declare module.exports: any;
}
declare module 'node-forge/lib/md5' {
declare module.exports: any;
}
declare module 'node-forge/lib/mgf' {
declare module.exports: any;
}
declare module 'node-forge/lib/mgf1' {
declare module.exports: any;
}
declare module 'node-forge/lib/oids' {
declare module.exports: any;
}
declare module 'node-forge/lib/pbe' {
declare module.exports: any;
}
declare module 'node-forge/lib/pbkdf2' {
declare module.exports: any;
}
declare module 'node-forge/lib/pem' {
declare module.exports: any;
}
declare module 'node-forge/lib/pkcs1' {
declare module.exports: any;
}
declare module 'node-forge/lib/pkcs12' {
declare module.exports: any;
}
declare module 'node-forge/lib/pkcs7' {
declare module.exports: any;
}
declare module 'node-forge/lib/pkcs7asn1' {
declare module.exports: any;
}
declare module 'node-forge/lib/pki' {
declare module.exports: any;
}
declare module 'node-forge/lib/prime' {
declare module.exports: any;
}
declare module 'node-forge/lib/prime.worker' {
declare module.exports: any;
}
declare module 'node-forge/lib/prng' {
declare module.exports: any;
}
declare module 'node-forge/lib/pss' {
declare module.exports: any;
}
declare module 'node-forge/lib/random' {
declare module.exports: any;
}
declare module 'node-forge/lib/rc2' {
declare module.exports: any;
}
declare module 'node-forge/lib/rsa' {
declare module.exports: any;
}
declare module 'node-forge/lib/sha1' {
declare module.exports: any;
}
declare module 'node-forge/lib/sha256' {
declare module.exports: any;
}
declare module 'node-forge/lib/sha512' {
declare module.exports: any;
}
declare module 'node-forge/lib/socket' {
declare module.exports: any;
}
declare module 'node-forge/lib/ssh' {
declare module.exports: any;
}
declare module 'node-forge/lib/task' {
declare module.exports: any;
}
declare module 'node-forge/lib/tls' {
declare module.exports: any;
}
declare module 'node-forge/lib/tlssocket' {
declare module.exports: any;
}
declare module 'node-forge/lib/util' {
declare module.exports: any;
}
declare module 'node-forge/lib/x509' {
declare module.exports: any;
}
declare module 'node-forge/lib/xhr' {
declare module.exports: any;
}
// Filename aliases
declare module 'node-forge/dist/forge.all.min.js' {
declare module.exports: $Exports<'node-forge/dist/forge.all.min'>;
}
declare module 'node-forge/dist/forge.min.js' {
declare module.exports: $Exports<'node-forge/dist/forge.min'>;
}
declare module 'node-forge/dist/prime.worker.min.js' {
declare module.exports: $Exports<'node-forge/dist/prime.worker.min'>;
}
declare module 'node-forge/lib/aes.js' {
declare module.exports: $Exports<'node-forge/lib/aes'>;
}
declare module 'node-forge/lib/aesCipherSuites.js' {
declare module.exports: $Exports<'node-forge/lib/aesCipherSuites'>;
}
declare module 'node-forge/lib/asn1.js' {
declare module.exports: $Exports<'node-forge/lib/asn1'>;
}
declare module 'node-forge/lib/baseN.js' {
declare module.exports: $Exports<'node-forge/lib/baseN'>;
}
declare module 'node-forge/lib/cipher.js' {
declare module.exports: $Exports<'node-forge/lib/cipher'>;
}
declare module 'node-forge/lib/cipherModes.js' {
declare module.exports: $Exports<'node-forge/lib/cipherModes'>;
}
declare module 'node-forge/lib/debug.js' {
declare module.exports: $Exports<'node-forge/lib/debug'>;
}
declare module 'node-forge/lib/des.js' {
declare module.exports: $Exports<'node-forge/lib/des'>;
}
declare module 'node-forge/lib/ed25519.js' {
declare module.exports: $Exports<'node-forge/lib/ed25519'>;
}
declare module 'node-forge/lib/forge.js' {
declare module.exports: $Exports<'node-forge/lib/forge'>;
}
declare module 'node-forge/lib/form.js' {
declare module.exports: $Exports<'node-forge/lib/form'>;
}
declare module 'node-forge/lib/hmac.js' {
declare module.exports: $Exports<'node-forge/lib/hmac'>;
}
declare module 'node-forge/lib/http.js' {
declare module.exports: $Exports<'node-forge/lib/http'>;
}
declare module 'node-forge/lib/index.all.js' {
declare module.exports: $Exports<'node-forge/lib/index.all'>;
}
declare module 'node-forge/lib/index.js' {
declare module.exports: $Exports<'node-forge/lib/index'>;
}
declare module 'node-forge/lib/jsbn.js' {
declare module.exports: $Exports<'node-forge/lib/jsbn'>;
}
declare module 'node-forge/lib/kem.js' {
declare module.exports: $Exports<'node-forge/lib/kem'>;
}
declare module 'node-forge/lib/log.js' {
declare module.exports: $Exports<'node-forge/lib/log'>;
}
declare module 'node-forge/lib/md.all.js' {
declare module.exports: $Exports<'node-forge/lib/md.all'>;
}
declare module 'node-forge/lib/md.js' {
declare module.exports: $Exports<'node-forge/lib/md'>;
}
declare module 'node-forge/lib/md5.js' {
declare module.exports: $Exports<'node-forge/lib/md5'>;
}
declare module 'node-forge/lib/mgf.js' {
declare module.exports: $Exports<'node-forge/lib/mgf'>;
}
declare module 'node-forge/lib/mgf1.js' {
declare module.exports: $Exports<'node-forge/lib/mgf1'>;
}
declare module 'node-forge/lib/oids.js' {
declare module.exports: $Exports<'node-forge/lib/oids'>;
}
declare module 'node-forge/lib/pbe.js' {
declare module.exports: $Exports<'node-forge/lib/pbe'>;
}
declare module 'node-forge/lib/pbkdf2.js' {
declare module.exports: $Exports<'node-forge/lib/pbkdf2'>;
}
declare module 'node-forge/lib/pem.js' {
declare module.exports: $Exports<'node-forge/lib/pem'>;
}
declare module 'node-forge/lib/pkcs1.js' {
declare module.exports: $Exports<'node-forge/lib/pkcs1'>;
}
declare module 'node-forge/lib/pkcs12.js' {
declare module.exports: $Exports<'node-forge/lib/pkcs12'>;
}
declare module 'node-forge/lib/pkcs7.js' {
declare module.exports: $Exports<'node-forge/lib/pkcs7'>;
}
declare module 'node-forge/lib/pkcs7asn1.js' {
declare module.exports: $Exports<'node-forge/lib/pkcs7asn1'>;
}
declare module 'node-forge/lib/pki.js' {
declare module.exports: $Exports<'node-forge/lib/pki'>;
}
declare module 'node-forge/lib/prime.js' {
declare module.exports: $Exports<'node-forge/lib/prime'>;
}
declare module 'node-forge/lib/prime.worker.js' {
declare module.exports: $Exports<'node-forge/lib/prime.worker'>;
}
declare module 'node-forge/lib/prng.js' {
declare module.exports: $Exports<'node-forge/lib/prng'>;
}
declare module 'node-forge/lib/pss.js' {
declare module.exports: $Exports<'node-forge/lib/pss'>;
}
declare module 'node-forge/lib/random.js' {
declare module.exports: $Exports<'node-forge/lib/random'>;
}
declare module 'node-forge/lib/rc2.js' {
declare module.exports: $Exports<'node-forge/lib/rc2'>;
}
declare module 'node-forge/lib/rsa.js' {
declare module.exports: $Exports<'node-forge/lib/rsa'>;
}
declare module 'node-forge/lib/sha1.js' {
declare module.exports: $Exports<'node-forge/lib/sha1'>;
}
declare module 'node-forge/lib/sha256.js' {
declare module.exports: $Exports<'node-forge/lib/sha256'>;
}
declare module 'node-forge/lib/sha512.js' {
declare module.exports: $Exports<'node-forge/lib/sha512'>;
}
declare module 'node-forge/lib/socket.js' {
declare module.exports: $Exports<'node-forge/lib/socket'>;
}
declare module 'node-forge/lib/ssh.js' {
declare module.exports: $Exports<'node-forge/lib/ssh'>;
}
declare module 'node-forge/lib/task.js' {
declare module.exports: $Exports<'node-forge/lib/task'>;
}
declare module 'node-forge/lib/tls.js' {
declare module.exports: $Exports<'node-forge/lib/tls'>;
}
declare module 'node-forge/lib/tlssocket.js' {
declare module.exports: $Exports<'node-forge/lib/tlssocket'>;
}
declare module 'node-forge/lib/util.js' {
declare module.exports: $Exports<'node-forge/lib/util'>;
}
declare module 'node-forge/lib/x509.js' {
declare module.exports: $Exports<'node-forge/lib/x509'>;
}
declare module 'node-forge/lib/xhr.js' {
declare module.exports: $Exports<'node-forge/lib/xhr'>;
}
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Utility functions.
*/
/** Alias of window.console.log() */
var debug = window.console.debug.bind(window.console);
var info = window.console.info.bind(window.console);
var error = window.console.error.bind(window.console);
var assert = window.console.assert.bind(window.console);
/** Creates a mixin class. */
function applyMixins(derivedCtor, baseCtors) {
baseCtors.forEach(function (baseCtor) {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {
derivedCtor.prototype[name] = baseCtor.prototype[name];
});
});
}
/** Simulates the C fmod() function. */
function fmod(x, y) {
var v = x % y;
return (0 <= v) ? v : v + y;
}
/** Alias of Math.floor */
var int = Math.floor;
/** Alias of Math.min */
var upperbound = Math.min;
/** Alias of Math.max */
var lowerbound = Math.max;
/** Limits the value so that v0 <= v <= v1.
* @param v0 Minimum value.
* @param v Number to limit.
* @param v1 Maximum value.
*/
function clamp(v0, v, v1) {
return Math.min(Math.max(v, v0), v1);
}
/** Returns -1, 0, or +1 depending on the sign. */
function sign(v) {
if (v < 0) {
return -1;
}
else if (0 < v) {
return +1;
}
else {
return 0;
}
}
/** Returns the phase for t with the given interval.
* @param t Current time.
* @param interval Interval.
* @param n Number of phrases.
*/
function phase(t, interval, n) {
if (n === void 0) { n = 2; }
if (interval === 0)
return 0;
return int(n * t / interval) % n;
}
/** Linear interpolation.
* @param t Current time.
* @param a Start value.
* @param b End value.
*/
function lerp(t, a, b) {
return a + t * (b - a);
}
/** Generates a random number in [0,a) or [a,b). */
function frnd(a, b) {
if (b === void 0) { b = 0; }
if (b < a) {
var c = a;
a = b;
b = c;
}
return a + (Math.random() * (b - a));
}
/** Generates an integer random number in [0,a) or [a,b). */
function rnd(a, b) {
if (b === void 0) { b = 0; }
return int(frnd(a, b));
}
/** Return the current time in seconds. */
function getTime() {
return Date.now() * 0.001;
}
/** Returns a pretty printed string.
* @param v Number to format.
* @param n Number of digits to fill.
* @param c Filler character.
*/
function format(v, n, c) {
if (n === void 0) { n = 3; }
if (c === void 0) { c = ' '; }
var s = '';
while (s.length < n) {
s = (v % 10) + s;
v = int(v / 10);
if (v <= 0)
break;
}
while (s.length < n) {
s = c + s;
}
return s;
}
/** Picks a random element. */
function choice(a) {
return a[rnd(a.length)];
}
/** Removes an element. */
function removeElement(a, obj) {
var i = a.indexOf(obj);
if (0 <= i) {
a.splice(i, 1);
}
return a;
}
/** Returns an array filled with a sequence. */
function range(n) {
var a = Array.apply(null, new Array(n));
return a.map(function (_, i) { return i; });
}
/** Creates an array from a string.
* @param s Source string.
* @param f Conversion function.
*/
function str2array(s, f) {
if (f === void 0) { f = parseInt; }
var a = new Int32Array(s.length);
for (var i = 0; i < s.length; i++) {
a[i] = f(s[i]);
}
return a;
}
/** Creates a 2D array for a given size.
* @param rows Number of rows.
* @param cols Number of columns.
* @param value Initial value (default=0).
*/
function makeMatrix(rows, cols, value) {
if (value === void 0) { value = 0; }
return range(rows).map(function () {
return new Int32Array(cols).fill(value);
});
}
/** Removes all child DOM Nodes with the given name.
* @param node Parent DOM Node.
* @param name Name of child Nodes to be removed.
*/
function removeChildren(node, name) {
name = name.toLowerCase();
// Iterate backwards to simplify array removal. (thanks to @the31)
for (var i = node.childNodes.length - 1; 0 <= i; i--) {
var c = node.childNodes[i];
if (c.nodeName.toLowerCase() === name) {
node.removeChild(c);
}
}
}
/** Creates a canvas with the given size.
* @param width Width.
* @param height Height.
*/
function createCanvas(width, height) {
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
/** Creates a pixellated canvas 2D context.
* @param canvas Target Canvas object.
*/
function getEdgeyContext(canvas) {
var ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.mozImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
return ctx;
}
/** Creates a 2D array from an image. */
function image2array(img, header) {
if (header === void 0) { header = 0; }
var width = img.width;
var height = img.height;
var canvas = createCanvas(width, height);
var ctx = getEdgeyContext(canvas);
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, width, height).data;
var i = 0;
var c2v = null;
if (0 < header) {
c2v = {};
for (var y = 0; y < header; y++) {
for (var x = 0; x < width; x++, i += 4) {
var c = ((data[i] << 16) | (data[i + 1] << 8) | data[i + 2]); // RGBA
if (!c2v.hasOwnProperty(c.toString())) {
c2v[c] = y * width + x;
}
}
}
}
var map = new Array(height - header);
for (var y = 0; y < height - header; y++) {
var a = new Int32Array(width);
for (var x = 0; x < width; x++, i += 4) {
var c = ((data[i] << 16) | (data[i + 1] << 8) | data[i + 2]); // RGBA
a[x] = (c2v !== null) ? c2v[c] : c;
}
map[y] = a;
}
return map;
}
/** Fill a rectangle.
* @param ctx Context to draw.
* @param rect Rectangle.
*/
function fillRect(ctx, rect) {
ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
}
/** Draw a rectangle.
* @param ctx Context to draw.
* @param rect Rectangle.
*/
function strokeRect(ctx, rect) {
ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
}
/** Draw an ellipse.
* @param ctx Context to draw.
* @param cx Center X.
* @param cy Center Y.
* @param rx Radius X.
* @param ry Radius Y.
*/
function ellipse(ctx, cx, cy, rx, ry) {
ctx.save();
ctx.translate(cx, cy);
if (ry < rx) {
ctx.scale(1, ry / rx);
}
else {
ctx.scale(rx / ry, 1);
}
ctx.arc(0, 0, Math.max(rx, ry), 0, Math.PI * 2);
ctx.restore();
}
/** Draw a scaled image.
* When the destination width/height is negative,
* the image is flipped.
* @param ctx Context to draw.
* @param src Source image.
* @param sx Source rectangle X.
* @param sy Source rectangle Y.
* @param sw Source rectangle width.
* @param sh Source rectangle height.
* @param dx Destination rectangle X.
* @param dy Destination rectangle Y.
* @param dw Destination rectangle width.
* @param dh Destination rectangle height.
*/
function drawImageScaled(ctx, src, sx, sy, sw, sh, dx, dy, dw, dh) {
ctx.save();
ctx.translate(dx + ((0 < dw) ? 0 : -dw), dy + ((0 < dh) ? 0 : -dh));
ctx.scale((0 < dw) ? 1 : -1, (0 < dh) ? 1 : -1);
ctx.drawImage(src, sx, sy, sw, sh, 0, 0, Math.abs(dw), Math.abs(dh));
ctx.restore();
}
/** Key Symbol */
var KeySym;
(function (KeySym) {
KeySym[KeySym["Unknown"] = 0] = "Unknown";
KeySym[KeySym["Left"] = 1] = "Left";
KeySym[KeySym["Right"] = 2] = "Right";
KeySym[KeySym["Up"] = 3] = "Up";
KeySym[KeySym["Down"] = 4] = "Down";
KeySym[KeySym["Action1"] = 5] = "Action1";
KeySym[KeySym["Action2"] = 6] = "Action2";
KeySym[KeySym["Cancel"] = 7] = "Cancel";
})(KeySym || (KeySym = {}));
/** Returns the key symbol for the key.
* cf. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
*/
function getKeySym(keyCode) {
switch (keyCode) {
case 37: // LEFT
case 65: // A
case 72: // H
case 81: // Q (AZERTY)
return KeySym.Left;
case 39: // RIGHT
case 68: // D
case 76: // L
return KeySym.Right;
case 38: // UP
case 87: // W
case 75: // K
case 90: // Z (AZERTY)
return KeySym.Up;
case 40: // DOWN
case 83: // S
case 74: // J
return KeySym.Down;
case 16: // SHIFT
case 32: // SPACE
case 88: // X
return KeySym.Action1;
case 13: // ENTER
case 69: // E
case 67: // C
return KeySym.Action2;
case 8: // BACKSPACE
case 27: // ESCAPE
return KeySym.Cancel;
default:
return KeySym.Unknown;
}
}
/** Subscribable event object.
* A Signal object can have multiple receivers.
*/
var Signal = /** @class */ (function () {
/** Creates a new Signal.
* @param params Base arguments.
*/
function Signal() {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
/** List of receivers. */
this.receivers = [];
this.baseargs = Array.prototype.slice.call(arguments);
}
Signal.prototype.toString = function () {
return ('<Signal(' + this.baseargs + ') ' + this.receivers + '>');
};
/** Adds a receiver function for the signal.
* @param recv Receiver function to add.
*/
Signal.prototype.subscribe = function (recv) {
this.receivers.push(recv);
};
/** Removes a receiver function for the signal.
* @param recv Receiver function to remove.
*/
Signal.prototype.unsubscribe = function (recv) {
removeElement(this.receivers, recv);
};
/** Notifies all the receivers with the given arguments.
* @param params Extra arguments.
*/
Signal.prototype.fire = function () {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
for (var _a = 0, _b = this.receivers; _a < _b.length; _a++) {
var receiver = _b[_a];
var args = Array.prototype.slice.call(arguments);
receiver.apply(null, this.baseargs.concat(args));
}
};
return Signal;
}());
/** Convenience object for generating/mixing RGB values.
*/
var Color = /** @class */ (function () {
/** Creates a new Color.
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
function Color(r, g, b, a) {
if (a === void 0) { a = 1.0; }
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
/** Generates a Color value.
* @param h Hue.
* @param v Brightness.
*/
Color.generate = function (h, v) {
if (v === void 0) { v = 1.0; }
h *= 2 * Math.PI;
v *= 0.5;
return new Color((Math.sin(h) + 1) * v, (Math.sin(h + 2 * Math.PI / 3) + 1) * v, (Math.sin(h + 4 * Math.PI / 3) + 1) * v, 1.0);
};
Color.prototype.toString = function () {
if (0 <= this.a) {
return ('rgba(' +
int(255 * clamp(0, this.r, 1)) + ',' +
int(255 * clamp(0, this.g, 1)) + ',' +
int(255 * clamp(0, this.b, 1)) + ',' +
clamp(0, this.a, 1) + ')');
}
else {
return ('rgb(' +
int(255 * clamp(0, this.r, 1)) + ',' +
int(255 * clamp(0, this.g, 1)) + ',' +
int(255 * clamp(0, this.b, 1)) + ')');
}
};
/** Changes the alpha value. */
Color.prototype.setAlpha = function (a) {
return new Color(this.r, this.g, this.b, a);
};
/** Multiplies the brightness. */
Color.prototype.multiply = function (t) {
return new Color(this.r * t, this.g * t, this.b * t, this.a);
};
/** Blends with another Color.
* @param color Color to bland.
* @param t Blending ratio.
*/
Color.prototype.blend = function (color, t) {
return new Color(this.r * (1 - t) + color.r * t, this.g * (1 - t) + color.g * t, this.b * (1 - t) + color.b * t, this.a * (1 - t) + color.a * t);
};
return Color;
}());
/** Simplified Perlin Noise function.
*/
var PERMS = [
28, 25, 0, 12, 2, 33, 59, 26, 62, 7, 9, 39, 66, 10, 57, 1, 58,
15, 56, 77, 70, 47, 96, 93, 53, 84, 80, 76, 67, 64, 30, 92, 88, 91,
74, 51, 8, 86, 97, 82, 38, 65, 17, 18, 52, 81, 87, 21, 61, 34, 68, 35,
71, 3, 16, 4, 27, 19, 13, 37, 41, 60, 83, 43, 31, 23, 14, 32, 48, 98,
50, 99, 36, 5, 54, 20, 49, 45, 72, 29, 42, 75, 44, 89, 6, 46, 94, 78,
90, 73, 95, 79, 85, 63, 55, 24, 69, 22, 40, 11
];
function perm(t) { return PERMS[t % PERMS.length]; }
function fade(t) { return t * t * t * (t * (t * 6 - 15) + 10); }
function grad(h, p, q) {
return ((h & 1) == 0 ? p : -p) + ((h & 2) == 0 ? q : -q);
}
function noise2d(x, y) {
var bx = Math.floor(x);
var by = Math.floor(y);
var dx = x - bx;
var dy = y - by;
var u = fade(dx);
var v = fade(dy);
var a = perm(bx);
var b = perm(bx + 1);
var s = lerp(v, lerp(u, grad(perm(a + by), dx, dy), grad(perm(b + by), dx - 1, dy)), lerp(u, grad(perm(a + by + 1), dx, dy - 1), grad(perm(b + by + 1), dx - 1, dy - 1)));
return (s + 1) / 2.0;
}
/// <reference path="utils.ts" />
/**
* Geometric objects and functions.
*/
/** Sufficiently small number that can be considered as zero. */
var EPSILON = 0.0001;
/** Vec2
* 2-element vector that can be used for a position or size.
*/
var Vec2 = /** @class */ (function () {
function Vec2(x, y) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
this.x = x;
this.y = y;
}
Vec2.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
/** Returns a copy of the object. */
Vec2.prototype.copy = function () {
return new Vec2(this.x, this.y);
};
/** Returns true if p is equivalent to the object. */
Vec2.prototype.equals = function (p) {
return (this.x == p.x && this.y == p.y);
};
/** Returns true if p.x == 0 and p.y == 0. */
Vec2.prototype.isZero = function () {
return (this.x == 0 && this.y == 0);
};
/** Returns the squared length of the vector. */
Vec2.prototype.len2 = function () {
return (this.x * this.x + this.y * this.y);
};
/** Returns the length of the vector. */
Vec2.prototype.len = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/** Returns a new vector consisting of the sign of each element. */
Vec2.prototype.sign = function () {
return new Vec2(sign(this.x), sign(this.y));
};
/** Returns a new vector (this + v). */
Vec2.prototype.add = function (v) {
return new Vec2(this.x + v.x, this.y + v.y);
};
/** Returns a new vector (this - v). */
Vec2.prototype.sub = function (v) {
return new Vec2(this.x - v.x, this.y - v.y);
};
/** Returns a new scaled vector by n. */
Vec2.prototype.scale = function (n) {
return new Vec2(this.x * n, this.y * n);
};
/** Returns |this - p|. */
Vec2.prototype.distance = function (p) {
return this.sub(p).len();
};
/** Clamp the position within a given rectangle. */
Vec2.prototype.clamp = function (bounds) {
return new Vec2(clamp(-bounds.x, this.x, +bounds.x), clamp(-bounds.y, this.y, +bounds.y));
};
/** Returns a new point that is moved by (dx, dy). */
Vec2.prototype.move = function (dx, dy) {
return new Vec2(this.x + dx, this.y + dy);
};
/** Returns a new interpolated vector between this and p.
* @param p The other point.
* @param t Interpolation value.
* When t=0.0 the new vector would be the same as this.
* When t=1.0 the new vector would be the same as p.
*/
Vec2.prototype.lerp = function (p, t) {
return new Vec2(lerp(t, this.x, p.x), lerp(t, this.y, p.y));
};
/** Returns a new vector rotated clockwise by d radian. */
Vec2.prototype.rotate = function (d) {
var s = Math.sin(d);
var c = Math.cos(d);
return new Vec2(this.x * c - this.y * s, this.x * s + this.y * c);
};
/** Returns a new vector rotated clockwise by d*90 degree. */
Vec2.prototype.rot90 = function (d) {
d = d % 4;
d = (0 <= d) ? d : d + 4;
switch (d) {
case 1:
return new Vec2(-this.y, this.x);
case 2:
return new Vec2(-this.x, -this.y);
case 3:
return new Vec2(this.y, -this.x);
default:
return this.copy();
}
};
/** Create a new rectangle based on this point.
* @param dw Width.
* @param dh Height.
*/
Vec2.prototype.inflate = function (dw, dh) {
return this.expand(dw * 2, dh * 2);
};
/** Create a new rectangle based on this point.
* @param dw Width.
* @param dh Height.
* @param anchor Anchor point.
*/
Vec2.prototype.expand = function (dw, dh, anchor) {
if (anchor === void 0) { anchor = 'c'; }
return new Rect(this.x, this.y).expand(dw, dh, anchor);
};
return Vec2;
}());
/** Vec3
* 3-element vector that can be used for a position or size.
*/
var Vec3 = /** @class */ (function () {
function Vec3(x, y, z) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
if (z === void 0) { z = 0; }
this.x = x;
this.y = y;
this.z = z;
}
Vec3.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ', ' + this.z + ')';
};
/** Returns a copy of the object. */
Vec3.prototype.copy = function () {
return new Vec3(this.x, this.y, this.z);
};
/** Returns true if p is equivalent to the object. */
Vec3.prototype.equals = function (p) {
return (this.x == p.x && this.y == p.y && this.z == p.z);
};
/** Returns true if p.x == 0, p.y == 0 and p.z == 0. */
Vec3.prototype.isZero = function () {
return (this.x == 0 && this.y == 0 && this.z == 0);
};
/** Returns the squared length of the vector. */
Vec3.prototype.len2 = function () {
return (this.x * this.x + this.y * this.y + this.z * this.z);
};
/** Returns the length of the vector. */
Vec3.prototype.len = function () {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
};
/** Returns a new vector consisting of the sign of each element. */
Vec3.prototype.sign = function () {
return new Vec3(sign(this.x), sign(this.y), sign(this.z));
};
/** Returns a new vector (this + v). */
Vec3.prototype.add = function (v) {
return new Vec3(this.x + v.x, this.y + v.y, this.z + v.z);
};
/** Returns a new vector (this - v). */
Vec3.prototype.sub = function (v) {
return new Vec3(this.x - v.x, this.y - v.y, this.z - v.z);
};
/** Returns a new scaled vector by n. */
Vec3.prototype.scale = function (n) {
return new Vec3(this.x * n, this.y * n, this.z * n);
};
/** Returns |this - p|. */
Vec3.prototype.distance = function (p) {
return this.sub(p).len();
};
/** Clamp the position within a given rectangle. */
Vec3.prototype.clamp = function (bounds) {
return new Vec3(clamp(-bounds.x, this.x, +bounds.x), clamp(-bounds.y, this.y, +bounds.y), clamp(-bounds.z, this.z, +bounds.z));
};
/** Returns a new point that is moved by (dx, dy, dz). */
Vec3.prototype.move = function (dx, dy, dz) {
return new Vec3(this.x + dx, this.y + dy, this.z + dz);
};
/** Returns a new interpolated vector between this and p.
* @param p The other point.
* @param t Interpolation value.
* When t=0.0 the new vector would be the same as this.
* When t=1.0 the new vector would be the same as p.
*/
Vec3.prototype.lerp = function (p, t) {
return new Vec3(lerp(t, this.x, p.x), lerp(t, this.y, p.y), lerp(t, this.z, p.z));
};
return Vec3;
}());
/** AALine
* Axis-aligned line
*/
var AALine = /** @class */ (function () {
function AALine(x0, y0, x1, y1) {
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
}
/** Returns a copy of the object. */
AALine.prototype.copy = function () {
return new AALine(this.x0, this.y0, this.x1, this.y1);
};
/** Returns true if line is equivalent to the object. */
AALine.prototype.equals = function (line) {
return (this.x0 == line.x0 && this.y0 == line.y0 &&
this.x1 == line.x1 && this.y1 == line.y1);
};
/** Returns a new AALine that is moved by (dx, dy). */
AALine.prototype.move = function (dx, dy) {
return new AALine(this.x0 + dx, this.y0 + dy, this.x1 + dx, this.y1 + dy);
};
/** Returns a new AALine that is moved by v. */
AALine.prototype.add = function (v) {
return new AALine(this.x0 + v.x, this.y0 + v.y, this.x1 + v.x, this.y1 + v.y);
};
/** Returns a new AALine that is moved by -v. */
AALine.prototype.sub = function (v) {
return new AALine(this.x0 - v.x, this.y0 - v.y, this.x1 - v.x, this.y1 - v.y);
};
/** Returns true if the given object is overlapping with this line. */
AALine.prototype.overlaps = function (collider) {
if (collider instanceof Rect) {
return this.overlapsRect(collider);
}
else if (collider instanceof Circle) {
return this.overlapsCircle(collider);
}
else {
return false;
}
};
/** Returns true if the rect is overlapping with this line. */
AALine.prototype.overlapsRect = function (rect) {
return !(this.x1 < rect.x || this.y1 < rect.y ||
rect.x1() < this.x0 || rect.y1() < this.y0);
};
/** Returns true if the circle is overlapping with this line. */
AALine.prototype.overlapsCircle = function (circle) {
if (this.x1 <= circle.center.x - circle.radius ||
this.y1 <= circle.center.y - circle.radius ||
circle.center.x + circle.radius <= this.x0 ||
circle.center.y + circle.radius <= this.y0) {
return false;
}
return (this.x0 < circle.center.x && circle.center.x < this.x1 ||
this.y0 < circle.center.y && circle.center.y < this.y1 ||
circle.containsPt(new Vec2(this.x0, this.y0)) ||
circle.containsPt(new Vec2(this.x1, this.y1)));
};
/** Trims a vector so that the given object does not collide with this line. */
AALine.prototype.contact = function (v, collider) {
if (collider instanceof Rect) {
return this.contactRect(v, collider);
}
else if (collider instanceof Circle) {
return this.contactCircle(v, collider);
}
else {
return v;
}
};
/** Trims a vector so that the rect does not collide with this line. */
AALine.prototype.contactRect = function (v, rect) {
if (this.y0 == this.y1) {
return this.contactRectH(v, rect, this.y0);
}
else if (this.x0 == this.x1) {
return this.contactRectV(v, rect, this.x0);
}
else {
return v;
}
};
/** Calculate a contact point when this line is horizontal. */
AALine.prototype.contactRectH = function (v, rect, y) {
var y0 = rect.y;
var y1 = y0 + rect.height;
var dy;
if (y <= y0 && y0 + v.y < y) {
dy = y - y0;
}
else if (y1 <= y && y < y1 + v.y) {
dy = y - y1;
}
else {
return v;
}
var dx = v.x * dy / v.y;
var x0 = rect.x + dx;
var x1 = x0 + rect.width;
if (x1 < this.x0 || this.x1 < x0 ||
(x1 == this.x0 && v.x <= 0) ||
(x0 == this.x1 && 0 <= v.x)) {
return v;
}
return new Vec2(dx, dy);
};
/** Calculate a contact point when this line is vertical. */
AALine.prototype.contactRectV = function (v, rect, x) {
var x0 = rect.x;
var x1 = x0 + rect.width;
var dx;
if (x <= x0 && x0 + v.x < x) {
dx = x - x0;
}
else if (x1 <= x && x < x1 + v.x) {
dx = x - x1;
}
else {
return v;
}
var dy = v.y * dx / v.x;
var y0 = rect.y + dy;
var y1 = y0 + rect.height;
if (y1 < this.y0 || this.y1 < y0 ||
(y1 == this.y0 && v.y <= 0) ||
(y0 == this.y1 && 0 <= v.y)) {
return v;
}
return new Vec2(dx, dy);
};
/** Trims a vector so that the circle does not collide with this line. */
AALine.prototype.contactCircle = function (v, circle) {
if (this.y0 == this.y1) {
return this.contactCircleH(v, circle, this.y0);
}
else if (this.x0 == this.x1) {
return this.contactCircleV(v, circle, this.x0);
}
else {
return v;
}
};
/** Calculate a contact point when this line is horizontal. */
AALine.prototype.contactCircleH = function (v, circle, y) {
var x = circle.center.x + v.x;
if (this.x0 < x && x < this.x1) {
y += (v.y < 0) ? circle.radius : -circle.radius;
var dy = y - circle.center.y;
var dt = dy / v.y;
if (0 <= dt && dt <= 1) {
return new Vec2(v.x * dt, dy);
}
}
return v;
};
/** Calculate a contact point when this line is vertical. */
AALine.prototype.contactCircleV = function (v, circle, x) {
var y = circle.center.y + v.y;
if (this.y0 < y && y < this.y1) {
x += (v.x < 0) ? circle.radius : -circle.radius;
var dx = x - circle.center.x;
var dt = dx / v.x;
if (0 <= dt && dt <= 1) {
return new Vec2(dx, v.y * dt);
}
}
return v;
};
/** Returns the boundary box of this line. */
AALine.prototype.getAABB = function () {
return new Rect(this.x0, this.y0, this.x1 - this.x0, this.y1 - this.y0);
};
/** Returns a random point on the line. */
AALine.prototype.rndPt = function () {
return new Vec2(rnd(this.x0, this.x1), rnd(this.y0, this.y1));
};
return AALine;
}());
/** Rect
* Rectangle.
*/
var Rect = /** @class */ (function () {
function Rect(x, y, width, height) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
if (width === void 0) { width = 0; }
if (height === void 0) { height = 0; }
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
Rect.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ', ' + this.width + ', ' + this.height + ')';
};
/** Returns a copy of the object. */
Rect.prototype.copy = function () {
return new Rect(this.x, this.y, this.width, this.height);
};
/** Returns true if rect is equivalent to the object. */
Rect.prototype.equals = function (rect) {
return (this.x == rect.x && this.y == rect.y &&
this.width == rect.width && this.height == rect.height);
};
/** Returns true if rect has zero or negative size. */
Rect.prototype.isZero = function () {
return (this.width <= 0 && this.height <= 0);
};
/** Returns the x-coords of the right edge of the rectangle. */
Rect.prototype.x1 = function () {
return this.x + this.width;
};
/** Returns the y-coords of the bottom edge of the rectangle. */
Rect.prototype.y1 = function () {
return this.y + this.height;
};
/** Returns the x-coords of the center. */
Rect.prototype.cx = function () {
return this.x + this.width / 2;
};
/** Returns the y-coords of the center. */
Rect.prototype.cy = function () {
return this.y + this.height / 2;
};
/** Returns the center of the rectangle. */
Rect.prototype.center = function () {
return new Vec2(this.x + this.width / 2, this.y + this.height / 2);
};
/** Returns the top left corner of the rectangle. */
Rect.prototype.topLeft = function () {
return new Vec2(this.x, this.y);
};
/** Returns the top right corner of the rectangle. */
Rect.prototype.topRight = function () {
return new Vec2(this.x + this.width, this.y);
};
/** Returns the bottom left corner of the rectangle. */
Rect.prototype.bottomLeft = function () {
return new Vec2(this.x, this.y + this.height);
};
/** Returns the bottom right corner of the rectangle. */
Rect.prototype.bottomRight = function () {
return new Vec2(this.x + this.width, this.y + this.height);
};
/** Returns an anchor point of the rectangle. */
Rect.prototype.anchor = function (anchor) {
switch (anchor) {
case 'nw':
return new Vec2(this.x, this.y);
case 'ne':
return new Vec2(this.x + this.width, this.y);
case 'sw':
return new Vec2(this.x, this.y + this.height);
case 'se':
return new Vec2(this.x + this.width, this.y + this.height);
case 'n':
return new Vec2(this.x + this.width / 2, this.y);
case 's':
return new Vec2(this.x + this.width / 2, this.y + this.height);
case 'e':
return new Vec2(this.x, this.y + this.height / 2);
case 'w':
return new Vec2(this.x + this.width, this.y + this.height / 2);
default:
return new Vec2(this.x + this.width / 2, this.y + this.height / 2);
}
};
/** Returns an edge of the rectangle. */
Rect.prototype.edge = function (direction) {
switch (direction) {
case 'w':
return new AALine(this.x, this.y, this.x, this.y + this.height);
case 'e':
return new AALine(this.x + this.width, this.y, this.x + this.width, this.y + this.height);
case 'n':
return new AALine(this.x, this.y, this.x + this.width, this.y);
case 's':
return new AALine(this.x, this.y + this.height, this.x + this.width, this.y + this.height);
default:
return null;
}
};
Rect.prototype.move = function (dx, dy) {
return new Rect(this.x + dx, this.y + dy, this.width, this.height);
};
Rect.prototype.add = function (v) {
return new Rect(this.x + v.x, this.y + v.y, this.width, this.height);
};
Rect.prototype.sub = function (v) {
return new Rect(this.x - v.x, this.y - v.y, this.width, this.height);
};
Rect.prototype.inflate = function (dw, dh) {
return this.expand(dw * 2, dh * 2);
};
Rect.prototype.scale = function (n, anchor) {
if (anchor === void 0) { anchor = 'c'; }
return this.expand(this.width * (n - 1), this.height * (n - 1), anchor);
};
Rect.prototype.expand = function (dw, dh, anchor) {
if (anchor === void 0) { anchor = 'c'; }
switch (anchor) {
case 'nw':
return new Rect(this.x, this.y, this.width + dw, this.height + dh);
case 'ne':
return new Rect(this.x - dw, this.y, this.width + dw, this.height + dh);
case 'sw':
return new Rect(this.x, this.y - dh, this.width + dw, this.height + dh);
case 'se':
return new Rect(this.x - dw, this.y - dh, this.width + dw, this.height + dh);
case 'n':
return new Rect(this.x - dw / 2, this.y, this.width + dw, this.height + dh);
case 's':
return new Rect(this.x - dw / 2, this.y - dh, this.width + dw, this.height + dh);
case 'e':
return new Rect(this.x - dw, this.y - dh / 2, this.width + dw, this.height + dh);
case 'w':
return new Rect(this.x, this.y - dh / 2, this.width + dw, this.height + dh);
default:
return new Rect(this.x - dw / 2, this.y - dh / 2, this.width + dw, this.height + dh);
}
};
Rect.prototype.resize = function (w, h, anchor) {
if (anchor === void 0) { anchor = 'c'; }
switch (anchor) {
case 'nw':
return new Rect(this.x, this.y, w, h);
case 'ne':
return new Rect(this.x + this.width - w, this.y, w, h);
case 'sw':
return new Rect(this.x, this.y + this.height - h, w, h);
case 'se':
return new Rect(this.x + this.width - w, this.y + this.height - h, w, h);
case 'n':
return new Rect(this.x + (this.width - w) / 2, this.y, w, h);
case 's':
return new Rect(this.x + (this.width - w) / 2, this.y + this.height - h, w, h);
case 'e':
return new Rect(this.x, this.y + (this.height - h) / 2, w, h);
case 'w':
return new Rect(this.x + this.width - w, this.y + (this.height - h) / 2, w, h);
default:
return new Rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h);
}
};
Rect.prototype.xdistance = function (rect) {
return Math.max(rect.x - (this.x + this.width), this.x - (rect.x + rect.width));
};
Rect.prototype.ydistance = function (rect) {
return Math.max(rect.y - (this.y + this.height), this.y - (rect.y + rect.height));
};
Rect.prototype.containsPt = function (p) {
return (this.x <= p.x && this.y <= p.y &&
p.x < this.x + this.width && p.y < this.y + this.height);
};
Rect.prototype.containsRect = function (rect) {
return (this.x <= rect.x &&
this.y <= rect.y &&
rect.x + rect.width <= this.x + this.width &&
rect.y + rect.height <= this.y + this.height);
};
Rect.prototype.overlapsRect = function (rect) {
return (rect.x < this.x + this.width &&
rect.y < this.y + this.height &&
this.x < rect.x + rect.width &&
this.y < rect.y + rect.height);
};
Rect.prototype.overlapsCircle = function (circle) {
var x0 = this.x;
var x1 = this.x1();
var y0 = this.y;
var y1 = this.y1();
var cx = circle.center.x;
var cy = circle.center.y;
var r = circle.radius;
return (circle.containsPt(new Vec2(x0, y0)) ||
circle.containsPt(new Vec2(x1, y0)) ||
circle.containsPt(new Vec2(x0, y1)) ||
circle.containsPt(new Vec2(x1, y1)) ||
((x0 < cx && cx < x1) &&
(Math.abs(y0 - cy) < r ||
Math.abs(y1 - cy) < r)) ||
((y0 < cy && cy < y1) &&
(Math.abs(x0 - cx) < r ||
Math.abs(x1 - cx) < r)));
};
Rect.prototype.union = function (rect) {
var x0 = Math.min(this.x, rect.x);
var y0 = Math.min(this.y, rect.y);
var x1 = Math.max(this.x + this.width, rect.x + rect.width);
var y1 = Math.max(this.y + this.height, rect.y + rect.height);
return new Rect(x0, y0, x1 - x0, y1 - y0);
};
Rect.prototype.intersection = function (rect) {
var x0 = Math.max(this.x, rect.x);
var y0 = Math.max(this.y, rect.y);
var x1 = Math.min(this.x + this.width, rect.x + rect.width);
var y1 = Math.min(this.y + this.height, rect.y + rect.height);
return new Rect(x0, y0, x1 - x0, y1 - y0);
};
Rect.prototype.clamp = function (bounds) {
var x = ((bounds.width < this.width) ? bounds.cx() :
clamp(bounds.x, this.x, bounds.x + bounds.width - this.width));
var y = ((bounds.height < this.height) ? bounds.cy() :
clamp(bounds.y, this.y, bounds.y + bounds.height - this.height));
return new Rect(x, y, this.width, this.height);
};
Rect.prototype.edgePt = function (t) {
t = fmod(t, this.width * 2 + this.height * 2);
if (t < this.width) {
return new Vec2(this.x + t, this.y);
}
t -= this.width;
if (t < this.height) {
return new Vec2(this.x + this.width, this.y + t);
}
t -= this.height;
if (t < this.width) {
return new Vec2(this.x + this.width - t, this.y + this.height);
}
// assert(t <= this.height);
return new Vec2(this.x, this.y + this.height - t);
};
Rect.prototype.rndPt = function () {
return new Vec2(this.x + frnd(this.width), this.y + frnd(this.height));
};
Rect.prototype.rndPtEdge = function () {
var t = frnd(this.width * 2 + this.height * 2);
return this.edgePt(t);
};
Rect.prototype.modPt = function (p) {
return new Vec2(this.x + fmod(p.x - this.x, this.width), this.y + fmod(p.y - this.y, this.height));
};
Rect.prototype.contactRect = function (v, rect) {
if (this.overlapsRect(rect)) {
return new Vec2();
}
if (0 < v.x) {
v = this.edge('w').contactRect(v, rect);
}
else if (v.x < 0) {
v = this.edge('e').contactRect(v, rect);
}
if (0 < v.y) {
v = this.edge('n').contactRect(v, rect);
}
else if (v.y < 0) {
v = this.edge('s').contactRect(v, rect);
}
return v;
};
Rect.prototype.contactCircle = function (v, circle) {
if (this.overlapsCircle(circle)) {
return new Vec2();
}
if (0 < v.x) {
v = this.edge('w').contactCircle(v, circle);
}
else if (v.x < 0) {
v = this.edge('e').contactCircle(v, circle);
}
if (0 < v.y) {
v = this.edge('n').contactCircle(v, circle);
}
else if (v.y < 0) {
v = this.edge('s').contactCircle(v, circle);
}
if (circle.center.x < this.x || circle.center.y < this.y) {
v = circle.contactCircle(v, new Circle(new Vec2(this.x, this.y)));
}
if (this.x1() < circle.center.x || circle.center.y < this.y) {
v = circle.contactCircle(v, new Circle(new Vec2(this.x1(), this.y)));
}
if (circle.center.x < this.x || this.y1() < circle.center.y) {
v = circle.contactCircle(v, new Circle(new Vec2(this.x, this.y1())));
}
if (this.x1() < circle.center.x || this.y1() < circle.center.y) {
v = circle.contactCircle(v, new Circle(new Vec2(this.x1(), this.y1())));
}
return v;
};
Rect.prototype.boundRect = function (v, rect) {
if (!this.overlapsRect(rect)) {
return new Vec2();
}
var x = (v.x < 0) ? this.x : this.x + this.width;
v = new AALine(x, -Infinity, x, +Infinity).contactRect(v, rect);
var y = (v.y < 0) ? this.y : this.y + this.height;
v = new AALine(-Infinity, y, +Infinity, y).contactRect(v, rect);
return v;
};
Rect.prototype.overlaps = function (collider) {
if (collider instanceof Rect) {
return this.overlapsRect(collider);
}
else if (collider instanceof Circle) {
return this.overlapsCircle(collider);
}
else {
return false;
}
};
Rect.prototype.contact = function (v, collider) {
if (collider instanceof Rect) {
return this.contactRect(v, collider);
}
else if (collider instanceof Circle) {
return this.contactCircle(v, collider);
}
else {
return v;
}
};
Rect.prototype.getAABB = function () {
return this;
};
return Rect;
}());
/** Circle
*/
var Circle = /** @class */ (function () {
function Circle(center, radius) {
if (radius === void 0) { radius = 0; }
this.center = center;
this.radius = radius;
}
Circle.prototype.toString = function () {
return 'Circle(center=' + this.center + ', radius=' + this.radius + ')';
};
Circle.prototype.copy = function () {
return new Circle(this.center.copy(), this.radius);
};
Circle.prototype.equals = function (circle) {
return (this.center.equals(circle.center) &&
this.radius == circle.radius);
};
Circle.prototype.isZero = function () {
return this.radius == 0;
};
Circle.prototype.move = function (dx, dy) {
return new Circle(this.center.move(dx, dy), this.radius);
};
Circle.prototype.add = function (v) {
return new Circle(this.center.add(v), this.radius);
};
Circle.prototype.sub = function (v) {
return new Circle(this.center.sub(v), this.radius);
};
Circle.prototype.inflate = function (dr) {
return new Circle(this.center, this.radius + dr);
};
Circle.prototype.resize = function (radius) {
return new Circle(this.center, radius);
};
Circle.prototype.distance = function (p) {
return this.center.sub(p).len();
};
Circle.prototype.containsPt = function (p) {
return this.distance(p) < this.radius;
};
Circle.prototype.containsCircle = function (circle) {
var d = this.distance(circle.center);
return d + circle.radius < this.radius;
};
Circle.prototype.overlapsCircle = function (circle) {
var d = this.distance(circle.center);
return d < this.radius + circle.radius;
};
Circle.prototype.overlapsRect = function (rect) {
return rect.overlapsCircle(this);
};
Circle.prototype.clamp = function (bounds) {
var x = ((bounds.width < this.radius) ? bounds.cx() :
clamp(bounds.x, this.center.x, bounds.x + bounds.width - this.radius));
var y = ((bounds.height < this.radius) ? bounds.cy() :
clamp(bounds.y, this.center.y, bounds.y + bounds.height - this.radius));
return new Circle(new Vec2(x, y), this.radius);
};
Circle.prototype.edgePt = function (t) {
return new Vec2(this.center.x + this.radius * Math.cos(t), this.center.y + this.radius * Math.sin(t));
};
Circle.prototype.rndPt = function () {
var r = frnd(this.radius);
var t = frnd(Math.PI * 2);
return new Vec2(this.center.x + r * Math.cos(t), this.center.y + r * Math.sin(t));
};
Circle.prototype.rndPtEdge = function () {
var t = frnd(Math.PI * 2);
return this.edgePt(t);
};
Circle.prototype.contactCircle = function (v, circle) {
if (this.overlapsCircle(circle)) {
return new Vec2();
}
var d = circle.center.sub(this.center);
var dv = d.x * v.x + d.y * v.y;
var v2 = v.len2();
var d2 = d.len2();
var R = (this.radius + circle.radius);
// |d - t*v|^2 = (r1+r2)^2
// t = { (d*v) + sqrt((d*v)^2 - v^2(d^2-R^2)) } / v^2
var s = dv * dv - v2 * (d2 - R * R);
if (0 < s) {
var t = (dv - Math.sqrt(s)) / v2;
if (t < -EPSILON) {
;
}
else if (t < EPSILON) {
v = new Vec2();
}
else if (t < 1 + EPSILON) {
v = v.scale(t / (1 + EPSILON));
}
}
return v;
};
Circle.prototype.overlaps = function (collider) {
if (collider instanceof Circle) {
return this.overlapsCircle(collider);
}
else if (collider instanceof Rect) {
return this.overlapsRect(collider);
}
else {
return false;
}
};
Circle.prototype.contact = function (v, collider) {
if (collider instanceof Circle) {
return this.contactCircle(v, collider);
}
else if (collider instanceof Rect) {
return collider.contactCircle(v.scale(-1), this).scale(-1);
}
else {
return v;
}
};
Circle.prototype.getAABB = function () {
return new Rect(this.center.x - this.radius, this.center.y - this.radius, this.radius * 2, this.radius * 2);
};
return Circle;
}());
// AAPlane
// Axis-aligned plane
//
var AAPlane = /** @class */ (function () {
function AAPlane(p0, p1) {
this.p0 = p0;
this.p1 = p1;
}
AAPlane.prototype.contactBox = function (v, box) {
if (this.p0.x == this.p1.x) {
return this.contactBoxYZ(v, box, this.p0.x);
}
else if (this.p0.y == this.p1.y) {
return this.contactBoxZX(v, box, this.p0.y);
}
else if (this.p0.z == this.p1.z) {
return this.contactBoxXY(v, box, this.p0.z);
}
else {
return v;
}
};
AAPlane.prototype.contactBoxYZ = function (v, box, x) {
var x0 = box.origin.x;
var x1 = x0 + box.size.x;
var dx;
if (x <= x0 && x0 + v.x < x) {
dx = x - x0;
}
else if (x1 <= x && x < x1 + v.x) {
dx = x - x1;
}
else {
return v;
}
var dy = v.y * dx / v.x;
var dz = v.z * dx / v.x;
var y0 = box.origin.y + dy;
var y1 = y0 + box.size.y;
var z0 = box.origin.z + dz;
var z1 = z0 + box.size.z;
if (y1 < this.p0.y || this.p1.y < y0 ||
z1 < this.p0.z || this.p1.z < z0 ||
(y1 == this.p0.y && v.y <= 0) || (this.p1.y == y0 && 0 <= v.y) ||
(z1 == this.p0.z && v.z <= 0) || (this.p1.z == z0 && 0 <= v.z)) {
return v;
}
return new Vec3(dx, dy, dz);
};
AAPlane.prototype.contactBoxZX = function (v, box, y) {
var y0 = box.origin.y;
var y1 = y0 + box.size.y;
var dy;
if (y <= y0 && y0 + v.y < y) {
dy = y - y0;
}
else if (y1 <= y && y < y1 + v.y) {
dy = y - y1;
}
else {
return v;
}
var dz = v.z * dy / v.y;
var dx = v.x * dy / v.y;
var z0 = box.origin.z + dx;
var z1 = z0 + box.size.z;
var x0 = box.origin.x + dy;
var x1 = x0 + box.size.x;
if (z1 < this.p0.z || this.p1.z < z0 ||
x1 < this.p0.x || this.p1.x < x0 ||
(z1 == this.p0.z && v.z <= 0) || (z0 == this.p1.z && 0 <= v.z) ||
(x1 == this.p0.x && v.x <= 0) || (x0 == this.p1.x && 0 <= v.x)) {
return v;
}
return new Vec3(dx, dy, dz);
};
AAPlane.prototype.contactBoxXY = function (v, box, z) {
var z0 = box.origin.z;
var z1 = z0 + box.size.z;
var dz;
if (z <= z0 && z0 + v.z < z) {
dz = z - z0;
}
else if (z1 <= z && z < z1 + v.z) {
dz = z - z1;
}
else {
return v;
}
var dx = v.x * dz / v.z;
var dy = v.y * dz / v.z;
var x0 = box.origin.x + dx;
var x1 = x0 + box.size.x;
var y0 = box.origin.y + dy;
var y1 = y0 + box.size.y;
if (x1 < this.p0.x || this.p1.x < x0 ||
y1 < this.p0.y || this.p1.y < y0 ||
(x1 == this.p0.x && v.x <= 0) || (x0 == this.p1.x && 0 <= v.x) ||
(y1 == this.p0.y && v.y <= 0) || (y0 == this.p1.y && 0 <= v.y)) {
return v;
}
return new Vec3(dx, dy, dz);
};
return AAPlane;
}());
// Box
//
var Box = /** @class */ (function () {
function Box(origin, size) {
if (size === void 0) { size = null; }
this.origin = origin;
this.size = (size !== null) ? size : new Vec3();
}
Box.prototype.toString = function () {
return '(' + this.origin + ', ' + this.size + ')';
};
Box.prototype.copy = function () {
return new Box(this.origin.copy(), this.size.copy());
};
Box.prototype.equals = function (box) {
return (this.origin.equals(box.origin) &&
this.size.equals(box.size));
};
Box.prototype.isZero = function () {
return this.size.isZero();
};
Box.prototype.center = function () {
return new Vec3(this.origin.x + this.size.x / 2, this.origin.y + this.size.y / 2, this.origin.z + this.size.z / 2);
};
Box.prototype.surface = function (vx, vy, vz) {
if (vx < 0) {
return new AAPlane(this.origin, this.origin.move(0, this.size.y, this.size.z));
}
else if (0 < vx) {
return new AAPlane(this.origin.move(this.size.x, 0, 0), this.origin.add(this.size));
}
else if (vy < 0) {
return new AAPlane(this.origin, this.origin.move(this.size.x, 0, this.size.z));
}
else if (0 < vy) {
return new AAPlane(this.origin.move(0, this.size.y, 0), this.origin.add(this.size));
}
else if (vz < 0) {
return new AAPlane(this.origin, this.origin.move(this.size.x, this.size.y, 0));
}
else if (0 < vz) {
return new AAPlane(this.origin.move(0, 0, this.size.z), this.origin.add(this.size));
}
else {
return null;
}
};
Box.prototype.anchor = function (vx, vy, vz) {
if (vx === void 0) { vx = 0; }
if (vy === void 0) { vy = 0; }
if (vz === void 0) { vz = 0; }
var x, y, z;
if (vx < 0) {
x = this.origin.x;
}
else if (0 < vx) {
x = this.origin.x + this.size.x;
}
else {
x = this.origin.x + this.size.x / 2;
}
if (vy < 0) {
y = this.origin.y;
}
else if (0 < vy) {
y = this.origin.y + this.size.y;
}
else {
y = this.origin.y + this.size.y / 2;
}
if (vz < 0) {
z = this.origin.z;
}
else if (0 < vz) {
z = this.origin.z + this.size.z;
}
else {
z = this.origin.z + this.size.z / 2;
}
return new Vec3(x, y, z);
};
Box.prototype.move = function (dx, dy, dz) {
return new Box(this.origin.move(dx, dy, dz), this.size);
};
Box.prototype.add = function (v) {
return new Box(this.origin.add(v), this.size);
};
Box.prototype.sub = function (v) {
return new Box(this.origin.sub(v), this.size);
};
Box.prototype.inflate = function (dx, dy, dz) {
return new Box(this.origin.move(-dx, -dy, -dz), this.size.move(dx * 2, dy * 2, dz * 2));
};
Box.prototype.xdistance = function (box) {
return Math.max(box.origin.x - (this.origin.x + this.size.x), this.origin.x - (box.origin.x + box.size.x));
};
Box.prototype.ydistance = function (box) {
return Math.max(box.origin.y - (this.origin.y + this.size.y), this.origin.y - (box.origin.y + box.size.y));
};
Box.prototype.zdistance = function (box) {
return Math.max(box.origin.z - (this.origin.z + this.size.z), this.origin.z - (box.origin.z + box.size.z));
};
Box.prototype.containsPt = function (p) {
return (this.origin.x <= p.x && this.origin.y <= p.y && this.origin.z <= p.z &&
p.x < this.origin.x + this.size.x &&
p.y < this.origin.y + this.size.y &&
p.z < this.origin.z + this.size.z);
};
Box.prototype.overlapsBox = function (box) {
return (this.xdistance(box) < 0 &&
this.ydistance(box) < 0 &&
this.zdistance(box) < 0);
};
Box.prototype.union = function (box) {
var x0 = Math.min(this.origin.x, box.origin.x);
var y0 = Math.min(this.origin.y, box.origin.y);
var z0 = Math.min(this.origin.z, box.origin.z);
var x1 = Math.max(this.origin.x + this.size.x, box.origin.x + box.size.x);
var y1 = Math.max(this.origin.y + this.size.y, box.origin.y + box.size.y);
var z1 = Math.max(this.origin.z + this.size.z, box.origin.z + box.size.z);
return new Box(new Vec3(x0, y0, z0), new Vec3(x1 - x0, y1 - y0, z1 - z0));
};
Box.prototype.intersection = function (box) {
var x0 = Math.max(this.origin.x, box.origin.x);
var y0 = Math.max(this.origin.y, box.origin.y);
var z0 = Math.max(this.origin.z, box.origin.z);
var x1 = Math.min(this.origin.x + this.size.x, box.origin.x + box.size.x);
var y1 = Math.min(this.origin.y + this.size.y, box.origin.y + box.size.y);
var z1 = Math.min(this.origin.z + this.size.z, box.origin.z + box.size.z);
return new Box(new Vec3(x0, y0, z0), new Vec3(x1 - x0, y1 - y0, z1 - z0));
};
Box.prototype.clamp = function (bounds) {
var x = ((bounds.size.x < this.size.x) ?
(bounds.origin.x + bounds.size.x / 2) :
clamp(bounds.origin.x, this.origin.x, bounds.origin.x + bounds.size.x - this.size.x));
var y = ((bounds.size.y < this.size.y) ?
(bounds.origin.y + bounds.size.y / 2) :
clamp(bounds.origin.y, this.origin.y, bounds.origin.y + bounds.size.y - this.size.y));
var z = ((bounds.size.z < this.size.z) ?
(bounds.origin.z + bounds.size.z / 2) :
clamp(bounds.origin.z, this.origin.z, bounds.origin.z + bounds.size.z - this.size.z));
return new Box(new Vec3(x, y, z), this.size);
};
Box.prototype.rndPt = function () {
return new Vec3(this.origin.x + frnd(this.size.x), this.origin.y + frnd(this.size.y), this.origin.z + frnd(this.size.z));
};
Box.prototype.contactBox = function (v, box) {
if (this.overlapsBox(box)) {
return new Vec3();
}
if (0 < v.x) {
v = this.surface(-1, 0, 0).contactBox(v, box);
}
else if (v.x < 0) {
v = this.surface(+1, 0, 0).contactBox(v, box);
}
if (0 < v.y) {
v = this.surface(0, -1, 0).contactBox(v, box);
}
else if (v.y < 0) {
v = this.surface(0, +1, 0).contactBox(v, box);
}
if (0 < v.z) {
v = this.surface(0, 0, -1).contactBox(v, box);
}
else if (v.z < 0) {
v = this.surface(0, 0, +1).contactBox(v, box);
}
return v;
};
return Box;
}());
// getContact: returns a motion vector that satisfies the given constraints.
function getContact(collider0, v, obstacles, fences) {
if (fences === void 0) { fences = null; }
if (obstacles !== null) {
for (var _i = 0, obstacles_1 = obstacles; _i < obstacles_1.length; _i++) {
var collider1 = obstacles_1[_i];
v = collider1.contact(v, collider0);
}
}
if (fences !== null) {
for (var _a = 0, fences_1 = fences; _a < fences_1.length; _a++) {
var rect = fences_1[_a];
v = rect.boundRect(v, collider0.getAABB());
}
}
return v;
}
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/** Sprite that is a solid filled rectangle.
* Typically used as placeholders.
*/
var RectSprite = /** @class */ (function () {
function RectSprite(color, dstRect) {
this.color = color;
this.dstRect = dstRect;
}
/** Returns the bounds of the image at (0, 0). */
RectSprite.prototype.getBounds = function () {
return this.dstRect;
};
/** Renders this image in the given context. */
RectSprite.prototype.render = function (ctx) {
if (this.color !== null) {
ctx.fillStyle = this.color;
fillRect(ctx, this.dstRect);
}
};
return RectSprite;
}());
/** Sprite that is a solid filled oval.
*/
var OvalSprite = /** @class */ (function () {
function OvalSprite(color, dstRect) {
this.color = color;
this.dstRect = dstRect;
}
/** Returns the bounds of the image at (0, 0). */
OvalSprite.prototype.getBounds = function () {
return this.dstRect;
};
/** Renders this image in the given context. */
OvalSprite.prototype.render = function (ctx) {
if (this.color !== null) {
ctx.save();
ctx.fillStyle = this.color;
ctx.translate(this.dstRect.cx(), this.dstRect.cy());
ctx.scale(this.dstRect.width / 2, this.dstRect.height / 2);
ctx.beginPath();
ctx.arc(0, 0, 1, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
};
return OvalSprite;
}());
/** Sprite that uses a canvas object.
*/
var CanvasSprite = /** @class */ (function () {
function CanvasSprite(canvas, srcRect, dstRect) {
if (srcRect === void 0) { srcRect = null; }
if (dstRect === void 0) { dstRect = null; }
this.canvas = canvas;
if (srcRect === null) {
srcRect = new Rect(0, 0, canvas.width, canvas.height);
}
this.srcRect = srcRect;
if (dstRect === null) {
dstRect = new Rect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
}
this.dstRect = dstRect;
}
/** Returns the bounds of the image at (0, 0). */
CanvasSprite.prototype.getBounds = function () {
return this.dstRect;
};
/** Renders this image in the given context. */
CanvasSprite.prototype.render = function (ctx) {
ctx.drawImage(this.canvas, this.srcRect.x, this.srcRect.y, this.srcRect.width, this.srcRect.height, this.dstRect.x, this.dstRect.y, this.dstRect.width, this.dstRect.height);
};
return CanvasSprite;
}());
/** Sprite that uses a (part of) HTML <img> element.
*/
var HTMLSprite = /** @class */ (function () {
function HTMLSprite(image, srcRect, dstRect) {
if (srcRect === void 0) { srcRect = null; }
if (dstRect === void 0) { dstRect = null; }
this.image = image;
if (srcRect === null) {
srcRect = new Rect(0, 0, image.width, image.height);
}
this.srcRect = srcRect;
if (dstRect === null) {
dstRect = new Rect(-image.width / 2, -image.height / 2, image.width, image.height);
}
this.dstRect = dstRect;
}
/** Returns the bounds of the image at (0, 0). */
HTMLSprite.prototype.getBounds = function () {
return this.dstRect;
};
/** Renders this image in the given context. */
HTMLSprite.prototype.render = function (ctx) {
ctx.drawImage(this.image, this.srcRect.x, this.srcRect.y, this.srcRect.width, this.srcRect.height, this.dstRect.x, this.dstRect.y, this.dstRect.width, this.dstRect.height);
};
return HTMLSprite;
}());
/** Sprite that consists of tiled images.
* A image is displayed repeatedly to fill up the specified bounds.
*/
var TiledSprite = /** @class */ (function () {
function TiledSprite(sprite, bounds, offset) {
if (offset === void 0) { offset = null; }
this.sprite = sprite;
this.bounds = bounds;
this.offset = (offset !== null) ? offset : new Vec2();
}
/** Returns the bounds of the image at a given pos. */
TiledSprite.prototype.getBounds = function () {
return this.bounds;
};
/** Renders this image in the given context. */
TiledSprite.prototype.render = function (ctx) {
ctx.save();
ctx.translate(int(this.bounds.x), int(this.bounds.y));
ctx.beginPath();
ctx.rect(0, 0, this.bounds.width, this.bounds.height);
ctx.clip();
var dstRect = this.sprite.getBounds();
var w = dstRect.width;
var h = dstRect.height;
var dx0 = int(Math.floor(this.offset.x / w) * w - this.offset.x);
var dy0 = int(Math.floor(this.offset.y / h) * h - this.offset.y);
for (var dy = dy0; dy < this.bounds.height; dy += h) {
for (var dx = dx0; dx < this.bounds.width; dx += w) {
ctx.save();
ctx.translate(dx, dy);
this.sprite.render(ctx);
ctx.restore();
}
}
ctx.restore();
};
return TiledSprite;
}());
/** Internal object that represents a star. */
var Star = /** @class */ (function () {
function Star() {
}
Star.prototype.init = function (maxdepth) {
this.z = Math.random() * maxdepth + 1;
this.s = (Math.random() * 2 + 1) / this.z;
};
return Star;
}());
/** Sprite for "star flowing" effects.
* A image is scattered across the area with a varied depth.
*/
var StarSprite = /** @class */ (function () {
function StarSprite(bounds, nstars, maxdepth, sprites) {
if (maxdepth === void 0) { maxdepth = 3; }
if (sprites === void 0) { sprites = null; }
this._stars = [];
this.bounds = bounds;
this.maxdepth = maxdepth;
if (sprites === null) {
sprites = [new RectSprite('white', new Rect(0, 0, 1, 1))];
}
this.sprites = sprites;
for (var i = 0; i < nstars; i++) {
var star = new Star();
star.sprite = choice(sprites);
star.init(this.maxdepth);
star.p = this.bounds.rndPt();
this._stars.push(star);
}
}
/** Returns the bounds of the image at a given pos. */
StarSprite.prototype.getBounds = function () {
return this.bounds;
};
/** Renders this image in the given context. */
StarSprite.prototype.render = function (ctx) {
for (var _i = 0, _a = this._stars; _i < _a.length; _i++) {
var star = _a[_i];
ctx.save();
ctx.translate(star.p.x, star.p.y);
ctx.scale(star.s, star.s);
star.sprite.render(ctx);
ctx.restore();
}
};
/** Moves the stars by the given offset. */
StarSprite.prototype.move = function (offset) {
for (var _i = 0, _a = this._stars; _i < _a.length; _i++) {
var star = _a[_i];
star.p.x += offset.x / star.z;
star.p.y += offset.y / star.z;
var rect = star.p.expand(star.s, star.s);
if (!this.bounds.overlapsRect(rect)) {
star.init(this.maxdepth);
star.p = this.bounds.modPt(star.p);
}
}
};
return StarSprite;
}());
/** Object that stores multiple Sprite objects.
* Each cell on the grid represents an individual Sprite.
*/
var SpriteSheet = /** @class */ (function () {
function SpriteSheet() {
}
/** Returns an Sprite at the given cell. */
SpriteSheet.prototype.get = function (x, y, w, h, origin) {
if (y === void 0) { y = 0; }
if (w === void 0) { w = 1; }
if (h === void 0) { h = 1; }
if (origin === void 0) { origin = null; }
return null;
};
return SpriteSheet;
}());
/** Array of Sprites.
*/
var ArraySpriteSheet = /** @class */ (function (_super) {
__extends(ArraySpriteSheet, _super);
function ArraySpriteSheet(sprites) {
var _this = _super.call(this) || this;
_this.sprites = sprites;
return _this;
}
/** Returns an Sprite at the given cell. */
ArraySpriteSheet.prototype.get = function (x, y, w, h, origin) {
if (y === void 0) { y = 0; }
if (w === void 0) { w = 1; }
if (h === void 0) { h = 1; }
if (origin === void 0) { origin = null; }
if (x < 0 || this.sprites.length <= x || y != 0)
return null;
return this.sprites[x];
};
/** Sets an Sprite at the given cell. */
ArraySpriteSheet.prototype.set = function (i, sprite) {
this.sprites[i] = sprite;
};
return ArraySpriteSheet;
}(SpriteSheet));
/** SpriteSheet that is based on a single HTML image.
*/
var ImageSpriteSheet = /** @class */ (function (_super) {
__extends(ImageSpriteSheet, _super);
function ImageSpriteSheet(image, size, origin) {
if (origin === void 0) { origin = null; }
var _this = _super.call(this) || this;
_this.image = image;
_this.size = size;
_this.origin = origin;
return _this;
}
/** Returns an Sprite at the given cell. */
ImageSpriteSheet.prototype.get = function (x, y, w, h, origin) {
if (y === void 0) { y = 0; }
if (w === void 0) { w = 1; }
if (h === void 0) { h = 1; }
if (origin === void 0) { origin = null; }
if (origin === null) {
origin = this.origin;
if (origin === null) {
origin = new Vec2(w * this.size.x / 2, h * this.size.y / 2);
}
}
var srcRect = new Rect(x * this.size.x, y * this.size.y, w * this.size.x, h * this.size.y);
var dstRect = new Rect(-origin.x, -origin.y, w * this.size.x, h * this.size.y);
return new HTMLSprite(this.image, srcRect, dstRect);
};
return ImageSpriteSheet;
}(SpriteSheet));
/// <reference path="utils.ts" />
var TaskState;
(function (TaskState) {
TaskState[TaskState["Scheduled"] = 0] = "Scheduled";
TaskState[TaskState["Running"] = 1] = "Running";
TaskState[TaskState["Finished"] = 2] = "Finished";
})(TaskState || (TaskState = {}));
/** Object that represents a continuous process.
* onTick() method is invoked at every frame.
*/
var Task = /** @class */ (function () {
function Task() {
/** List to which this task belongs (assigned by TaskList). */
this.parent = null;
/** True if the task is running. */
this.state = TaskState.Scheduled;
/** Lifetime.
* This task automatically terminates itself after
* the time specified here passes. */
this.lifetime = Infinity;
/** Start time. */
this.startTime = Infinity;
this.stopped = new Signal(this);
}
Task.prototype.toString = function () {
return '<Task: time=' + this.getTime() + '>';
};
/** Returns the number of seconds elapsed since
* this task has started. */
Task.prototype.getTime = function () {
return (getTime() - this.startTime);
};
/** Returns true if the task is scheduled but not yet running. */
Task.prototype.isScheduled = function () {
return (this.state == TaskState.Scheduled);
};
/** Returns true if the task is running. */
Task.prototype.isRunning = function () {
return (this.state == TaskState.Running);
};
/** Invoked when the task is started. */
Task.prototype.onStart = function () {
if (this.state == TaskState.Scheduled) {
this.state = TaskState.Running;
this.startTime = getTime();
}
};
/** Invoked when the task is stopped. */
Task.prototype.onStop = function () {
};
/** Invoked at every frame while the task is running. */
Task.prototype.onTick = function () {
if (this.lifetime <= this.getTime()) {
this.stop();
}
};
/** Terminates the task. */
Task.prototype.stop = function () {
if (this.state == TaskState.Running) {
this.state = TaskState.Finished;
this.stopped.fire();
}
};
/** Schedules another task right after this task.
* @param next Next Task.
*/
Task.prototype.chain = function (next, signal) {
var _this = this;
if (signal === void 0) { signal = null; }
switch (this.state) {
case TaskState.Scheduled:
case TaskState.Running:
signal = (signal !== null) ? signal : this.stopped;
signal.subscribe(function () {
if (_this.parent !== null) {
_this.parent.add(next);
}
});
break;
case TaskState.Finished:
// Start immediately if this task has already finished.
if (this.parent !== null) {
this.parent.add(next);
}
}
return next;
};
return Task;
}());
/** Task that plays a sound.
*/
var SoundTask = /** @class */ (function (_super) {
__extends(SoundTask, _super);
/** Constructor.
* @param sound Sound object to play.
* @param soundStart Start time of the sound.
*/
function SoundTask(sound, soundStart, soundEnd) {
if (soundStart === void 0) { soundStart = MP3_GAP; }
if (soundEnd === void 0) { soundEnd = 0; }
var _this = _super.call(this) || this;
_this.sound = sound;
_this.soundStart = soundStart;
_this.soundEnd = soundEnd;
return _this;
}
/** Invoked when the task is started. */
SoundTask.prototype.onStart = function () {
_super.prototype.onStart.call(this);
// Start playing.
this.sound.currentTime = this.soundStart;
this.sound.play();
};
/** Invoked when the task is stopped. */
SoundTask.prototype.onStop = function () {
// Stop playing.
this.sound.pause();
_super.prototype.onStop.call(this);
};
/** Invoked at every frame while the task is running. */
SoundTask.prototype.onTick = function () {
_super.prototype.onTick.call(this);
// Check if the playing is finished.
if (0 < this.soundEnd && this.soundEnd <= this.sound.currentTime) {
this.stop();
}
else if (this.sound.ended) {
this.stop();
}
};
return SoundTask;
}(Task));
/** List of Tasks that run parallely.
*/
var ParallelTaskList = /** @class */ (function (_super) {
__extends(ParallelTaskList, _super);
function ParallelTaskList() {
var _this = _super !== null && _super.apply(this, arguments) || this;
/** List of current tasks. */
_this.tasks = [];
/** If true, this task is stopped when the list becomes empty. */
_this.stopWhenEmpty = true;
return _this;
}
ParallelTaskList.prototype.toString = function () {
return ('<ParalellTaskList: tasks=' + this.tasks + '>');
};
/** Empties the task list. */
ParallelTaskList.prototype.onStart = function () {
_super.prototype.onStart.call(this);
this.tasks = [];
};
/** Invoked at every frame. Update the current tasks. */
ParallelTaskList.prototype.onTick = function () {
for (var _i = 0, _a = this.tasks; _i < _a.length; _i++) {
var task = _a[_i];
if (task.isScheduled()) {
task.onStart();
}
if (task.isRunning()) {
task.onTick();
}
}
// Remove the finished tasks from the list.
var removed = this.tasks.filter(function (task) { return !task.isRunning(); });
for (var _b = 0, removed_1 = removed; _b < removed_1.length; _b++) {
var task = removed_1[_b];
this.remove(task);
}
// Terminates itself then the list is empty.
if (this.stopWhenEmpty && this.tasks.length == 0) {
this.stop();
}
};
/** Add a new Task to the list.
* @param task Task to add.
*/
ParallelTaskList.prototype.add = function (task) {
task.parent = this;
this.tasks.push(task);
};
/** Remove an existing Task from the list.
* @param task Task to remove.
*/
ParallelTaskList.prototype.remove = function (task) {
if (!task.isScheduled()) {
task.onStop();
}
removeElement(this.tasks, task);
};
return ParallelTaskList;
}(Task));
/** List of Tasks that run sequentially.
*/
var SequentialTaskList = /** @class */ (function (_super) {
__extends(SequentialTaskList, _super);
/** Constructor.
* @param tasks List of tasks. (optional)
*/
function SequentialTaskList(tasks) {
if (tasks === void 0) { tasks = null; }
var _this = _super.call(this) || this;
/** List of current tasks. */
_this.tasks = null;
/** If true, this task is stopped when the list becomes empty. */
_this.stopWhenEmpty = true;
_this.tasks = tasks;
return _this;
}
/** Empties the task list. */
SequentialTaskList.prototype.onStart = function () {
_super.prototype.onStart.call(this);
if (this.tasks === null) {
this.tasks = [];
}
};
/** Add a new Task to the list.
* @param task Task to add.
*/
SequentialTaskList.prototype.add = function (task) {
task.parent = this;
this.tasks.push(task);
};
/** Remove an existing Task from the list.
* @param task Task to remove.
*/
SequentialTaskList.prototype.remove = function (task) {
removeElement(this.tasks, task);
};
/** Returns the task that is currently running
* (or null if empty) */
SequentialTaskList.prototype.getCurrentTask = function () {
return (0 < this.tasks.length) ? this.tasks[0] : null;
};
/** Invoked at every frame. Update the current tasks. */
SequentialTaskList.prototype.onTick = function () {
var task = null;
while (true) {
task = this.getCurrentTask();
if (task === null)
break;
// Starts the next task.
if (task.isScheduled()) {
task.onStart();
}
if (task.isRunning()) {
task.onTick();
break;
}
// Finishes the current task.
this.remove(task);
}
// Terminates itself then the list is empty.
if (this.stopWhenEmpty && task === null) {
this.stop();
}
};
return SequentialTaskList;
}(Task));
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="sprite.ts" />
// TileMap
//
var TileMap = /** @class */ (function () {
function TileMap(tilesize, width, height, map) {
if (map === void 0) { map = null; }
this._rangemap = {};
this.tilesize = tilesize;
this.width = width;
this.height = height;
if (map === null) {
map = range(height).map(function () { return new Int32Array(width); });
}
this.map = map;
this.bounds = new Rect(0, 0, this.width * this.tilesize, this.height * this.tilesize);
}
TileMap.prototype.toString = function () {
return '<TileMap: ' + this.width + ',' + this.height + '>';
};
TileMap.prototype.get = function (x, y) {
if (0 <= x && 0 <= y && x < this.width && y < this.height) {
return this.map[y][x];
}
else {
return -1;
}
};
TileMap.prototype.set = function (x, y, c) {
if (0 <= x && 0 <= y && x < this.width && y < this.height) {
this.map[y][x] = c;
this._rangemap = {};
}
};
TileMap.prototype.fill = function (c, rect) {
if (rect === void 0) { rect = null; }
if (rect === null) {
rect = new Rect(0, 0, this.width, this.height);
}
for (var dy = 0; dy < rect.height; dy++) {
var y = rect.y + dy;
for (var dx = 0; dx < rect.width; dx++) {
var x = rect.x + dx;
this.map[y][x] = c;
}
}
this._rangemap = {};
};
TileMap.prototype.copy = function () {
var map = [];
for (var _i = 0, _a = this.map; _i < _a.length; _i++) {
var a = _a[_i];
map.push(a.slice());
}
return new TileMap(this.tilesize, this.width, this.height, map);
};
TileMap.prototype.coord2map = function (rect) {
var ts = this.tilesize;
if (rect instanceof Rect) {
var x0 = Math.floor(rect.x / ts);
var y0 = Math.floor(rect.y / ts);
var x1 = Math.ceil((rect.x + rect.width) / ts);
var y1 = Math.ceil((rect.y + rect.height) / ts);
return new Rect(x0, y0, x1 - x0, y1 - y0);
}
else {
var x = Math.floor(rect.x / ts);
var y = Math.floor(rect.y / ts);
return new Rect(x, y, 1, 1);
}
};
TileMap.prototype.map2coord = function (rect) {
var ts = this.tilesize;
if (rect instanceof Vec2) {
return new Rect(rect.x * ts, rect.y * ts, ts, ts);
}
else if (rect instanceof Rect) {
return new Rect(rect.x * ts, rect.y * ts, rect.width * ts, rect.height * ts);
}
else {
return null;
}
};
TileMap.prototype.apply = function (f, rect) {
if (rect === void 0) { rect = null; }
if (rect === null) {
rect = new Rect(0, 0, this.width, this.height);
}
for (var dy = 0; dy < rect.height; dy++) {
var y = rect.y + dy;
for (var dx = 0; dx < rect.width; dx++) {
var x = rect.x + dx;
var c = this.get(x, y);
if (f(x, y, c)) {
return new Vec2(x, y);
}
}
}
return null;
};
TileMap.prototype.shift = function (vx, vy, rect) {
if (rect === void 0) { rect = null; }
if (rect === null) {
rect = new Rect(0, 0, this.width, this.height);
}
var src = [];
for (var dy = 0; dy < rect.height; dy++) {
var a = new Int32Array(rect.width);
for (var dx = 0; dx < rect.width; dx++) {
a[dx] = this.map[rect.y + dy][rect.x + dx];
}
src.push(a);
}
for (var dy = 0; dy < rect.height; dy++) {
for (var dx = 0; dx < rect.width; dx++) {
var x = (dx + vx + rect.width) % rect.width;
var y = (dy + vy + rect.height) % rect.height;
this.map[rect.y + y][rect.x + x] = src[dy][dx];
}
}
};
TileMap.prototype.findTile = function (f0, rect) {
if (rect === void 0) { rect = null; }
return this.apply(function (x, y, c) { return f0(c); }, rect);
};
TileMap.prototype.findTileByCoord = function (f0, range) {
var p = this.apply(function (x, y, c) { return f0(c); }, this.coord2map(range));
return (p === null) ? null : this.map2coord(p);
};
TileMap.prototype.getTileRects = function (f0, range) {
var ts = this.tilesize;
var rects = [];
var f = function (x, y, c) {
if (f0(c)) {
rects.push(new Rect(x * ts, y * ts, ts, ts));
}
return false;
};
this.apply(f, this.coord2map(range));
return rects;
};
TileMap.prototype.getRangeMap = function (key, f) {
var map = this._rangemap[key];
if (map === undefined) {
map = new RangeMap(this, f);
this._rangemap[key] = map;
}
return map;
};
TileMap.prototype.render = function (ctx, sprites) {
this.renderFromBottomLeft(ctx, function (x, y, c) { return sprites.get(c); });
};
TileMap.prototype.renderFromBottomLeft = function (ctx, ft, x0, y0, w, h) {
if (x0 === void 0) { x0 = 0; }
if (y0 === void 0) { y0 = 0; }
if (w === void 0) { w = 0; }
if (h === void 0) { h = 0; }
// Align the pos to the bottom left corner.
var ts = this.tilesize;
w = (w != 0) ? w : this.width;
h = (h != 0) ? h : this.height;
// Draw tiles from the bottom-left first.
for (var dy = h - 1; 0 <= dy; dy--) {
var y = y0 + dy;
for (var dx = 0; dx < w; dx++) {
var x = x0 + dx;
var c = this.get(x, y);
var sprite = ft(x, y, c);
if (sprite !== null) {
ctx.save();
ctx.translate(ts * dx, ts * dy);
sprite.render(ctx);
ctx.restore();
}
}
}
};
TileMap.prototype.renderFromTopRight = function (ctx, ft, x0, y0, w, h) {
if (x0 === void 0) { x0 = 0; }
if (y0 === void 0) { y0 = 0; }
if (w === void 0) { w = 0; }
if (h === void 0) { h = 0; }
// Align the pos to the bottom left corner.
var ts = this.tilesize;
w = (w != 0) ? w : this.width;
h = (h != 0) ? h : this.height;
// Draw tiles from the top-right first.
for (var dy = 0; dy < h; dy++) {
var y = y0 + dy;
for (var dx = w - 1; 0 <= dx; dx--) {
var x = x0 + dx;
var c = this.get(x, y);
var sprite = ft(x, y, c);
if (sprite !== null) {
ctx.save();
ctx.translate(ts * dx, ts * dy);
sprite.render(ctx);
ctx.restore();
}
}
}
};
TileMap.prototype.renderWindow = function (ctx, window, sprites) {
this.renderWindowFromBottomLeft(ctx, window, function (x, y, c) { return sprites.get(c); });
};
TileMap.prototype.renderWindowFromBottomLeft = function (ctx, window, ft) {
var ts = this.tilesize;
var x0 = Math.floor(window.x / ts);
var y0 = Math.floor(window.y / ts);
var x1 = Math.ceil((window.x + window.width) / ts);
var y1 = Math.ceil((window.y + window.height) / ts);
ctx.save();
ctx.translate(x0 * ts - window.x, y0 * ts - window.y);
this.renderFromBottomLeft(ctx, ft, x0, y0, x1 - x0 + 1, y1 - y0 + 1);
ctx.restore();
};
TileMap.prototype.renderWindowFromTopRight = function (ctx, window, ft) {
var ts = this.tilesize;
var x0 = Math.floor(window.x / ts);
var y0 = Math.floor(window.y / ts);
var x1 = Math.ceil((window.x + window.width) / ts);
var y1 = Math.ceil((window.y + window.height) / ts);
ctx.save();
ctx.translate(x0 * ts - window.x, y0 * ts - window.y);
this.renderFromTopRight(ctx, ft, x0, y0, x1 - x0 + 1, y1 - y0 + 1);
ctx.restore();
};
return TileMap;
}());
// RangeMap
//
var RangeMap = /** @class */ (function () {
function RangeMap(tilemap, f) {
var data = new Array(tilemap.height + 1);
var row0 = new Int32Array(tilemap.width + 1);
for (var x = 0; x < tilemap.width; x++) {
row0[x + 1] = 0;
}
data[0] = row0;
for (var y = 0; y < tilemap.height; y++) {
var row1 = new Int32Array(tilemap.width + 1);
var n = 0;
for (var x = 0; x < tilemap.width; x++) {
if (f(tilemap.get(x, y))) {
n++;
}
row1[x + 1] = row0[x + 1] + n;
}
data[y + 1] = row1;
row0 = row1;
}
this.width = tilemap.width;
this.height = tilemap.height;
this._data = data;
}
RangeMap.prototype.get = function (x0, y0, x1, y1) {
var t;
if (x1 < x0) {
t = x0;
x0 = x1;
x1 = t;
// assert(x0 <= x1);
}
if (y1 < y0) {
t = y0;
y0 = y1;
y1 = t;
// assert(y0 <= y1);
}
x0 = clamp(0, x0, this.width);
y0 = clamp(0, y0, this.height);
x1 = clamp(0, x1, this.width);
y1 = clamp(0, y1, this.height);
return (this._data[y1][x1] - this._data[y1][x0] -
this._data[y0][x1] + this._data[y0][x0]);
};
RangeMap.prototype.exists = function (rect) {
return (this.get(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height) !== 0);
};
return RangeMap;
}());
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="task.ts" />
/// <reference path="sprite.ts" />
/// <reference path="tilemap.ts" />
/** Entity: a thing that can interact with other things.
*/
var Entity = /** @class */ (function (_super) {
__extends(Entity, _super);
function Entity(pos) {
var _this = _super.call(this) || this;
_this.world = null;
_this.collider = null;
_this.sprites = [];
_this.order = 0;
_this.rotation = 0;
_this.scale = null;
_this.alpha = 1.0;
_this.pos = (pos !== null) ? pos.copy() : pos;
return _this;
}
Entity.prototype.toString = function () {
return '<Entity: ' + this.pos + '>';
};
Entity.prototype.isVisible = function () {
return this.isRunning();
};
Entity.prototype.render = function (ctx) {
ctx.save();
if (this.pos !== null) {
ctx.translate(this.pos.x, this.pos.y);
}
if (this.rotation) {
ctx.rotate(this.rotation);
}
if (this.scale !== null) {
ctx.scale(this.scale.x, this.scale.y);
}
ctx.globalAlpha = this.alpha;
for (var _i = 0, _a = this.sprites; _i < _a.length; _i++) {
var sprite = _a[_i];
sprite.render(ctx);
}
ctx.restore();
};
Entity.prototype.movePos = function (v) {
this.pos = this.pos.add(v);
};
Entity.prototype.getCollider = function (pos) {
if (pos === void 0) { pos = null; }
if (this.collider === null)
return null;
if (pos === null) {
pos = this.pos;
if (pos === null)
return null;
}
return this.collider.add(pos);
};
Entity.prototype.canMove = function (v0, context) {
if (context === void 0) { context = null; }
var v1 = this.getMove(this.pos, v0, context);
return v1.equals(v0);
};
Entity.prototype.getMove = function (pos, v, context) {
if (context === void 0) { context = null; }
if (this.collider === null)
return v;
var collider = this.collider.add(pos);
var hitbox0 = collider.getAABB();
var range = hitbox0.union(hitbox0.add(v));
var obstacles = this.getObstaclesFor(range, v, context);
var fences = this.getFencesFor(range, v, context);
var d = getContact(collider, v, obstacles, fences);
v = v.sub(d);
collider = collider.add(d);
if (v.x != 0) {
d = getContact(collider, new Vec2(v.x, 0), obstacles, fences);
v = v.sub(d);
collider = collider.add(d);
}
if (v.y != 0) {
d = getContact(collider, new Vec2(0, v.y), obstacles, fences);
v = v.sub(d);
collider = collider.add(d);
}
var hitbox1 = collider.getAABB();
return new Vec2(hitbox1.x - hitbox0.x, hitbox1.y - hitbox0.y);
};
Entity.prototype.moveIfPossible = function (v, context) {
if (context === void 0) { context = null; }
v = this.getMove(this.pos, v, context);
this.movePos(v);
return v;
};
Entity.prototype.getObstaclesFor = function (range, v, context) {
// [OVERRIDE]
return null;
};
Entity.prototype.getFencesFor = function (range, v, context) {
// [OVERRIDE]
return null;
};
Entity.prototype.onCollided = function (entity) {
// [OVERRIDE]
};
return Entity;
}(Task));
// Particle
//
var Particle = /** @class */ (function (_super) {
__extends(Particle, _super);
function Particle() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.movement = null;
return _this;
}
Particle.prototype.onTick = function () {
_super.prototype.onTick.call(this);
if (this.movement !== null) {
this.movePos(this.movement);
var frame = this.getFrame();
if (frame !== null) {
var collider = this.getCollider();
if (collider !== null && !collider.overlaps(frame)) {
this.stop();
}
}
}
};
Particle.prototype.getFrame = function () {
// [OVERRIDE]
return null;
};
return Particle;
}(Entity));
// TileMapEntity
//
var TileMapEntity = /** @class */ (function (_super) {
__extends(TileMapEntity, _super);
function TileMapEntity(tilemap, isObstacle, pos) {
var _this = _super.call(this, pos) || this;
_this.tilemap = tilemap;
_this.isObstacle = isObstacle;
return _this;
}
TileMapEntity.prototype.hasTile = function (f, pos) {
if (pos === void 0) { pos = null; }
var range = this.getCollider(pos).getAABB();
return (this.tilemap.findTileByCoord(f, range) !== null);
};
TileMapEntity.prototype.getObstaclesFor = function (range, v, context) {
return this.tilemap.getTileRects(this.isObstacle, range);
};
return TileMapEntity;
}(Entity));
// PhysicsConfig
//
var PhysicsConfig = /** @class */ (function () {
function PhysicsConfig() {
this.jumpfunc = (function (vy, t) {
return (0 <= t && t <= 5) ? -4 : vy + 1;
});
this.maxspeed = new Vec2(6, 6);
this.isObstacle = (function (c) { return false; });
this.isGrabbable = (function (c) { return false; });
this.isStoppable = (function (c) { return false; });
}
return PhysicsConfig;
}());
// PhysicalEntity
//
var PhysicalEntity = /** @class */ (function (_super) {
__extends(PhysicalEntity, _super);
function PhysicalEntity(physics, pos) {
var _this = _super.call(this, pos) || this;
_this.velocity = new Vec2();
_this._jumpt = Infinity;
_this._jumpend = 0;
_this._landed = false;
_this.physics = physics;
return _this;
}
PhysicalEntity.prototype.onTick = function () {
_super.prototype.onTick.call(this);
this.fall(this._jumpt);
if (this.isJumping()) {
this._jumpt++;
}
else {
this._jumpt = Infinity;
}
};
PhysicalEntity.prototype.setJump = function (jumpend) {
if (0 < jumpend) {
if (this.canJump()) {
this._jumpt = 0;
this.onJumped();
}
}
this._jumpend = jumpend;
};
PhysicalEntity.prototype.fall = function (t) {
if (this.canFall()) {
var vy = this.physics.jumpfunc(this.velocity.y, t);
var v = new Vec2(this.velocity.x, vy);
v = this.moveIfPossible(v, 'fall');
this.velocity = v.clamp(this.physics.maxspeed);
var landed = (0 < vy && this.velocity.y == 0);
if (!this._landed && landed) {
this.onLanded();
}
this._landed = landed;
}
else {
this.velocity = new Vec2();
if (!this._landed) {
this.onLanded();
}
this._landed = true;
}
};
PhysicalEntity.prototype.canJump = function () {
return this.isLanded();
};
PhysicalEntity.prototype.canFall = function () {
return true;
};
PhysicalEntity.prototype.isJumping = function () {
return (this._jumpt < this._jumpend);
};
PhysicalEntity.prototype.isLanded = function () {
return this._landed;
};
PhysicalEntity.prototype.onJumped = function () {
// [OVERRIDE]
};
PhysicalEntity.prototype.onLanded = function () {
// [OVERRIDE]
};
return PhysicalEntity;
}(Entity));
// PlatformerEntity
//
var PlatformerEntity = /** @class */ (function (_super) {
__extends(PlatformerEntity, _super);
function PlatformerEntity(tilemap, physics, pos) {
var _this = _super.call(this, physics, pos) || this;
_this.tilemap = tilemap;
return _this;
}
PlatformerEntity.prototype.hasTile = function (f, pos) {
if (pos === void 0) { pos = null; }
var range = this.getCollider(pos).getAABB();
return (this.tilemap.findTileByCoord(f, range) !== null);
};
PlatformerEntity.prototype.getObstaclesFor = function (range, v, context) {
var f = ((context == 'fall') ?
this.physics.isStoppable :
this.physics.isObstacle);
return this.tilemap.getTileRects(f, range);
};
return PlatformerEntity;
}(PhysicalEntity));
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="task.ts" />
/// <reference path="sprite.ts" />
/// <reference path="entity.ts" />
function makeGlyphs(src, color, inverted) {
if (color === void 0) { color = null; }
if (inverted === void 0) { inverted = false; }
var dst = createCanvas(src.width, src.height);
var ctx = getEdgeyContext(dst);
ctx.clearRect(0, 0, dst.width, dst.height);
ctx.drawImage(src, 0, 0);
if (color !== null) {
ctx.globalCompositeOperation = (inverted) ? 'source-out' : 'source-in';
ctx.fillStyle = color;
ctx.fillRect(0, 0, dst.width, dst.height);
}
return dst;
}
// Font
//
var Font = /** @class */ (function () {
function Font(glyphs, color, scale) {
if (color === void 0) { color = null; }
if (scale === void 0) { scale = 1; }
this.background = null;
this._csize = glyphs.height;
this.width = this._csize * scale;
this.height = this._csize * scale;
this.initGlyphs(glyphs, color);
}
Font.prototype.getSize = function (text) {
return new Vec2(this.width * text.length, this.height);
};
Font.prototype.initGlyphs = function (glyphs, color) {
if (color === void 0) { color = null; }
this._glyphs = makeGlyphs(glyphs, color);
};
Font.prototype.renderString = function (ctx, text, x, y) {
this.renderBackground(ctx, text, x, y);
this.renderGlyphs(ctx, this._glyphs, this._csize, text, x, y);
};
Font.prototype.renderBackground = function (ctx, text, x, y) {
if (this.background !== null) {
var size = this.getSize(text);
ctx.fillStyle = this.background;
ctx.fillRect(x, y, size.x, size.y);
}
};
Font.prototype.renderGlyphs = function (ctx, glyphs, csize, text, x, y) {
for (var i = 0; i < text.length; i++) {
var c = text.charCodeAt(i) - 32;
if (0 <= c) {
ctx.drawImage(glyphs, c * csize, 0, csize, glyphs.height, x + this.width * i, y, this.width, this.height);
}
}
};
return Font;
}());
// InvertedFont
//
var InvertedFont = /** @class */ (function (_super) {
__extends(InvertedFont, _super);
function InvertedFont() {
return _super !== null && _super.apply(this, arguments) || this;
}
InvertedFont.prototype.initGlyphs = function (glyphs, color) {
if (color === void 0) { color = null; }
this._glyphs = makeGlyphs(glyphs, color, true);
};
return InvertedFont;
}(Font));
// ShadowFont
//
var ShadowFont = /** @class */ (function (_super) {
__extends(ShadowFont, _super);
function ShadowFont(glyphs, color, scale, shadowColor, shadowDist) {
if (color === void 0) { color = null; }
if (scale === void 0) { scale = 1; }
if (shadowColor === void 0) { shadowColor = 'black'; }
if (shadowDist === void 0) { shadowDist = 1; }
var _this = _super.call(this, glyphs, color, scale) || this;
_this.shadowDist = shadowDist;
_this._glyphs2 = makeGlyphs(glyphs, shadowColor);
return _this;
}
ShadowFont.prototype.getSize2 = function (text) {
var size = _super.prototype.getSize.call(this, text);
return size.move(this.shadowDist, this.shadowDist);
};
ShadowFont.prototype.renderString = function (ctx, text, x, y) {
this.renderBackground(ctx, text, x, y);
this.renderGlyphs(ctx, this._glyphs2, this._csize, text, x + this.shadowDist, y + this.shadowDist);
this.renderGlyphs(ctx, this._glyphs, this._csize, text, x, y);
};
return ShadowFont;
}(Font));
// TextSegment
//
var TextSegment = /** @class */ (function () {
function TextSegment(p, text, font) {
var size = font.getSize(text);
this.bounds = new Rect(p.x, p.y, size.x, size.y);
this.text = text;
this.font = font;
}
return TextSegment;
}());
// TextBox
//
var TextBox = /** @class */ (function () {
function TextBox(frame, font) {
if (font === void 0) { font = null; }
this.header = '';
this.lineSpace = 0;
this.padding = 0;
this.background = null;
this.borderColor = null;
this.borderWidth = 2;
this._segments = [];
this.frame = frame.copy();
this.font = font;
}
TextBox.prototype.toString = function () {
return '<TextBox: ' + this.frame + '>';
};
TextBox.prototype.getBounds = function () {
return this.frame;
};
TextBox.prototype.getInnerBounds = function () {
return this.frame.inflate(-this.padding, -this.padding);
};
TextBox.prototype.render = function (ctx) {
ctx.save();
ctx.translate(int(this.frame.x), int(this.frame.y));
if (this.background !== null) {
ctx.fillStyle = this.background;
ctx.fillRect(0, 0, this.frame.width, this.frame.height);
}
if (this.borderColor !== null) {
var b = this.borderWidth;
ctx.strokeStyle = 'white';
ctx.lineWidth = b;
ctx.strokeRect(-b, -b, this.frame.width + b * 2, this.frame.height + b * 2);
}
for (var _i = 0, _a = this._segments; _i < _a.length; _i++) {
var seg = _a[_i];
seg.font.renderString(ctx, seg.text, this.padding + seg.bounds.x, this.padding + seg.bounds.y);
}
ctx.restore();
};
TextBox.prototype.clear = function () {
this._segments = [];
};
TextBox.prototype.add = function (seg) {
this._segments.push(seg);
};
TextBox.prototype.addSegment = function (p, text, font) {
if (font === void 0) { font = null; }
font = (font !== null) ? font : this.font;
var seg = new TextSegment(p, text, font);
this.add(seg);
return seg;
};
TextBox.prototype.addNewline = function (font) {
if (font === void 0) { font = null; }
font = (font !== null) ? font : this.font;
var height = this.frame.height - this.padding * 2;
var y = 0;
if (this._segments.length !== 0) {
y = this._segments[this._segments.length - 1].bounds.y1() + this.lineSpace;
}
var newseg = this.addSegment(new Vec2(0, y), '', font);
var dy = newseg.bounds.y1() - height;
if (0 < dy) {
// scrolling.
this._segments = this._segments.filter(function (seg) {
seg.bounds.y -= dy;
return 0 <= seg.bounds.y;
});
}
return newseg;
};
TextBox.prototype.getSize = function (lines, font) {
if (font === void 0) { font = null; }
font = (font !== null) ? font : this.font;
var w = 0, h = 0;
for (var i = 0; i < lines.length; i++) {
var size = font.getSize(lines[i]);
w = Math.max(w, size.x);
h = h + size.y + this.lineSpace;
}
return new Vec2(w, h - this.lineSpace);
};
TextBox.prototype.addText = function (text, font) {
if (font === void 0) { font = null; }
font = (font !== null) ? font : this.font;
var width = this.frame.width - this.padding * 2;
for (var i = 0; i < text.length;) {
if (text[i] == '\n') {
this.addNewline(font);
i++;
continue;
}
var j = text.indexOf('\n', i);
if (j < 0) {
j = text.length;
}
var s = text.substring(i, j);
var size = font.getSize(s);
var last = ((this._segments.length === 0) ? null :
this._segments[this._segments.length - 1]);
if (last === null || width < last.bounds.x1() + size.x) {
last = this.addNewline(font);
}
else if (last.font !== font) {
var pt = new Vec2(last.bounds.x1(), last.bounds.y);
last = this.addSegment(pt, '', font);
}
last.text += s;
last.bounds.width += size.x;
last.bounds.height = Math.max(last.bounds.height, size.y);
i = j;
}
};
TextBox.prototype.splitWords = function (x, text, font, header) {
if (font === void 0) { font = null; }
if (header === void 0) { header = null; }
font = (font !== null) ? font : this.font;
header = (header !== null) ? header : this.header;
var line = '';
var a = [];
var word = /\w+\W*/;
var width = this.frame.width - this.padding * 2;
while (true) {
var m = word.exec(text);
if (m == null) {
a.push(line + text);
break;
}
var i = m.index + m[0].length;
var w = text.substr(0, i);
var size = font.getSize(w);
if (width < x + size.x) {
a.push(line);
line = header;
x = font.getSize(line).x;
}
line += w;
x += size.x;
text = text.substr(i);
}
return a;
};
TextBox.prototype.wrapLines = function (text, font, header) {
if (font === void 0) { font = null; }
if (header === void 0) { header = null; }
var x = ((this._segments.length === 0) ? 0 :
this._segments[this._segments.length - 1].bounds.x1());
var a = this.splitWords(x, text, font, header);
var s = '';
for (var i = 0; i < a.length; i++) {
if (i != 0) {
s += '\n';
}
s += a[i];
}
return s;
};
TextBox.prototype.putText = function (lines, halign, valign, font) {
if (halign === void 0) { halign = 'left'; }
if (valign === void 0) { valign = 'top'; }
if (font === void 0) { font = null; }
font = (font !== null) ? font : this.font;
var width = this.frame.width - this.padding * 2;
var height = this.frame.height - this.padding * 2;
var y = 0;
switch (valign) {
case 'center':
y += (height - this.getSize(lines, font).y) / 2;
break;
case 'bottom':
y += height - this.getSize(lines, font).y;
break;
}
for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
var text = lines_1[_i];
var size = font.getSize(text);
var x = 0;
switch (halign) {
case 'center':
x += (width - size.x) / 2;
break;
case 'right':
x += width - size.x;
break;
}
var bounds = new Rect(x, y, size.x, size.y);
this._segments.push({ bounds: bounds, text: text, font: font });
y += size.y + this.lineSpace;
}
};
return TextBox;
}());
// BannerBox
//
var BannerBox = /** @class */ (function (_super) {
__extends(BannerBox, _super);
function BannerBox(frame, font, lines, lineSpace) {
if (lines === void 0) { lines = null; }
if (lineSpace === void 0) { lineSpace = 4; }
var _this = _super.call(this, null) || this;
_this.interval = 0;
_this.textbox = new TextBox(frame, font);
_this.textbox.lineSpace = lineSpace;
_this.sprites = [_this.textbox];
if (lines !== null) {
_this.putText(lines);
}
return _this;
}
BannerBox.prototype.putText = function (lines, halign, valign) {
if (halign === void 0) { halign = 'center'; }
if (valign === void 0) { valign = 'center'; }
this.textbox.putText(lines, halign, valign);
};
BannerBox.prototype.isVisible = function () {
return (this.isRunning() &&
((this.interval <= 0) ||
(phase(this.getTime(), this.interval) != 0)));
};
return BannerBox;
}(Entity));
// TextParticle
//
var TextParticle = /** @class */ (function (_super) {
__extends(TextParticle, _super);
function TextParticle(pos, font, text, borderWidth) {
if (borderWidth === void 0) { borderWidth = 1; }
var _this = this;
var size = font.getSize(text);
var frame = new Vec2().expand(size.x + borderWidth * 2, size.y + borderWidth * 2);
_this = _super.call(this, frame, font, [text], 0) || this;
_this.pos = pos;
_this.movement = null;
return _this;
}
TextParticle.prototype.onTick = function () {
_super.prototype.onTick.call(this);
if (this.movement !== null) {
this.movePos(this.movement);
}
};
return TextParticle;
}(BannerBox));
// TextTask
//
var TextTask = /** @class */ (function (_super) {
__extends(TextTask, _super);
function TextTask(dialog) {
var _this = _super.call(this) || this;
_this.dialog = dialog;
return _this;
}
TextTask.prototype.ff = function () {
};
TextTask.prototype.onKeyDown = function (key) {
this.ff();
};
TextTask.prototype.onMouseDown = function (p, button) {
this.ff();
};
TextTask.prototype.onMouseUp = function (p, button) {
};
TextTask.prototype.onMouseMove = function (p) {
};
return TextTask;
}(Task));
// PauseTask
//
var PauseTask = /** @class */ (function (_super) {
__extends(PauseTask, _super);
function PauseTask(dialog, duration) {
var _this = _super.call(this, dialog) || this;
_this.lifetime = duration;
return _this;
}
PauseTask.prototype.ff = function () {
this.stop();
};
return PauseTask;
}(TextTask));
// DisplayTask
//
var DisplayTask = /** @class */ (function (_super) {
__extends(DisplayTask, _super);
function DisplayTask(dialog, text) {
var _this = _super.call(this, dialog) || this;
_this.speed = 0;
_this.sound = null;
_this._index = 0;
_this.text = text;
_this.font = dialog.textbox.font;
return _this;
}
DisplayTask.prototype.onStart = function () {
_super.prototype.onStart.call(this);
this.text = this.dialog.textbox.wrapLines(this.text, this.font);
};
DisplayTask.prototype.onTick = function () {
_super.prototype.onTick.call(this);
if (this.text.length <= this._index) {
this.stop();
}
else if (this.speed === 0) {
this.ff();
}
else {
var n = this.getTime() * this.speed;
var sound = false;
while (this._index < n) {
var c = this.text.substr(this._index, 1);
this.dialog.textbox.addText(c, this.font);
this._index++;
sound = sound || (/\w/.test(c));
}
if (sound && this.sound !== null) {
APP.playSound(this.sound);
}
}
};
DisplayTask.prototype.ff = function () {
while (this._index < this.text.length) {
this.dialog.textbox.addText(this.text.substr(this._index, 1), this.font);
this._index++;
}
this.stop();
};
return DisplayTask;
}(TextTask));
// MenuTask
//
var MenuItem = /** @class */ (function () {
function MenuItem(pos, text, value) {
this.seg = null;
this.pos = pos.copy();
this.text = text;
this.value = value;
}
return MenuItem;
}());
var MenuTask = /** @class */ (function (_super) {
__extends(MenuTask, _super);
function MenuTask(dialog) {
var _this = _super.call(this, dialog) || this;
_this.vertical = true;
_this.items = [];
_this.current = null;
_this.focus = null;
_this.sound = null;
_this.selected = new Signal(_this);
return _this;
}
MenuTask.prototype.addItem = function (pos, text, value) {
if (value === void 0) { value = null; }
value = (value !== null) ? value : text;
var item = new MenuItem(pos, text, value);
this.items.push(item);
if (2 <= this.items.length) {
var item0 = this.items[0];
var item1 = this.items[this.items.length - 1];
this.vertical = (Math.abs(item0.pos.x - item1.pos.x) <
Math.abs(item0.pos.y - item1.pos.y));
}
return item;
};
MenuTask.prototype.onStart = function () {
_super.prototype.onStart.call(this);
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
item.seg = this.dialog.textbox.addSegment(item.pos, item.text);
}
this.updateSelection();
};
MenuTask.prototype.onKeyDown = function (key) {
var d = 0;
var keysym = getKeySym(key);
switch (keysym) {
case KeySym.Left:
d = (this.vertical) ? -Infinity : -1;
break;
case KeySym.Right:
d = (this.vertical) ? +Infinity : +1;
break;
case KeySym.Up:
d = (this.vertical) ? -1 : -Infinity;
break;
case KeySym.Down:
d = (this.vertical) ? +1 : +Infinity;
break;
case KeySym.Action1:
case KeySym.Action2:
if (this.current !== null) {
this.stop();
this.selected.fire(this.current.value);
}
;
return;
case KeySym.Cancel:
this.stop();
this.selected.fire(null);
return;
}
var i = 0;
if (this.current !== null) {
i = this.items.indexOf(this.current);
i = clamp(0, i + d, this.items.length - 1);
}
this.current = this.items[i];
this.updateSelection();
if (this.sound !== null) {
APP.playSound(this.sound);
}
};
MenuTask.prototype.onMouseDown = function (p, button) {
this.updateFocus(p);
this.updateSelection();
if (button == 0 && this.focus !== null) {
this.current = this.focus;
}
};
MenuTask.prototype.onMouseUp = function (p, button) {
this.updateFocus(p);
this.updateSelection();
if (button == 0 && this.focus !== null) {
if (this.current === this.focus) {
this.stop();
this.selected.fire(this.current.value);
}
}
};
MenuTask.prototype.onMouseMove = function (p) {
this.updateFocus(p);
this.updateSelection();
};
MenuTask.prototype.updateFocus = function (p) {
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
if (item.seg !== null) {
if (item.seg.bounds.inflate(1, 1).containsPt(p)) {
this.focus = item;
return;
}
}
}
this.focus = null;
};
MenuTask.prototype.updateSelection = function () {
for (var _i = 0, _a = this.items; _i < _a.length; _i++) {
var item = _a[_i];
if (item === this.current ||
item === this.focus) {
item.seg.font = this.dialog.hiFont;
}
else {
item.seg.font = this.dialog.textbox.font;
}
}
};
return MenuTask;
}(TextTask));
var WaitTask = /** @class */ (function (_super) {
__extends(WaitTask, _super);
function WaitTask(dialog) {
var _this = _super.call(this, dialog) || this;
_this.ended = new Signal(_this);
return _this;
}
WaitTask.prototype.onKeyDown = function (key) {
var keysym = getKeySym(key);
switch (keysym) {
case KeySym.Action1:
case KeySym.Action2:
case KeySym.Cancel:
this.stop();
this.ended.fire();
return;
}
};
WaitTask.prototype.onMouseUp = function (p, button) {
if (button == 0) {
this.stop();
this.ended.fire();
}
};
return WaitTask;
}(TextTask));
// DialogBox
//
var DialogBox = /** @class */ (function (_super) {
__extends(DialogBox, _super);
function DialogBox(textbox, hiFont) {
if (hiFont === void 0) { hiFont = null; }
var _this = _super.call(this, new Vec2()) || this;
_this.speed = 0;
_this.autoHide = false;
_this.sound = null;
_this._tasks = [];
_this.sprites = [textbox];
_this.textbox = textbox;
_this.hiFont = hiFont;
return _this;
}
DialogBox.prototype.isVisible = function () {
return (!this.autoHide || 0 < this._tasks.length);
};
DialogBox.prototype.clear = function () {
this.textbox.clear();
this._tasks = [];
};
DialogBox.prototype.onTick = function () {
_super.prototype.onTick.call(this);
var task = null;
while (true) {
task = this.getCurrentTask();
if (task === null)
break;
if (task.isScheduled()) {
task.onStart();
}
if (task.isRunning()) {
task.onTick();
break;
}
this.remove(task);
}
};
DialogBox.prototype.onKeyDown = function (key) {
var task = this.getCurrentTask();
if (task !== null) {
task.onKeyDown(key);
}
};
DialogBox.prototype.onMouseDown = function (p, button) {
var task = this.getCurrentTask();
if (task !== null) {
var bounds = this.textbox.getInnerBounds();
p = p.move(-bounds.x, -bounds.y);
task.onMouseDown(p, button);
}
};
DialogBox.prototype.onMouseUp = function (p, button) {
var task = this.getCurrentTask();
if (task !== null) {
var bounds = this.textbox.getInnerBounds();
p = p.move(-bounds.x, -bounds.y);
task.onMouseUp(p, button);
}
};
DialogBox.prototype.onMouseMove = function (p) {
var task = this.getCurrentTask();
if (task !== null) {
var bounds = this.textbox.getInnerBounds();
p = p.move(-bounds.x, -bounds.y);
task.onMouseMove(p);
}
};
DialogBox.prototype.ff = function () {
while (true) {
var task = this.getCurrentTask();
if (task === null)
break;
if (task.isScheduled()) {
task.onStart();
}
task.ff();
if (task.isRunning())
break;
this.remove(task);
}
};
DialogBox.prototype.getCurrentTask = function () {
return (0 < this._tasks.length) ? this._tasks[0] : null;
};
DialogBox.prototype.add = function (task) {
task.parent = this;
if (task instanceof TextTask) {
this._tasks.push(task);
}
};
DialogBox.prototype.remove = function (task) {
removeElement(this._tasks, task);
};
DialogBox.prototype.addPause = function (duration) {
var task = new PauseTask(this, duration);
this.add(task);
return task;
};
DialogBox.prototype.addDisplay = function (text, speed, sound, font) {
if (speed === void 0) { speed = -1; }
if (sound === void 0) { sound = null; }
if (font === void 0) { font = null; }
var task = new DisplayTask(this, text);
task.speed = (0 <= speed) ? speed : this.speed;
task.sound = (sound !== null) ? sound : this.sound;
task.font = (font !== null) ? font : this.textbox.font;
this.add(task);
return task;
};
DialogBox.prototype.addMenu = function () {
var task = new MenuTask(this);
this.add(task);
return task;
};
DialogBox.prototype.addWait = function () {
var task = new WaitTask(this);
this.add(task);
return task;
};
return DialogBox;
}(Entity));
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="task.ts" />
/// <reference path="entity.ts" />
// World
//
var World = /** @class */ (function (_super) {
__extends(World, _super);
function World(area) {
var _this = _super.call(this) || this;
_this.mouseFocus = null;
_this.mouseActive = null;
_this.mouseDown = new Signal(_this);
_this.mouseUp = new Signal(_this);
_this.area = area.copy();
_this.reset();
return _this;
}
World.prototype.toString = function () {
return '<World: ' + this.area + '>';
};
World.prototype.reset = function () {
this.window = this.area.copy();
this.entities = [];
};
World.prototype.onTick = function () {
_super.prototype.onTick.call(this);
this.checkEntityCollisions();
};
World.prototype.add = function (task) {
if (task instanceof Entity) {
task.world = this;
this.entities.push(task);
this.sortEntitiesByOrder();
}
_super.prototype.add.call(this, task);
};
World.prototype.remove = function (task) {
if (task instanceof Entity) {
removeElement(this.entities, task);
}
_super.prototype.remove.call(this, task);
};
World.prototype.render = function (ctx) {
ctx.save();
ctx.translate(-this.window.x, -this.window.y);
for (var _i = 0, _a = this.entities; _i < _a.length; _i++) {
var entity = _a[_i];
if (!entity.isVisible())
continue;
if (entity.pos === null)
continue;
entity.render(ctx);
}
ctx.restore();
for (var _b = 0, _c = this.entities; _b < _c.length; _b++) {
var entity = _c[_b];
if (!entity.isVisible())
continue;
if (entity.pos !== null)
continue;
entity.render(ctx);
}
};
World.prototype.findEntityAt = function (p) {
var found = null;
for (var _i = 0, _a = this.entities; _i < _a.length; _i++) {
var entity = _a[_i];
if (!entity.isVisible())
continue;
var collider = entity.getCollider();
if (collider instanceof Rect) {
if (collider.containsPt(p)) {
if (found === null || entity.order < found.order) {
found = entity;
}
}
}
}
return found;
};
World.prototype.moveCenter = function (v) {
this.window = this.window.add(v);
};
World.prototype.setCenter = function (target, bounds) {
if (bounds === void 0) { bounds = null; }
if (this.window.width < target.width) {
this.window.x = (target.width - this.window.width) / 2;
}
else if (target.x < this.window.x) {
this.window.x = target.x;
}
else if (this.window.x + this.window.width < target.x + target.width) {
this.window.x = target.x + target.width - this.window.width;
}
if (this.window.height < target.height) {
this.window.y = (target.height - this.window.height) / 2;
}
else if (target.y < this.window.y) {
this.window.y = target.y;
}
else if (this.window.y + this.window.height < target.y + target.height) {
this.window.y = target.y + target.height - this.window.height;
}
if (bounds !== null) {
this.window = this.window.clamp(bounds);
}
};
World.prototype.moveAll = function (v) {
for (var _i = 0, _a = this.entities; _i < _a.length; _i++) {
var entity = _a[_i];
if (!entity.isRunning())
continue;
if (entity.pos === null)
continue;
entity.movePos(v);
}
};
World.prototype.onMouseDown = function (p, button) {
if (button == 0) {
this.mouseFocus = this.findEntityAt(p);
this.mouseActive = this.mouseFocus;
if (this.mouseActive !== null) {
this.mouseDown.fire(this.mouseActive, p);
}
}
};
World.prototype.onMouseUp = function (p, button) {
if (button == 0) {
this.mouseFocus = this.findEntityAt(p);
if (this.mouseActive !== null) {
this.mouseUp.fire(this.mouseActive, p);
}
this.mouseActive = null;
}
};
World.prototype.onMouseMove = function (p) {
if (this.mouseActive === null) {
this.mouseFocus = this.findEntityAt(p);
}
};
World.prototype.applyEntities = function (f, collider0) {
if (collider0 === void 0) { collider0 = null; }
for (var _i = 0, _a = this.entities; _i < _a.length; _i++) {
var entity1 = _a[_i];
if (!entity1.isRunning())
continue;
if (collider0 !== null) {
var collider1 = entity1.getCollider();
if (collider1 !== null && !collider1.overlaps(collider0))
continue;
}
if (f(entity1)) {
return entity1;
}
}
return null;
};
World.prototype.sortEntitiesByOrder = function () {
this.entities.sort(function (a, b) { return a.order - b.order; });
};
World.prototype.getEntityColliders = function (f0, range) {
if (range === void 0) { range = null; }
var a = [];
var f = function (entity) {
if (f0(entity)) {
var collider = entity.getCollider();
if (collider != null) {
a.push(collider);
}
}
return false;
};
this.applyEntities(f, range);
return a;
};
World.prototype.checkEntityCollisions = function () {
this.applyEntityPairs(function (e0, e1) {
e0.onCollided(e1);
e1.onCollided(e0);
});
};
World.prototype.applyEntityPairs = function (f) {
for (var i = 0; i < this.entities.length; i++) {
var entity0 = this.entities[i];
if (!entity0.isRunning())
continue;
var collider0 = entity0.getCollider();
if (collider0 === null)
continue;
for (var j = i + 1; j < this.entities.length; j++) {
var entity1 = this.entities[j];
if (!entity1.isRunning())
continue;
var collider1 = entity1.getCollider();
if (collider1 === null)
continue;
if (collider0.overlaps(collider1)) {
f(entity0, entity1);
}
}
}
};
return World;
}(ParallelTaskList));
// Scene
//
var Scene = /** @class */ (function () {
function Scene() {
this.screen = new Rect(0, 0, APP.canvas.width, APP.canvas.height);
}
Scene.prototype.changeScene = function (scene) {
APP.post(function () { APP.init(scene); });
};
Scene.prototype.reset = function () {
this.onStop();
this.onStart();
};
Scene.prototype.onStart = function () {
// [OVERRIDE]
};
Scene.prototype.onStop = function () {
// [OVERRIDE]
};
Scene.prototype.onTick = function () {
// [OVERRIDE]
};
Scene.prototype.render = function (ctx) {
// [OVERRIDE]
};
Scene.prototype.onDirChanged = function (v) {
// [OVERRIDE]
};
Scene.prototype.onButtonPressed = function (keysym) {
// [OVERRIDE]
};
Scene.prototype.onButtonReleased = function (keysym) {
// [OVERRIDE]
};
Scene.prototype.onKeyDown = function (key) {
// [OVERRIDE]
};
Scene.prototype.onKeyUp = function (key) {
// [OVERRIDE]
};
Scene.prototype.onKeyPress = function (char) {
// [OVERRIDE]
};
Scene.prototype.onMouseDown = function (p, button) {
// [OVERRIDE]
};
Scene.prototype.onMouseUp = function (p, button) {
// [OVERRIDE]
};
Scene.prototype.onMouseMove = function (p) {
// [OVERRIDE]
};
Scene.prototype.onFocus = function () {
// [OVERRIDE]
};
Scene.prototype.onBlur = function () {
// [OVERRIDE]
};
return Scene;
}());
// HTMLScene
//
var HTMLScene = /** @class */ (function (_super) {
__extends(HTMLScene, _super);
function HTMLScene(text) {
var _this = _super.call(this) || this;
_this.text = text;
return _this;
}
HTMLScene.prototype.onStart = function () {
_super.prototype.onStart.call(this);
var scene = this;
var bounds = APP.elem.getBoundingClientRect();
var e = APP.addElement(new Rect(bounds.width / 8, bounds.height / 4, 3 * bounds.width / 4, bounds.height / 2));
e.align = 'left';
e.style.padding = '10px';
e.style.color = 'black';
e.style.background = 'white';
e.style.border = 'solid black 2px';
e.innerHTML = this.text;
e.onmousedown = (function (e) { scene.onChanged(); });
};
HTMLScene.prototype.render = function (ctx) {
ctx.fillStyle = 'rgb(0,0,0)';
fillRect(ctx, this.screen);
};
HTMLScene.prototype.onChanged = function () {
// [OVERRIDE]
};
HTMLScene.prototype.onMouseDown = function (p, button) {
this.onChanged();
};
HTMLScene.prototype.onKeyDown = function (key) {
this.onChanged();
};
return HTMLScene;
}(Scene));
// GameScene
//
var GameScene = /** @class */ (function (_super) {
__extends(GameScene, _super);
function GameScene() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.world = null;
return _this;
}
GameScene.prototype.onStart = function () {
_super.prototype.onStart.call(this);
this.world = new World(this.screen);
this.world.onStart();
};
GameScene.prototype.onTick = function () {
_super.prototype.onTick.call(this);
this.world.onTick();
};
GameScene.prototype.render = function (ctx) {
_super.prototype.render.call(this, ctx);
this.world.render(ctx);
};
GameScene.prototype.add = function (task) {
this.world.add(task);
};
GameScene.prototype.remove = function (task) {
this.world.remove(task);
};
GameScene.prototype.onMouseDown = function (p, button) {
_super.prototype.onMouseDown.call(this, p, button);
this.world.onMouseDown(p, button);
};
GameScene.prototype.onMouseUp = function (p, button) {
_super.prototype.onMouseUp.call(this, p, button);
this.world.onMouseUp(p, button);
};
GameScene.prototype.onMouseMove = function (p) {
_super.prototype.onMouseMove.call(this, p);
this.world.onMouseMove(p);
};
return GameScene;
}(Scene));
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="text.ts" />
/// <reference path="scene.ts" />
/** Initial gap of lame-encded MP3 files */
var MP3_GAP = 0.025;
function getprops(a) {
var d = {};
for (var i = 0; i < a.length; i++) {
d[a[i].id] = a[i];
}
return d;
}
// App
// handles the event loop and global state management.
// It also has shared resources (images, sounds, etc.)
//
var App = /** @class */ (function () {
function App(size, framerate, elem) {
this.scene = null;
this.active = false;
this.keys = {};
this.keyDir = new Vec2();
this.mousePos = new Vec2();
this.mouseButton = false;
this._keylock = 0;
this._msgs = [];
this._music = null;
this._loop_start = 0;
this._loop_end = 0;
this._touch_id = null;
this.size = size;
this.framerate = framerate;
this.elem = elem;
// Initialize the off-screen bitmap.
this.canvas = createCanvas(this.size.x, this.size.y);
this.ctx = getEdgeyContext(this.canvas);
// WebAudio!
try {
this.audioContext = new AudioContext();
}
catch (e) {
this.audioContext = null;
}
// Resources;
this.images = getprops(document.getElementsByTagName('img'));
this.sounds = getprops(document.getElementsByTagName('audio'));
this.labels = getprops(document.getElementsByClassName('label'));
}
App.prototype.init = function (scene) {
removeChildren(this.elem, 'div');
this.setMusic();
if (this.scene !== null) {
this.scene.onStop();
}
this.scene = scene;
this.scene.onStart();
};
App.prototype.post = function (msg) {
this._msgs.push(msg);
};
App.prototype.addElement = function (bounds) {
var e = document.createElement('div');
e.style.position = 'absolute';
e.style.left = bounds.x + 'px';
e.style.top = bounds.y + 'px';
e.style.width = bounds.width + 'px';
e.style.height = bounds.height + 'px';
e.style.padding = '0px';
this.elem.appendChild(e);
return e;
};
App.prototype.removeElement = function (e) {
e.parentNode.removeChild(e);
};
App.prototype.lockKeys = function (t) {
if (t === void 0) { t = 1; }
this._keylock = getTime() + t;
};
App.prototype.keyDown = function (ev) {
if (0 < this._keylock)
return;
var keysym = getKeySym(ev.keyCode);
switch (keysym) {
case KeySym.Left:
this.keyDir.x = -1;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Right:
this.keyDir.x = +1;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Up:
this.keyDir.y = -1;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Down:
this.keyDir.y = +1;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Action1:
case KeySym.Action2:
case KeySym.Cancel:
if (!this.keys[keysym]) {
this.scene.onButtonPressed(keysym);
}
break;
default:
switch (ev.keyCode) {
case 112: // F1
break;
case 27: // ESC
if (this.active) {
this.blur();
}
else {
this.focus();
}
break;
}
break;
}
this.keys[keysym] = true;
this.scene.onKeyDown(ev.keyCode);
};
App.prototype.keyUp = function (ev) {
var keysym = getKeySym(ev.keyCode);
switch (keysym) {
case KeySym.Left:
this.keyDir.x = (this.keys[KeySym.Right]) ? +1 : 0;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Right:
this.keyDir.x = (this.keys[KeySym.Left]) ? -1 : 0;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Up:
this.keyDir.y = (this.keys[KeySym.Down]) ? +1 : 0;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Down:
this.keyDir.y = (this.keys[KeySym.Up]) ? -1 : 0;
this.scene.onDirChanged(this.keyDir);
break;
case KeySym.Action1:
case KeySym.Action2:
case KeySym.Cancel:
if (this.keys[keysym]) {
this.scene.onButtonReleased(keysym);
}
break;
}
this.keys[keysym] = false;
this.scene.onKeyUp(ev.keyCode);
};
App.prototype.keyPress = function (ev) {
this.scene.onKeyPress(ev.charCode);
};
App.prototype.updateMousePos = function (ev) {
var bounds = this.elem.getBoundingClientRect();
this.mousePos = new Vec2((ev.clientX - bounds.left) * this.canvas.width / bounds.width, (ev.clientY - bounds.top) * this.canvas.height / bounds.height);
};
App.prototype.mouseDown = function (ev) {
this.updateMousePos(ev);
switch (ev.button) {
case 0:
this.mouseButton = true;
break;
}
this.scene.onMouseDown(this.mousePos, ev.button);
};
App.prototype.mouseUp = function (ev) {
this.updateMousePos(ev);
switch (ev.button) {
case 0:
this.mouseButton = false;
break;
}
this.scene.onMouseUp(this.mousePos, ev.button);
};
App.prototype.mouseMove = function (ev) {
this.updateMousePos(ev);
this.scene.onMouseMove(this.mousePos);
};
App.prototype.touchStart = function (ev) {
var touches = ev.changedTouches;
for (var i = 0; i < touches.length; i++) {
var t = touches[i];
if (this._touch_id === null) {
this._touch_id = t.identifier;
this.mouseButton = true;
this.updateMousePos(t);
this.scene.onMouseDown(this.mousePos, 0);
}
}
};
App.prototype.touchEnd = function (ev) {
var touches = ev.changedTouches;
for (var i = 0; i < touches.length; i++) {
var t = touches[i];
if (this._touch_id !== null) {
this._touch_id = null;
this.mouseButton = false;
this.updateMousePos(t);
this.scene.onMouseUp(this.mousePos, 0);
}
}
};
App.prototype.touchMove = function (ev) {
var touches = ev.changedTouches;
for (var i = 0; i < touches.length; i++) {
var t = touches[i];
if (this._touch_id == t.identifier) {
this.updateMousePos(t);
this.scene.onMouseMove(this.mousePos);
}
}
};
App.prototype.focus = function () {
this.active = true;
if (this._music !== null && 0 < this._music.currentTime) {
this._music.play();
}
this.scene.onFocus();
};
App.prototype.blur = function () {
this.scene.onBlur();
if (this._music !== null) {
this._music.pause();
}
this.active = false;
};
App.prototype.tick = function () {
this.scene.onTick();
if (0 < this._keylock && this._keylock < getTime()) {
this._keylock = 0;
}
if (this._music !== null &&
this._loop_start < this._loop_end &&
this._loop_end <= this._music.currentTime) {
this._music.currentTime = this._loop_start;
}
while (0 < this._msgs.length) {
var msg = this._msgs.shift();
msg();
}
};
App.prototype.repaint = function () {
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.save();
this.scene.render(this.ctx);
this.ctx.restore();
};
App.prototype.setMusic = function (name, start, end) {
if (name === void 0) { name = null; }
if (start === void 0) { start = MP3_GAP; }
if (end === void 0) { end = 0; }
if (this._music !== null) {
this._music.pause();
}
if (name === null) {
this._music = null;
}
else {
var sound = this.sounds[name];
this._loop_start = start;
this._loop_end = (end < 0) ? sound.duration : end;
if (0 < sound.readyState) { // for IE bug
sound.currentTime = MP3_GAP;
}
this._music = sound;
this._music.play();
}
};
/** Play a sound resource.
* @param sound Sound name.
* @param start Start position.
*/
App.prototype.playSound = function (name, start) {
if (start === void 0) { start = MP3_GAP; }
var elem = this.sounds[name];
elem.currentTime = start;
elem.play();
};
return App;
}());
// Global hook.
var HOOKS = [];
// addInitHook: adds an initialization hoook.
function addInitHook(hook) {
HOOKS.push(hook);
}
var APP = null;
// main: sets up the browser interaction.
function main(scene0, width, height, elemId, framerate) {
if (width === void 0) { width = 320; }
if (height === void 0) { height = 240; }
if (elemId === void 0) { elemId = 'game'; }
if (framerate === void 0) { framerate = 30; }
var elem = document.getElementById(elemId);
var size = new Vec2(width, height);
var app = new App(size, framerate, elem);
var canvas = app.canvas;
function tick() {
if (app.active) {
app.tick();
app.repaint();
}
}
function keydown(e) {
if (app.active) {
switch (e.keyCode) {
case 17: // Control
case 18: // Meta
break;
default:
app.keyDown(e);
break;
}
switch (e.keyCode) {
case 8: // Backspace
case 9: // Tab
case 13: // Return
case 14: // Enter
case 32: // Space
case 33: // PageUp
case 34: // PageDown
case 35: // End
case 36: // Home
case 37: // Left
case 38: // Up
case 39: // Right
case 40: // Down
e.preventDefault();
break;
}
}
}
function keyup(e) {
if (app.active) {
switch (e.keyCode) {
case 17: // Control
case 18: // Meta
break;
default:
app.keyUp(e);
break;
}
}
}
function keypress(e) {
if (app.active) {
app.keyPress(e);
}
}
function mousedown(e) {
if (app.active) {
app.mouseDown(e);
}
}
function mouseup(e) {
if (app.active) {
app.mouseUp(e);
}
}
function mousemove(e) {
if (app.active) {
app.mouseMove(e);
}
}
function touchstart(e) {
if (app.active) {
app.touchStart(e);
e.preventDefault();
}
}
function touchend(e) {
if (app.active) {
app.touchEnd(e);
e.preventDefault();
}
}
function touchmove(e) {
if (app.active) {
app.touchMove(e);
e.preventDefault();
}
}
function focus(e) {
info("app.focus");
if (!app.active) {
app.focus();
}
}
function blur(e) {
info("app.blur");
if (app.active) {
app.blur();
}
var size = Math.min(canvas.width, canvas.height) / 8;
var ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = 'rgba(0,0,64, 0.5)'; // gray out.
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'lightgray';
ctx.beginPath(); // draw a play button.
ctx.moveTo(canvas.width / 2 - size, canvas.height / 2 - size);
ctx.lineTo(canvas.width / 2 - size, canvas.height / 2 + size);
ctx.lineTo(canvas.width / 2 + size, canvas.height / 2);
ctx.fill();
ctx.restore();
}
function resize(e) {
info("app.resize");
var bounds = elem.getBoundingClientRect();
// Center the canvas.
var cw = bounds.width, ch = bounds.height;
if (canvas.height * bounds.width < canvas.width * bounds.height) {
ch = int(canvas.height * bounds.width / canvas.width);
}
else {
cw = int(canvas.width * bounds.height / canvas.height);
}
canvas.style.position = 'absolute';
canvas.style.padding = '0px';
canvas.style.left = ((bounds.width - cw) / 2) + 'px';
canvas.style.top = ((bounds.height - ch) / 2) + 'px';
canvas.style.width = cw + 'px';
canvas.style.height = ch + 'px';
}
APP = app;
if (APP.audioContext !== null) {
for (var id in APP.sounds) {
var source = APP.audioContext.createMediaElementSource(APP.sounds[id]);
source.connect(APP.audioContext.destination);
}
}
for (var _i = 0, HOOKS_1 = HOOKS; _i < HOOKS_1.length; _i++) {
var hook = HOOKS_1[_i];
hook();
}
app.init(new scene0());
app.focus();
elem.appendChild(canvas);
elem.addEventListener('mousedown', mousedown, false);
elem.addEventListener('mouseup', mouseup, false);
elem.addEventListener('mousemove', mousemove, false);
elem.addEventListener('touchstart', touchstart, false);
elem.addEventListener('touchend', touchend, false);
elem.addEventListener('touchmove', touchmove, false);
elem.focus();
resize(null);
window.addEventListener('focus', focus);
window.addEventListener('blur', blur);
window.addEventListener('keydown', keydown);
window.addEventListener('keyup', keyup);
window.addEventListener('keypress', keypress);
window.addEventListener('resize', resize);
window.setInterval(tick, 1000 / framerate);
window.focus();
}
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="tilemap.ts" />
/// <reference path="entity.ts" />
// GridConfig
//
var GridConfig = /** @class */ (function () {
function GridConfig(tilemap, resolution) {
if (resolution === void 0) { resolution = 1; }
this.tilemap = tilemap;
this.gridsize = tilemap.tilesize / resolution;
this.offset = fmod(this.gridsize, tilemap.tilesize) / 2;
}
GridConfig.prototype.coord2grid = function (p) {
return new Vec2(int((p.x - this.offset) / this.gridsize), int((p.y - this.offset) / this.gridsize));
};
GridConfig.prototype.grid2coord = function (p) {
return new Vec2(int((p.x + .5) * this.gridsize) + this.offset, int((p.y + .5) * this.gridsize) + this.offset);
};
GridConfig.prototype.clip = function (rect) {
return this.tilemap.bounds.intersection(rect);
};
return GridConfig;
}());
// PlanAction
//
function getKey(x, y, context) {
if (context === void 0) { context = null; }
return (context === null) ? (x + ',' + y) : (x + ',' + y + ':' + context);
}
var PlanAction = /** @class */ (function () {
function PlanAction(p, next, cost, context) {
if (next === void 0) { next = null; }
if (cost === void 0) { cost = 0; }
if (context === void 0) { context = null; }
this.p = p.copy();
this.next = next;
this.cost = cost;
this.context = context;
}
PlanAction.prototype.getKey = function () {
return getKey(this.p.x, this.p.y, this.context);
};
PlanAction.prototype.getColor = function () {
return null;
};
PlanAction.prototype.getList = function () {
var a = [];
var action = this;
while (action !== null) {
a.push(action);
action = action.next;
}
return a;
};
PlanAction.prototype.chain = function (next) {
var action = this;
while (true) {
if (action.next === null) {
action.next = next;
break;
}
action = action.next;
}
return next;
};
PlanAction.prototype.toString = function () {
return ('<PlanAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
return PlanAction;
}());
var NullAction = /** @class */ (function (_super) {
__extends(NullAction, _super);
function NullAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
NullAction.prototype.toString = function () {
return ('<NullAction(' + this.p.x + ',' + this.p.y + ')>');
};
return NullAction;
}(PlanAction));
// PlanMap
//
var PlanActionEntry = /** @class */ (function () {
function PlanActionEntry(action, total) {
this.action = action;
this.total = total;
}
return PlanActionEntry;
}());
var PlanMap = /** @class */ (function () {
function PlanMap() {
this._map = {};
this._queue = [];
this._goal = null; // for debugging
this._start = null; // for debugging
}
PlanMap.prototype.toString = function () {
return ('<PlanMap>');
};
PlanMap.prototype.addAction = function (start, action) {
var key = action.getKey();
var prev = this._map[key];
if (prev === undefined || action.cost < prev.cost) {
this._map[key] = action;
var dist = ((start === null) ? Infinity :
(Math.abs(start.x - action.p.x) +
Math.abs(start.y - action.p.y)));
this._queue.push(new PlanActionEntry(action, dist + action.cost));
}
};
PlanMap.prototype.getAction = function (x, y, context) {
if (context === void 0) { context = null; }
var k = getKey(x, y, context);
if (this._map.hasOwnProperty(k)) {
return this._map[k];
}
else {
return null;
}
};
PlanMap.prototype.render = function (ctx, grid) {
var gs = grid.gridsize;
var rs = gs / 2;
ctx.lineWidth = 1;
for (var k in this._map) {
var action = this._map[k];
var color = action.getColor();
if (color !== null) {
var p0 = grid.grid2coord(action.p);
ctx.strokeStyle = color;
ctx.strokeRect(p0.x - rs / 2 + .5, p0.y - rs / 2 + .5, rs, rs);
if (action.next !== null) {
var p1 = grid.grid2coord(action.next.p);
ctx.beginPath();
ctx.moveTo(p0.x + .5, p0.y + .5);
ctx.lineTo(p1.x + .5, p1.y + .5);
ctx.stroke();
}
}
}
if (this._goal !== null) {
var p = grid.grid2coord(this._goal);
ctx.strokeStyle = '#00ff00';
ctx.strokeRect(p.x - gs / 2 + .5, p.y - gs / 2 + .5, gs, gs);
}
if (this._start !== null) {
var p = grid.grid2coord(this._start);
ctx.strokeStyle = '#ff0000';
ctx.strokeRect(p.x - gs / 2 + .5, p.y - gs / 2 + .5, gs, gs);
}
};
PlanMap.prototype.build = function (actor, goal, range, start, maxcost) {
if (start === void 0) { start = null; }
if (maxcost === void 0) { maxcost = Infinity; }
//info("build: goal="+goal+", start="+start+", range="+range+", maxcost="+maxcost);
this._map = {};
this._queue = [];
this._goal = goal;
this._start = start;
this.addAction(null, new NullAction(goal));
while (0 < this._queue.length) {
var entry = this._queue.shift();
var action = entry.action;
if (start !== null && start.equals(action.p))
return action;
if (maxcost <= action.cost)
continue;
this.expand(actor, range, action, start);
// A* search.
if (start !== null) {
this._queue.sort(function (a, b) {
return a.total - b.total;
});
}
}
return null;
};
PlanMap.prototype.expand = function (actor, range, prev, start) {
if (start === void 0) { start = null; }
// [OVERRIDE]
};
return PlanMap;
}());
// ActionRunner
//
var ActionRunner = /** @class */ (function (_super) {
__extends(ActionRunner, _super);
function ActionRunner(actor, action, timeout) {
if (timeout === void 0) { timeout = Infinity; }
var _this = _super.call(this) || this;
_this.actor = actor;
_this.timeout = timeout;
_this.actor.setAction(action);
_this.action = action;
_this.lifetime = timeout;
return _this;
}
ActionRunner.prototype.toString = function () {
return ('<ActionRunner: actor=' + this.actor + ', action=' + this.action + '>');
};
ActionRunner.prototype.onTick = function () {
_super.prototype.onTick.call(this);
var action = this.action;
if (action !== null) {
action = this.execute(action);
if (action === null) {
this.actor.setAction(action);
this.stop();
}
else if (action !== this.action) {
this.actor.setAction(action);
this.lifetime = this.timeout;
}
this.action = action;
}
};
ActionRunner.prototype.execute = function (action) {
if (action instanceof NullAction) {
return action.next;
}
return action;
};
return ActionRunner;
}(Task));
// WalkerAction
//
var WalkerAction = /** @class */ (function (_super) {
__extends(WalkerAction, _super);
function WalkerAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
WalkerAction.prototype.toString = function () {
return ('<WalkerAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
WalkerAction.prototype.getColor = function () { return null; };
return WalkerAction;
}(PlanAction));
var WalkerWalkAction = /** @class */ (function (_super) {
__extends(WalkerWalkAction, _super);
function WalkerWalkAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
WalkerWalkAction.prototype.toString = function () {
return ('<WalkerWalkAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
WalkerWalkAction.prototype.getColor = function () { return 'white'; };
return WalkerWalkAction;
}(WalkerAction));
// WalkerPlanMap
//
var WalkerPlanMap = /** @class */ (function (_super) {
__extends(WalkerPlanMap, _super);
function WalkerPlanMap(grid, obstacle) {
var _this = _super.call(this) || this;
_this.grid = grid;
_this.obstacle = obstacle;
return _this;
}
WalkerPlanMap.prototype.expand = function (actor, range, prev, start) {
if (start === void 0) { start = null; }
var p0 = prev.p;
var cost0 = prev.cost;
// assert(range.containsPt(p0));
// try walking.
for (var i = 0; i < 4; i++) {
var d = new Vec2(1, 0).rot90(i);
var p1 = p0.add(d);
if (range.containsPt(p1) &&
actor.canMoveTo(p1)) {
this.addAction(start, new WalkerWalkAction(p1, prev, cost0 + 1, null));
}
}
};
return WalkerPlanMap;
}(PlanMap));
// WalkerActionRunner
//
var WalkerActionRunner = /** @class */ (function (_super) {
__extends(WalkerActionRunner, _super);
function WalkerActionRunner(actor, action, goal, timeout) {
if (timeout === void 0) { timeout = Infinity; }
var _this = _super.call(this, actor, action, timeout) || this;
_this.goal = goal;
return _this;
}
WalkerActionRunner.prototype.execute = function (action) {
var actor = this.actor;
;
if (action instanceof WalkerWalkAction) {
var dst = action.next.p;
actor.moveToward(dst);
if (actor.isCloseTo(dst)) {
return action.next;
}
}
return _super.prototype.execute.call(this, action);
};
return WalkerActionRunner;
}(ActionRunner));
// WalkerEntity
//
var WalkerEntity = /** @class */ (function (_super) {
__extends(WalkerEntity, _super);
function WalkerEntity(tilemap, isObstacle, grid, speed, hitbox, pos, allowance) {
if (allowance === void 0) { allowance = 0; }
var _this = _super.call(this, tilemap, isObstacle, pos) || this;
_this.runner = null;
_this.grid = grid;
_this.speed = speed;
var gs = grid.gridsize;
_this.gridbox = new Rect(0, 0, Math.ceil(hitbox.width / gs) * gs, Math.ceil(hitbox.height / gs) * gs);
var obstacle = _this.tilemap.getRangeMap('obstacle', _this.isObstacle);
_this.planmap = new WalkerPlanMap(_this.grid, obstacle);
_this.allowance = (allowance !== 0) ? allowance : grid.gridsize / 2;
return _this;
}
WalkerEntity.prototype.buildPlan = function (goal, start, size, maxcost) {
if (start === void 0) { start = null; }
if (size === void 0) { size = 0; }
if (maxcost === void 0) { maxcost = 20; }
start = (start !== null) ? start : this.getGridPos();
var range = (size == 0) ? this.tilemap.bounds : goal.inflate(size, size);
range = this.grid.clip(range);
return this.planmap.build(this, goal, range, start, maxcost);
};
WalkerEntity.prototype.setRunner = function (runner) {
var _this = this;
if (this.runner !== null) {
this.runner.stop();
}
this.runner = runner;
if (this.runner !== null) {
this.runner.stopped.subscribe(function () { _this.runner = null; });
this.parent.add(this.runner);
}
};
WalkerEntity.prototype.setAction = function (action) {
// [OVERRIDE]
};
// WalkerActor methods
WalkerEntity.prototype.canMoveTo = function (p) {
var hitbox = this.getGridBoxAt(p);
return !this.planmap.obstacle.exists(this.tilemap.coord2map(hitbox));
};
WalkerEntity.prototype.moveToward = function (p) {
var p0 = this.pos;
var p1 = this.getGridBoxAt(p).center();
var v = p1.sub(p0);
var speed = this.speed;
v.x = clamp(-speed.x, v.x, +speed.x);
v.y = clamp(-speed.y, v.y, +speed.y);
this.moveIfPossible(v);
};
WalkerEntity.prototype.isCloseTo = function (p) {
return this.grid.grid2coord(p).distance(this.pos) < this.allowance;
};
WalkerEntity.prototype.getGridPos = function () {
return this.grid.coord2grid(this.pos);
};
WalkerEntity.prototype.getGridBoxAt = function (p) {
return this.grid.grid2coord(p).expand(this.gridbox.width, this.gridbox.height);
};
return WalkerEntity;
}(TileMapEntity));
/// <reference path="utils.ts" />
/// <reference path="geom.ts" />
/// <reference path="tilemap.ts" />
/// <reference path="entity.ts" />
/// <reference path="pathfind.ts" />
// PlatformerAction
//
var PlatformerAction = /** @class */ (function (_super) {
__extends(PlatformerAction, _super);
function PlatformerAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlatformerAction.prototype.toString = function () {
return ('<PlatformAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
PlatformerAction.prototype.getColor = function () { return null; };
return PlatformerAction;
}(PlanAction));
var PlatformerWalkAction = /** @class */ (function (_super) {
__extends(PlatformerWalkAction, _super);
function PlatformerWalkAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlatformerWalkAction.prototype.toString = function () {
return ('<PlatformWalkAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
PlatformerWalkAction.prototype.getColor = function () { return 'white'; };
return PlatformerWalkAction;
}(PlatformerAction));
var PlatformerFallAction = /** @class */ (function (_super) {
__extends(PlatformerFallAction, _super);
function PlatformerFallAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlatformerFallAction.prototype.toString = function () {
return ('<PlatformFallAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
PlatformerFallAction.prototype.getColor = function () { return 'blue'; };
return PlatformerFallAction;
}(PlatformerAction));
var PlatformerJumpAction = /** @class */ (function (_super) {
__extends(PlatformerJumpAction, _super);
function PlatformerJumpAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlatformerJumpAction.prototype.toString = function () {
return ('<PlatformJumpAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
PlatformerJumpAction.prototype.getColor = function () { return 'magenta'; };
return PlatformerJumpAction;
}(PlatformerAction));
var PlatformerClimbAction = /** @class */ (function (_super) {
__extends(PlatformerClimbAction, _super);
function PlatformerClimbAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
PlatformerClimbAction.prototype.toString = function () {
return ('<PlatformClimbAction(' + this.p.x + ',' + this.p.y + '): cost=' + this.cost + '>');
};
PlatformerClimbAction.prototype.getColor = function () { return 'cyan'; };
return PlatformerClimbAction;
}(PlatformerAction));
// PlatformerPlanMap
//
var PlatformerPlanMap = /** @class */ (function (_super) {
__extends(PlatformerPlanMap, _super);
function PlatformerPlanMap(grid, tilemap, physics) {
var _this = _super.call(this) || this;
_this.grid = grid;
_this.obstacle = tilemap.getRangeMap('obstacle', physics.isObstacle);
_this.grabbable = tilemap.getRangeMap('grabbable', physics.isGrabbable);
_this.stoppable = tilemap.getRangeMap('stoppable', physics.isStoppable);
return _this;
}
PlatformerPlanMap.prototype.expand = function (actor, range, prev, start) {
if (start === void 0) { start = null; }
var p0 = prev.p;
var cost0 = prev.cost;
// assert(range.containsPt(p0));
// try climbing down.
var dp = new Vec2(p0.x, p0.y - 1);
if (range.containsPt(dp) &&
actor.canClimbDown(dp)) {
this.addAction(start, new PlatformerClimbAction(dp, prev, cost0 + 1, null));
}
// try climbing up.
var up = new Vec2(p0.x, p0.y + 1);
if (range.containsPt(up) &&
actor.canClimbUp(up)) {
this.addAction(start, new PlatformerClimbAction(up, prev, cost0 + 1, null));
}
// for left and right.
for (var vx = -1; vx <= +1; vx += 2) {
// try walking.
var wp = new Vec2(p0.x - vx, p0.y);
if (range.containsPt(wp) &&
actor.canMoveTo(wp) &&
(actor.canGrabAt(wp) ||
actor.canStandAt(wp))) {
this.addAction(start, new PlatformerWalkAction(wp, prev, cost0 + 1, null));
}
// try falling.
if (actor.canStandAt(p0)) {
var fallpts = actor.getFallPoints();
for (var _i = 0, fallpts_1 = fallpts; _i < fallpts_1.length; _i++) {
var v = fallpts_1[_i];
// try the v.x == 0 case only once.
if (v.x === 0 && vx < 0)
continue;
var fp = p0.move(-v.x * vx, -v.y);
if (!range.containsPt(fp))
continue;
if (!actor.canMoveTo(fp))
continue;
// +--+.... [vx = +1]
// | |....
// +-X+.... (fp.x,fp.y) original position.
// ##.......
// ...+--+
// ...| |
// ...+-X+ (p0.x,p0.y)
// ######
if (actor.canFallTo(fp, p0)) {
var dc = Math.abs(v.x) + Math.abs(v.y);
this.addAction(start, new PlatformerFallAction(fp, prev, cost0 + dc, null));
}
}
}
// try jumping.
if (prev instanceof PlatformerFallAction) {
var jumppts = actor.getJumpPoints();
for (var _a = 0, jumppts_1 = jumppts; _a < jumppts_1.length; _a++) {
var v = jumppts_1[_a];
// try the v.x == 0 case only once.
if (v.x === 0 && vx < 0)
continue;
var jp = p0.move(-v.x * vx, -v.y);
if (!range.containsPt(jp))
continue;
if (!actor.canMoveTo(jp))
continue;
if (!actor.canGrabAt(jp) && !actor.canStandAt(jp))
continue;
// ....+--+ [vx = +1]
// ....| |
// ....+-X+ (p0.x,p0.y) tip point
// .......
// +--+...
// | |...
// +-X+... (jp.x,jp.y) original position.
// ######
if (actor.canJumpTo(jp, p0)) {
var dc = Math.abs(v.x) + Math.abs(v.y);
this.addAction(start, new PlatformerJumpAction(jp, prev, cost0 + dc, null));
}
}
}
else if (actor.canStandAt(p0)) {
var jumppts = actor.getJumpPoints();
for (var _b = 0, jumppts_2 = jumppts; _b < jumppts_2.length; _b++) {
var v = jumppts_2[_b];
if (v.x === 0)
continue;
var jp = p0.move(-v.x * vx, -v.y);
if (!range.containsPt(jp))
continue;
if (!actor.canMoveTo(jp))
continue;
if (!actor.canGrabAt(jp) && !actor.canStandAt(jp))
continue;
// ....+--+ [vx = +1]
// ....| |
// ....+-X+ (p0.x,p0.y) tip point
// .....##
// +--+...
// | |...
// +-X+... (jp.x,jp.y) original position.
// ######
if (actor.canJumpTo(jp, p0)) {
var dc = Math.abs(v.x) + Math.abs(v.y);
this.addAction(start, new PlatformerJumpAction(jp, prev, cost0 + dc, null));
}
}
}
}
};
return PlatformerPlanMap;
}(PlanMap));
// PointSet
//
var PointSet = /** @class */ (function () {
function PointSet() {
this.pts = {};
}
PointSet.prototype.add = function (p) {
this.pts[p.x + ',' + p.y] = p;
};
PointSet.prototype.exists = function (p) {
return (this.pts[p.x + ',' + p.y] !== undefined);
};
PointSet.prototype.values = function () {
var a = [];
for (var k in this.pts) {
a.push(this.pts[k]);
}
return a;
};
return PointSet;
}());
// PlatformerCaps
//
var PlatformerCaps = /** @class */ (function () {
function PlatformerCaps(grid, physics, speed, maxtime) {
if (maxtime === void 0) { maxtime = 15; }
this.grid = grid;
this.physics = physics;
this.speed = speed;
this.jumppts = this.calcJumpRange(maxtime);
this.fallpts = this.calcFallRange(maxtime);
}
PlatformerCaps.prototype.calcJumpRange = function (maxtime) {
if (maxtime === void 0) { maxtime = 15; }
var gridsize = this.grid.gridsize;
var jumpfunc = this.physics.jumpfunc;
var dx = this.speed.x;
var pts = new PointSet();
for (var jt = 1; jt < maxtime; jt++) {
var p = new Vec2();
var vy = 0;
for (var t = 0; t < maxtime; t++) {
vy = (t < jt) ? jumpfunc(vy, t) : jumpfunc(vy, Infinity);
if (0 <= vy) {
// tip point.
var cy = Math.ceil(p.y / gridsize);
for (var x = 0; x <= p.x; x++) {
var c = new Vec2(int(x / gridsize + .5), cy);
if (c.x == 0 && c.y == 0)
continue;
pts.add(c);
}
break;
}
p.x += dx;
p.y += vy;
}
}
return pts.values();
};
PlatformerCaps.prototype.calcFallRange = function (maxtime) {
if (maxtime === void 0) { maxtime = 15; }
var gridsize = this.grid.gridsize;
var jumpfunc = this.physics.jumpfunc;
var dx = this.speed.x;
var p = new Vec2();
var vy = 0;
var pts = new PointSet();
for (var t = 0; t < maxtime; t++) {
vy = jumpfunc(vy, Infinity);
p.x += dx;
p.y += vy;
var cy = Math.ceil(p.y / gridsize);
for (var x = 0; x <= p.x; x++) {
var c = new Vec2(int(x / gridsize + .5), cy);
if (c.x == 0 && c.y == 0)
continue;
pts.add(c);
}
}
return pts.values();
};
return PlatformerCaps;
}());
// PlatformerActionRunner
//
var PlatformerActionRunner = /** @class */ (function (_super) {
__extends(PlatformerActionRunner, _super);
function PlatformerActionRunner(actor, action, goal, timeout) {
if (timeout === void 0) { timeout = Infinity; }
var _this = _super.call(this, actor, action, timeout) || this;
_this.goal = goal;
return _this;
}
PlatformerActionRunner.prototype.execute = function (action) {
var actor = this.actor;
;
var cur = actor.getGridPos();
// Get a micro-level (greedy) plan.
if (action instanceof PlatformerWalkAction ||
action instanceof PlatformerClimbAction) {
var dst = action.next.p;
actor.moveToward(dst);
if (actor.isCloseTo(dst)) {
return action.next;
}
}
else if (action instanceof PlatformerFallAction) {
var dst = action.next.p;
var path = this.findSimplePath(cur, dst);
for (var i = 0; i < path.length; i++) {
var r0 = actor.getGridBoxAt(path[i]);
var r1 = actor.getGridBox();
var v = new Vec2(r0.x - r1.x, r0.y - r1.y);
if (actor.canMove(v)) {
actor.moveToward(path[i]);
break;
}
}
if (actor.isCloseTo(dst)) {
return action.next;
}
}
else if (action instanceof PlatformerJumpAction) {
var dst = action.next.p;
if (actor.canJump() && actor.canFall() &&
actor.isClearedFor(dst)) {
actor.jumpToward(dst);
// once you leap, the action is considered finished.
return new PlatformerFallAction(dst, action.next, action.next.cost, null);
}
else {
// not landed, holding something, or has no clearance.
actor.moveToward(cur);
}
}
return _super.prototype.execute.call(this, action);
};
// findSimplePath(x0, y0, x1, x1, cb):
// returns a list of points that a character can proceed without being blocked.
// returns null if no such path exists. This function takes O(w*h).
// Note: this returns only a straightforward path without any detour.
PlatformerActionRunner.prototype.findSimplePath = function (p0, p1) {
var PathEntry = /** @class */ (function () {
function PathEntry(p, d, next) {
this.p = p.copy();
this.d = d;
this.next = next;
}
return PathEntry;
}());
var a = [];
var w = Math.abs(p1.x - p0.x);
var h = Math.abs(p1.y - p0.y);
var vx = (p0.x <= p1.x) ? +1 : -1;
var vy = (p0.y <= p1.y) ? +1 : -1;
var actor = this.actor;
for (var dy = 0; dy <= h; dy++) {
a.push([]);
// y: y0...y1
var y = p0.y + dy * vy;
for (var dx = 0; dx <= w; dx++) {
// x: x0...x1
var x = p0.x + dx * vx;
// for each point, compare the cost of (x-1,y) and (x,y-1).
var p = new Vec2(x, y);
var d = void 0;
var e_1 = null; // the closest neighbor (if exists).
if (dx === 0 && dy === 0) {
d = 0;
}
else {
d = Infinity;
if (actor.canMoveTo(p)) {
if (0 < dx && a[dy][dx - 1].d < d) {
e_1 = a[dy][dx - 1];
d = e_1.d + 1;
}
if (0 < dy && a[dy - 1][dx].d < d) {
e_1 = a[dy - 1][dx];
d = e_1.d + 1;
}
}
}
// populate a[dy][dx].
a[dy].push(new PathEntry(p, d, e_1));
}
}
// trace them in a reverse order: from goal to start.
var r = [];
var e = a[h][w];
while (e !== null) {
r.push(e.p);
e = e.next;
}
return r;
};
return PlatformerActionRunner;
}(ActionRunner));
// PlanningEntity
//
var PlanningEntity = /** @class */ (function (_super) {
__extends(PlanningEntity, _super);
function PlanningEntity(tilemap, physics, grid, caps, hitbox, pos, allowance) {
if (allowance === void 0) { allowance = 0; }
var _this = _super.call(this, tilemap, physics, pos) || this;
_this.runner = null;
_this.grid = grid;
_this.caps = caps;
var gs = grid.gridsize;
_this.gridbox = new Rect(0, 0, Math.ceil(hitbox.width / gs) * gs, Math.ceil(hitbox.height / gs) * gs);
_this.planmap = new PlatformerPlanMap(_this.grid, tilemap, physics);
_this.allowance = (allowance !== 0) ? allowance : grid.gridsize / 2;
return _this;
}
PlanningEntity.prototype.buildPlan = function (goal, start, size, maxcost) {
if (start === void 0) { start = null; }
if (size === void 0) { size = 0; }
if (maxcost === void 0) { maxcost = 20; }
start = (start !== null) ? start : this.getGridPos();
var range = (size == 0) ? this.tilemap.bounds : goal.inflate(size, size);
range = this.grid.clip(range);
return this.planmap.build(this, goal, range, start, maxcost);
};
PlanningEntity.prototype.setRunner = function (runner) {
var _this = this;
if (this.runner !== null) {
this.runner.stop();
}
this.runner = runner;
if (this.runner !== null) {
this.runner.stopped.subscribe(function () { _this.runner = null; });
this.parent.add(this.runner);
}
};
PlanningEntity.prototype.setAction = function (action) {
// [OVERRIDE]
};
PlanningEntity.prototype.isCloseTo = function (p) {
return this.grid.grid2coord(p).distance(this.pos) < this.allowance;
};
// PlatformerActor methods
PlanningEntity.prototype.getJumpPoints = function () {
return this.caps.jumppts;
};
PlanningEntity.prototype.getFallPoints = function () {
return this.caps.fallpts;
};
PlanningEntity.prototype.getGridPos = function () {
return this.grid.coord2grid(this.pos);
};
PlanningEntity.prototype.getGridBox = function () {
return this.pos.expand(this.gridbox.width, this.gridbox.height);
};
PlanningEntity.prototype.getGridBoxAt = function (p) {
return this.grid.grid2coord(p).expand(this.gridbox.width, this.gridbox.height);
};
PlanningEntity.prototype.canMoveTo = function (p) {
var hitbox = this.getGridBoxAt(p);
return !this.planmap.obstacle.exists(this.tilemap.coord2map(hitbox));
};
PlanningEntity.prototype.canGrabAt = function (p) {
var hitbox = this.getGridBoxAt(p);
return this.planmap.grabbable.exists(this.tilemap.coord2map(hitbox));
};
PlanningEntity.prototype.canStandAt = function (p) {
var hitbox = this.getGridBoxAt(p).move(0, this.grid.gridsize);
return this.planmap.stoppable.exists(this.tilemap.coord2map(hitbox));
};
PlanningEntity.prototype.canClimbUp = function (p) {
var hitbox = this.getGridBoxAt(p);
return this.planmap.grabbable.exists(this.tilemap.coord2map(hitbox));
};
PlanningEntity.prototype.canClimbDown = function (p) {
var rect = this.collider.getAABB();
var hitbox = this.getGridBoxAt(p).move(0, rect.height);
return this.planmap.grabbable.exists(this.tilemap.coord2map(hitbox));
};
PlanningEntity.prototype.canFallTo = function (p0, p1) {
// +--+.....
// | |.....
// +-X+..... (p0.x,p0.y) original position.
// ## .....
// .+--+
// .| |
// .+-X+ (p1.x,p1.y)
// ######
var hb0 = this.getGridBoxAt(p0);
var hb1 = this.getGridBoxAt(p1);
var xc = (hb0.x < hb1.x) ? hb0.x1() : hb0.x;
var x0 = Math.min(xc, hb1.x);
var x1 = Math.max(xc, hb1.x1());
var y0 = Math.min(hb0.y, hb1.y);
var y1 = Math.max(hb0.y1(), hb1.y1());
var rect = new Rect(x0, y0, x1 - x0, y1 - y0);
return !this.planmap.stoppable.exists(this.tilemap.coord2map(rect));
};
PlanningEntity.prototype.canJumpTo = function (p0, p1) {
// .....+--+
// .....| |
// .....+-X+ (p1.x,p1.y) tip point
// .....
// +--+.
// | |.
// +-X+. (p0.x,p0.y) original position.
// ######
var hb0 = this.getGridBoxAt(p0);
var hb1 = this.getGridBoxAt(p1);
var xc = (p0.x < p1.x) ? hb1.x : hb1.x1();
var x0 = Math.min(xc, hb0.x);
var x1 = Math.max(xc, hb0.x1());
var y0 = Math.min(hb0.y, hb1.y);
var y1 = Math.max(hb0.y1(), hb1.y1());
if (this.planmap.obstacle.exists(this.tilemap.coord2map(new Rect(x0, y0, x1 - x0, y1 - y0)))) {
return false;
}
// Extra care is needed not to allow the following case:
// .# [rect1]
// +--+
// | | (this is impossiburu!)
// +-X+
// # [rect2]
var rect = this.tilemap.coord2map(hb1);
var dx = sign(p1.x - p0.x);
var rect1 = (0 < dx) ? rect.resize(1, 1, 'ne') : rect.resize(1, 1, 'nw');
var rect2 = (0 < dx) ? rect.resize(1, 1, 'se') : rect.resize(1, 1, 'sw');
if (this.planmap.obstacle.exists(rect1) &&
!this.planmap.obstacle.exists(rect1.move(-dx, 0)) &&
this.planmap.obstacle.exists(rect2)) {
return false;
}
return true;
};
PlanningEntity.prototype.moveToward = function (p) {
var p0 = this.pos;
var p1 = this.getGridBoxAt(p).center();
var v = p1.sub(p0);
var speed = this.caps.speed;
v.x = clamp(-speed.x, v.x, +speed.x);
v.y = clamp(-speed.y, v.y, +speed.y);
this.moveIfPossible(v);
};
PlanningEntity.prototype.jumpToward = function (p) {
this.setJump(Infinity);
this.moveToward(p);
};
PlanningEntity.prototype.isClearedFor = function (p1) {
var hb0 = this.getGridBox();
var hb1 = this.getGridBoxAt(p1);
var xc = (hb0.x < hb1.x) ? hb1.x : hb1.x1();
var x0 = Math.min(xc, hb0.x);
var x1 = Math.max(xc, hb0.x1());
var y0 = Math.min(hb0.y, hb1.y);
var y1 = Math.max(hb0.y1(), hb1.y1());
var rect = new Rect(x0, y0, x1 - x0, y1 - y0);
return !this.planmap.obstacle.exists(this.tilemap.coord2map(rect));
};
return PlanningEntity;
}(PlatformerEntity));
/// <reference path="../../../base/utils.ts" />
/// <reference path="../../../base/geom.ts" />
/// <reference path="../../../base/sprite.ts" />
/// <reference path="../../../base/entity.ts" />
/// <reference path="../../../base/text.ts" />
/// <reference path="../../../base/scene.ts" />
/// <reference path="../../../base/app.ts" />
/// <reference path="../../../base/tilemap.ts" />
/// <reference path="../../../base/pathfind.ts" />
/// <reference path="../../../base/planplat.ts" />
// Platformer
//
// An example of intermediate level using
// basic physics and path finding.
//
// Initialize the resources.
var SPRITES;
var S;
(function (S) {
S[S["PLAYER"] = 0] = "PLAYER";
S[S["SHADOW"] = 1] = "SHADOW";
S[S["THINGY"] = 2] = "THINGY";
S[S["YAY"] = 3] = "YAY";
S[S["MONSTER"] = 4] = "MONSTER";
})(S || (S = {}));
;
var TILES;
var T;
(function (T) {
T[T["BACKGROUND"] = 0] = "BACKGROUND";
T[T["BLOCK"] = 1] = "BLOCK";
T[T["LADDER"] = 2] = "LADDER";
T[T["THINGY"] = 3] = "THINGY";
T[T["ENEMY"] = 8] = "ENEMY";
T[T["PLAYER"] = 9] = "PLAYER";
})(T || (T = {}));
addInitHook(function () {
SPRITES = new ImageSpriteSheet(APP.images['sprites'], new Vec2(32, 32), new Vec2(16, 16));
TILES = new ImageSpriteSheet(APP.images['tiles'], new Vec2(48, 48), new Vec2(0, 16));
});
function findShadowPos(tilemap, pos) {
var rect = tilemap.coord2map(pos);
var p = new Vec2(rect.x, rect.y);
while (p.y < tilemap.height) {
var c = tilemap.get(p.x, p.y + 1);
if (c == T.BLOCK || c == -1)
break;
p.y++;
}
var y = tilemap.map2coord(p).center().y;
return new Vec2(0, y - pos.y);
}
// ShadowSprite
//
var ShadowSprite = /** @class */ (function () {
function ShadowSprite() {
this.shadowPos = null;
this.shadow = SPRITES.get(S.SHADOW);
}
ShadowSprite.prototype.getBounds = function () {
return this.shadow.getBounds();
};
ShadowSprite.prototype.render = function (ctx) {
var shadow = this.shadow;
var pos = this.shadowPos;
if (pos !== null) {
ctx.save();
ctx.translate(pos.x, pos.y);
var srcRect = shadow.srcRect;
var dstRect = shadow.dstRect;
// Shadow gets smaller based on its ground distance.
var d = pos.y / 4;
if (d * 2 <= dstRect.width && d * 2 <= dstRect.height) {
ctx.drawImage(shadow.image, srcRect.x, srcRect.y, srcRect.width, srcRect.height, dstRect.x + d, dstRect.y + d * 2, dstRect.width - d * 2, dstRect.height - d * 2);
}
ctx.restore();
}
};
return ShadowSprite;
}());
// Player
//
var Player = /** @class */ (function (_super) {
__extends(Player, _super);
function Player(scene, pos) {
var _this = _super.call(this, scene.tilemap, scene.physics, pos) || this;
_this.shadow = new ShadowSprite();
_this.usermove = new Vec2();
_this.holding = true;
var sprite = SPRITES.get(S.PLAYER);
_this.sprites = [_this.shadow, sprite];
_this.collider = sprite.getBounds();
_this.scene = scene;
_this.picked = new Signal(_this);
return _this;
}
Player.prototype.onJumped = function () {
_super.prototype.onJumped.call(this);
// Release a ladder when jumping.
this.holding = false;
};
Player.prototype.onLanded = function () {
_super.prototype.onLanded.call(this);
// Grab a ladder when landed.
this.holding = true;
};
Player.prototype.hasLadder = function () {
return this.hasTile(this.physics.isGrabbable);
};
Player.prototype.canFall = function () {
return !(this.holding && this.hasLadder());
};
Player.prototype.getObstaclesFor = function (range, v, context) {
if (!this.holding) {
return this.tilemap.getTileRects(this.physics.isObstacle, range);
}
return _super.prototype.getObstaclesFor.call(this, range, v, context);
};
Player.prototype.getFencesFor = function (range, v, context) {
return [this.world.area];
};
Player.prototype.onTick = function () {
_super.prototype.onTick.call(this);
var v = this.usermove;
if (!this.holding) {
v = new Vec2(v.x, 0);
}
else if (!this.hasLadder()) {
v = new Vec2(v.x, lowerbound(0, v.y));
}
this.moveIfPossible(v);
this.shadow.shadowPos = findShadowPos(this.tilemap, this.pos);
};
Player.prototype.setJump = function (jumpend) {
_super.prototype.setJump.call(this, jumpend);
if (0 < jumpend && this.isJumping()) {
APP.playSound('jump');
}
};
Player.prototype.setMove = function (v) {
this.usermove = v.scale(8);
if (v.y != 0) {
// Grab the ladder in air.
this.holding = true;
}
};
Player.prototype.onCollided = function (entity) {
_super.prototype.onCollided.call(this, entity);
if (entity instanceof Thingy) {
APP.playSound('pick');
entity.stop();
var yay = new Particle(this.pos.move(0, -16));
yay.sprites = [SPRITES.get(S.YAY)];
yay.movement = new Vec2(0, -4);
yay.lifetime = 0.5;
this.world.add(yay);
this.picked.fire();
}
};
return Player;
}(PlatformerEntity));
// Monster
//
var Monster = /** @class */ (function (_super) {
__extends(Monster, _super);
function Monster(scene, pos, target) {
var _this = this;
var sprite = SPRITES.get(S.MONSTER);
_this = _super.call(this, scene.tilemap, scene.physics, scene.grid, scene.caps, sprite.getBounds(), pos, 4) || this;
_this.scene = scene;
_this.target = target;
_this.shadow = new ShadowSprite();
_this.sprites = [sprite];
_this.collider = sprite.getBounds();
return _this;
}
Monster.prototype.onTick = function () {
_super.prototype.onTick.call(this);
var goal = this.grid.coord2grid(this.target.pos);
if (this.runner instanceof PlatformerActionRunner) {
if (!this.runner.goal.equals(goal)) {
// abandon an obsolete plan.
this.setRunner(null);
}
}
if (this.runner === null) {
var action = this.buildPlan(goal);
if (action !== null) {
this.setRunner(new PlatformerActionRunner(this, action, goal));
}
}
this.shadow.shadowPos = findShadowPos(this.tilemap, this.pos);
};
Monster.prototype.setAction = function (action) {
_super.prototype.setAction.call(this, action);
if (action !== null && !(action instanceof NullAction)) {
info("setAction: " + action);
}
};
Monster.prototype.getFencesFor = function (range, v, context) {
return [this.world.area];
};
return Monster;
}(PlanningEntity));
// Thingy
//
var Thingy = /** @class */ (function (_super) {
__extends(Thingy, _super);
function Thingy(pos) {
var _this = _super.call(this, pos) || this;
var sprite = SPRITES.get(S.THINGY);
_this.sprites = [sprite];
_this.collider = sprite.getBounds().inflate(-4, -4);
return _this;
}
return Thingy;
}(Entity));
// Game
//
var Game = /** @class */ (function (_super) {
__extends(Game, _super);
function Game() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.debug = false;
_this.watch = null;
return _this;
}
Game.prototype.onStart = function () {
var _this = this;
_super.prototype.onStart.call(this);
this.physics = new PhysicsConfig();
this.physics.jumpfunc = (function (vy, t) {
return (0 <= t && t <= 6) ? -8 : vy + 2;
});
this.physics.maxspeed = new Vec2(16, 16);
this.physics.isObstacle =
(function (c) { return c == T.BLOCK; });
this.physics.isGrabbable =
(function (c) { return c == T.LADDER; });
this.physics.isStoppable =
(function (c) { return c == T.BLOCK || c == T.LADDER; });
var MAP = [
"00000000000000300000",
"00002111210001121100",
"00112000200000020000",
"00000000200000111211",
"00300011111000000200",
"00100300002000000200",
"00000000002111121100",
"00000110002000020000",
"00000000002000020830",
"00110002111000111111",
"00000002000000002000",
"11030111112110002003",
"00010000002000112110",
"31020100092000002000",
"11111111111111111111",
];
this.tilemap = new TileMap(32, 20, 15, MAP.map(function (v) { return str2array(v); }));
this.grid = new GridConfig(this.tilemap);
this.caps = new PlatformerCaps(this.grid, this.physics, new Vec2(4, 4));
// Place the player.
var p = this.tilemap.findTile(function (c) { return c == T.PLAYER; });
this.player = new Player(this, this.tilemap.map2coord(p).center());
this.player.picked.subscribe(function (entity) {
_this.onPicked(entity);
});
this.add(this.player);
// Place monsters and stuff.
this.thingies = 0;
this.tilemap.apply(function (x, y, c) {
var rect = _this.tilemap.map2coord(new Vec2(x, y));
switch (c) {
case T.THINGY:
var thingy = new Thingy(rect.center());
_this.add(thingy);
_this.thingies++;
break;
case T.ENEMY:
var monster = new Monster(_this, rect.center(), _this.player);
_this.add(monster);
_this.watch = monster;
break;
}
return false;
});
};
Game.prototype.onTick = function () {
_super.prototype.onTick.call(this);
this.world.setCenter(this.player.pos.expand(80, 80), this.tilemap.bounds);
};
Game.prototype.onDirChanged = function (v) {
this.player.setMove(v);
};
Game.prototype.onButtonPressed = function (keysym) {
this.player.setJump(Infinity);
};
Game.prototype.onButtonReleased = function (keysym) {
this.player.setJump(0);
};
Game.prototype.onPicked = function (entity) {
var _this = this;
this.thingies--;
if (this.thingies == 0) {
var task = new Task();
task.lifetime = 2;
task.stopped.subscribe(function () {
APP.lockKeys();
_this.changeScene(new Ending());
});
this.add(task);
}
};
Game.prototype.render = function (ctx) {
ctx.fillStyle = 'rgb(0,0,0)';
fillRect(ctx, this.screen);
// Render the background tiles.
this.tilemap.renderWindowFromBottomLeft(ctx, this.world.window, function (x, y, c) {
return (c != T.BLOCK) ? TILES.get(T.BACKGROUND) : null;
});
// Render the map tiles.
this.tilemap.renderWindowFromBottomLeft(ctx, this.world.window, function (x, y, c) {
return (c == T.BLOCK || c == T.LADDER) ? TILES.get(c) : null;
});
_super.prototype.render.call(this, ctx);
// Render the planmap.
if (this.debug) {
if (this.watch !== null && this.watch.runner !== null) {
this.watch.planmap.render(ctx, this.grid);
}
}
};
return Game;
}(GameScene));
// Ending
//
var Ending = /** @class */ (function (_super) {
__extends(Ending, _super);
function Ending() {
var _this = this;
var html = '<strong>You Won!</strong><p>Yay!';
_this = _super.call(this, html) || this;
return _this;
}
Ending.prototype.change = function () {
this.changeScene(new Game());
};
return Ending;
}(HTMLScene));
|
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.2.0
Version: 1.3.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v1.3/
*/
var handleGoogleMapSetting = function() {
"use strict";
var mapDefault;
function initialize() {
var mapOptions = {
zoom: 6,
center: new google.maps.LatLng(-33.397, 145.644),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
};
mapDefault = new google.maps.Map(document.getElementById('google-map-default'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(window).resize(function() {
google.maps.event.trigger(mapDefault, "resize");
});
var defaultMapStyles = [];
var flatMapStyles = [{"stylers":[{"visibility":"off"}]},{"featureType":"road","stylers":[{"visibility":"on"},{"color":"#ffffff"}]},{"featureType":"road.arterial","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"road.highway","stylers":[{"visibility":"on"},{"color":"#fee379"}]},{"featureType":"landscape","stylers":[{"visibility":"on"},{"color":"#f3f4f4"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#7fc8ed"}]},{},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#83cead"}]},{"elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"weight":0.9},{"visibility":"off"}]}];
var turquoiseWaterStyles = [{"featureType":"landscape.natural","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"color":"#e0efef"}]},{"featureType":"poi","elementType":"geometry.fill","stylers":[{"visibility":"on"},{"hue":"#1900ff"},{"color":"#c0e8e8"}]},{"featureType":"landscape.man_made","elementType":"geometry.fill"},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"color":"#7dcdcd"}]},{"featureType":"transit.line","elementType":"geometry","stylers":[{"visibility":"on"},{"lightness":700}]}];
var icyBlueStyles = [{"stylers":[{"hue":"#2c3e50"},{"saturation":250}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":50},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]}];
var oldDryMudStyles = [{"featureType":"landscape","stylers":[{"hue":"#FFAD00"},{"saturation":50.2},{"lightness":-34.8},{"gamma":1}]},{"featureType":"road.highway","stylers":[{"hue":"#FFAD00"},{"saturation":-19.8},{"lightness":-1.8},{"gamma":1}]},{"featureType":"road.arterial","stylers":[{"hue":"#FFAD00"},{"saturation":72.4},{"lightness":-32.6},{"gamma":1}]},{"featureType":"road.local","stylers":[{"hue":"#FFAD00"},{"saturation":74.4},{"lightness":-18},{"gamma":1}]},{"featureType":"water","stylers":[{"hue":"#00FFA6"},{"saturation":-63.2},{"lightness":38},{"gamma":1}]},{"featureType":"poi","stylers":[{"hue":"#FFC300"},{"saturation":54.2},{"lightness":-14.4},{"gamma":1}]}];
var cobaltStyles = [{"featureType":"all","elementType":"all","stylers":[{"invert_lightness":true},{"saturation":10},{"lightness":10},{"gamma":0.8},{"hue":"#293036"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#293036"}]}];
var darkRedStyles = [{"featureType":"all","elementType":"all","stylers":[{"invert_lightness":true},{"saturation":10},{"lightness":10},{"gamma":0.8},{"hue":"#000000"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"color":"#293036"}]}];
$('[data-map-theme]').click(function() {
var targetTheme = $(this).attr('data-map-theme');
var targetLi = $(this).closest('li');
var targetText = $(this).text();
var inverseContentMode = false;
$('#map-theme-selection li').not(targetLi).removeClass('active');
$('#map-theme-text').text(targetText);
$(targetLi).addClass('active');
switch(targetTheme) {
case 'flat':
mapDefault.setOptions({styles: flatMapStyles});
break;
case 'turquoise-water':
mapDefault.setOptions({styles: turquoiseWaterStyles});
break;
case 'icy-blue':
mapDefault.setOptions({styles: icyBlueStyles});
break;
case 'cobalt':
mapDefault.setOptions({styles: cobaltStyles});
inverseContentMode = true;
break;
case 'old-dry-mud':
mapDefault.setOptions({styles: oldDryMudStyles});
break;
case 'dark-red':
mapDefault.setOptions({styles: darkRedStyles});
inverseContentMode = true;
break;
default:
mapDefault.setOptions({styles: defaultMapStyles});
break;
}
if (inverseContentMode === true) {
$('#content').addClass('content-inverse-mode');
} else {
$('#content').removeClass('content-inverse-mode');
}
});
};
var MapGoogle = function () {
"use strict";
return {
//main function
init: function () {
handleGoogleMapSetting();
}
};
}(); |
Module.register("jokes", {
defaults:{
baseUrl: "http://tambal.azurewebsites.net/joke/random"
},
getHeader: function(){
return this.data.header
},
getTranslations: function(){
return false
},
start: function(){
Log.info("Starting module " + this.name);
moment.locale(config.language);
this.joke = null;
this.sendSocketNotification("DISPLAY_JOKE");
this.loaded = false;
},
getDom: function(){
var div = document.createElement('div');
div.className = "jokes-container";
var jokeDisplay = document.createElement('span');
jokeDisplay.className = 'joke-display';
jokeDisplay.innerHTML = this.joke;
div.appendChild(jokeDisplay);
return div
},
notificationReceived: function(notification) {
var notArr = notification.split(" ");
if (notArr.includes("joke")){
console.log("========== joke request ==========");
this.sendSocketNotification("JOKE", this.defaults);
this.show();
}else{
this.hide();
}
},
socketNotificationReceived: function (notification, payload) {
Log.log("socket recieved from Node Helper");
if (notification === "JOKE_RESULT") {
this.parsedDataSetter(payload);
}
},
parsedDataSetter: function(data){
this.joke = data["joke"]
this.updateDom();
},
})
|
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name : class_statement.js
* Created at : 2019-08-04
* Updated at : 2019-08-22
* Author : jeefo
* Purpose :
* Description :
* Reference : https://www.ecma-international.org/ecma-262/6.0/#sec-class-definitions
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/
// ignore:start
"use strict";
/* globals*/
/* exported*/
// ignore:end
const { AST_Node_Definition } = require("@jeefo/parser");
const { terminal_definition } = require("../../common");
const precedence_enum = require("../../es6/enums/precedence_enum");
const static_method_def = require("../common/static_method_definition");
const generate_next_method = require("../helpers/generate_method_definition");
const {
property_name_definition : property_name,
} = require("../../es6/common");
const {
is_identifier,
is_terminator,
is_open_curly,
is_close_curly,
} = require("../../helpers");
const is_static = (parser) => {
const { next_token : token } = parser;
if (token.id === "Identifier" && token.value === "static") {
const next_token = parser.look_ahead(true);
return next_token.id !== "Delimiter" || next_token.value !== '(';
}
};
const class_body = new AST_Node_Definition({
id : "Class body",
type : "Expression",
precedence : -1,
is : () => {},
initialize : (node, current_token, parser) => {
const element_list = [];
parser.change_state("delimiter");
parser.expect('{', is_open_curly);
const open_curly_bracket = parser.generate_next_node();
parser.prepare_next_state("expression", true);
while (! is_close_curly(parser)) {
let element;
if (is_terminator(parser)) {
element = parser.generate_next_node();
} else if (is_static(parser)) {
element = static_method_def.generate_new_node(parser);
} else {
parser.prev_node = property_name.generate_new_node(parser);
const next_token = parser.look_ahead(true);
element = generate_next_method(parser, next_token);
}
element_list.push(element);
parser.prepare_next_state("expression", true);
}
const close_curly_bracket = parser.generate_next_node();
node.open_curly_bracket = open_curly_bracket;
node.element_list = element_list;
node.close_curly_bracket = close_curly_bracket;
node.start = open_curly_bracket.start;
node.end = close_curly_bracket.end;
}
});
const class_tail = new AST_Node_Definition({
id : "Class tail",
type : "Expression",
precedence : -1,
is : () => {},
initialize : (node, current_token, parser) => {
let heritage = null;
parser.prepare_next_state("class_heritage", true);
if (parser.is_next_node("Class heritage")) {
heritage = parser.generate_next_node();
} else if (parser.next_token.id === "Identifier") {
parser.throw_unexpected_token("Unexpected identifier");
}
const body = class_body.generate_new_node(parser);
node.heritage = heritage;
node.body = body;
node.start = (heritage || body).start;
node.end = body.end;
}
});
const class_statement = {
id : "Class statement",
type : "Statement",
precedence : precedence_enum.STATEMENT,
is : () => true,
initialize : (node, current_token, parser) => {
const keyword = terminal_definition.generate_new_node(parser);
parser.prepare_next_state("expression");
parser.expect("identifier", is_identifier);
const name = parser.generate_next_node();
const tail = class_tail.generate_new_node(parser);
node.keyword = keyword;
node.name = name;
node.tail = tail;
node.start = keyword.start;
node.end = tail.end;
}
};
module.exports = ast_node_table => {
delete ast_node_table.reserved_words.class;
ast_node_table.register_reserved_word("class", class_statement);
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var ic_transform = exports.ic_transform = { "viewBox": "0 0 24 24", "children": [{ "name": "path", "attribs": { "d": "M22 18v-2H8V4h2L7 1 4 4h2v2H2v2h4v8c0 1.1.9 2 2 2h8v2h-2l3 3 3-3h-2v-2h4zM10 8h6v6h2V8c0-1.1-.9-2-2-2h-6v2z" } }] }; |
/**
* impress.js
*
* impress.js is a presentation tool based on the power of CSS3 transforms and transitions
* in modern browsers and inspired by the idea behind prezi.com.
*
*
* Copyright 2011-2012 Bartek Szopka (@bartaz), 2016-2018 Henrik Ingo (@henrikingo)
*
* Released under the MIT and GPL Licenses.
*
* ------------------------------------------------
* author: Bartek Szopka, Henrik Ingo
* version: 1.0.0
* url: http://impress.js.org
* source: http://github.com/impress/impress.js/
*/
// You are one of those who like to know how things work inside?
// Let me show you the cogs that make impress.js run...
( function( document, window ) {
"use strict";
var lib;
// HELPER FUNCTIONS
// `pfx` is a function that takes a standard CSS property name as a parameter
// and returns it's prefixed version valid for current browser it runs in.
// The code is heavily inspired by Modernizr http://www.modernizr.com/
var pfx = ( function() {
var style = document.createElement( "dummy" ).style,
prefixes = "Webkit Moz O ms Khtml".split( " " ),
memory = {};
return function( prop ) {
if ( typeof memory[ prop ] === "undefined" ) {
var ucProp = prop.charAt( 0 ).toUpperCase() + prop.substr( 1 ),
props = ( prop + " " + prefixes.join( ucProp + " " ) + ucProp ).split( " " );
memory[ prop ] = null;
for ( var i in props ) {
if ( style[ props[ i ] ] !== undefined ) {
memory[ prop ] = props[ i ];
break;
}
}
}
return memory[ prop ];
};
} )();
var validateOrder = function( order, fallback ) {
var validChars = "xyz";
var returnStr = "";
if ( typeof order === "string" ) {
for ( var i in order.split( "" ) ) {
if ( validChars.indexOf( order[ i ] ) >= 0 ) {
returnStr += order[ i ];
// Each of x,y,z can be used only once.
validChars = validChars.split( order[ i ] ).join( "" );
}
}
}
if ( returnStr ) {
return returnStr;
} else if ( fallback !== undefined ) {
return fallback;
} else {
return "xyz";
}
};
// `css` function applies the styles given in `props` object to the element
// given as `el`. It runs all property names through `pfx` function to make
// sure proper prefixed version of the property is used.
var css = function( el, props ) {
var key, pkey;
for ( key in props ) {
if ( props.hasOwnProperty( key ) ) {
pkey = pfx( key );
if ( pkey !== null ) {
el.style[ pkey ] = props[ key ];
}
}
}
return el;
};
// `translate` builds a translate transform string for given data.
var translate = function( t ) {
return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) ";
};
// `rotate` builds a rotate transform string for given data.
// By default the rotations are in X Y Z order that can be reverted by passing `true`
// as second parameter.
var rotate = function( r, revert ) {
var order = r.order ? r.order : "xyz";
var css = "";
var axes = order.split( "" );
if ( revert ) {
axes = axes.reverse();
}
for ( var i = 0; i < axes.length; i++ ) {
css += " rotate" + axes[ i ].toUpperCase() + "(" + r[ axes[ i ] ] + "deg)";
}
return css;
};
// `scale` builds a scale transform string for given data.
var scale = function( s ) {
return " scale(" + s + ") ";
};
// `computeWindowScale` counts the scale factor between window size and size
// defined for the presentation in the config.
var computeWindowScale = function( config ) {
var hScale = window.innerHeight / config.height,
wScale = window.innerWidth / config.width,
scale = hScale > wScale ? wScale : hScale;
if ( config.maxScale && scale > config.maxScale ) {
scale = config.maxScale;
}
if ( config.minScale && scale < config.minScale ) {
scale = config.minScale;
}
return scale;
};
// CHECK SUPPORT
var body = document.body;
var impressSupported =
// Browser should support CSS 3D transtorms
( pfx( "perspective" ) !== null ) &&
// And `classList` and `dataset` APIs
( body.classList ) &&
( body.dataset );
if ( !impressSupported ) {
// We can't be sure that `classList` is supported
body.className += " impress-not-supported ";
}
// GLOBALS AND DEFAULTS
// This is where the root elements of all impress.js instances will be kept.
// Yes, this means you can have more than one instance on a page, but I'm not
// sure if it makes any sense in practice ;)
var roots = {};
var preInitPlugins = [];
var preStepLeavePlugins = [];
// Some default config values.
var defaults = {
width: 1024,
height: 768,
maxScale: 1,
minScale: 0,
perspective: 1000,
transitionDuration: 1000
};
// It's just an empty function ... and a useless comment.
var empty = function() { return false; };
// IMPRESS.JS API
// And that's where interesting things will start to happen.
// It's the core `impress` function that returns the impress.js API
// for a presentation based on the element with given id ("impress"
// by default).
var impress = window.impress = function( rootId ) {
// If impress.js is not supported by the browser return a dummy API
// it may not be a perfect solution but we return early and avoid
// running code that may use features not implemented in the browser.
if ( !impressSupported ) {
return {
init: empty,
goto: empty,
prev: empty,
next: empty,
swipe: empty,
tear: empty,
lib: {}
};
}
rootId = rootId || "impress";
// If given root is already initialized just return the API
if ( roots[ "impress-root-" + rootId ] ) {
return roots[ "impress-root-" + rootId ];
}
// The gc library depends on being initialized before we do any changes to DOM.
lib = initLibraries( rootId );
body.classList.remove( "impress-not-supported" );
body.classList.add( "impress-supported" );
// Data of all presentation steps
var stepsData = {};
// Element of currently active step
var activeStep = null;
// Current state (position, rotation and scale) of the presentation
var currentState = null;
// Array of step elements
var steps = null;
// Configuration options
var config = null;
// Scale factor of the browser window
var windowScale = null;
// Root presentation elements
var root = lib.util.byId( rootId );
var canvas = document.createElement( "div" );
var initialized = false;
// STEP EVENTS
//
// There are currently two step events triggered by impress.js
// `impress:stepenter` is triggered when the step is shown on the
// screen (the transition from the previous one is finished) and
// `impress:stepleave` is triggered when the step is left (the
// transition to next step just starts).
// Reference to last entered step
var lastEntered = null;
// `onStepEnter` is called whenever the step element is entered
// but the event is triggered only if the step is different than
// last entered step.
// We sometimes call `goto`, and therefore `onStepEnter`, just to redraw a step, such as
// after screen resize. In this case - more precisely, in any case - we trigger a
// `impress:steprefresh` event.
var onStepEnter = function( step ) {
if ( lastEntered !== step ) {
lib.util.triggerEvent( step, "impress:stepenter" );
lastEntered = step;
}
lib.util.triggerEvent( step, "impress:steprefresh" );
};
// `onStepLeave` is called whenever the currentStep element is left
// but the event is triggered only if the currentStep is the same as
// lastEntered step.
var onStepLeave = function( currentStep, nextStep ) {
if ( lastEntered === currentStep ) {
lib.util.triggerEvent( currentStep, "impress:stepleave", { next: nextStep } );
lastEntered = null;
}
};
// `initStep` initializes given step element by reading data from its
// data attributes and setting correct styles.
var initStep = function( el, idx ) {
var data = el.dataset,
step = {
translate: {
x: lib.util.toNumber( data.x ),
y: lib.util.toNumber( data.y ),
z: lib.util.toNumber( data.z )
},
rotate: {
x: lib.util.toNumber( data.rotateX ),
y: lib.util.toNumber( data.rotateY ),
z: lib.util.toNumber( data.rotateZ || data.rotate ),
order: validateOrder( data.rotateOrder )
},
scale: lib.util.toNumber( data.scale, 1 ),
transitionDuration: lib.util.toNumber(
data.transitionDuration, config.transitionDuration
),
el: el
};
if ( !el.id ) {
el.id = "step-" + ( idx + 1 );
}
stepsData[ "impress-" + el.id ] = step;
css( el, {
position: "absolute",
transform: "translate(-50%,-50%)" +
translate( step.translate ) +
rotate( step.rotate ) +
scale( step.scale ),
transformStyle: "preserve-3d"
} );
};
// Initialize all steps.
// Read the data-* attributes, store in internal stepsData, and render with CSS.
var initAllSteps = function() {
steps = lib.util.$$( ".step", root );
steps.forEach( initStep );
};
// `init` API function that initializes (and runs) the presentation.
var init = function() {
if ( initialized ) { return; }
execPreInitPlugins( root );
// First we set up the viewport for mobile devices.
// For some reason iPad goes nuts when it is not done properly.
var meta = lib.util.$( "meta[name='viewport']" ) || document.createElement( "meta" );
meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no";
if ( meta.parentNode !== document.head ) {
meta.name = "viewport";
document.head.appendChild( meta );
}
// Initialize configuration object
var rootData = root.dataset;
config = {
width: lib.util.toNumber( rootData.width, defaults.width ),
height: lib.util.toNumber( rootData.height, defaults.height ),
maxScale: lib.util.toNumber( rootData.maxScale, defaults.maxScale ),
minScale: lib.util.toNumber( rootData.minScale, defaults.minScale ),
perspective: lib.util.toNumber( rootData.perspective, defaults.perspective ),
transitionDuration: lib.util.toNumber(
rootData.transitionDuration, defaults.transitionDuration
)
};
windowScale = computeWindowScale( config );
// Wrap steps with "canvas" element
lib.util.arrayify( root.childNodes ).forEach( function( el ) {
canvas.appendChild( el );
} );
root.appendChild( canvas );
// Set initial styles
document.documentElement.style.height = "100%";
css( body, {
height: "100%",
overflow: "hidden"
} );
var rootStyles = {
position: "absolute",
transformOrigin: "top left",
transition: "all 0s ease-in-out",
transformStyle: "preserve-3d"
};
css( root, rootStyles );
css( root, {
top: "50%",
left: "50%",
perspective: ( config.perspective / windowScale ) + "px",
transform: scale( windowScale )
} );
css( canvas, rootStyles );
body.classList.remove( "impress-disabled" );
body.classList.add( "impress-enabled" );
// Get and init steps
initAllSteps();
// Set a default initial state of the canvas
currentState = {
translate: { x: 0, y: 0, z: 0 },
rotate: { x: 0, y: 0, z: 0, order: "xyz" },
scale: 1
};
initialized = true;
lib.util.triggerEvent( root, "impress:init",
{ api: roots[ "impress-root-" + rootId ] } );
};
// `getStep` is a helper function that returns a step element defined by parameter.
// If a number is given, step with index given by the number is returned, if a string
// is given step element with such id is returned, if DOM element is given it is returned
// if it is a correct step element.
var getStep = function( step ) {
if ( typeof step === "number" ) {
step = step < 0 ? steps[ steps.length + step ] : steps[ step ];
} else if ( typeof step === "string" ) {
step = lib.util.byId( step );
}
return ( step && step.id && stepsData[ "impress-" + step.id ] ) ? step : null;
};
// Used to reset timeout for `impress:stepenter` event
var stepEnterTimeout = null;
// `goto` API function that moves to step given as `el` parameter (by index, id or element).
// `duration` optionally given as second parameter, is the transition duration in css.
// `reason` is the string "next", "prev" or "goto" (default) and will be made available to
// preStepLeave plugins.
// `origEvent` may contain event that caused the call to goto, such as a key press event
var goto = function( el, duration, reason, origEvent ) {
reason = reason || "goto";
origEvent = origEvent || null;
if ( !initialized ) {
return false;
}
// Re-execute initAllSteps for each transition. This allows to edit step attributes
// dynamically, such as change their coordinates, or even remove or add steps, and have
// that change apply when goto() is called.
initAllSteps();
if ( !( el = getStep( el ) ) ) {
return false;
}
// Sometimes it's possible to trigger focus on first link with some keyboard action.
// Browser in such a case tries to scroll the page to make this element visible
// (even that body overflow is set to hidden) and it breaks our careful positioning.
//
// So, as a lousy (and lazy) workaround we will make the page scroll back to the top
// whenever slide is selected
//
// If you are reading this and know any better way to handle it, I'll be glad to hear
// about it!
window.scrollTo( 0, 0 );
var step = stepsData[ "impress-" + el.id ];
duration = ( duration !== undefined ? duration : step.transitionDuration );
// If we are in fact moving to another step, start with executing the registered
// preStepLeave plugins.
if ( activeStep && activeStep !== el ) {
var event = { target: activeStep, detail: {} };
event.detail.next = el;
event.detail.transitionDuration = duration;
event.detail.reason = reason;
if ( origEvent ) {
event.origEvent = origEvent;
}
if ( execPreStepLeavePlugins( event ) === false ) {
// PreStepLeave plugins are allowed to abort the transition altogether, by
// returning false.
// see stop and substep plugins for an example of doing just that
return false;
}
// Plugins are allowed to change the detail values
el = event.detail.next;
step = stepsData[ "impress-" + el.id ];
duration = event.detail.transitionDuration;
}
if ( activeStep ) {
activeStep.classList.remove( "active" );
body.classList.remove( "impress-on-" + activeStep.id );
}
el.classList.add( "active" );
body.classList.add( "impress-on-" + el.id );
// Compute target state of the canvas based on given step
var target = {
rotate: {
x: -step.rotate.x,
y: -step.rotate.y,
z: -step.rotate.z,
order: step.rotate.order
},
translate: {
x: -step.translate.x,
y: -step.translate.y,
z: -step.translate.z
},
scale: 1 / step.scale
};
// Check if the transition is zooming in or not.
//
// This information is used to alter the transition style:
// when we are zooming in - we start with move and rotate transition
// and the scaling is delayed, but when we are zooming out we start
// with scaling down and move and rotation are delayed.
var zoomin = target.scale >= currentState.scale;
duration = lib.util.toNumber( duration, config.transitionDuration );
var delay = ( duration / 2 );
// If the same step is re-selected, force computing window scaling,
// because it is likely to be caused by window resize
if ( el === activeStep ) {
windowScale = computeWindowScale( config );
}
var targetScale = target.scale * windowScale;
// Trigger leave of currently active element (if it's not the same step again)
if ( activeStep && activeStep !== el ) {
onStepLeave( activeStep, el );
}
// Now we alter transforms of `root` and `canvas` to trigger transitions.
//
// And here is why there are two elements: `root` and `canvas` - they are
// being animated separately:
// `root` is used for scaling and `canvas` for translate and rotations.
// Transitions on them are triggered with different delays (to make
// visually nice and "natural" looking transitions), so we need to know
// that both of them are finished.
css( root, {
// To keep the perspective look similar for different scales
// we need to "scale" the perspective, too
// For IE 11 support we must specify perspective independent
// of transform.
perspective: ( config.perspective / targetScale ) + "px",
transform: scale( targetScale ),
transitionDuration: duration + "ms",
transitionDelay: ( zoomin ? delay : 0 ) + "ms"
} );
css( canvas, {
transform: rotate( target.rotate, true ) + translate( target.translate ),
transitionDuration: duration + "ms",
transitionDelay: ( zoomin ? 0 : delay ) + "ms"
} );
// Here is a tricky part...
//
// If there is no change in scale or no change in rotation and translation, it means
// there was actually no delay - because there was no transition on `root` or `canvas`
// elements. We want to trigger `impress:stepenter` event in the correct moment, so
// here we compare the current and target values to check if delay should be taken into
// account.
//
// I know that this `if` statement looks scary, but it's pretty simple when you know
// what is going on - it's simply comparing all the values.
if ( currentState.scale === target.scale ||
( currentState.rotate.x === target.rotate.x &&
currentState.rotate.y === target.rotate.y &&
currentState.rotate.z === target.rotate.z &&
currentState.translate.x === target.translate.x &&
currentState.translate.y === target.translate.y &&
currentState.translate.z === target.translate.z ) ) {
delay = 0;
}
// Store current state
currentState = target;
activeStep = el;
// And here is where we trigger `impress:stepenter` event.
// We simply set up a timeout to fire it taking transition duration (and possible delay)
// into account.
//
// I really wanted to make it in more elegant way. The `transitionend` event seemed to
// be the best way to do it, but the fact that I'm using transitions on two separate
// elements and that the `transitionend` event is only triggered when there was a
// transition (change in the values) caused some bugs and made the code really
// complicated, cause I had to handle all the conditions separately. And it still
// needed a `setTimeout` fallback for the situations when there is no transition at all.
// So I decided that I'd rather make the code simpler than use shiny new
// `transitionend`.
//
// If you want learn something interesting and see how it was done with `transitionend`
// go back to version 0.5.2 of impress.js:
// http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js
window.clearTimeout( stepEnterTimeout );
stepEnterTimeout = window.setTimeout( function() {
onStepEnter( activeStep );
}, duration + delay );
return el;
};
// `prev` API function goes to previous step (in document order)
// `event` is optional, may contain the event that caused the need to call prev()
var prev = function( origEvent ) {
var prev = steps.indexOf( activeStep ) - 1;
prev = prev >= 0 ? steps[ prev ] : steps[ steps.length - 1 ];
return goto( prev, undefined, "prev", origEvent );
};
// `next` API function goes to next step (in document order)
// `event` is optional, may contain the event that caused the need to call next()
var next = function( origEvent ) {
var next = steps.indexOf( activeStep ) + 1;
next = next < steps.length ? steps[ next ] : steps[ 0 ];
return goto( next, undefined, "next", origEvent );
};
// Swipe for touch devices by @and3rson.
// Below we extend the api to control the animation between the currently
// active step and a presumed next/prev step. See touch plugin for
// an example of using this api.
// Helper function
var interpolate = function( a, b, k ) {
return a + ( b - a ) * k;
};
// Animate a swipe.
//
// Pct is a value between -1.0 and +1.0, designating the current length
// of the swipe.
//
// If pct is negative, swipe towards the next() step, if positive,
// towards the prev() step.
//
// Note that pre-stepleave plugins such as goto can mess with what is a
// next() and prev() step, so we need to trigger the pre-stepleave event
// here, even if a swipe doesn't guarantee that the transition will
// actually happen.
//
// Calling swipe(), with any value of pct, won't in itself cause a
// transition to happen, this is just to animate the swipe. Once the
// transition is committed - such as at a touchend event - caller is
// responsible for also calling prev()/next() as appropriate.
//
// Note: For now, this function is made available to be used by the swipe plugin (which
// is the UI counterpart to this). It is a semi-internal API and intentionally not
// documented in DOCUMENTATION.md.
var swipe = function( pct ) {
if ( Math.abs( pct ) > 1 ) {
return;
}
// Prepare & execute the preStepLeave event
var event = { target: activeStep, detail: {} };
event.detail.swipe = pct;
// Will be ignored within swipe animation, but just in case a plugin wants to read this,
// humor them
event.detail.transitionDuration = config.transitionDuration;
var idx; // Needed by jshint
if ( pct < 0 ) {
idx = steps.indexOf( activeStep ) + 1;
event.detail.next = idx < steps.length ? steps[ idx ] : steps[ 0 ];
event.detail.reason = "next";
} else if ( pct > 0 ) {
idx = steps.indexOf( activeStep ) - 1;
event.detail.next = idx >= 0 ? steps[ idx ] : steps[ steps.length - 1 ];
event.detail.reason = "prev";
} else {
// No move
return;
}
if ( execPreStepLeavePlugins( event ) === false ) {
// If a preStepLeave plugin wants to abort the transition, don't animate a swipe
// For stop, this is probably ok. For substep, the plugin it self might want to do
// some animation, but that's not the current implementation.
return false;
}
var nextElement = event.detail.next;
var nextStep = stepsData[ "impress-" + nextElement.id ];
// If the same step is re-selected, force computing window scaling,
var nextScale = nextStep.scale * windowScale;
var k = Math.abs( pct );
var interpolatedStep = {
translate: {
x: interpolate( currentState.translate.x, -nextStep.translate.x, k ),
y: interpolate( currentState.translate.y, -nextStep.translate.y, k ),
z: interpolate( currentState.translate.z, -nextStep.translate.z, k )
},
rotate: {
x: interpolate( currentState.rotate.x, -nextStep.rotate.x, k ),
y: interpolate( currentState.rotate.y, -nextStep.rotate.y, k ),
z: interpolate( currentState.rotate.z, -nextStep.rotate.z, k ),
// Unfortunately there's a discontinuity if rotation order changes. Nothing I
// can do about it?
order: k < 0.7 ? currentState.rotate.order : nextStep.rotate.order
},
scale: interpolate( currentState.scale, nextScale, k )
};
css( root, {
// To keep the perspective look similar for different scales
// we need to 'scale' the perspective, too
perspective: config.perspective / interpolatedStep.scale + "px",
transform: scale( interpolatedStep.scale ),
transitionDuration: "0ms",
transitionDelay: "0ms"
} );
css( canvas, {
transform: rotate( interpolatedStep.rotate, true ) +
translate( interpolatedStep.translate ),
transitionDuration: "0ms",
transitionDelay: "0ms"
} );
};
// Teardown impress
// Resets the DOM to the state it was before impress().init() was called.
// (If you called impress(rootId).init() for multiple different rootId's, then you must
// also call tear() once for each of them.)
var tear = function() {
lib.gc.teardown();
delete roots[ "impress-root-" + rootId ];
};
// Adding some useful classes to step elements.
//
// All the steps that have not been shown yet are given `future` class.
// When the step is entered the `future` class is removed and the `present`
// class is given. When the step is left `present` class is replaced with
// `past` class.
//
// So every step element is always in one of three possible states:
// `future`, `present` and `past`.
//
// There classes can be used in CSS to style different types of steps.
// For example the `present` class can be used to trigger some custom
// animations when step is shown.
lib.gc.addEventListener( root, "impress:init", function() {
// STEP CLASSES
steps.forEach( function( step ) {
step.classList.add( "future" );
} );
lib.gc.addEventListener( root, "impress:stepenter", function( event ) {
event.target.classList.remove( "past" );
event.target.classList.remove( "future" );
event.target.classList.add( "present" );
}, false );
lib.gc.addEventListener( root, "impress:stepleave", function( event ) {
event.target.classList.remove( "present" );
event.target.classList.add( "past" );
}, false );
}, false );
// Adding hash change support.
lib.gc.addEventListener( root, "impress:init", function() {
// Last hash detected
var lastHash = "";
// `#/step-id` is used instead of `#step-id` to prevent default browser
// scrolling to element in hash.
//
// And it has to be set after animation finishes, because in Chrome it
// makes transtion laggy.
// BUG: http://code.google.com/p/chromium/issues/detail?id=62820
lib.gc.addEventListener( root, "impress:stepenter", function( event ) {
window.location.hash = lastHash = "#/" + event.target.id;
}, false );
lib.gc.addEventListener( window, "hashchange", function() {
// When the step is entered hash in the location is updated
// (just few lines above from here), so the hash change is
// triggered and we would call `goto` again on the same element.
//
// To avoid this we store last entered hash and compare.
if ( window.location.hash !== lastHash ) {
goto( lib.util.getElementFromHash() );
}
}, false );
// START
// by selecting step defined in url or first step of the presentation
goto( lib.util.getElementFromHash() || steps[ 0 ], 0 );
}, false );
body.classList.add( "impress-disabled" );
// Store and return API for given impress.js root element
return ( roots[ "impress-root-" + rootId ] = {
init: init,
initAllSteps: initAllSteps,
steps: () => {initAllSteps(); return steps},
goto: goto,
next: next,
prev: prev,
swipe: swipe,
tear: tear,
lib: lib
} );
};
// Flag that can be used in JS to check if browser have passed the support test
impress.supported = impressSupported;
// ADD and INIT LIBRARIES
// Library factories are defined in src/lib/*.js, and register themselves by calling
// impress.addLibraryFactory(libraryFactoryObject). They're stored here, and used to augment
// the API with library functions when client calls impress(rootId).
// See src/lib/README.md for clearer example.
// (Advanced usage: For different values of rootId, a different instance of the libaries are
// generated, in case they need to hold different state for different root elements.)
var libraryFactories = {};
impress.addLibraryFactory = function( obj ) {
for ( var libname in obj ) {
if ( obj.hasOwnProperty( libname ) ) {
libraryFactories[ libname ] = obj[ libname ];
}
}
};
// Call each library factory, and return the lib object that is added to the api.
var initLibraries = function( rootId ) { //jshint ignore:line
var lib = {};
for ( var libname in libraryFactories ) {
if ( libraryFactories.hasOwnProperty( libname ) ) {
if ( lib[ libname ] !== undefined ) {
throw "impress.js ERROR: Two libraries both tried to use libname: " + libname;
}
lib[ libname ] = libraryFactories[ libname ]( rootId );
}
}
return lib;
};
// `addPreInitPlugin` allows plugins to register a function that should
// be run (synchronously) at the beginning of init, before
// impress().init() itself executes.
impress.addPreInitPlugin = function( plugin, weight ) {
weight = parseInt( weight ) || 10;
if ( weight <= 0 ) {
throw "addPreInitPlugin: weight must be a positive integer";
}
if ( preInitPlugins[ weight ] === undefined ) {
preInitPlugins[ weight ] = [];
}
preInitPlugins[ weight ].push( plugin );
};
// Called at beginning of init, to execute all pre-init plugins.
var execPreInitPlugins = function( root ) { //jshint ignore:line
for ( var i = 0; i < preInitPlugins.length; i++ ) {
var thisLevel = preInitPlugins[ i ];
if ( thisLevel !== undefined ) {
for ( var j = 0; j < thisLevel.length; j++ ) {
thisLevel[ j ]( root );
}
}
}
};
// `addPreStepLeavePlugin` allows plugins to register a function that should
// be run (synchronously) at the beginning of goto()
impress.addPreStepLeavePlugin = function( plugin, weight ) { //jshint ignore:line
weight = parseInt( weight ) || 10;
if ( weight <= 0 ) {
throw "addPreStepLeavePlugin: weight must be a positive integer";
}
if ( preStepLeavePlugins[ weight ] === undefined ) {
preStepLeavePlugins[ weight ] = [];
}
preStepLeavePlugins[ weight ].push( plugin );
};
// Called at beginning of goto(), to execute all preStepLeave plugins.
var execPreStepLeavePlugins = function( event ) { //jshint ignore:line
for ( var i = 0; i < preStepLeavePlugins.length; i++ ) {
var thisLevel = preStepLeavePlugins[ i ];
if ( thisLevel !== undefined ) {
for ( var j = 0; j < thisLevel.length; j++ ) {
if ( thisLevel[ j ]( event ) === false ) {
// If a plugin returns false, the stepleave event (and related transition)
// is aborted
return false;
}
}
}
}
};
} )( document, window );
// THAT'S ALL FOLKS!
//
// Thanks for reading it all.
// Or thanks for scrolling down and reading the last part.
//
// I've learnt a lot when building impress.js and I hope this code and comments
// will help somebody learn at least some part of it.
|
/**
* HeadsUp 1.5.9
* A smart header for smart people
* @author Kyle Foster (@hkfoster)
* @license MIT
*/
;( function( root, factory ) {
if ( typeof define === 'function' && define.amd ) {
define( factory );
} else if ( typeof exports === 'object' ) {
module.exports = factory;
} else {
root.headsUp = factory( root );
}
})( this, function( root ) {
'use strict';
// Public API object
var headsUp = {};
// Overridable defaults
headsUp.defaults = {
delay : 300,
sensitivity : 20
};
// Init function
headsUp.init = function( element, settings ) {
// Scoped variables
var options = extend( this.defaults, settings ),
selector = document.querySelector( element ),
docHeight = document.body.scrollHeight,
winHeight = window.innerHeight,
calcDelay = ( options.delay.toString().indexOf( '%' ) != -1 ) ? parseFloat( options.delay ) / 100.0 * docHeight - winHeight : options.delay,
oldScrollY = 0;
// Attach listeners
if ( selector ) {
// Scroll throttle function init
throttle( 'scroll', 'optimizedScroll' );
// Resize throttle function init
throttle( 'resize', 'optimizedResize' );
// Resize function listener
window.addEventListener( 'optimizedResize', resizeHandler, false );
// Scroll function listener
window.addEventListener( 'optimizedScroll', scrollHandler, false );
}
// Resize handler function
function resizeHandler() {
// Update window height variable
winHeight = window.innerHeight;
}
// Scroll handler function
function scrollHandler() {
// Scoped variables
var newScrollY = window.pageYOffset,
pastDelay = newScrollY > calcDelay,
goingDown = newScrollY > oldScrollY,
fastEnough = newScrollY < oldScrollY - options.sensitivity,
rockBottom = newScrollY < 0 || newScrollY + winHeight >= docHeight;
// Where the magic happens
if ( pastDelay && goingDown ) {
selector.classList.add( 'heads-up' );
} else if ( !goingDown && fastEnough && !rockBottom || !pastDelay ) {
selector.classList.remove( 'heads-up' );
}
// Keep on keeping on
oldScrollY = newScrollY;
}
};
// Extend function
function extend( a, b ) {
for( var key in b ) {
if( b.hasOwnProperty( key ) ) {
a[ key ] = b[ key ];
}
}
return a;
}
// Event throttle function - http://mzl.la/1OasQYz
function throttle( type, name, obj ) {
obj = obj || window;
var running = false;
var func = function() {
if ( running ) { return; }
running = true;
requestAnimationFrame( function() {
obj.dispatchEvent( new CustomEvent( name ) );
running = false;
});
};
obj.addEventListener( type, func );
}
// Public API
return headsUp;
});
// Instantiation
headsUp.init( 'selector', {
delay : '75%', // percentage of document height
delay : 300, // number of pixels from top of document
sensitivity : 30
}); |
function solve(args) {
let len = args.length,
newArr = [],
people = [],
person,
i;
for (i = 0; i < len; i += 3) { //Create array of persons
person = createPerson(args[i], args[i + 1], +args[i + 2]);
people.push(person);
}
newArr = people
.filter(x => x.age > 18)
.map(x => x)
.forEach(x => console.log(x));
function createPerson(fName, lName, age) { //Create person
return {
firstName: fName,
lastName: lName,
age: age
}
}
}
var args = [
'Gosho', 'Petrov', '32',
'Bay', 'Ivan', '81',
'John', 'Doe', '42'
];
var args2 = [
'Penka', 'Hristova', '61',
'System', 'Failiure', '88',
'Bat', 'Man', '16',
'Malko', 'Kote', '72'
];
solve(args2); |
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import { nextBuild } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
const appDir = join(__dirname, '../react-site')
describe('Build Stats Output', () => {
it('Shows correct package count in output', async () => {
const { stdout } = await nextBuild(appDir, undefined, { stdout: true })
expect(stdout).toMatch(/\/something .*?4/)
})
})
|
/* jshint browser:true */
/* global angular */
angular.module('griddy.directives').directive('column', function () {
return {
restrict: 'E',
templateUrl: 'partials/column.tpl.html',
replace: true,
link: function ($scope, element, attrs) {
var prefs = $scope.project.preferences,
col = $scope.column;
$scope.$watch('project.preferences.currentBreakpoint', function (newbp, oldbp) {
if (newbp !== oldbp) {
var oldSpan = col.getPropertyAt('span', oldbp),
oldOffset = col.getPropertyAt('offset', oldbp),
newSpan = col.getPropertyAt('span', newbp),
newOffset = col.getPropertyAt('offset', newbp);
element.removeClass('gd-column-' + oldSpan).removeClass('gd-offset-' + oldOffset).addClass('gd-column-' + newSpan);
if (newOffset !== undefined) {
element.addClass('gd-offset-' + newOffset);
}
}
});
$scope.expandColumn = function () {
var span = col.getPropertyAt('span', prefs.currentBreakpoint) || 1,
offset = col.getPropertyAt('offset', prefs.currentBreakpoint) || 0;
if (span + offset + 1 <= prefs.columnsCount) {
element.removeClass('gd-column-' + span).addClass('gd-column-' + (span + 1));
var bp = col.breakpoints[prefs.currentBreakpoint] || (col.breakpoints[prefs.currentBreakpoint] = {});
bp.span = span + 1;
}
};
$scope.collapseColumn = function () {
var span = col.getPropertyAt('span', prefs.currentBreakpoint) || 1;
if (span > 1) {
element.removeClass('gd-column-' + span).addClass('gd-column-' + (span - 1));
var bp = col.breakpoints[prefs.currentBreakpoint] || (col.breakpoints[prefs.currentBreakpoint] = {});
bp.span = span - 1;
}
};
$scope.addOffset = function () {
var span = col.getPropertyAt('span', prefs.currentBreakpoint) || 1,
offset = col.getPropertyAt('offset', prefs.currentBreakpoint) || 0;
if (span + offset + 1 <= prefs.columnsCount) {
element.removeClass('gd-offset-' + offset).addClass('gd-offset-' + (offset + 1));
var bp = col.breakpoints[prefs.currentBreakpoint] || (col.breakpoints[prefs.currentBreakpoint] = {});
bp.offset = offset + 1;
}
};
$scope.removeOffset = function () {
var offset = col.getPropertyAt('offset', prefs.currentBreakpoint) || 0;
if (offset > 0) {
element.removeClass('gd-offset-' + offset).addClass('gd-offset-' + (offset - 1));
var bp = col.breakpoints[prefs.currentBreakpoint] || (col.breakpoints[prefs.currentBreakpoint] = {});
bp.offset = offset - 1;
}
};
}
};
}); |
'use strict';
var nodeFormatProps = require('./parts/nodeFormatProps'),
linkFormatProps = require('./parts/linkFormatProps'),
labelFormatProps = require('./parts/labelFormatProps'),
gridFormatProps = require('./parts/gridFormatProps')
;
function formatTab(element, entryFactory, icons) {
var elemFormatGroup = {
id: 'elementFormat',
label: 'Element format',
entries: []
};
var labelFormatGroup = {
id: 'labelFormat',
label: 'Label format',
entries: []
};
var gridFormatGroup = {
id: 'gridFormat',
label: 'Grid format',
entries: []
};
nodeFormatProps(elemFormatGroup, element, entryFactory, icons);
linkFormatProps(elemFormatGroup, element, entryFactory);
labelFormatProps(labelFormatGroup, element, entryFactory);
gridFormatProps(gridFormatGroup, element, entryFactory);
return {
id: 'format',
label: 'Format',
groups: [
elemFormatGroup,
labelFormatGroup,
gridFormatGroup
]
};
}
module.exports = formatTab; |
(function() {
'use strict';
angular
.module('g2MatriculaApp')
.controller('LoginController', LoginController);
LoginController.$inject = ['$rootScope', '$state', '$timeout', 'Auth', '$uibModalInstance'];
function LoginController ($rootScope, $state, $timeout, Auth, $uibModalInstance) {
var vm = this;
vm.authenticationError = false;
vm.cancel = cancel;
vm.credentials = {};
vm.login = login;
vm.password = null;
vm.register = register;
vm.rememberMe = true;
vm.requestResetPassword = requestResetPassword;
vm.username = null;
$timeout(function (){angular.element('#username').focus();});
function cancel () {
vm.credentials = {
username: null,
password: null,
rememberMe: true
};
vm.authenticationError = false;
$uibModalInstance.dismiss('cancel');
}
function login (event) {
event.preventDefault();
Auth.login({
username: vm.username,
password: vm.password,
rememberMe: vm.rememberMe
}).then(function () {
vm.authenticationError = false;
$uibModalInstance.close();
if ($state.current.name === 'register' || $state.current.name === 'activate' ||
$state.current.name === 'finishReset' || $state.current.name === 'requestReset') {
$state.go('home');
}
$rootScope.$broadcast('authenticationSuccess');
// previousState was set in the authExpiredInterceptor before being redirected to login modal.
// since login is successful, go to stored previousState and clear previousState
if (Auth.getPreviousState()) {
var previousState = Auth.getPreviousState();
Auth.resetPreviousState();
$state.go(previousState.name, previousState.params);
}
}).catch(function () {
vm.authenticationError = true;
});
}
function register () {
$uibModalInstance.dismiss('cancel');
$state.go('register');
}
function requestResetPassword () {
$uibModalInstance.dismiss('cancel');
$state.go('requestReset');
}
}
})();
|
'use strict';
exports.get = get;
exports._get = _get;
exports.set = set;
exports._set = _set;
exports.remove = remove;
exports._remove = _remove;
var mix = require('mix2');
function is_object (subject) {
return Object(subject) === subject;
}
function _keys (key) {
if (typeof key !== 'string') {
return;
}
var keys = key.split('.').filter(Boolean);
if (!keys.length) {
return;
}
return keys;
};
// .get() -> undefined
// .get('a')
// .get('a.b')
function get (data, key) {
var keys = _keys(key);
return keys && _get(data, keys);
};
function _get (data, keys) {
var result = data;
keys.forEach(function (key) {
result = Object(result) === result
? result[key]
: undefined;
});
return result;
};
// .set('a', 1);
// .set('a.b', 1);
function set (data, key, value) {
if (Object(key) === key) {
mix(data, key);
return;
}
var keys = _keys(key);
keys && _set(data, keys, value);
};
// For better testing
function _set (data, keys, value) {
var i = 0;
var prop;
var length = keys.length;
for(; i < length; i ++){
prop = keys[i];
if (i === length - 1) {
// if the last key, set value
data[prop] = value;
return;
}
if (
!(prop in data)
// If the current value is not an object, we will override it.
// The logic who invoke `.set()` method should make sure `data[prop]` is an object,
// which `.set()` doesn't concern
|| !is_object(data[prop])
) {
data[prop] = {};
}
data = data[prop];
}
};
function remove (data, key) {
var keys = _keys(key);
keys && _remove(data, keys);
};
function _remove (data, keys) {
var length = keys.length;
var i = 0;
var key;
for (; i < length; i ++){
if (!is_object(data)) {
break;
}
key = keys[i];
if (i === length - 1) {
delete data[key];
} else {
data = data[key];
}
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var router_1 = require("@angular/router");
var dashboard_component_1 = require("./dashboard.component");
var dashboard_users_component_1 = require("./users/dashboard-users.component");
var dashboard_user_detail_component_1 = require("./users/dashboard-user-detail.component");
var dashboard_users_home_component_1 = require("./users/dashboard-users-home.component");
var dashboardRoutes = [
{
path: "",
children: [
{
path: "",
component: dashboard_component_1.DashboardComponent
},
{
path: "users",
component: dashboard_users_component_1.DashboardUsersComponent,
children: [
{
path: "",
component: dashboard_users_home_component_1.DashboardUsersHomeComponent
},
{
path: ":username",
component: dashboard_user_detail_component_1.DashboardUserDetailComponent
}
]
}
]
}
];
exports.dashboardRouting = router_1.RouterModule.forChild(dashboardRoutes);
//# sourceMappingURL=dashboard.routing.js.map |
'use strict';
var _ = require('lodash'),
os = require('os'),
Alias = require('./alias.js'),
util = require('./util.js');
/*----------------------------------------------------------------------------*/
function cleanValue(string) {
string = string == null ? '' : (string + '');
return _.trim(string.replace(/(?:^|\n)[\t ]*\*[\t ]*/g, ' '));
}
function getMultilineValue(string, tagName) {
var prelude = tagName == 'description' ? '^ */\\*\\*(?: *\\n *\\* *)?' : ('^ *\\*[\\t ]*@' + _.escapeRegExp(tagName) + '\\b'),
postlude = '(?=\\*\\s+\\@[a-z]|\\*/)',
result = _.result(RegExp(prelude + '([\\s\\S]*?)' + postlude, 'gm').exec(string), 1, '');
return _.trim(result.replace(RegExp('(?:^|\\n)[\\t ]*\\*[\\t ]?', 'g'), '\n'));
}
function getValue(string, tagName) {
tagName = tagName == 'member' ? (tagName + '(?:Of)?') : _.escapeRegExp(tagName);
var result = _.result(RegExp('^ *\\*[\\t ]*@' + tagName + '\\s+(.+)', 'm').exec(string), 1, '');
return cleanValue(result);
}
function hasTag(string, tagName) {
tagName = tagName == '*' ? '\\w+' : _.escapeRegExp(tagName);
return RegExp('^ *\\*[\\t ]*@' + tagName + '\\b', 'm').test(string);
}
/*----------------------------------------------------------------------------*/
/**
* The Entry constructor.
*
* @constructor
* @param {string} entry The documentation entry to analyse.
* @param {string} source The source code.
* @param {string} [lang='js'] The language highlighter used for code examples.
*/
function Entry(entry, source, lang) {
this.entry = entry;
this.lang = lang == null ? 'js' : lang;
this.source = source.replace(os.EOL, '\n');
this.getCall = _.memoize(this.getCall);
this.getCategory = _.memoize(this.getCategory);
this.getDesc = _.memoize(this.getDesc);
this.getExample = _.memoize(this.getExample);
this.isAlias = _.memoize(this.isAlias);
this.isCtor = _.memoize(this.isCtor);
this.isFunction = _.memoize(this.isFunction);
this.isLicense = _.memoize(this.isLicense);
this.isPlugin = _.memoize(this.isPlugin);
this.isPrivate = _.memoize(this.isPrivate);
this.isStatic = _.memoize(this.isStatic);
this.getLineNumber = _.memoize(this.getLineNumber);
this.getName = _.memoize(this.getName);
this.getReturns = _.memoize(this.getReturns);
this.getType = _.memoize(this.getType);
this._aliases = this._members = this._params = undefined;
}
/**
* Extracts the documentation entries from source code.
*
* @static
* @memberOf Entry
* @param {string} source The source code.
* @returns {Array} The array of entries.
*/
function getEntries(source) {
source = source == null ? '' : (source + '');
return source.match(/\/\*\*(?![-!])[\s\S]*?\*\/\s*.+/g) || [];
}
/**
* Extracts the entry's `alias` objects.
*
* @memberOf Entry
* @param {number} index The index of the array value to return.
* @returns {Array|string} The entry's `alias` objects.
*/
function getAliases(index) {
if (this._aliases === undefined) {
var result = _.result(/\*[\t ]*@alias\s+(.+)/.exec(this.entry), 1);
if (result) {
result = result.replace(/(?:^|\n)[\t ]*\*[\t ]*/, ' ').trim();
result = result.split(/,\s*/);
result.sort(util.compareNatural);
result = _.map(result, _.bind(function(value) {
return new Alias(value, this);
}, this));
}
this._aliases = result;
}
return index != null
? this._aliases[index]
: this._aliases;
}
/**
* Extracts the function call from the entry.
*
* @memberOf Entry
* @returns {string} The function call.
*/
function getCall() {
var result = /\*\/\s*(?:function\s+([^(]*)|(.*?)(?=[:=,]))/.exec(this.entry);
if (result) {
result = (result[1] || result[2]).split('.').pop();
result = _.trim(_.trim(result), "'").split('var ').pop();
result = _.trim(result);
}
// Get the function name.
// Avoid `this.getName()` because it calls `this.getCall()`.
var name = _.result(/\*[\t ]*@name\s+(.+)/.exec(this.entry), 1, result || '');
if (!this.isFunction()) {
return name;
}
var params = this.getParams(),
paramNames = [];
// Compile the function call syntax.
result = [result];
_.each(params, function(param) {
var paramValue = param[1]
// Skip params that are properties of other params (e.g. `options.leading`).
if (!/\./.test(paramValue.split(/\s/)[0])) {
result.push(paramValue);
}
paramNames.push(_.trim(paramValue, '[]'));
});
// Format the function call.
return name + '(' + result.slice(1).join(', ') + ')';
}
/**
* Extracts the entry's `category` data.
*
* @memberOf Entry
* @returns {string} The entry's `category` data.
*/
function getCategory() {
var result = _.result(/\*[\t ]*@category\s+(.+)/.exec(this.entry), 1, '');
return result
? cleanValue(result)
: (this.getType() == 'Function' ? 'Methods' : 'Properties');
}
/**
* Extracts the entry's description.
*
* @memberOf Entry
* @returns {string} The entry's description.
*/
function getDesc() {
var result = getMultilineValue(this.entry, 'description');
if (!result) {
return result;
}
result = _.trim(result
.replace(/:\n(?=[\t ]*\S)/g, ':<br>\n')
.replace(/(?:^|\n)[\t ]*\*\n[\t ]*\*[\t ]*/g, '\n\n')
.replace(/(?:^|\n)[\t ]*\*[\t ]/g, ' ')
.replace(/\n( *)[-*](?=[\t ]+\S)/g, '\n<br>\n$1*')
.replace(/^[\t ]*\n/gm, '<br>\n<br>\n')
);
var type = this.getType();
if (type != 'unknown') {
result = (type == 'Function' ? '' : '(' + type.replace(/\|/g, ', ') + '): ') + result;
}
return result;
}
/**
* Extracts the entry's `example` data.
*
* @memberOf Entry
* @returns {string} The entry's `example` data.
*/
function getExample() {
var result = getMultilineValue(this.entry, 'example');
if (result) {
result = '```' + this.lang + '\n' + result + '\n```';
result = removeEmptyCodeBlocks(result, this.lang)
}
return result
}
/**
* Removes empty code blocks (e.g., ```\n```) from `sourceStr`.
*
* @private
* @static
* @param {string} sourceStr The source code to purge of empty code blocks.
* @param {string} lang The `sourceStr` language Markdown abbreviation (e.g., 'js').
* @returns {string} Returns `sourceStr` without empty code blocks.
*/
function removeEmptyCodeBlocks(sourceStr, lang) {
var reCodeBlockBound = RegExp('\n?```(' + lang + ')?\n?', 'g')
var prevBoundEndIdx = 0
var prevBoundStartIdx = 0
var codeBlockOpen = false
var matchArray
while ((matchArray = reCodeBlockBound.exec(sourceStr)) !== null) {
var boundEndIdx = reCodeBlockBound.lastIndex
var boundStartIdx = boundEndIdx - matchArray[0].length
if (codeBlockOpen && prevBoundEndIdx === boundStartIdx) {
sourceStr = sourceStr.substring(0, prevBoundStartIdx) + sourceStr.substring(boundEndIdx)
codeBlockOpen = false
} else {
prevBoundEndIdx = boundEndIdx
prevBoundStartIdx = boundStartIdx
codeBlockOpen = !codeBlockOpen
}
}
return sourceStr
}
/**
* Checks if the entry is an alias.
*
* @memberOf Entry
* @returns {boolean} Returns `false`.
*/
function isAlias() {
return false;
}
/**
* Checks if the entry is a constructor.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if a constructor, else `false`.
*/
function isCtor() {
return hasTag(this.entry, 'constructor');
}
/**
* Checks if the entry is a function reference.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if the entry is a function reference, else `false`.
*/
function isFunction() {
return !!(
this.isCtor() ||
_.size(this.getParams()) ||
_.size(this.getReturns()) ||
/\*[\t ]*@function\b/.test(this.entry) ||
/\*\/\s*function/.test(this.entry)
);
}
/**
* Checks if the entry is a license.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if a license, else `false`.
*/
function isLicense() {
return hasTag(this.entry, 'license');
}
/**
* Checks if the entry *is* assigned to a prototype.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if assigned to a prototype, else `false`.
*/
function isPlugin() {
return (
(!this.isCtor()) &&
(!this.isPrivate()) &&
(!this.isStatic())
);
}
/**
* Checks if the entry is private.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if private, else `false`.
*/
function isPrivate() {
return (
this.isLicense() ||
hasTag(this.entry, 'private') ||
!hasTag(this.entry, '*')
);
}
/**
* Checks if the entry is *not* assigned to a prototype.
*
* @memberOf Entry
* @returns {boolean} Returns `true` if not assigned to a prototype, else `false`.
*/
function isStatic() {
var isPublic = !this.isPrivate(),
result = isPublic && hasTag(this.entry, 'static');
// Get the result in cases where it isn't explicitly stated.
if (isPublic && !result) {
var parent = _.last((this.getMembers(0) || '').split(/[#.]/));
if (!parent) {
return true;
}
var source = this.source;
_.each(getEntries(source), function(entry) {
entry = new Entry(entry, source);
if (entry.getName() == parent) {
result = !entry.isCtor();
return false;
}
});
}
return result;
}
/**
* Resolves the entry's line number.
*
* @memberOf Entry
* @returns {number} The entry's line number.
*/
function getLineNumber() {
var entry = this.entry,
lines = this.source.slice(0, this.source.indexOf(entry) + entry.length).match(/\n/g).slice(1);
// Offset by 2 because the first line number is before a line break and the
// last line doesn't include a line break.
return lines.length + 2;
}
/**
* Extracts the entry's `member` data.
*
* @memberOf Entry
* @param {number} [index] The index of the array value to return.
* @returns {Array|string} The entry's `member` data.
*/
function getMembers(index) {
if (this._members === undefined) {
var result = getValue(this.entry, 'member');
if (result) {
result = result.split(/,\s*/);
result.sort(util.compareNatural);
}
this._members = result || [];
}
return index != null
? this._members[index]
: this._members;
}
/**
* Extracts the entry's `name` data.
*
* @memberOf Entry
* @returns {string} The entry's `name` data.
*/
function getName() {
var result = hasTag(this.entry, 'name')
? getValue(this.entry, 'name')
: _.first(this.getCall().split('('));
return (result || '').replace(/\'/g, '');
}
/**
* Extracts the entry's `param` data.
*
* @memberOf Entry
* @param {number} [index] The index of the array value to return.
* @returns {Array} The entry's `param` data.
*/
function getParams(index) {
if (this._params === undefined) {
var match,
re = /@param\s+\{\(?([^}]+?)\)?\}\s+(\[.+\]|[\w\.]+(?:\[.+\])?)\s+([\s\S]*?)(?=\@|\*\/)/gim,
result = [];
while (match = re.exec(this.entry)) {
match = match.slice(1);
match = match.map(function(aParamPart,index) {
return aParamPart.trim()
});
match[2] = match[2].replace(/(?:^|\n)[\t ]*\*[\t ]*/g, ' ');
result.push(match);
}
var tuples = _.compact(match);
_.each(tuples, function(tuple){
result.push(tuple.trim());
});
this._params = result;
}
return index !== undefined
? this._params[index]
: this._params;
}
/**
* Extracts the entry's `returns` data.
*
* @memberOf Entry
* @returns {array} The entry's `returns` data.
*/
function getReturns() {
var result = getMultilineValue(this.entry, 'returns'),
returnType = _.result(/(?:\{)([\w|\*]*)(?:\})/gi.exec(result), 1);
return returnType
? [returnType, result.replace(/(\{[\w|\*]*\})/gi,'')]
: [];
}
/**
* Extracts the entry's `type` data.
*
* @memberOf Entry
* @returns {string} The entry's `type` data.
*/
function getType() {
var result = getValue(this.entry, 'type');
if (result) {
if (/^(?:array|function|object|regexp)$/.test(result)) {
result = _.capitalize(result);
}
} else {
result = this.isFunction() ? 'Function' : 'unknown';
}
return result;
}
/**
* Extracts the entry's hash value for permalinking.
*
* @memberOf Entry
* @param {string} [style] The hash style.
* @returns {string} The entry's hash value (without a hash itself).
*/
function getHash(style) {
var result = this.getMembers(0) || '';
switch (style) {
case 'github':
if (result) {
result += this.isPlugin() ? 'prototype' : '';
}
result += this.getCall();
return result
.replace(/\(\[|\[\]/g, '')
.replace(/[\t =|\'"{}.()\]]/g, '')
.replace(/[\[#,]+/g, '-')
.toLowerCase();
case 'default':
default:
if (result) {
result += '-' + (this.isPlugin() ? 'prototype-' : '');
}
result += this.isAlias() ? this.getOwner().getName() : this.getName();
return result
.replace(/\./g, '-')
.replace(/^_-/, '');
}
}
/*----------------------------------------------------------------------------*/
Entry.getEntries = getEntries;
_.assign(Entry.prototype, {
'getAliases': getAliases,
'getCall': getCall,
'getCategory': getCategory,
'getDesc': getDesc,
'getExample': getExample,
'isAlias': isAlias,
'isCtor': isCtor,
'isFunction': isFunction,
'isLicense': isLicense,
'isPlugin': isPlugin,
'isPrivate': isPrivate,
'isStatic': isStatic,
'getLineNumber': getLineNumber,
'getMembers': getMembers,
'getName': getName,
'getParams': getParams,
'getReturns': getReturns,
'getType': getType,
'getHash': getHash
});
module.exports = Entry; |
(function () {
'use strict';
angular.module('accordion', []);
})(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.