code
stringlengths 2
1.05M
|
---|
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
module.exports = app;
|
'use strict';
module.exports = {
...require('./au-run'),
...require('./au-build'),
...require('./au-test'),
...require('../generic/au-lint'),
...require('./au-protractor'),
...require('../generic/au-jest'),
dotnet: {
...require('../generic/dotnet-run')
}
};
|
var del = require('del');
var nib = require('nib');
var gulp = require('gulp');
var pump = require('pump');
var pug = require('gulp-pug');
var header = require('gulp-header');
var stylus = require('gulp-stylus');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync').create();
var dist = 'dist';
var src = 'src';
// ---------------------------------------------------------------------
// | Helper tasks |
// ---------------------------------------------------------------------
gulp.task('serve', function() {
browserSync.init({
server: {
baseDir: './' + dist,
},
open: false,
browser: 'google chrome'
});
gulp.watch(src + '/styl/**/*.styl', ['stylus']);
gulp.watch(src + '/**/*.pug', ['pug']);
gulp.watch(src + '/js/plugins/*.js', ['pluginjs']);
gulp.watch(src + '/js/*.js', ['copy:js']);
gulp.watch(src + '/images/**/*', ['copy:images']);
gulp.watch(src + '/uploads/**/*', ['copy:uploads']);
});
gulp.task('stylus', function() {
var banner = '/*!\n main.css\n */\n';
return gulp.src(src + '/styl/main.styl')
.pipe(stylus({
compress: true,
use: [nib()]
}))
.pipe(header(banner))
.pipe(gulp.dest(dist + '/static/css'))
.pipe(browserSync.stream());
});
gulp.task('pug', function() {
return gulp.src(src + '/*.pug')
.pipe(pug({
'pretty': ' '
}))
.pipe(gulp.dest(dist))
.pipe(browserSync.stream());
});
gulp.task('pluginjs', function(done) {
pump([
gulp.src(src + '/js/plugins/*.js'),
concat('plugins.js'),
uglify({ output: { comments: 'some' } }),
gulp.dest(dist + '/static/js/vendor'),
browserSync.stream()
], done);
});
// ---------------------------------------------------------------------
// | Clean tasks |
// ---------------------------------------------------------------------
gulp.task('clean', function() {
return del([dist]);
});
gulp.task('clean:js', function() {
return del([dist + '/static/js/*.js']);
});
gulp.task('clean:images', function() {
return del([dist + '/static/images/**/*']);
});
gulp.task('clean:uploads', function() {
return del([dist + '/uploads/**/*']);
});
gulp.task('clean:fonts', function() {
return del([dist + '/static/fonts/*']);
});
// ---------------------------------------------------------------------
// | Copy tasks |
// ---------------------------------------------------------------------
gulp.task('copy', [
'copy:js',
'copy:images',
'copy:uploads',
'copy:fonts',
'copy:bootstrap-css',
'copy:bootstrap-js',
'copy:jquery'
]);
gulp.task('copy:js', ['clean:js'], function() {
return gulp.src(src + '/js/*.js')
.pipe(gulp.dest(dist + '/static/js'))
.pipe(browserSync.stream());
});
gulp.task('copy:images', ['clean:images'], function() {
return gulp.src([src + '/images/**/*'])
.pipe(gulp.dest(dist + '/static/images'))
.pipe(browserSync.stream());
});
gulp.task('copy:uploads', ['clean:uploads'], function() {
return gulp.src([src + '/uploads/**/*'])
.pipe(gulp.dest(dist + '/uploads'))
.pipe(browserSync.stream());
});
gulp.task('copy:fonts', ['clean:fonts'], function() {
return gulp.src([src + '/fonts/*'])
.pipe(gulp.dest(dist + '/static/fonts'))
.pipe(browserSync.stream());
});
gulp.task('copy:bootstrap-css', function() {
return gulp.src('node_modules/bootstrap/dist/css/bootstrap.min.css')
.pipe(gulp.dest(dist + '/static/css'));
});
gulp.task('copy:bootstrap-js', function() {
return gulp.src('node_modules/bootstrap/dist/js/bootstrap.bundle.min.js')
.pipe(gulp.dest(dist + '/static/js/vendor'));
});
gulp.task('copy:jquery', function() {
return gulp.src('node_modules/jquery/dist/jquery.min.js')
.pipe(gulp.dest(dist + '/static/js/vendor'));
});
// ---------------------------------------------------------------------
// | Main tasks |
// ---------------------------------------------------------------------
gulp.task('build', function(done) {
runSequence(
['clean'],
'pug', 'stylus', 'copy', 'pluginjs',
done);
});
gulp.task('dev', function(done) {
runSequence(
['clean'],
'pug', 'stylus', 'copy', 'pluginjs', 'serve',
done);
});
gulp.task('default', ['dev']);
|
define([
'lodash'
, 'backbone'
, 'plugins/console'
// , 'plugins/backbone.analytics'
], function(_, Backbone, createConsole) {
"use strict";
createConsole();
console.log('main app.js loaded');
// Provide a global location to place configuration settings and module
// creation.
var app = {
// The root path to run the application.
root: '/'
};
// If you have a function used across the app you should attach it to the app
// object here.
// Mix Backbone.Event and the global app settings into the app object.
return _.extend(app, window.app, Backbone.Events);
});
|
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import {reducer as reduxAsyncConnect} from 'redux-async-connect';
import auth from './auth';
import {reducer as form} from 'redux-form';
import info from './info';
export default combineReducers({
routing: routerReducer,
reduxAsyncConnect,
auth,
form,
info,
});
|
'use strict';
import {isDevelop, basePaths} from './config';
let {source, app, dest} = basePaths;
const paths = {
source: {
files: {
scipts: `${app}/**/*!(.spec.js).js`,
indexHTML: `${source}/index.pug`,
fonts: `${source}/fonts/**/*`,
test: `${app}/**/*.spec.js`,
stylus: `${app}/root.styl`,
images: `${source}/img/**/*`,
templates: `${app}/**/*.pug`,
mainJS: `${app}/root.module.js`
},
folders: {
scripts: app,
base: source
}
},
dest: {
folders: {
base: `${dest}`,
scripts: `${dest}/js`,
styles: `${dest}/css`,
images: `${dest}/img`,
fonts: `${dest}/fonts`
}
}
};
export let {
source: {files: sFiles, folders: sFolders},
dest: {folders: dFolders}
} = paths;
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Sale = mongoose.model('Sale');
/**
* Globals
*/
var user, sale;
/**
* Unit tests
*/
describe('Sale Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function() {
sale = new Sale({
name: 'Sale Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
this.timeout(0);
return sale.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
sale.name = '';
return sale.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Sale.remove().exec(function(){
User.remove().exec(function(){
done();
});
});
});
});
|
var ThumbnailGenerator = require("./thumbnail-generator");
var SimpleThumbnailGenerator = require("./simple-thumbnail-generator");
var ThumbnailGeneratorService = require("./thumbnail-generator-service");
module.exports = {
ThumbnailGenerator: ThumbnailGenerator,
SimpleThumbnailGenerator: SimpleThumbnailGenerator,
ThumbnailGeneratorService: ThumbnailGeneratorService
};
|
/* eslint-disable no-param-reassign, no-underscore-dangle */
import { tokTypes as tt } from 'acorn'
export default function parseFromInput () {
return function ha (node) {
this.next()
// For the `导入 「./xxx」;`, it should be handled by parseImport.
node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected()
this.expect(tt._import)
node.specifiers = this.parseImportSpecifiers()
this.semicolon()
return this.finishNode(node, 'ImportDeclaration')
}
}
|
heebeegeebees.controller('MainController', ['$scope', function($scope) {
$scope.greeting = 'Hola!';
}]);
|
var Nconf = require('nconf'),
path = require('path'),
_debug = require('ghost-ignition').debug._base,
debug = _debug('ghost:config'),
localUtils = require('./utils'),
env = process.env.NODE_ENV || 'development',
_private = {};
_private.loadNconf = function loadNconf(options) {
debug('config start');
options = options || {};
var baseConfigPath = options.baseConfigPath || __dirname,
customConfigPath = options.customConfigPath || process.cwd(),
nconf = new Nconf.Provider();
/**
* no channel can override the overrides
*/
nconf.file('overrides', path.join(baseConfigPath, 'overrides.json'));
/**
* command line arguments
*/
nconf.argv();
/**
* env arguments
*/
nconf.env({
separator: '__'
});
nconf.file('custom-env', path.join(customConfigPath, 'config.' + env + '.json'));
nconf.file('default-env', path.join(baseConfigPath, 'env', 'config.' + env + '.json'));
nconf.file('defaults', path.join(baseConfigPath, 'defaults.json'));
// set settings manually from azure app service
nconf.set('server:port', process.env.PORT);
/**
* transform all relative paths to absolute paths
* transform sqlite filename path for Ghost-CLI
*/
nconf.makePathsAbsolute = localUtils.makePathsAbsolute.bind(nconf);
nconf.isPrivacyDisabled = localUtils.isPrivacyDisabled.bind(nconf);
nconf.getContentPath = localUtils.getContentPath.bind(nconf);
nconf.sanitizeDatabaseProperties = localUtils.sanitizeDatabaseProperties.bind(nconf);
nconf.doesContentPathExist = localUtils.doesContentPathExist.bind(nconf);
nconf.sanitizeDatabaseProperties();
nconf.makePathsAbsolute(nconf.get('paths'), 'paths');
nconf.makePathsAbsolute(nconf.get('database:connection'), 'database:connection');
/**
* Check if the URL in config has a protocol
*/
nconf.checkUrlProtocol = localUtils.checkUrlProtocol.bind(nconf);
nconf.checkUrlProtocol();
/**
* Ensure that the content path exists
*/
nconf.doesContentPathExist();
/**
* values we have to set manual
*/
nconf.set('env', env);
// Wrap this in a check, because else nconf.get() is executed unnecessarily
// To output this, use DEBUG=ghost:*,ghost-config
if (_debug.enabled('ghost-config')) {
debug(nconf.get());
}
debug('config end');
return nconf;
};
module.exports = _private.loadNconf();
module.exports.loadNconf = _private.loadNconf;
|
var { Router, history } = Backbone;
class Workspace extends Router {
constructor() {
this.routes = {
'videos': 'videos'
}
this._bindRoutes();
}
videos(query, page) {
console.log('videos');
}
};
(() => {
new Workspace();
Backbone.history.start();
})();
|
photosApp.controller('ordersListCtrl', ['$scope', 'customerService', 'uiGridConstants', 'i18nService', '$stateParams', '$state', 'uiGridExporterConstants',
function ($scope, customerService, uiGridConstants, i18nService, $stateParams, $state, uiGridExporterConstants) {
$scope.customerService = customerService;
i18nService.setCurrentLang('fr');
$scope.auth = $stateParams.auth;
if ($scope.auth === undefined) {
$state.go("auth.authOrder");
}
$scope.gridOptions = {
exporterPdfDefaultStyle: {
fontSize: 10,
bold: false
},
exporterPdfTableStyle: {},
exporterPdfTableHeaderStyle: {
fontSize: 10,
bold: true,
color: 'red'
},
exporterPdfOrientation: 'portrait',
exporterPdfPageSize: 'A4',
exporterPdfMaxGridWidth: 420,
exporterPdfCustomFormatter: function (docDefinition) {
docDefinition.styles.headerStyle = {
fontSize: 15,
bold: true,
margin: [10, 10, 10, 10]
};
docDefinition.styles.footerStyle = {
fontSize: 10,
bold: true
};
return docDefinition;
},
exporterPdfHeader: {
text: "Récapitulatif des commandes",
style: 'headerStyle'
},
exporterFieldCallback: function (grid, row, col, value) {
if (col.name === 'order.total_eur') {
value = value + '€';
}
return value;
},
enableColumnResizing: true,
enableFiltering: false,
showGridFooter: false,
showColumnFooter: true,
fastWatch: false,
enableGroupHeaderSelection: true,
enableHorizontalScrollbar: uiGridConstants.scrollbars.NEVER,
onRegisterApi: function (gridApi) {
$scope.gridApi = gridApi;
}
};
// return the height of the grid
$scope.getHeight = util.gridHeight;
$(window).on("resize.doResize", _.debounce(function () {
// alert(window.innerWidth);
$scope.$apply(function () {
if (window.innerWidth < 700) {
$scope.gridApi.grid.columns[2].hideColumn();
$scope.gridApi.grid.columns[3].hideColumn();
$scope.gridApi.grid.columns[4].hideColumn();
$scope.gridApi.grid.columns[5].hideColumn();
$scope.gridApi.grid.columns[6].hideColumn();
$scope.gridApi.grid.columns[7].hideColumn();
}
else {
$scope.gridApi.grid.columns[2].showColumn();
$scope.gridApi.grid.columns[3].showColumn();
$scope.gridApi.grid.columns[4].showColumn();
$scope.gridApi.grid.columns[5].showColumn();
$scope.gridApi.grid.columns[6].showColumn();
$scope.gridApi.grid.columns[7].showColumn();
}
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
});
}, 10));
$scope.$on("$destroy", function () {
$(window).off("resize.doResize"); //remove the handler added earlier
});
$scope.gridOptions.rowIdentity = function (row) {
return row.id;
};
$scope.gridOptions.getRowIdentity = function (row) {
return row.id;
};
$scope.gridOptions.columnDefs = [{
name: 'name',
displayName: "Nom",
enableColumnMenu: false,
sort: {
direction: uiGridConstants.ASC
}
}, {
name: 'surname',
displayName: "Prénom",
enableColumnMenu: false
}, {
name: 'order.photo_1',
displayName: "Photo 1",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.photo_2',
displayName: "Photo 2",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.photo_3',
displayName: "Photo 3",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.photo_4',
displayName: "Photo 4",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.photo_5',
displayName: "Photo 5",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.photo_6',
displayName: "Photo 6",
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.total',
displayName: 'Total',
enableColumnMenu: false,
aggregationType: uiGridConstants.aggregationTypes.sum
}, {
name: 'order.total_eur',
displayName: 'Total €',
enableColumnMenu: false,
cellTemplate: '<div class="ui-grid-cell-contents">{{ COL_FIELD | currency }}</div>',
aggregationType: uiGridConstants.aggregationTypes.sum
}];
customerService.getGroupList($scope.auth).then(function (data) {
$scope.gridOptions.data = data;
if (window.innerWidth < 700) {
$scope.gridApi.grid.columns[2].hideColumn();
$scope.gridApi.grid.columns[3].hideColumn();
$scope.gridApi.grid.columns[4].hideColumn();
$scope.gridApi.grid.columns[5].hideColumn();
$scope.gridApi.grid.columns[6].hideColumn();
$scope.gridApi.grid.columns[7].hideColumn();
}
else {
$scope.gridApi.grid.columns[2].showColumn();
$scope.gridApi.grid.columns[3].showColumn();
$scope.gridApi.grid.columns[4].showColumn();
$scope.gridApi.grid.columns[5].showColumn();
$scope.gridApi.grid.columns[6].showColumn();
$scope.gridApi.grid.columns[7].showColumn();
}
$scope.gridApi.core.notifyDataChange(uiGridConstants.dataChange.COLUMN);
});
$scope.export = function () {
$scope.gridApi.exporter.pdfExport(uiGridExporterConstants.ALL, uiGridExporterConstants.ALL);
};
customerService.getCustomerFromAuthToken($scope.auth).then(function (user) {
$scope.group = user.group.num;
$scope.email = user.email;
});
}
]);
|
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var _s = require('underscore.string');
var MavenGenerator = module.exports = function MavenGenerator(args, options, config) {
yeoman.generators.Base.apply(this, arguments);
this.on('end', function () {
this.installDependencies({ skipInstall: options['skip-install'] });
});
this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};
util.inherits(MavenGenerator, yeoman.generators.Base);
MavenGenerator.prototype.askFor = function askFor() {
var cb = this.async();
// have Yeoman greet the user.
console.log(this.yeoman);
var prompts = [
{
type: 'input',
name: 'baseName',
message: '(1/2) What is the base name of your application?',
default: 'example'
},
{
type: 'input',
name: 'packageName',
message: '(2/2) What is your default package name?',
default: 'com.mycompany.myapp'
}
];
this.prompt(prompts, function (props) {
this.baseName = props.baseName;
this.packageName = props.packageName;
this.version = '1.0-SNAPSHOT';
cb();
}.bind(this));
};
MavenGenerator.prototype.app = function app() {
//this.mkdir('app');
//this.mkdir('app/templates');
var packageFolder = this.packageName.replace(/\./g, '/');
this.mkdir("src/main/java/" + packageFolder);
this.mkdir("src/main/webapp/");
this.mkdir("src/main/web/");
this.mkdir("src/test/java/");
this.mkdir("src/test/web/");
// Java sources
var srcFolder = 'src/main/java/' + packageFolder + '/';
this.mkdir(srcFolder);
this.template('src/main/java/Application.java', srcFolder + '/Application.java');
this.template('src/main/java/rest/HelloRestService.java', srcFolder + 'rest/HelloRestService.java');
this.template('src/main/java/dao/api/GenericDao.java', srcFolder + 'dao/api/GenericDao.java');
this.template('src/main/java/dao/api/UserDao.java', srcFolder + 'dao/api/UserDao.java');
this.template('src/main/java/dao/impl/GenericJPADao.java', srcFolder + 'dao/impl/GenericJPADao.java');
this.template('src/main/java/dao/impl/UserJPADao.java', srcFolder + 'dao/impl/UserJPADao.java');
this.template('src/main/java/entity/User.java', srcFolder + 'entity/User.java');
this.template('src/main/java/rest/UserRestService.java', srcFolder + 'rest/UserRestService.java');
this.template('src/main/resources/META-INF/persistence.xml', 'src/main/resources/META-INF/persistence.xml');
// Webapp folder
this.copy('src/main/webapp/WEB-INF/web.xml', 'src/main/webapp/WEB-INF/web.xml');
this.copy('src/main/webapp/WEB-INF/openejb-jar.xml', 'src/main/webapp/WEB-INF/openejb-jar.xml');
this.copy('src/main/webapp/WEB-INF/beans.xml', 'src/main/webapp/WEB-INF/beans.xml');
this.copy('src/main/webapp/rest.html', 'src/main/webapp/rest.html');
this.copy('src/main/webapp/wadl/wadl.xsl', 'src/main/webapp/wadl/wadl.xsl');
// Web folder
this.template('src/main/web/_index.html', 'src/main/web/index.html');
this.copy('src/main/web/views/main.html', 'src/main/web/views/main.html');
this.template('src/main/web/scripts/_app.js', 'src/main/web/scripts/app.js');
this.template('src/main/web/scripts/controllers/_main.js', 'src/main/web/scripts/controllers/main.js');
this.template('src/main/web/scripts/controllers/_application-ctrl.js', 'src/main/web/scripts/controllers/application-ctrl.js');
this.copy('src/main/web/styles/main.css', 'src/main/web/styles/main.css');
this.copy('src/main/web/favicon.ico', 'src/main/web/favicon.ico');
this.copy('src/main/web/robots.txt', 'src/main/web/robots.txt');
// Web test folder
this.template('src/test/web/spec/controllers/_main.js', 'src/test/web/spec/controllers/main.js');
// Root folder
this.copy('bowerrc', '.bowerrc');
this.copy('jshintrc', '.jshintrc');
this.template('gitignore', '.gitignore');
this.copy('Gruntfile.js', 'Gruntfile.js');
this.copy('karma.conf.js', 'karma.conf.js');
this.template('_pom.xml', 'pom.xml');
this.template('_package.json', 'package.json');
this.template('_bower.json', 'bower.json');
};
MavenGenerator.prototype.projectfiles = function projectfiles() {
this.copy('editorconfig', '.editorconfig');
this.copy('jshintrc', '.jshintrc');
};
|
module.exports = function (grunt) {
var browsers = [{
browserName: 'googlechrome',
platform: 'XP'
}, {
browserName: 'internet explorer',
platform: 'WIN7',
version: '8'
}, {
browserName: 'internet explorer',
platform: 'WIN8.1',
version: '11'
}];
//browsers = [{
// browserName: 'googlechrome',
// platform: 'WIN7',
// version: 'dev'
//}, {
// browserName: 'googlechrome',
// platform: 'WIN7',
// version: 'beta'
//}, {
// browserName: 'googlechrome',
// platform: 'WIN7',
// version: '42'
//}, {
// browserName: 'googlechrome',
// platform: 'WIN7',
// version: '41'
//}, {
// browserName: 'googlechrome',
// platform: 'WIN8.1',
// version: 'dev'
//}];
browsers = [];
// CHROME
['42', '28'].forEach(function (version) {
['WIN7', 'WIN8.1', 'WIN8', 'XP'].forEach(function (platform) {
browsers.push({
browserName: 'googlechrome',
platform: platform,
version: version
});
});
});
['11', '10', '9', '8'].forEach(function (val) {
browsers.push({
browserName: 'internet explorer',
platform: 'WIN7',
version: val
});
});
browsers = browsers.concat([
{
browserName: 'internet explorer',
platform: 'WIN8.1',
version: '11'
},
{
browserName: 'internet explorer',
platform: 'WIN8',
version: '10'
},
{
browserName: 'internet explorer',
platform: 'XP',
version: '8'
},
{
browserName: 'safari',
platform: 'OS X 10.10',
version: '8.0'
},
{
browserName: 'firefox',
platform: 'WIN7',
version: 37
},
{
browserName: 'firefox',
platform: 'WIN8',
version: 37
},
{
browserName: 'firefox',
platform: 'WIN8.1',
version: 37
}
]);
// ['7','6'].forEach(function (val) {
// browsers.push({
// browserName: 'internet explorer',
// platform: 'XP',
// version: val
// });
// });
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
server: {
options: {
base: '',
port: 9999
}
}
},
'saucelabs-jasmine': {
all: {
options: {
username: '21paradox_test', // if not provided it'll default to ENV SAUCE_USERNAME (if applicable)
key: 'ff8739e5-04bd-489e-9b56-f4e35032c5fa', // if
urls: [
'http://127.0.0.1:9999/spec_1page.html',
'http://127.0.0.1:9999/spec_2page.html',
'http://127.0.0.1:9999/spec_2.1page.html'
],
browsers: browsers,
build: process.env.TRAVIS_JOB_ID,
testname: 'tabHub tests',
throttled: 3,
sauceConfig: {
'video-upload-on-pass': false
},
pollInterval: 20000,
statusCheckAttempts: 100
}
}
},
watch: {}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-saucelabs');
grunt.registerTask('default', ['connect', 'saucelabs-jasmine']);
};
|
/*BOOTKIT*/
var Botkit = require('botkit');
var controller = Botkit.slackbot({
debug: false
});
controller.spawn({
token: 'xoxb-xxxxxxxxxxxxx'
}).startRTM(function (err) {
if (err) {
throw new Error(err);
}
});
var tokken = "CLDYYP9SIe4alYW5U2FsdGVkX198t4LRL8I6paWYMHozsir9gGRSDu796dHJKuyL0B%2FSW0o0Xq33lTqdq4%2BbLjAGxrpyFgi57My9sKbM6emeMnT%2F2kKqKfaIsSnXTuI8FG1vDdT7dbUGkV0ibeYcWogeoTFhq1j7QyhF3IfPM%2FXBYOHbeHF%2FGcjxrm6G0JMAZNHtfYECQqZl%2Bop3MOTYgPfk%2BRfYlu9swBljPg%3D%3D";
////////// Obtener Proyectos
controller.hears('obtener proyectos', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
controller.storage.users.get(message.user, function (err, user) {
var http = require('http');
var extServerOptions = {
host: 'xxx.azurewebsites.net',
path: '/GDP2WSREST.svc/GetProjects/?tokken=' + tokken,
method: 'GET'
};
var normalize = (function() {
var from = "ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç",
to = "AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc",
mapping = {};
for(var i = 0, j = from.length; i < j; i++ )
mapping[ from.charAt( i ) ] = to.charAt( i );
return function( str ) {
var ret = [];
for( var i = 0, j = str.length; i < j; i++ ) {
var c = str.charAt( i );
if( mapping.hasOwnProperty( str.charAt( i ) ) )
ret.push( mapping[ c ] );
else
ret.push( c );
}
return ret.join( '' );
}
})();
String.prototype.contains = function(str, ignoreCase) {
return (ignoreCase ? this.toUpperCase() : this)
.indexOf(ignoreCase ? str.toUpperCase() : str) >= 0;
};
function removeCharsFromProject(parameter) {
var textFromJSON = parameter;
textFromJSON.replace('"ProjectName":"', '');
textFromJSON.replace('"', '');
textFromJSON.replace('}', '');
textFromJSON.replace(']', '');
textFromJSON.replace(']', '');
return textFromJSON;
}
function removeCharsFromJSON(parameter) {
var textFromJSON = parameter;
textFromJSON.replace('"', '');
textFromJSON.replace('"UserName":"', '');
textFromJSON.replace('[', '');
textFromJSON.replace('{', '');
textFromJSON.replace('Active', '');
textFromJSON.replace(':', '');
textFromJSON.replace(/['"]+/g, '');
textFromJSON.replace('LastName', '');
textFromJSON.replace('"UserName":"', '');
return textFromJSON;
}
function get() {
http.request(extServerOptions, function (res) {
res.setEncoding('utf8');
res.on('data', function (data) {
var arrStr = data.split(",");
var infoFormat = "";
for (var i = 0; i < arrStr.length; i++) {
if (arrStr[i].contains("ProjectName"))
{
arrStr[i] = removeCharsFromProject(arrStr[i]);
infoFormat = infoFormat + "\n" + "*Nombre del Proyecto:* " + arrStr[i];
}
}
arrStr = [];
bot.reply(message,
{
'text': infoFormat
});
});
}).end();
};
get();
});
});
////////// Obtener Usuarios
controller.hears('obtener usuarios', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
controller.storage.users.get(message.user, function (err, user) {
var http = require('http');
var extServerOptionsUsers = {
host: 'xxx.azurewebsites.net',
path: '/GDP2WSREST.svc/GetAllUsers/?tokken=' + tokken,
method: 'GET'
};
String.prototype.contains = function(str, ignoreCase) {
return (ignoreCase ? this.toUpperCase() : this)
.indexOf(ignoreCase ? str.toUpperCase() : str) >= 0;
};
function get() {
http.request(extServerOptionsUsers, function (res) {
res.setEncoding('utf8');
res.on('data', function (data) {
var arrStr = data.split(",");
var infoFormat = "";
for (var i = 0; i < arrStr.length; i++) {
if (arrStr[i].contains("UserName"))
{
arrStr[i] = removeCharsFromJSON(arrStr[i]);
infoFormat = infoFormat + "\n" + "*Usuario:* " + arrStr[i];
}
}
arrStr = [];
bot.reply(message,
{
'text': infoFormat
});
});
}).end();
};
get();
});
});
////////// Obtener un Usuario específico
controller.hears('obtener usuario (.*)', ['direct_message', 'direct_mention', 'mention'], function (bot, message) {
controller.storage.users.get(message.user, function (err, user) {
var user = message.match[1];
var http = require('http');
var extServerOptionsUsers = {
host: 'xxx.azurewebsites.net',
path: '/GDP2WSREST.svc/GetAllUsers/?tokken=' + tokken,
method: 'GET'
};
String.prototype.contains = function(str, ignoreCase) {
return (ignoreCase ? this.toUpperCase() : this)
.indexOf(ignoreCase ? str.toUpperCase() : str) >= 0;
};
function get() {
http.request(extServerOptionsUsers, function (res) {
res.setEncoding('utf8');
res.on('data', function (data) {
var arrStr = data.split(",");
var infoFormat = "";
var userData = "";
var finalMsg = "";
for (var i = 0; i < arrStr.length; i++) {
if (arrStr[i].contains("Active"))
{
arrStr[i] = removeCharsFromJSON(arrStr[i]);
userData = userData + "\n" + "*Active:* " + arrStr[i];
i = i++;
}
if (arrStr[i].contains("LastName"))
{
arrStr[i] = removeCharsFromJSON(arrStr[i]);
userData = userData + "\n" + "*LastName:* " + arrStr[i];
i = i++;
}
if (arrStr[i].contains("UserName"))
{
arrStr[i] = removeCharsFromJSON(arrStr[i]);
infoFormat = userData + "\n" + "*Usuario:* " + arrStr[i];
if (arrStr[i] == user) {
i = arrStr.length;
finalMsg = infoFormat;
break;
} else {
userData = "";
infoFormat = "";
}
}
}
arrStr = [];
bot.reply(message,
{
'text': finalMsg
});
});
}).end();
};
get();
});
});
|
var utils = require('./utils')
var webpack = require('webpack')
var config = require('../config')
var merge = require('webpack-merge')
var baseWebpackConfig = require('./webpack.base.conf')
var HtmlWebpackPlugin = require('html-webpack-plugin')
var FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
// add hot-reload related code to entry chunks
Object.keys(baseWebpackConfig.entry).forEach(function (name) {
baseWebpackConfig.entry[name] = ['./build/dev-client'].concat(baseWebpackConfig.entry[name])
})
module.exports = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap })
},
// cheap-module-eval-source-map is faster for development#cheap-module-source-map
devtool: '#cheap-module-eval-source-map',
plugins: [
new webpack.DefinePlugin({
'process.env': config.dev.env
}),
// https://github.com/glenjamin/webpack-hot-middleware#installation--usage
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
new FriendlyErrorsPlugin()
]
})
|
/**
* Created by USER: tarso.
* On DATE: 17/08/16.
* By NAME: http06.js.
*
* Objective : Test of error management
*/
const path = require('path')
const express = require('express');
const exphbs = require('express-handlebars')
const app = express();
const nPort = 3333;
/**
* THE HANDLEBARS
*/
app.engine('.hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs',
layoutsDir: path.join(__dirname, 'views/layouts')
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, 'views'));
/**
* THE MIDDLEWARES
*/
app.use(function (request, response, next) {
console.log("======>>> Middleware for sample - START <<<======");
console.log("*** URL requested ***\n", request.url);
console.log("*** Request Headers ***\n", request.headers);
console.log("*** Request Body ***\n", request.body);
console.log("======>>> Middleware for sample - END <<<======");
next();
});
/**
* THE ROUTES
*/
app.get('/', function (request, response) {
console.log('Root location');
response.render('home', {
name: 'Root page...'
});
});
/**
* THE ERROR HANDLER
*
* The error handler function should be the last function added with app.use.
* The error handler has a next callback - it can be used to chain multiple error handlers.
*/
app.use(function (err, request, response, next) {
// log the error, for now just console.log
console.log(err);
response.status(500).send('Something broke!');
});
/**
* THE MAIN LISTEN FUNCTION
*
*/
app.listen(nPort, function (err) {
if (err) {
return console.log('something bad happened', err);
}
console.log(`server is listening on ${nPort}`);
});
|
'use strict';
/**
* Trustroots
*
* App's main entry file
*/
var app = require('./config/lib/app');
app.start();
|
import React from 'react'
class Tab extends React.Component {
static propTypes = {
label: React.PropTypes.string,
active: React.PropTypes.bool,
onChangeTab: React.PropTypes.func
}
static defaultProps = {
active: false
}
render() {
const { label, index, active } = this.props
const classes = active ? 'item active' : 'item'
return (
<div className={classes} onClick={this._handleChangeTab.bind(this, index)}>
{label}
</div>
)
}
_handleChangeTab(index) {
this.props.onChangeTab(index)
}
}
export default Tab
|
/**
* @class gx.zeyos.Factory
* @description Use to easily create ZeyOS html elements.
*
* @extends gx.ui.Container
*/
gx.zeyos.Factory = {
gx: 'gx.zeyos.Factory',
/**
* icons: {
* 'list'
* 'plus'
* 'clock'
* 'range'
* 'reload'
* 'clear'
* 'settings'
* 'eye'
* 'trash'
* 'fields'
* 'search'
* 'lock'
* 'checked'
* }
*
* @method Icon
* @description Get icon sign from icon name. Used for buttons.
* @param {string} ico Icon name.
*/
Icon: function(ico) {
if ( ico == 'list' )
ico = 'l';
else if ( ico == 'plus' )
ico = '⊕';
else if ( ico == 'clock' )
ico = '⌚';
else if ( ico == 'range' )
ico = 's';
else if ( ico == 'reload' )
ico = '⟲';
else if ( ico == 'clear' )
ico = 'd';
else if ( ico == 'settings' )
ico = 'e';
else if ( ico == 'eye' )
ico = 'E';
else if ( ico == 'trash' )
ico = 'T';
else if ( ico == 'fields' )
ico = 'g';
else if ( ico == 'search' )
ico = 'z';
else if ( ico == 'lock' )
ico = 'L';
else if ( ico == 'checked' )
ico = '✔';
else if ( ico == 'question' )
ico = '?';
else
alert('unsupported icon');
return ico;
},
/**
* types: {
* '' = gray
* 'em' = gray
* 'grey' = gray
* 'gray' = gray
*
* 'dark' = dark
* }
*
* ico @see gx.zeyos.Factory.Icon()
*
* @method Button
* @description Return button element.
* @param {string} ico Icon name.
*/
Button: function(text, type, ico, options) {
if ( options == undefined )
options = {};
if ( type == null )
type = '';
else if ( type == 'dark' )
type = 'em';
else if ( type == 'gray' || type == 'grey' )
type = '';
if ( ico != undefined )
ico = gx.zeyos.Factory.Icon(ico);
else
ico = '';
var button = new Element('button', Object.merge({
'type': 'button',
'value': text,
'class': type,
'html': text
}, options));
if ( text == null || text == '' )
button.set('data-ico', ico);
else
button.set('data-ico-a', ico);
return button;
},
/**
* @method ButtonsGroup
* @description Create group of buttons
* @param {array} buttons Array of buttons to group.
*/
ButtonsGroup: function(buttons) {
return new Element('div', {
'class': 'grp'
}).adopt(buttons);
},
/**
* @method Panel
* @description Create simple toggle panel
* @param {html element} display Html element to adopt the panel.
* @param {string|html element} title Title of the panel.
* @param {string|html element} content Content of the panel.
* @param {boolean} open Open panel after creation.
*/
Panel: new Class({
Extends: gx.ui.Container,
initialize: function(display, title, content, open) {
var root = this;
this._title = new Element('h1').addEvent('click', function(){
root.toggle();
});
this._content = new Element('div', {
'class': 'b-25 bg-W d-b'
});
this._section = new Element('section', {
'class': 'bg-E br_b-5 bsd-3 p-7'
});
this.parent(display);
this.toElement().set({'class': 'm_l-10 m_r-10 m_t-10'}).adopt([
this._title,
this._section.adopt([
this._content
])
]);
if ( title != null )
this.setTitle(title);
if ( content != null )
this.setContent(content);
if ( open == undefined || open != false )
this.open();
},
setTitle: function(title) {
if ( isString(title) ) {
this._title.set('html', title);
} else {
this._title.empty();
this._title.adopt(title);
}
},
setContent: function(content) {
if ( isString(content) ) {
this._content.set('html', content);
} else {
this._content.empty();
this._content.adopt(content);
}
},
open: function() {
this._title.addClass('act');
this._section.show();
},
close: function() {
this._title.removeClass('act');
this._section.hide();
},
toggle: function() {
if ( this._title.hasClass('act') )
this.close();
else
this.open();
}
})
};
|
import Model from '../model';
import ValidateMixin from '../mixins/validate';
import MessageView from './message';
import FormView from './form-styling';
import app from '../ridge';
import View from '../view';
const LoginFormView = View.extend();
const LoginFormModel = Model.extend();
_.extend(LoginFormModel.prototype, ValidateMixin, {
urlRoot: '/auth/local',
validation: {
email: {
email: true,
required: true,
},
password: {
required: true,
},
},
});
_.extend(LoginFormView.prototype, require('../mixins/observe'), {
template: 'partials/login-form',
events: {
'click a.external': 'externalLogin',
'click .close': 'close',
'submit form': 'save',
},
subviews: {
form: ['form', FormView],
},
elements: {
button: 'button',
form: 'form',
},
initialize(opts) {
if (opts && opts.removeOnLogin) {
this.listenTo(app, 'login', this.remove);
}
this.model = opts && opts.model || new Model();
this.bindings = _.mapValues(this.model.validation, (value, key) => {
const binding = {};
binding[`[name="${key}"],[data-name="${key}"]`] = {
both: 'value',
};
return binding;
});
},
error(model, xhr) {
if (this.message) {
this.message.leave({ animateHeight: true });
}
const resp = xhr.responseJSON;
this.message = new MessageView({
message: {
type: 'error',
heading: resp.statusText,
body: resp.message,
},
}).enter(this.elements.form, { method: 'prepend', animateHeight: true });
},
save(e) {
e.preventDefault();
if (this.model.isValid()) {
$(document.body).addClass('progress');
this.elements.button.prop('disabled', true);
this.model.save(null, {
error: this.error,
success: this.success,
complete: this.complete,
context: this,
validate: false,
});
}
},
complete() {
this.elements.button.prop('disabled', false);
$(document.body).removeClass('progress');
},
success(model, resp, options) {
model.reset({ silent: true });
app.login(resp, options.xhr.getResponseHeader('location'));
},
attach() {
this.observe({ validate: true });
},
externalLogin(e) {
e.preventDefault();
const _view = this;
const newWindow = window.open(`${$(e.currentTarget).attr('href')}?loginWindow=true`, 'name', 'height=600,width=450');
if (window.focus) {
newWindow.focus();
}
this.listenToOnce(window.broadcast, 'authenticate', (err, user, newUser, redirect) => {
if (err) {
if (_view.message) {
_view.message.leave({ animateHeight: true });
}
_view.message = new app.views.Message({
animateHeight: true,
message: {
type: 'error',
heading: err.statusText,
body: err.message,
},
}).enter(e.currentTarget, 'before', true);
} else {
app.login(user, redirect);
}
});
},
});
export default LoginFormView;
|
var naan = require('naan');
var async = require('async');
var request = require('request');
var _ = require('underscore');
var assert = require('assert');
var util = require('util');
var Core = require('seraph-core');
// Bind all functions of an object to a context (recursively)
var bindAllTo = function(context, all) {
return Object.keys(all).reduce(function(bound, key) {
if (typeof all[key] == 'object') bound[key] = bindAllTo(context, all[key]);
else if (typeof all[key] == 'function') bound[key] = all[key].bind(context);
else bound[key] = all[key];
return bound;
}, {});
}
// Polyfill Object.setPrototypeOf for older node versions.
var setPrototypeOf = Object.setPrototypeOf || function setPrototypeOfPolyfill(obj, proto) { obj.__proto__ = proto; };
function Seraph(options) {
if (options.bolt) return require('./bolt/seraph')(options);
var core = new Core(options);
setPrototypeOf(Object.getPrototypeOf(this), core);
this.options = core.options;
_.bindAll.apply(_, [this].concat(_.functions(this)));
this.node = bindAllTo(this, require('./node'));
this.relationship = this.rel = bindAllTo(this, require('./relationship'));
this.index = bindAllTo(this, require('./index'));
this.constraints = bindAllTo(this, require('./constraints'));
var legacyindexGeneric = bindAllTo(this, require('./legacyindex'));
// Alias & curry seraph.index on seraph.node & seraph.rel
this.node.legacyindex = naan.curry(legacyindexGeneric.add, 'node');
this.rel.legacyindex = naan.curry(legacyindexGeneric.add, 'relationship');
naan.ecrock(this.node.legacyindex, legacyindexGeneric, naan.curry, 'node');
naan.ecrock(this.rel.legacyindex, legacyindexGeneric, naan.curry, 'relationship');
_.extend(this, this.node);
}
// returns a new batch if the context was not already that of a batch - prevents
// batch nesting which can break intra-batch referencing
Seraph.prototype._safeBatch = function() {
return this.isBatch ? this : this.batch();
};
// similarly, this takes a BatchSeraph and only commits it if the calling context
// is not that of a batch.
Seraph.prototype._safeBatchCommit = function(txn, callback) {
if (this.isBatch) {
if (callback) this.commitCallbacks.push(callback);
} else {
txn.commit(callback);
}
};
/**
* If `obj` is an object, return the value of key <options.id>. Otherwise,
* return `obj`.
*
* If `requireData` is truthy, `obj` must be an object, otherwise undefined is
* returned.
*/
Seraph.prototype._getId = function(obj, requireData) {
var id;
if (requireData) {
id = typeof obj == 'object' ? obj[this.options.id] : undefined;
} else if (this._isBatchId(obj)) {
return obj;
} else {
id = typeof obj == 'object' ? obj[this.options.id] : obj;
}
if (id != null) id = parseInt(id, 10);
return id;
};
Seraph.prototype._isValidId = function(id) {
return !isNaN(parseInt(id, 10)) || this._isBatchId(id);
};
/**
* Take the end off a url and parse it as an int
*/
Seraph.prototype._extractId = function(location) {
var matches = location.match(/\/(\d+)$/);
if (!matches) {
return null;
}
return parseInt(matches[1], 10);
};
/**
* Infer whether or not the given object is a node
*/
Seraph.nodeFlags = [
'outgoing_relationships',
'incoming_relationships',
'all_relationships',
'data',
'properties',
'self'
];
Seraph.prototype._isNode = function(node) {
if (!node || typeof node !== 'object') {
return false;
}
var inNode = node.hasOwnProperty.bind(node);
return Seraph.nodeFlags.every(inNode) &&
typeof node.data === 'object';
};
/**
* Infer whether or not the given object is a relationship
*/
Seraph.relationshipFlags = [
'start',
'data',
'self',
'properties',
'end'
];
Seraph.prototype._isRelationship = function(rel) {
if (!rel || typeof rel !== 'object') {
return false;
}
var inRelationship = rel.hasOwnProperty.bind(rel);
return Seraph.relationshipFlags.every(inRelationship) &&
typeof rel.data === 'object';
};
Seraph.prototype._isBatchId = function(id) {
return this.isBatch && typeof id == 'string' && id.match(/^{\d+}$/);
};
Seraph.prototype._nodeRoot = function(id) {
return this._isBatchId(id) ? id : 'node/' + id;
};
Seraph.prototype._relRoot = function(id) {
return this._isBatchId(id) ? id : 'relationship/' + id;
};
/**
* Returns the url to an entity given an id
*/
Seraph.prototype._location = function(type, id) {
if (this._isBatchId(id)) return id;
return util.format('%s%s/%s/%d',
this.options.server, this.options.endpoint, type, id);
};
/**
* Create a relationship object from the given relationship data returned from
* the neo4j server
*/
Seraph.prototype._createRelationshipObject = function(relationshipData) {
var relationshipObj = {
start: this._extractId(relationshipData.start),
end: this._extractId(relationshipData.end),
type: relationshipData.type,
properties: relationshipData.data
};
relationshipObj[this.options.id] = this._extractId(relationshipData.self);
return relationshipObj;
};
/**
* Create a node object from the given node data return from the neo4j server
*/
Seraph.prototype._createNodeObject = function(nodeData) {
var nodeObj = nodeData.data || {};
nodeObj[this.options.id] = this._extractId(nodeData.self);
return nodeObj;
};
/**
* Perform a cypher query. Maps to POST cypher
*/
Seraph.prototype.queryRaw = function(query, params, callback) {
if (typeof query !== 'string') {
return callback(new Error('Invalid Query'));
}
if (typeof params !== 'object') {
if (typeof params === 'function') {
callback = params;
}
params = {};
}
query = { statements: [ {
statement: query,
parameters: params,
resultDataContents: ['REST']
} ] } ;
var op = this.operation('transaction/commit', query);
this.call(op, function(err, result) {
if (err || result.errors[0]) {
callback(err || result.errors[0]);
} else {
result = result.results[0];
result.data = result.data.map(function(row) { return row.rest });
callback(null, result);
}
});
};
Seraph.prototype._parseQueryResult = function(result) {
var self = this;
var namedResults = result.data.map(function(row) {
return result.columns.reduce(function(rowObj, columnName, columnIndex) {
var resultItem = row[columnIndex];
function extractAttributes(item) {
if (self._isNode(item)) {
return self._createNodeObject(item);
} else if (self._isRelationship(item)) {
return self._createRelationshipObject(item);
} else if (Array.isArray(item)) {
return item.map(extractAttributes);
} else if (item === Object(item)) {
return _.mapObject(item, extractAttributes);
} else {
return item;
}
}
rowObj[columnName] = extractAttributes(resultItem);
return rowObj;
}, {});
});
if (namedResults.length > 0) {
var resultsAreObjects = typeof namedResults[0][result.columns[0]] == 'object';
if (result.columns.length === 1 && resultsAreObjects) {
namedResults = namedResults.map(function(namedResult) {
return namedResult[result.columns[0]];
});
}
}
return namedResults;
}
/**
* Perform a cypher query and map the columns and results together.
*/
Seraph.prototype.query = function(query, params, callback) {
if (typeof params !== 'object') {
if (typeof params === 'function') {
callback = params;
}
params = {};
}
var self = this;
this.queryRaw(query, params, function(err, result) {
if (err) {
return callback(err);
}
callback(null, self._parseQueryResult(result));
});
};
var globalCounter = 0;
function wrapForBatchFormat(id) { return '{' + id + '}' };
function BatchSeraphId(id, refersTo, batch) {
if (Array.isArray(refersTo)) {
refersTo = refersTo.map(wrapForBatchFormat);
refersTo.forEach(function(id, index) {
this[index] = id;
}.bind(this));
} else {
refersTo = wrapForBatchFormat(refersTo);
}
this.id = id;
this.refersTo = refersTo;
this.batch = batch;
}
Object.defineProperty(BatchSeraphId.prototype, 'valueOf', {
enumerable: false, configurable: false, writable: false,
value: function() { return this.id }
});
Object.defineProperty(BatchSeraphId.prototype, 'toString', {
enumerable: false, configurable: false, writable: false,
value: function() { return this.id }
});
function BatchSeraph(parentSeraph) {
var self = this;
var uniq = Date.now() + ++globalCounter;
function isBatchId(id) {
return id instanceof BatchSeraphId && id.batch == uniq;
};
function createId(id, refersTo) {
return new BatchSeraphId(id, refersTo, uniq);
};
function transformBatchArgs(args) {
return args.map(function(arg) {
if (Array.isArray(arg)) return transformBatchArgs(arg);
return isBatchId(arg) ? arg.refersTo : arg;
});
};
function wrapFunctions(parent, target) {
var derived = target || {};
// parent could be undefined or null, so skip walking such
parent && Object.keys(parent).forEach(function(key) {
if (key == 'agent') return;
var valueType = typeof parent[key];
if (valueType === 'function') {
derived[key] = wrapFunction(parent[key]);
if (Object.keys(parent[key]).length > 0) {
derived[key] = wrapFunctions(parent[key], derived[key]);
}
} else if (valueType === 'object') {
derived[key] = wrapFunctions(parent[key]);
} else {
derived[key] = parent[key];
}
});
return derived;
}
function wrapFunction(fn) {
fn = naan.rcurry(fn, function(err, result) {
if (err && !self.error) self.error = err;
self.results.push(result);
var cb = self.callbacks.shift();
if (cb) cb(err, result);
});
return function() {
self.operationQueueStack.unshift([]);
var args = [].slice.apply(arguments);
if (args.length > 1 && typeof args[args.length - 1] == 'function') {
self.callbacks.push(args.pop());
} else {
self.callbacks.push(null);
}
args = transformBatchArgs(args);
// Context does not matter because all functions are bound upon seraph init
fn.apply(undefined, args);
var operationIds = _.pluck(self.operationQueueStack[0], 'id');
self.operationQueueStack.shift();
var operationId = operationIds.length
? operationIds[0] - self.operationOffset : undefined;
if (operationIds.length > 1) {
self.operationOffset += operationIds.length - 1;
operationId = createId(operationId, operationIds);
} else if (operationId != null) {
operationId = createId(operationId, operationIds[0]);
}
return operationId;
};
}
this.super = new Seraph(parentSeraph.options);
this.__proto__ = wrapFunctions(this.super);
this.isBatch = this.super.isBatch = true;
this.batch = undefined; // disabled nesting.
this.processors = [];
this.operations = [];
this.callbacks = [];
this.results = [];
this.operationOffset = 0;
this.operationQueueStack = [];
this.commitCallbacks = [];
this.super.call = function(operation, processor) {
operation.id = self.operations.length;
if (!operation.body) delete operation.body;
self.operations.push(operation);
self.processors.push(processor.bind(self.super));
self.operationQueueStack[0].push(operation);
};
function handleSelfError(error) {
self.commitCallbacks.forEach(function(callback) {
callback(error);
});
}
this.commit = function(callback) {
if (callback) self.commitCallbacks.push(callback);
if (self.error) return handleSelfError(self.error)
var op = parentSeraph.operation('batch', 'POST', self.operations);
parentSeraph.call(op, function(err, results) {
if (err) {
while (self.callbacks.length) {
var cb = self.callbacks.shift();
if (cb) cb(err);
}
return self.commitCallbacks.forEach(function(callback) {
callback(err);
});
}
results.forEach(function(result) {
self.processors.shift()(null, result.body || {}, result.location);
});
if (self.error) return handleSelfError(self.error)
self.commitCallbacks.forEach(function(callback) {
callback(null, self.results);
});
});
};
}
Seraph.prototype.isBatch = false;
Seraph.prototype.batch = function(operations, callback) {
if (!arguments.length) return new BatchSeraph(this);
var batchSeraph = new BatchSeraph(this);
operations(batchSeraph);
batchSeraph.commit(callback);
};
module.exports = function(options) {
if (options && options.thunkify) {
delete options.thunkify;
return require('../co')(options);
}
return new Seraph(options);
};
|
/*
Simple OpenID Plugin
http://code.google.com/p/openid-selector/
This code is licenced under the New BSD License.
*/
var providers_large = {
bishops: {
id: 'bishops',
file: 'bishops.gif',
name: "The Bishop's School Student Email",
url: 'https://www.google.com/accounts/o8/id',
}/*,
bishops: {
id: 'bishops',
file: 'bishops.gif',
name: "The Bishop's School Student Email",
url: 'https://google.com/accounts/o8/site-xrds?hd=bishopsstudent.org',
},
google: {
id: 'google',
file: 'google.gif',
name: 'Google',
url: 'https://www.google.com/accounts/o8/id',
},
yahoo: {
id: 'yahoo',
name: 'Yahoo',
url: 'http://yahoo.com/',
file: 'yahoo.gif'
},
myopenid: {
id: 'myopenid',
name: 'MyOpenID',
label: 'Enter your MyOpenID username',
url: 'http://{username}.myopenid.com/',
file: 'myopenid.png'
},
aol: {
id: 'aol',
name: 'AOL',
label: 'Enter your AOL screenname',
url: 'http://openid.aol.com/{username}',
file: 'aol.gif'
}*/
};
var providers_small = {
// livejournal: {
// name: 'LiveJournal',
// label: 'Enter your Livejournal username',
// url: 'http://{username}.livejournal.com/',
// file: 'livejournal.ico'
// },
/*wordpress: {
id: 'wordpress',
name: 'Wordpress',
label: 'Enter your Wordpress.com username',
url: 'http://{username}.wordpress.com/',
file: 'wordpress.ico'
},
blogger: {
id: 'blogger',
name: 'Blogger',
label: 'Enter your Blogger account',
url: 'http://{username}.blogspot.com/',
file: 'blogger.ico'
},
verisign: {
id: 'verisign',
name: 'Verisign',
label: 'Enter your Verisign username',
url: 'http://{username}.pip.verisignlabs.com/',
file: 'verisign.ico'
},
flickr: {
id: 'flickr',
name: 'Flickr',
label: 'Enter your Flickr username.',
url: 'http://flickr.com/{username}/',
file: 'flickr.ico'
},
claimid: {
id: 'claimid',
name: 'ClaimID',
label: 'Enter your ClaimID username',
url: 'http://openid.claimid.com/{username}',
file: 'claimid.ico'
},
google_profile: {
id: 'google_profile',
name: 'Google Profile',
label: 'Enter your Google Profile username',
url: 'http://www.google.com/profiles/{username}',
file: 'google_profile.png'
}*/
};
var providers = $.extend({}, providers_large, providers_small);
var openid = {
cookie_expires: 6 * 30, // 6 months.
cookie_name: 'openid_provider',
cookie_path: '/',
img_path: '/static/openid/',
input_id: null,
provider_url: null,
init: function (input_id) {
// turn off hourglass
$('body').css('cursor', 'default');
$('#openid_submit').css('cursor', 'default');
// enable submit button on form
$('input[type=submit]').removeAttr('disabled');
var openid_btns = $('#openid_btns');
this.input_id = input_id;
$('#openid_choice').show();
$('#openid_input_area').empty();
// add box for each provider
for (id in providers_large) {
openid_btns.append(this.getBoxHTML(providers_large[id], 'large'));
}
if (providers_small) {
openid_btns.append('<br>');
for (id in providers_small) {
openid_btns.append(this.getBoxHTML(providers_small[id], 'small', '.png'));
}
}
$('#openid_form').submit(this.submitx);
},
getBoxHTML: function (provider, box_size) {
var file = provider["file"];
var box_id = provider.id;
return '<a title="' + provider["name"] + '" href="javascript:openid.signin(\'' + box_id + '\');"' +
' style="background: #FFF url(' + this.img_path + file + ') no-repeat center center" ' +
'class="' + box_id + ' openid_' + box_size + '_btn"></a>';
},
/* provider image click */
signin: function (box_id, onload) {
var provider = providers[box_id];
if (!provider) { return; }
this.highlight(box_id);
if (box_id == 'openid') {
$('#openid_input_area').empty();
this.setOpenIdUrl("");
$("#openid_identifier").focus();
return;
}
// prompt user for input?
if (provider['label']) {
this.useInputBox(provider);
this.provider_url = provider['url'];
} else {
$('.' + box_id).css('cursor', 'wait');
this.setOpenIdUrl(provider['url']);
this.provider_url = null;
if (!onload) {
$('#openid_form').submit();
}
}
},
/* Sign-in button click */
submitx: function () {
if ($('#openid_username').val() == "") return true;
// set up hourglass on body
$('body').css('cursor', 'wait');
$('#openid_submit').css('cursor', 'wait');
// disable submit button on form
$('input[type=submit]', this).attr('disabled', 'disabled');
var url = openid.provider_url;
if (url) {
url = url.replace('{username}', $('#openid_username').val());
openid.setOpenIdUrl(url);
}
return true;
},
setOpenIdUrl: function (url) {
var hidden = $('#' + this.input_id);
hidden.val(url);
},
highlight: function (box_id) {
// remove previous highlight.
var highlight = $('#openid_highlight');
if (highlight) {
highlight.replaceWith($('#openid_highlight a')[0]);
}
// add new highlight.
$('.' + box_id).wrap('<div id="openid_highlight"></div>');
},
useInputBox: function (provider) {
var input_area = $('#openid_input_area');
var html = '';
var id = 'openid_username';
var value = '';
var label = provider['label'];
var style = '';
if (label) {
html = '<p>' + label + '</p>';
}
html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />' +
'<input id="openid_submit" type="submit" value="Sign In"/>';
input_area.empty();
input_area.append(html);
$('#' + id).focus();
}
};
|
import Handler from './handler.js';
import exportObj from '../../utils/utils.js';
let proRequest = exportObj.proRequest;
let handler = new Handler();
// es6 format
let log4js = require('log4js');
let writeFile = require('../../utils/ioUtils.js').writeFile;
// let defaultConfig = require('../../conf/default.js');
import defaultConfig from '../../conf/default.js';
let options = require('../../data/headers/options.js');
let options_get = options.options_get;
let Queue = require('./message.js');
let queue = new Queue();
// get all urls from one webpage
let getURL = require('../Images/getURL.js').getURL;
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
class Scrapyer {
constructor(options) {
//default configuration
Object.assign(this, defaultConfig);
this.queue = queue;
// options used for initial Scrapyer
if (typeof options === 'object') {
Object.assign(this, options);
this.options = options;
// All url must be into queue!
if (options.url) {
this.queue.push(options.url);
}
} else if (typeof options === 'string') {
let name = options;
this.name = name;
}
/* else {
throw new Error('options must be object or string');
}*/
this.logger = log4js.getLogger(this.name); //logger
this.logger.setLevel(this.loggerLevel);
// handler success from scrapyer
handler.setRecurrent(this.recurrent);
}
start(callback) {
let that = this;
// check if it can start first
if (that.url === undefined) {
that.looger.fatal('can not scrapy due to no url');
throw new Error('url is undefined,please set url fisrt');
}
if (that.selector === undefined) {
that.looger.fatal('can not scrapy due to no selector');
throw new Error('selector is undeined,please set it first');
}
// log all configuration
that.inform();
// master process to deal with queue
this.masterProcess(that);
// slave process to deal with preurl
this.slaveProcess(that, this.urlSelector, callback);
}
// set functions
seturl(url) {
// check url format
this.url = url;
if (this.options) {
this.options.url = url;
}
this.queue.push(url);
}
setNotText() {
this.isText = 0;
// set handler isText
handler.setIsText(0);
}
setUrlSelector(urlSelector) {
this.urlSelector = urlSelector;
}
setSelector(selector) {
// check ....
this.selector = selector;
// at the same time set handler selector
handler.setSelector(selector);
}
setIsDownloadPage(flag) {
this.isDownloadPage = flag;
}
setRecurrent(flag) {
this.recurrent = flag;
handler.setRecurrent(this.recurrent);
}
setDownloadPagePath(path) {
this.downloadPagePath = path;
}
setLoggerLevel(level) {
this.loggerLevel = level;
this.logger.setLevel(level);
}
// set chraset such as UTF-8 or GBK or ACSII
setChraset(chraset) {
this.chraset = chraset;
}
/*var http = require('http');
http.createServer(function)*/
initial() {
if (this.HEAD) {
if (this.options === undefined) {
this.options = options_get;
} else {
Object.assign(this.options, options_get);
}
}
}
//download webpage into /data/html/
_downloadPage(filename, page) {
if (this.isDownloadPage) {
writeFile(this.downloadPagePath + filename + '.html', page)
.then(function() {
this.logger.info('download webpage success');
})
.catch(function(err) {
throw err;
});
}
}
// display all configurations
inform() {
if (!cluster.isMaster) {
return;
}
this.logger.info('set isText: ' + this.isText);
this.logger.info('set url: ' + this.url);
this.logger.info('set it download page: ' + this.isDownloadPage);
this.logger.info('set recurrent: ' + this.recurrent);
this.logger.info('set it logger level: ' + this.loggerLevel);
this.logger.info('set it downloadPage path: ' + this.downloadPagePath);
if (typeof this.selector === 'string') {
this.logger.info('set selector: ' + this.selector);
} else {
let tmp = '';
this.selector.forEach(function(one) {
tmp += one;
tmp += '\n';
});
this.logger.info('set selector: ' + tmp);
}
// start
this.logger.trace('scrapyer start working');
}
// _enableRecurrent(url, urlSelector) {
// /*this.logger.info('The number of urls is ' + this.queue.getLength());*/
// if (!this.recurrent) {
// return;
// }
// if (urlSelector === undefined) {
// this.logger.fatal('urlSelector is undefined');
// throw new Error('urlSelector is undefined');
// return;
// }
// // let tmp = this.options||this.url;
// let tmp = url;
// // get urls from webpage
// getURL(tmp, urlSelector)
// .then(function(urls) {
// if (urls.length === 0) {
// this.logger.warn('No urls for uesing');
// return;
// }
// // console.log(urls.length);
// this.queue.pushAllFilter(urls);
// })
// .catch(function(err) {
// this.fatal(err);
// });
// }
slaveProcess(that, urlSelector, callback) {
// it is better to use 'this' not 'that',but sth wrong with it
let geturlWorker = cluster.worker;
if (cluster.isWorker) {
process.on('message', function(url) {
that.logger.info('slaveProcess(' + geturlWorker.id + ') get url from masterProcess');
if (url === undefined) {
that.logger.warn('url from masterProcess is undefined,please check urls in queue');
return;
}
let tmp = that.options || that.url;
if (typeof tmp === 'object') {
tmp.url = url;
} else {
tmp = url;
}
proRequest(tmp)
.then(function(retobj) {
let page = retobj[0];
let requrl = retobj[1];
/* handler(page, that.selector, requrl, that.isText, that.recurrent);*/
handler.handle(page, requrl);
// plugins functions
that._downloadPage(that.filename, page);
if (callback) {
callback(null, page);
}
})
.catch(function(err) {
if (callback) {
callback(err, null);
}
});
if (!that.recurrent) {
return;
}
that.logger.debug('recurrent');
// just url at present
that.logger.debug(urlSelector);
getURL(tmp, urlSelector)
.then(function(urls) {
if (urls.length === 0 || urls === undefined) {
that.logger.warn('urls is undefined or empty,please change urlSelector');
}
that.logger.debug('urls in slave process: ' + urls.length);
// console.log(urls[0]);
process.send(urls);
})
.catch(function(err) {
// send error to master process
process.send('error');
that.logger.fatal(err);
});
});
}
}
masterProcess(that) {
// master process
if (cluster.isMaster) {
// if not empty fork a slave process
if (!that.queue.isEmpty()) {
let worker = cluster.fork();
let front = queue.pop();
worker.send(front);
}
// listen to slaveProcess
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message', function(msg) {
that.logger.info('one epoch start, ' + that.queue.getLength() + ' urls left');
// if msg is not error ,receive all url into queue
if (msg === 'error') {
that.logger.warn('url in slave process is not useful');
} else {
that.queue.pushAllFilter(msg);
}
// if empty ,process exit
if (that.queue.isEmpty()) {
that.logger.info('no url for using');
// cluster.workers[id].send('empty');
// process.exit();
return;
}
// send url to slave process
let preurl = that.queue.pop();
cluster.workers[id].send(preurl);
});
});
}
}
}
export default Scrapyer;
|
/*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('.page-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
$(function() {
$('.postpage-scroll a').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top - 80
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
// Floating label headings for the contact form
$(function() {
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top'
})
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
|
const path = require("path");
module.exports = {
includePaths: [
path.join(__dirname, "core")
]
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {
const { Provider } = ReactRedux;
// redux_store will be available to acceptDialog
// and message event listener by closure
const redux_store = window.__configure_redux_store__();
const sendMessageToParent = (msg, origin) => {
// parent and window are same thing if the current page is not in any frame
if (window !== parent) {
parent.postMessage(msg, origin);
}
};
window.addEventListener("message", e => {
// extentions and other 3rd party scripts talk via postMeessage api(same orgin)
// so it is very important to filter those events
if (e.origin !== window.location.origin || !e.data || e.data.source !== "dialog-message") {
return;
}
sendMessageToParent(
{ messageRecieved: true, source: "dialog-message" },
`${window.location.origin}/iframe-testing-ground`
);
const state = Object.assign({}, e.data);
// updating state with data sent via message event
redux_store.dispatch(window.__global_actions__.updateItems(state));
});
ReactDOM.render(
<Provider store={redux_store}>
<CalendarAlarmDialog />
</Provider>,
document.getElementById("root")
);
})();
|
const Endpoint = cubic.nodes.core.Endpoint
class Foo extends Endpoint {
main (req, res) {
res.send('bar')
}
}
module.exports = Foo
|
export const stationsByFavouriteAndDistance = state =>
Object.values(state.stations.data)
.map(({ id, name, distance }) => ({
id,
name,
distance,
isFavouritePending:
state.favourites[id] && state.favourites[id].pending,
isFavourite:
state.favourites[id] && state.favourites[id].isFavourite,
}))
.sort((a, b) => parseInt(a.distance, 10) - parseInt(b.distance, 10))
.sort((a, b) => !!b.isFavourite - !!a.isFavourite);
|
var OnBeforeActions = {
requireLogin: function() {
if (!Meteor.user()) {
if (Meteor.loggingIn()) {
this.render(this.loadingTemplate);
} else {
this.render(this.loginTemplate);
}
} else {
this.next();
}
}
};
Router.onBeforeAction(OnBeforeActions.requireLogin, {
except: ['home']
});
Router.route('/', {
name: 'home',
waitOn: function() {
return [
Meteor.subscribe('usersTopTen')
];
},
data: function() {
return Meteor.users.find();
},
action: function() {
this.render('home');
SEO.set({
title: 'Home -' + Meteor.App.NAME
});
}
});
|
module.exports={A:{A:{"1":"E A B","132":"L H G jB"},B:{"1":"8 C D e K I N J"},C:{"1":"0 1 2 3 7 9 U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB","132":"4 5 gB BB F L H G E A B C D e K I N J P Q R S T aB ZB"},D:{"1":"0 1 2 3 4 5 7 8 9 F L H G E A B C D e K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z JB IB CB DB EB O GB HB TB PB NB mB OB LB QB RB"},E:{"1":"4 6 L H G E A B C D UB VB WB XB YB p bB","132":"F SB KB"},F:{"1":"0 1 2 3 5 6 7 B C K I N J P Q R S T U V W X Y Z a b c d f g h i j k l m n o M q r s t u v w x y z eB fB p AB hB","132":"E cB dB"},G:{"2":"KB iB FB","772":"G D kB lB MB nB oB pB qB rB sB tB uB vB"},H:{"2":"wB"},I:{"2":"BB F O xB yB zB 1B 2B","132":"0B FB"},J:{"260":"H A"},K:{"1":"6 B C M p AB","132":"A"},L:{"1":"LB"},M:{"1":"O"},N:{"1":"A B"},O:{"1":"3B"},P:{"2":"F","1028":"4B 5B 6B 7B 8B"},Q:{"1":"9B"},R:{"1028":"AC"},S:{"1":"BC"}},B:4,C:"CSS background-attachment"};
|
export const REQUEST_BY_QUERYSTRING = 'REQUEST_BY_QUERYSTRING';
export const RECEIVE_BY_QUERYSTRING = 'RECEIVE_BY_QUERYSTRING';
export const REQUEST_BY_ID = 'REQUEST_BY_ID';
export const RECEIVE_BY_ID = 'RECEIVE_BY_ID';
|
version https://git-lfs.github.com/spec/v1
oid sha256:ea7770cfb7bfcc3becd55cf601ddadb2ba89968c94409694d138e179704c7d0c
size 2115
|
var mongoose = require('mongoose');
var Categoria = mongoose.model('Categoria');
var Empresa = mongoose.model('Empresa');
var Sucursal = mongoose.model('Sucursal');
var Schema = mongoose.Schema;
var montoCategoriaSchema = new Schema({
creado: {
type: Date,
default: Date.now
},
categoria: {
type: Schema.ObjectId,
ref: 'Categoria',
required: true
},
empresa: {
type: Schema.ObjectId,
ref: 'Empresa',
required: true
},
sucursal: {
type: Schema.ObjectId,
ref: 'Sucursal',
required: true
},
montos: [{
destinadoA: {
type: String,
required: 'El campo destinado es obligatorio'
},
monto: {
type: Number,
required: 'El monto es obligatorio'
}
}],
montoMax: {
type: Number
}
});
montoCategoriaSchema.pre('save', function(next){
if(!this.montos){
this.montoMax = 0;
this.montos = [];
} else {
this.montoMax = 0;
for(var i in this.montos){
this.montoMax = Number(this.montos[i].monto) + Number(this.montoMax);
}
}
next();
})
mongoose.model('MontoCategoria', montoCategoriaSchema);
|
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
// get and fire up bear on port 8000
var bear = require('../lib/bear.js').create( 8000 );
var dexec = require( 'deferred-exec' );
var dfs = require( '../lib/deferred-fs.js' );
var site = JSON.parse('{"repo":"danheberden/payloads","git":"test/gits/original-copy/","deploy":"test/site/deploy/","live":"test/site/live/","liveBranch":"master","deployOnTag":"true"}');
// make a new site
var testSite = bear( site );
// sanity:
bear.verbose( false );
var siteVerifiers = {
live: function( test, deployedVersion, dontEndTest ) {
var folder = deployedVersion ? site.deploy + 'master/' : site.live;
var update1 = dfs.readFile( folder + 'master.txt', 'utf8' );
var update2 = update1.then( function( err, data ) {
test.equal( data, 'updated-master\n', 'master.txt should get updated' );
return dfs.readFile( folder + 'additional-master.txt', 'utf8' )
});
var update3 = update2.then( function( err, data ) {
test.equal( data, 'additional-master\n', 'additional-master.txt should get copied' );
}, function(){
console.log( 'failed', arguments );
}).always( function() {
if ( !dontEndTest ) {
test.done();
}
});
},
stage: function( test, folder ) {
var update1 = dfs.readFile( folder + 'master.txt', 'utf8' );
var update2 = update1.then( function( err, data ) {
test.equal( data, 'updated-master\n', 'master.txt should get updated' );
return dfs.readFile( folder + 'stage.txt', 'utf8' )
});
var update3 = update2.then( function( err, data ) {
test.equal( data, 'staging\n', 'stage.txt should get created' );
return dfs.readFile( folder + 'additional-master.txt', 'utf8' );
});
var update4 = update3.then( function( err, data ) {
test.equal( data, 'additional-master\n', 'additional-master.txt should get copied' );
}, function(){
console.log( 'failed', arguments );
}).always( function() {
test.done();
});
}
};
// failsafe
setTimeout( function() {
process.exit(127);
}, 10000 );
exports['bear update stage and master'] = {
setUp: function(done) {
// clean up our testing area
var commands = [
'rm -rf test/gits/original-copy',
'cp -r test/gits/original test/gits/original-copy',
'rm -rf test/site/deploy test/site/live',
'mkdir test/site/deploy test/site/live',
'git --git-dir="test/gits/original-copy/.git" remote add origin "$(pwd)/test/gits/origin/.git"'
];
dexec( commands.join( '; ' ) )
.then( function() {
done();
}, function() {
console.log( 'An error occurred setting up the test suite. Make sure the `gits` and `site` folders are present.', arguments );
process.exit(1);
});
},
tearDown: function(done) {
// clean up behind ourselvesj
dexec( 'rm -rf test/gits/original-copy; rm -rf test/site/live; rm -r test/site/deploy' )
.then( function() {
done();
}, function() {
console.log( 'An error occurred tearing down the test suite. ', arguments );
done();
});
},
'update master manually': function(test) {
test.expect( 2 );
// tests here
testSite.live().then( function(){
return siteVerifiers.live( test );
});
},
'update staging manually' : function(test) {
test.expect( 3 );
var folder = site.deploy + 'stage/';
testSite.stage( 'stage' ).then( function(){
return siteVerifiers.stage( test, folder );
});
},
'gith server created on default port': function(test) {
test.expect(1);
testSite.start().then( function( g ) {
test.ok( testSite.gith.port, 8000, "gith server should be running on port 8000" );
test.done();
});
},
'test payload - update master with tag' : function(test) {
test.expect(4);
var json = require( './payloads/update-master-tag.json' );
// verify the site once gith runs
testSite.attr( 'githCallback', function() {
siteVerifiers.live( test, false, true );
siteVerifiers.live( test, true );
});
// broadcast the payload
testSite.start().then( function( g ) {
testSite.gith.payload( json );
});
},
'test file loading of settings' : function( test ) {
test.expect(1);
var otherSite = bear( 'test/site.json' );
otherSite.ready.done( function() {
test.equal( otherSite.attr('live'), 'test/site/live/', 'settings from json file should match initialized object' );
test.done();
});
}
};
|
import data from './data';
export default {
data,
template : {
root : '$.store.bicycle.(color|price)'
},
result : {
root : 'red'
}
}
|
// graphql function doesn't throw an error so we have to check to check for the result.errors to throw manually
const wrapper = promise =>
promise.then(result => {
if (result.errors) {
throw result.errors
}
return result
})
exports.createPages = async ({ graphql, actions }) => {
const { createPage } = actions
const projectTemplate = require.resolve('./src/templates/project.tsx')
const result = await wrapper(
graphql(`
{
projects: allProjectsYaml {
nodes {
slug
images
}
}
}
`)
)
result.data.projects.nodes.forEach(node => {
createPage({
path: node.slug,
component: projectTemplate,
context: {
slug: node.slug,
images: `/${node.images}/`,
},
})
})
}
|
var SimpleFileWriter = require('../lib/SimpleFileWriter');
var assert = require('assert');
var Readable = require('stream').Readable;
var $u = require('util');
var fs = require('fs');
var testutil = require('./testutil');
var uuid = require('node-uuid');
var ROWS = 100;
var ROW_SIZE = 2511;
describe('basic tests - write stuff to disk - ', function () {
it('strings with specified encoding', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
assert.ok(writer instanceof SimpleFileWriter);
writer.write(new Buffer('boo').toString('base64'), 'base64');
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, 'base64', function(err, data) {
if (err) {
assert.fail(err);
}
assert.strictEqual(new Buffer('boo').toString('base64'), data)
done();
});
}, 1000)
});
it('strings with a callback', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
var callbackCalled = false;
writer.write('boo', function() {
callbackCalled = true;
});
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, function(err, data) {
if (err) {
assert.fail(err);
}
assert.deepEqual(new Buffer('boo'), data)
assert.strictEqual(true, callbackCalled, 'callback not fired');
done();
});
}, 1000)
});
it('strings with a callback and encoding specified', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
var callbackCalled = false;
writer.write(new Buffer('boo').toString('base64'), 'base64', function() {
callbackCalled = true;
});
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, 'base64', function(err, data) {
if (err) {
assert.fail(err);
}
assert.strictEqual(new Buffer('boo').toString('base64'), data)
assert.strictEqual(true, callbackCalled, 'callback not fired');
done();
});
}, 1000)
});
it('buffers', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
writer.write(new Buffer('boo'));
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, function(err, data) {
if (err) {
assert.fail(err);
}
assert.deepEqual(new Buffer('boo'), data)
done();
});
}, 1000)
});
it('buffers with callback', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
var callbackCalled = false;
writer.write(new Buffer('boo'), function() {
callbackCalled = true;
});
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, function(err, data) {
if (err) {
assert.fail(err);
}
assert.deepEqual(new Buffer('boo'), data)
assert.strictEqual(true, callbackCalled, 'callback not fired');
done();
});
}, 1000)
});
it('streams', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
writer.write(new testutil.TestStream(testutil.createRowData(20)));
this.timeout(2000);
setTimeout(function () {
fs.readFile(logfile, 'utf8', testutil.verifyDataIntegrity(1, 20, done, writer.currentPath));
}, 1000)
});
it('streams with callback', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
var callbackFired = false;
writer.write(new testutil.TestStream(testutil.createRowData(20)), function () {
callbackFired = true;
});
this.timeout(2000);
setTimeout(function () {
assert.strictEqual(true, callbackFired);
fs.readFile(logfile, 'utf8', testutil.verifyDataIntegrity(1, 20, done, writer.currentPath));
}, 1000)
});
it('mix', function (done) {
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
writer.write(new Buffer('boo\n'));
writer.write(new testutil.TestStream('A' + testutil.createRowData(20)));
writer.write(new testutil.TestStream('B' + testutil.createRowData(20)));
writer.write('C' + testutil.createRowData(100));
this.timeout(5000);
setTimeout(function () {
assert.strictEqual(0, writer._buffer.length);
fs.readFile(logfile, 'utf8', function (err, data) {
if (err)
return assert.fail(err);
var parsed = data.split('\n');
assert.strictEqual(5, parsed.length);
assert.strictEqual('', parsed[4]); // the empty row
assert.strictEqual('boo', parsed[0]);
assert.strictEqual('A', parsed[1][0]);
assert.strictEqual('B', parsed[2][0]);
assert.strictEqual('C', parsed[3][0]);
done();
});
}, 1000)
});
it('ends', function (done) {
this.timeout(15000);
var logfile = testutil.newLogFilename();
var writer = testutil.newWriter(logfile);
for (var i = 0; i < 100000; i++) {
writer.write('abracadabra!!!! abracadabra!!!! abracadabra!!!! abracadabra!!!!');
}
assert.ok(writer._buffer.length > 0);
writer.end(done);
try {
writer.write('should not be written');
assert.fail('as exception should have been thrown');
} catch (e) {
assert.ok(e);
}
console.log('if this test times out it means that there was a problem with the flushing, its either too slow or not happening at all');
});
it('can be paused and resumed', function (done) {
var logFile = testutil.newLogFilename()
var writer = testutil.newWriter(logFile);
writer.pause()
writer.write('123')
writer.write('123')
writer.write('123')
assert.strictEqual(writer._buffer.length, 3)
fs.readFile(logFile, 'utf8', function(err, data) {
if (err) return done(err)
assert(!data)
writer.resume()
setTimeout(function () {
assert.strictEqual(writer._buffer.length, 0)
fs.readFile(logFile, 'utf8', function(err, data) {
if (err) return done(err)
assert.strictEqual(data, '123123123')
done()
})
}, 500)
})
})
});
|
/* global app:true */
(function() {
'use strict';
app = app || {};
app.Site = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
success: false,
errors: [],
errfor: {},
owners: {},
permissions: {
read: {},
write: {}
},
path: '',
name: '',
_location:''
},
url: function() {
return '/account/sites/' + this.id + '/';
}
});
app.Account = Backbone.Model.extend({
idAttribute: '_id',
url: '/account/settings/'
});
app.HeaderView = Backbone.View.extend({
el: '#header',
template: _.template($('#tmpl-header').html()),
initialize: function() {
this.model = app.mainView.model;
this.listenTo(this.model, 'change', this.render);
this.render();
},
render: function() {
this.$el.html(this.template(this.model.attributes));
}
});
app.DetailsView = Backbone.View.extend({
el: '#details',
template: _.template($('#tmpl-details').html()),
events: {
'click .btn-update': 'update'
},
initialize: function() {
this.model = new app.Site();
this.syncUp();
this.listenTo(app.mainView.model, 'change', this.syncUp);
this.listenTo(this.model, 'sync', this.render);
this.render();
},
syncUp: function() {
this.model.set({
_id: app.mainView.model.id,
name: app.mainView.model.get('name'),
path: app.mainView.model.get('path')
});
},
render: function() {
console.log(JSON.stringify(this.model.attributes))
this.$el.html(this.template(this.model.attributes));
for (var key in this.model.attributes) {
if (this.model.attributes.hasOwnProperty(key)) {
this.$el.find('[name="' + key + '"]').val(this.model.attributes[key]);
}
}
},
update: function() {
this.model.save({
name: this.$el.find('[name="name"]').val()
}, {
patch: true
});
}
});
app.MainView = Backbone.View.extend({
el: '.page .container',
initialize: function() {
app.mainView = this;
this.model = new app.Site(JSON.parse(unescape($('#data-site').html())));
this.account = new app.Account(JSON.parse(unescape($('#data-account').html())));
app.detailsView = new app.DetailsView();
app.headerView = new app.HeaderView();
}
});
$(document).ready(function() {
app.mainView = new app.MainView();
});
}());
|
import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div id="notfound">
<h2>
404 Page Not Found
</h2>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
define('kitchen-sink/demo', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers', 'ace/multi_select', 'ace/ext/spellcheck', 'kitchen-sink/inline_editor', 'kitchen-sink/dev_util', 'kitchen-sink/file_drop', 'ace/config', 'ace/lib/dom', 'ace/lib/net', 'ace/lib/lang', 'ace/lib/useragent', 'ace/lib/event', 'ace/theme/textmate', 'ace/edit_session', 'ace/undomanager', 'ace/keyboard/hash_handler', 'ace/virtual_renderer', 'ace/editor', 'ace/ext/whitespace', 'kitchen-sink/doclist', 'ace/ext/modelist', 'ace/ext/themelist', 'kitchen-sink/layout', 'kitchen-sink/token_tooltip', 'kitchen-sink/util', 'ace/ext/elastic_tabstops_lite', 'ace/incremental_search', 'ace/worker/worker_client', 'ace/split', 'ace/keyboard/vim', 'ace/ext/statusbar', 'ace/ext/emmet', 'ace/snippets', 'ace/ext/language_tools', 'ace/ext/beautify'], function(require, exports, module) {
require("ace/lib/fixoldbrowsers");
require("ace/multi_select");
require("ace/ext/spellcheck");
require("./inline_editor");
require("./dev_util");
require("./file_drop");
var config = require("ace/config");
config.init();
var env = {};
var dom = require("ace/lib/dom");
var net = require("ace/lib/net");
var lang = require("ace/lib/lang");
var useragent = require("ace/lib/useragent");
var event = require("ace/lib/event");
var theme = require("ace/theme/textmate");
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
var Editor = require("ace/editor").Editor;
var whitespace = require("ace/ext/whitespace");
var doclist = require("./doclist");
var modelist = require("ace/ext/modelist");
var themelist = require("ace/ext/themelist");
var layout = require("./layout");
var TokenTooltip = require("./token_tooltip").TokenTooltip;
var util = require("./util");
var saveOption = util.saveOption;
var fillDropdown = util.fillDropdown;
var bindCheckbox = util.bindCheckbox;
var bindDropdown = util.bindDropdown;
var ElasticTabstopsLite = require("ace/ext/elastic_tabstops_lite").ElasticTabstopsLite;
var IncrementalSearch = require("ace/incremental_search").IncrementalSearch;
var workerModule = require("ace/worker/worker_client");
if (location.href.indexOf("noworker") !== -1) {
workerModule.WorkerClient = workerModule.UIWorkerClient;
}
var container = document.getElementById("editor-container");
var Split = require("ace/split").Split;
var split = new Split(container, theme, 1);
env.editor = split.getEditor(0);
split.on("focus", function(editor) {
env.editor = editor;
updateUIEditorOptions();
});
env.split = split;
window.env = env;
var consoleEl = dom.createElement("div");
container.parentNode.appendChild(consoleEl);
consoleEl.style.cssText = "position:fixed; bottom:1px; right:0;\
border:1px solid #baf; z-index:100";
var cmdLine = new layout.singleLineEditor(consoleEl);
cmdLine.editor = env.editor;
env.editor.cmdLine = cmdLine;
env.editor.showCommandLine = function(val) {
this.cmdLine.focus();
if (typeof val == "string")
this.cmdLine.setValue(val, 1);
};
env.editor.commands.addCommands([{
name: "gotoline",
bindKey: {win: "Ctrl-L", mac: "Command-L"},
exec: function(editor, line) {
if (typeof line == "object") {
var arg = this.name + " " + editor.getCursorPosition().row;
editor.cmdLine.setValue(arg, 1);
editor.cmdLine.focus();
return;
}
line = parseInt(line, 10);
if (!isNaN(line))
editor.gotoLine(line);
},
readOnly: true
}, {
name: "snippet",
bindKey: {win: "Alt-C", mac: "Command-Alt-C"},
exec: function(editor, needle) {
if (typeof needle == "object") {
editor.cmdLine.setValue("snippet ", 1);
editor.cmdLine.focus();
return;
}
var s = snippetManager.getSnippetByName(needle, editor);
if (s)
snippetManager.insertSnippet(editor, s.content);
},
readOnly: true
}, {
name: "focusCommandLine",
bindKey: "shift-esc|ctrl-`",
exec: function(editor, needle) { editor.cmdLine.focus(); },
readOnly: true
}, {
name: "nextFile",
bindKey: "Ctrl-tab",
exec: function(editor) { doclist.cycleOpen(editor, 1); },
readOnly: true
}, {
name: "previousFile",
bindKey: "Ctrl-shift-tab",
exec: function(editor) { doclist.cycleOpen(editor, -1); },
readOnly: true
}, {
name: "execute",
bindKey: "ctrl+enter",
exec: function(editor) {
try {
var r = window.eval(editor.getCopyText() || editor.getValue());
} catch(e) {
r = e;
}
editor.cmdLine.setValue(r + "");
},
readOnly: true
}, {
name: "showKeyboardShortcuts",
bindKey: {win: "Ctrl-Alt-h", mac: "Command-Alt-h"},
exec: function(editor) {
config.loadModule("ace/ext/keybinding_menu", function(module) {
module.init(editor);
editor.showKeyboardShortcuts();
});
}
}, {
name: "increaseFontSize",
bindKey: "Ctrl-=|Ctrl-+",
exec: function(editor) {
var size = parseInt(editor.getFontSize(), 10) || 12;
editor.setFontSize(size + 1);
}
}, {
name: "decreaseFontSize",
bindKey: "Ctrl+-|Ctrl-_",
exec: function(editor) {
var size = parseInt(editor.getFontSize(), 10) || 12;
editor.setFontSize(Math.max(size - 1 || 1));
}
}, {
name: "resetFontSize",
bindKey: "Ctrl+0|Ctrl-Numpad0",
exec: function(editor) {
editor.setFontSize(12);
}
}]);
env.editor.commands.addCommands(whitespace.commands);
cmdLine.commands.bindKeys({
"Shift-Return|Ctrl-Return|Alt-Return": function(cmdLine) { cmdLine.insert("\n"); },
"Esc|Shift-Esc": function(cmdLine){ cmdLine.editor.focus(); },
"Return": function(cmdLine){
var command = cmdLine.getValue().split(/\s+/);
var editor = cmdLine.editor;
editor.commands.exec(command[0], editor, command[1]);
editor.focus();
}
});
cmdLine.commands.removeCommands(["find", "gotoline", "findall", "replace", "replaceall"]);
var commands = env.editor.commands;
commands.addCommand({
name: "save",
bindKey: {win: "Ctrl-S", mac: "Command-S"},
exec: function(arg) {
var session = env.editor.session;
var name = session.name.match(/[^\/]+$/);
localStorage.setItem(
"saved_file:" + name,
session.getValue()
);
env.editor.cmdLine.setValue("saved "+ name);
}
});
commands.addCommand({
name: "load",
bindKey: {win: "Ctrl-O", mac: "Command-O"},
exec: function(arg) {
var session = env.editor.session;
var name = session.name.match(/[^\/]+$/);
var value = localStorage.getItem("saved_file:" + name);
if (typeof value == "string") {
session.setValue(value);
env.editor.cmdLine.setValue("loaded "+ name);
} else {
env.editor.cmdLine.setValue("no previuos value saved for "+ name);
}
}
});
var keybindings = {
ace: null, // Null = use "default" keymapping
vim: require("ace/keyboard/vim").handler,
emacs: "ace/keyboard/emacs",
custom: new HashHandler({
"gotoright": "Tab",
"indent": "]",
"outdent": "[",
"gotolinestart": "^",
"gotolineend": "$"
})
};
var consoleHeight = 20;
function onResize() {
var left = env.split.$container.offsetLeft;
var width = document.documentElement.clientWidth - left;
container.style.width = width + "px";
container.style.height = document.documentElement.clientHeight - consoleHeight + "px";
env.split.resize();
consoleEl.style.width = width + "px";
cmdLine.resize();
}
window.onresize = onResize;
onResize();
var docEl = document.getElementById("doc");
var modeEl = document.getElementById("mode");
var wrapModeEl = document.getElementById("soft_wrap");
var themeEl = document.getElementById("theme");
var foldingEl = document.getElementById("folding");
var selectStyleEl = document.getElementById("select_style");
var highlightActiveEl = document.getElementById("highlight_active");
var showHiddenEl = document.getElementById("show_hidden");
var showGutterEl = document.getElementById("show_gutter");
var showPrintMarginEl = document.getElementById("show_print_margin");
var highlightSelectedWordE = document.getElementById("highlight_selected_word");
var showHScrollEl = document.getElementById("show_hscroll");
var showVScrollEl = document.getElementById("show_vscroll");
var animateScrollEl = document.getElementById("animate_scroll");
var softTabEl = document.getElementById("soft_tab");
var behavioursEl = document.getElementById("enable_behaviours");
fillDropdown(docEl, doclist.all);
fillDropdown(modeEl, modelist.modes);
var modesByName = modelist.modesByName;
bindDropdown("mode", function(value) {
env.editor.session.setMode(modesByName[value].mode || modesByName.text.mode);
env.editor.session.modeName = value;
});
doclist.history = doclist.docs.map(function(doc) {
return doc.name;
});
doclist.history.index = 0;
doclist.cycleOpen = function(editor, dir) {
var h = this.history;
h.index += dir;
if (h.index >= h.length)
h.index = 0;
else if (h.index <= 0)
h.index = h.length - 1;
var s = h[h.index];
docEl.value = s;
docEl.onchange();
};
doclist.addToHistory = function(name) {
var h = this.history;
var i = h.indexOf(name);
if (i != h.index) {
if (i != -1)
h.splice(i, 1);
h.index = h.push(name);
}
};
bindDropdown("doc", function(name) {
doclist.loadDoc(name, function(session) {
if (!session)
return;
doclist.addToHistory(session.name);
session = env.split.setSession(session);
whitespace.detectIndentation(session);
updateUIEditorOptions();
env.editor.focus();
});
});
function updateUIEditorOptions() {
var editor = env.editor;
var session = editor.session;
session.setFoldStyle(foldingEl.value);
saveOption(docEl, session.name);
saveOption(modeEl, session.modeName || "text");
saveOption(wrapModeEl, session.getUseWrapMode() ? session.getWrapLimitRange().min || "free" : "off");
saveOption(selectStyleEl, editor.getSelectionStyle() == "line");
saveOption(themeEl, editor.getTheme());
saveOption(highlightActiveEl, editor.getHighlightActiveLine());
saveOption(showHiddenEl, editor.getShowInvisibles());
saveOption(showGutterEl, editor.renderer.getShowGutter());
saveOption(showPrintMarginEl, editor.renderer.getShowPrintMargin());
saveOption(highlightSelectedWordE, editor.getHighlightSelectedWord());
saveOption(showHScrollEl, editor.renderer.getHScrollBarAlwaysVisible());
saveOption(animateScrollEl, editor.getAnimatedScroll());
saveOption(softTabEl, session.getUseSoftTabs());
saveOption(behavioursEl, editor.getBehavioursEnabled());
}
themelist.themes.forEach(function(x){ x.value = x.theme });
fillDropdown(themeEl, {
Bright: themelist.themes.filter(function(x){return !x.isDark}),
Dark: themelist.themes.filter(function(x){return x.isDark}),
});
event.addListener(themeEl, "mouseover", function(e){
themeEl.desiredValue = e.target.value;
if (!themeEl.$timer)
themeEl.$timer = setTimeout(themeEl.updateTheme);
});
event.addListener(themeEl, "mouseout", function(e){
themeEl.desiredValue = null;
if (!themeEl.$timer)
themeEl.$timer = setTimeout(themeEl.updateTheme, 20);
});
themeEl.updateTheme = function(){
env.split.setTheme((themeEl.desiredValue || themeEl.selectedValue));
themeEl.$timer = null;
};
bindDropdown("theme", function(value) {
if (!value)
return;
env.editor.setTheme(value);
themeEl.selectedValue = value;
});
bindDropdown("keybinding", function(value) {
env.editor.setKeyboardHandler(keybindings[value]);
});
bindDropdown("fontsize", function(value) {
env.split.setFontSize(value);
});
bindDropdown("folding", function(value) {
env.editor.session.setFoldStyle(value);
env.editor.setShowFoldWidgets(value !== "manual");
});
bindDropdown("soft_wrap", function(value) {
var session = env.editor.session;
var renderer = env.editor.renderer;
switch (value) {
case "off":
session.setUseWrapMode(false);
renderer.setPrintMarginColumn(80);
break;
case "free":
session.setUseWrapMode(true);
session.setWrapLimitRange(null, null);
renderer.setPrintMarginColumn(80);
break;
default:
session.setUseWrapMode(true);
var col = parseInt(value, 10);
session.setWrapLimitRange(col, col);
renderer.setPrintMarginColumn(col);
}
});
bindCheckbox("select_style", function(checked) {
env.editor.setSelectionStyle(checked ? "line" : "text");
});
bindCheckbox("highlight_active", function(checked) {
env.editor.setHighlightActiveLine(checked);
});
bindCheckbox("show_hidden", function(checked) {
env.editor.setShowInvisibles(checked);
});
bindCheckbox("display_indent_guides", function(checked) {
env.editor.setDisplayIndentGuides(checked);
});
bindCheckbox("show_gutter", function(checked) {
env.editor.renderer.setShowGutter(checked);
});
bindCheckbox("show_print_margin", function(checked) {
env.editor.renderer.setShowPrintMargin(checked);
});
bindCheckbox("highlight_selected_word", function(checked) {
env.editor.setHighlightSelectedWord(checked);
});
bindCheckbox("show_hscroll", function(checked) {
env.editor.setOption("hScrollBarAlwaysVisible", checked);
});
bindCheckbox("show_vscroll", function(checked) {
env.editor.setOption("vScrollBarAlwaysVisible", checked);
});
bindCheckbox("animate_scroll", function(checked) {
env.editor.setAnimatedScroll(checked);
});
bindCheckbox("soft_tab", function(checked) {
env.editor.session.setUseSoftTabs(checked);
});
bindCheckbox("enable_behaviours", function(checked) {
env.editor.setBehavioursEnabled(checked);
});
bindCheckbox("fade_fold_widgets", function(checked) {
env.editor.setFadeFoldWidgets(checked);
});
bindCheckbox("read_only", function(checked) {
env.editor.setReadOnly(checked);
});
bindCheckbox("scrollPastEnd", function(checked) {
env.editor.setOption("scrollPastEnd", checked);
});
bindDropdown("split", function(value) {
var sp = env.split;
if (value == "none") {
sp.setSplits(1);
} else {
var newEditor = (sp.getSplits() == 1);
sp.setOrientation(value == "below" ? sp.BELOW : sp.BESIDE);
sp.setSplits(2);
if (newEditor) {
var session = sp.getEditor(0).session;
var newSession = sp.setSession(session, 1);
newSession.name = session.name;
}
}
});
bindCheckbox("elastic_tabstops", function(checked) {
env.editor.setOption("useElasticTabstops", checked);
});
var iSearchCheckbox = bindCheckbox("isearch", function(checked) {
env.editor.setOption("useIncrementalSearch", checked);
});
env.editor.addEventListener('incrementalSearchSettingChanged', function(event) {
iSearchCheckbox.checked = event.isEnabled;
});
function synchroniseScrolling() {
var s1 = env.split.$editors[0].session;
var s2 = env.split.$editors[1].session;
s1.on('changeScrollTop', function(pos) {s2.setScrollTop(pos)});
s2.on('changeScrollTop', function(pos) {s1.setScrollTop(pos)});
s1.on('changeScrollLeft', function(pos) {s2.setScrollLeft(pos)});
s2.on('changeScrollLeft', function(pos) {s1.setScrollLeft(pos)});
}
bindCheckbox("highlight_token", function(checked) {
var editor = env.editor;
if (editor.tokenTooltip && !checked) {
editor.tokenTooltip.destroy();
delete editor.tokenTooltip;
} else if (checked) {
editor.tokenTooltip = new TokenTooltip(editor);
}
});
var StatusBar = require("ace/ext/statusbar").StatusBar;
new StatusBar(env.editor, cmdLine.container);
var Emmet = require("ace/ext/emmet");
net.loadScript("https://nightwing.github.io/emmet-core/emmet.js", function() {
Emmet.setCore(window.emmet);
env.editor.setOption("enableEmmet", true);
});
var snippetManager = require("ace/snippets").snippetManager;
env.editSnippets = function() {
var sp = env.split;
if (sp.getSplits() == 2) {
sp.setSplits(1);
return;
}
sp.setSplits(1);
sp.setSplits(2);
sp.setOrientation(sp.BESIDE);
var editor = sp.$editors[1];
var id = sp.$editors[0].session.$mode.$id || "";
var m = snippetManager.files[id];
if (!doclist["snippets/" + id]) {
var text = m.snippetText;
var s = doclist.initDoc(text, "", {});
s.setMode("ace/mode/snippets");
doclist["snippets/" + id] = s;
}
editor.on("blur", function() {
m.snippetText = editor.getValue();
snippetManager.unregister(m.snippets);
m.snippets = snippetManager.parseSnippetFile(m.snippetText, m.scope);
snippetManager.register(m.snippets);
});
sp.$editors[0].once("changeMode", function() {
sp.setSplits(1);
});
editor.setSession(doclist["snippets/" + id], 1);
editor.focus();
};
require("ace/ext/language_tools");
env.editor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true
});
var beautify = require("ace/ext/beautify");
env.editor.commands.addCommands(beautify.commands);
});
define('ace/incremental_search', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/search', 'ace/search_highlight', 'ace/commands/incremental_search_commands', 'ace/lib/dom', 'ace/commands/command_manager', 'ace/editor', 'ace/config'], function(require, exports, module) {
var oop = require("./lib/oop");
var Range = require("./range").Range;
var Search = require("./search").Search;
var SearchHighlight = require("./search_highlight").SearchHighlight;
var iSearchCommandModule = require("./commands/incremental_search_commands");
var ISearchKbd = iSearchCommandModule.IncrementalSearchKeyboardHandler;
function IncrementalSearch() {
this.$options = {wrap: false, skipCurrent: false};
this.$keyboardHandler = new ISearchKbd(this);
}
oop.inherits(IncrementalSearch, Search);
;(function() {
this.activate = function(ed, backwards) {
this.$editor = ed;
this.$startPos = this.$currentPos = ed.getCursorPosition();
this.$options.needle = '';
this.$options.backwards = backwards;
ed.keyBinding.addKeyboardHandler(this.$keyboardHandler);
this.$originalEditorOnPaste = ed.onPaste; ed.onPaste = this.onPaste.bind(this);
this.$mousedownHandler = ed.addEventListener('mousedown', this.onMouseDown.bind(this));
this.selectionFix(ed);
this.statusMessage(true);
}
this.deactivate = function(reset) {
this.cancelSearch(reset);
var ed = this.$editor;
ed.keyBinding.removeKeyboardHandler(this.$keyboardHandler);
if (this.$mousedownHandler) {
ed.removeEventListener('mousedown', this.$mousedownHandler);
delete this.$mousedownHandler;
}
ed.onPaste = this.$originalEditorOnPaste;
this.message('');
}
this.selectionFix = function(editor) {
if (editor.selection.isEmpty() && !editor.session.$emacsMark) {
editor.clearSelection();
}
}
this.highlight = function(regexp) {
var sess = this.$editor.session,
hl = sess.$isearchHighlight = sess.$isearchHighlight || sess.addDynamicMarker(
new SearchHighlight(null, "ace_isearch-result", "text"));
hl.setRegexp(regexp);
sess._emit("changeBackMarker"); // force highlight layer redraw
}
this.cancelSearch = function(reset) {
var e = this.$editor;
this.$prevNeedle = this.$options.needle;
this.$options.needle = '';
if (reset) {
e.moveCursorToPosition(this.$startPos);
this.$currentPos = this.$startPos;
} else {
e.pushEmacsMark && e.pushEmacsMark(this.$startPos, false);
}
this.highlight(null);
return Range.fromPoints(this.$currentPos, this.$currentPos);
}
this.highlightAndFindWithNeedle = function(moveToNext, needleUpdateFunc) {
if (!this.$editor) return null;
var options = this.$options;
if (needleUpdateFunc) {
options.needle = needleUpdateFunc.call(this, options.needle || '') || '';
}
if (options.needle.length === 0) {
this.statusMessage(true);
return this.cancelSearch(true);
};
options.start = this.$currentPos;
var session = this.$editor.session,
found = this.find(session);
if (found) {
if (options.backwards) found = Range.fromPoints(found.end, found.start);
this.$editor.moveCursorToPosition(found.end);
if (moveToNext) this.$currentPos = found.end;
this.highlight(options.re)
}
this.statusMessage(found);
return found;
}
this.addString = function(s) {
return this.highlightAndFindWithNeedle(false, function(needle) {
return needle + s;
});
}
this.removeChar = function(c) {
return this.highlightAndFindWithNeedle(false, function(needle) {
return needle.length > 0 ? needle.substring(0, needle.length-1) : needle;
});
}
this.next = function(options) {
options = options || {};
this.$options.backwards = !!options.backwards;
this.$currentPos = this.$editor.getCursorPosition();
return this.highlightAndFindWithNeedle(true, function(needle) {
return options.useCurrentOrPrevSearch && needle.length === 0 ?
this.$prevNeedle || '' : needle;
});
}
this.onMouseDown = function(evt) {
this.deactivate();
return true;
}
this.onPaste = function(text) {
this.addString(text);
}
this.statusMessage = function(found) {
var options = this.$options, msg = '';
msg += options.backwards ? 'reverse-' : '';
msg += 'isearch: ' + options.needle;
msg += found ? '' : ' (not found)';
this.message(msg);
}
this.message = function(msg) {
if (this.$editor.showCommandLine) {
this.$editor.showCommandLine(msg);
this.$editor.focus();
} else {
console.log(msg);
}
}
}).call(IncrementalSearch.prototype);
exports.IncrementalSearch = IncrementalSearch;
var dom = require('./lib/dom');
dom.importCssString && dom.importCssString("\
.ace_marker-layer .ace_isearch-result {\
position: absolute;\
z-index: 6;\
-moz-box-sizing: border-box;\
-webkit-box-sizing: border-box;\
box-sizing: border-box;\
}\
div.ace_isearch-result {\
border-radius: 4px;\
background-color: rgba(255, 200, 0, 0.5);\
box-shadow: 0 0 4px rgb(255, 200, 0);\
}\
.ace_dark div.ace_isearch-result {\
background-color: rgb(100, 110, 160);\
box-shadow: 0 0 4px rgb(80, 90, 140);\
}", "incremental-search-highlighting");
var commands = require("./commands/command_manager");
(function() {
this.setupIncrementalSearch = function(editor, val) {
if (this.usesIncrementalSearch == val) return;
this.usesIncrementalSearch = val;
var iSearchCommands = iSearchCommandModule.iSearchStartCommands;
var method = val ? 'addCommands' : 'removeCommands';
this[method](iSearchCommands);
};
}).call(commands.CommandManager.prototype);
var Editor = require("./editor").Editor;
require("./config").defineOptions(Editor.prototype, "editor", {
useIncrementalSearch: {
set: function(val) {
this.keyBinding.$handlers.forEach(function(handler) {
if (handler.setupIncrementalSearch) {
handler.setupIncrementalSearch(this, val);
}
});
this._emit('incrementalSearchSettingChanged', {isEnabled: val});
}
}
});
});
define('ace/commands/incremental_search_commands', ['require', 'exports', 'module' , 'ace/config', 'ace/lib/oop', 'ace/keyboard/hash_handler', 'ace/commands/occur_commands'], function(require, exports, module) {
var config = require("../config");
var oop = require("../lib/oop");
var HashHandler = require("../keyboard/hash_handler").HashHandler;
var occurStartCommand = require("./occur_commands").occurStartCommand;
exports.iSearchStartCommands = [{
name: "iSearch",
bindKey: {win: "Ctrl-F", mac: "Command-F"},
exec: function(editor, options) {
config.loadModule(["core", "ace/incremental_search"], function(e) {
var iSearch = e.iSearch = e.iSearch || new e.IncrementalSearch();
iSearch.activate(editor, options.backwards);
if (options.jumpToFirstMatch) iSearch.next(options);
});
},
readOnly: true
}, {
name: "iSearchBackwards",
exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {backwards: true}); },
readOnly: true
}, {
name: "iSearchAndGo",
bindKey: {win: "Ctrl-K", mac: "Command-G"},
exec: function(editor, jumpToNext) { editor.execCommand('iSearch', {jumpToFirstMatch: true, useCurrentOrPrevSearch: true}); },
readOnly: true
}, {
name: "iSearchBackwardsAndGo",
bindKey: {win: "Ctrl-Shift-K", mac: "Command-Shift-G"},
exec: function(editor) { editor.execCommand('iSearch', {jumpToFirstMatch: true, backwards: true, useCurrentOrPrevSearch: true}); },
readOnly: true
}];
exports.iSearchCommands = [{
name: "restartSearch",
bindKey: {win: "Ctrl-F", mac: "Command-F"},
exec: function(iSearch) {
iSearch.cancelSearch(true);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "searchForward",
bindKey: {win: "Ctrl-S|Ctrl-K", mac: "Ctrl-S|Command-G"},
exec: function(iSearch, options) {
options.useCurrentOrPrevSearch = true;
iSearch.next(options);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "searchBackward",
bindKey: {win: "Ctrl-R|Ctrl-Shift-K", mac: "Ctrl-R|Command-Shift-G"},
exec: function(iSearch, options) {
options.useCurrentOrPrevSearch = true;
options.backwards = true;
iSearch.next(options);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "extendSearchTerm",
exec: function(iSearch, string) {
iSearch.addString(string);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "extendSearchTermSpace",
bindKey: "space",
exec: function(iSearch) { iSearch.addString(' '); },
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "shrinkSearchTerm",
bindKey: "backspace",
exec: function(iSearch) {
iSearch.removeChar();
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: 'confirmSearch',
bindKey: 'return',
exec: function(iSearch) { iSearch.deactivate(); },
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: 'cancelSearch',
bindKey: 'esc|Ctrl-G',
exec: function(iSearch) { iSearch.deactivate(true); },
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: 'occurisearch',
bindKey: 'Ctrl-O',
exec: function(iSearch) {
var options = oop.mixin({}, iSearch.$options);
iSearch.deactivate();
occurStartCommand.exec(iSearch.$editor, options);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "yankNextWord",
bindKey: "Ctrl-w",
exec: function(iSearch) {
var ed = iSearch.$editor,
range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorWordRight(); }),
string = ed.session.getTextRange(range);
iSearch.addString(string);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: "yankNextChar",
bindKey: "Ctrl-Alt-y",
exec: function(iSearch) {
var ed = iSearch.$editor,
range = ed.selection.getRangeOfMovements(function(sel) { sel.moveCursorRight(); }),
string = ed.session.getTextRange(range);
iSearch.addString(string);
},
readOnly: true,
isIncrementalSearchCommand: true
}, {
name: 'recenterTopBottom',
bindKey: 'Ctrl-l',
exec: function(iSearch) { iSearch.$editor.execCommand('recenterTopBottom'); },
readOnly: true,
isIncrementalSearchCommand: true
}];
function IncrementalSearchKeyboardHandler(iSearch) {
this.$iSearch = iSearch;
}
oop.inherits(IncrementalSearchKeyboardHandler, HashHandler);
;(function() {
this.attach = function(editor) {
var iSearch = this.$iSearch;
HashHandler.call(this, exports.iSearchCommands, editor.commands.platform);
this.$commandExecHandler = editor.commands.addEventListener('exec', function(e) {
if (!e.command.isIncrementalSearchCommand) return undefined;
e.stopPropagation();
e.preventDefault();
return e.command.exec(iSearch, e.args || {});
});
}
this.detach = function(editor) {
if (!this.$commandExecHandler) return;
editor.commands.removeEventListener('exec', this.$commandExecHandler);
delete this.$commandExecHandler;
}
var handleKeyboard$super = this.handleKeyboard;
this.handleKeyboard = function(data, hashId, key, keyCode) {
if (((hashId === 1/*ctrl*/ || hashId === 8/*command*/) && key === 'v')
|| (hashId === 1/*ctrl*/ && key === 'y')) return null;
var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode);
if (cmd.command) { return cmd; }
if (hashId == -1) {
var extendCmd = this.commands.extendSearchTerm;
if (extendCmd) { return {command: extendCmd, args: key}; }
}
return {command: "null", passEvent: hashId == 0 || hashId == 4};
}
}).call(IncrementalSearchKeyboardHandler.prototype);
exports.IncrementalSearchKeyboardHandler = IncrementalSearchKeyboardHandler;
});
define('ace/commands/occur_commands', ['require', 'exports', 'module' , 'ace/config', 'ace/occur', 'ace/keyboard/hash_handler', 'ace/lib/oop'], function(require, exports, module) {
var config = require("../config"),
Occur = require("../occur").Occur;
var occurStartCommand = {
name: "occur",
exec: function(editor, options) {
var alreadyInOccur = !!editor.session.$occur;
var occurSessionActive = new Occur().enter(editor, options);
if (occurSessionActive && !alreadyInOccur)
OccurKeyboardHandler.installIn(editor);
},
readOnly: true
};
var occurCommands = [{
name: "occurexit",
bindKey: 'esc|Ctrl-G',
exec: function(editor) {
var occur = editor.session.$occur;
if (!occur) return;
occur.exit(editor, {});
if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor);
},
readOnly: true
}, {
name: "occuraccept",
bindKey: 'enter',
exec: function(editor) {
var occur = editor.session.$occur;
if (!occur) return;
occur.exit(editor, {translatePosition: true});
if (!editor.session.$occur) OccurKeyboardHandler.uninstallFrom(editor);
},
readOnly: true
}];
var HashHandler = require("../keyboard/hash_handler").HashHandler;
var oop = require("../lib/oop");
function OccurKeyboardHandler() {}
oop.inherits(OccurKeyboardHandler, HashHandler);
;(function() {
this.isOccurHandler = true;
this.attach = function(editor) {
HashHandler.call(this, occurCommands, editor.commands.platform);
this.$editor = editor;
}
var handleKeyboard$super = this.handleKeyboard;
this.handleKeyboard = function(data, hashId, key, keyCode) {
var cmd = handleKeyboard$super.call(this, data, hashId, key, keyCode);
return (cmd && cmd.command) ? cmd : undefined;
}
}).call(OccurKeyboardHandler.prototype);
OccurKeyboardHandler.installIn = function(editor) {
var handler = new this();
editor.keyBinding.addKeyboardHandler(handler);
editor.commands.addCommands(occurCommands);
}
OccurKeyboardHandler.uninstallFrom = function(editor) {
editor.commands.removeCommands(occurCommands);
var handler = editor.getKeyboardHandler();
if (handler.isOccurHandler)
editor.keyBinding.removeKeyboardHandler(handler);
}
exports.occurStartCommand = occurStartCommand;
});
define('ace/ext/elastic_tabstops_lite', ['require', 'exports', 'module' , 'ace/editor', 'ace/config'], function(require, exports, module) {
var ElasticTabstopsLite = function(editor) {
this.$editor = editor;
var self = this;
var changedRows = [];
var recordChanges = false;
this.onAfterExec = function() {
recordChanges = false;
self.processRows(changedRows);
changedRows = [];
};
this.onExec = function() {
recordChanges = true;
};
this.onChange = function(e) {
var range = e.data.range
if (recordChanges) {
if (changedRows.indexOf(range.start.row) == -1)
changedRows.push(range.start.row);
if (range.end.row != range.start.row)
changedRows.push(range.end.row);
}
};
};
(function() {
this.processRows = function(rows) {
this.$inChange = true;
var checkedRows = [];
for (var r = 0, rowCount = rows.length; r < rowCount; r++) {
var row = rows[r];
if (checkedRows.indexOf(row) > -1)
continue;
var cellWidthObj = this.$findCellWidthsForBlock(row);
var cellWidths = this.$setBlockCellWidthsToMax(cellWidthObj.cellWidths);
var rowIndex = cellWidthObj.firstRow;
for (var w = 0, l = cellWidths.length; w < l; w++) {
var widths = cellWidths[w];
checkedRows.push(rowIndex);
this.$adjustRow(rowIndex, widths);
rowIndex++;
}
}
this.$inChange = false;
};
this.$findCellWidthsForBlock = function(row) {
var cellWidths = [], widths;
var rowIter = row;
while (rowIter >= 0) {
widths = this.$cellWidthsForRow(rowIter);
if (widths.length == 0)
break;
cellWidths.unshift(widths);
rowIter--;
}
var firstRow = rowIter + 1;
rowIter = row;
var numRows = this.$editor.session.getLength();
while (rowIter < numRows - 1) {
rowIter++;
widths = this.$cellWidthsForRow(rowIter);
if (widths.length == 0)
break;
cellWidths.push(widths);
}
return { cellWidths: cellWidths, firstRow: firstRow };
};
this.$cellWidthsForRow = function(row) {
var selectionColumns = this.$selectionColumnsForRow(row);
var tabs = [-1].concat(this.$tabsForRow(row));
var widths = tabs.map(function(el) { return 0; } ).slice(1);
var line = this.$editor.session.getLine(row);
for (var i = 0, len = tabs.length - 1; i < len; i++) {
var leftEdge = tabs[i]+1;
var rightEdge = tabs[i+1];
var rightmostSelection = this.$rightmostSelectionInCell(selectionColumns, rightEdge);
var cell = line.substring(leftEdge, rightEdge);
widths[i] = Math.max(cell.replace(/\s+$/g,'').length, rightmostSelection - leftEdge);
}
return widths;
};
this.$selectionColumnsForRow = function(row) {
var selections = [], cursor = this.$editor.getCursorPosition();
if (this.$editor.session.getSelection().isEmpty()) {
if (row == cursor.row)
selections.push(cursor.column);
}
return selections;
};
this.$setBlockCellWidthsToMax = function(cellWidths) {
var startingNewBlock = true, blockStartRow, blockEndRow, maxWidth;
var columnInfo = this.$izip_longest(cellWidths);
for (var c = 0, l = columnInfo.length; c < l; c++) {
var column = columnInfo[c];
if (!column.push) {
console.error(column);
continue;
}
column.push(NaN);
for (var r = 0, s = column.length; r < s; r++) {
var width = column[r];
if (startingNewBlock) {
blockStartRow = r;
maxWidth = 0;
startingNewBlock = false;
}
if (isNaN(width)) {
blockEndRow = r;
for (var j = blockStartRow; j < blockEndRow; j++) {
cellWidths[j][c] = maxWidth;
}
startingNewBlock = true;
}
maxWidth = Math.max(maxWidth, width);
}
}
return cellWidths;
};
this.$rightmostSelectionInCell = function(selectionColumns, cellRightEdge) {
var rightmost = 0;
if (selectionColumns.length) {
var lengths = [];
for (var s = 0, length = selectionColumns.length; s < length; s++) {
if (selectionColumns[s] <= cellRightEdge)
lengths.push(s);
else
lengths.push(0);
}
rightmost = Math.max.apply(Math, lengths);
}
return rightmost;
};
this.$tabsForRow = function(row) {
var rowTabs = [], line = this.$editor.session.getLine(row),
re = /\t/g, match;
while ((match = re.exec(line)) != null) {
rowTabs.push(match.index);
}
return rowTabs;
};
this.$adjustRow = function(row, widths) {
var rowTabs = this.$tabsForRow(row);
if (rowTabs.length == 0)
return;
var bias = 0, location = -1;
var expandedSet = this.$izip(widths, rowTabs);
for (var i = 0, l = expandedSet.length; i < l; i++) {
var w = expandedSet[i][0], it = expandedSet[i][1];
location += 1 + w;
it += bias;
var difference = location - it;
if (difference == 0)
continue;
var partialLine = this.$editor.session.getLine(row).substr(0, it );
var strippedPartialLine = partialLine.replace(/\s*$/g, "");
var ispaces = partialLine.length - strippedPartialLine.length;
if (difference > 0) {
this.$editor.session.getDocument().insertInLine({row: row, column: it + 1}, Array(difference + 1).join(" ") + "\t");
this.$editor.session.getDocument().removeInLine(row, it, it + 1);
bias += difference;
}
if (difference < 0 && ispaces >= -difference) {
this.$editor.session.getDocument().removeInLine(row, it + difference, it);
bias += difference;
}
}
};
this.$izip_longest = function(iterables) {
if (!iterables[0])
return [];
var longest = iterables[0].length;
var iterablesLength = iterables.length;
for (var i = 1; i < iterablesLength; i++) {
var iLength = iterables[i].length;
if (iLength > longest)
longest = iLength;
}
var expandedSet = [];
for (var l = 0; l < longest; l++) {
var set = [];
for (var i = 0; i < iterablesLength; i++) {
if (iterables[i][l] === "")
set.push(NaN);
else
set.push(iterables[i][l]);
}
expandedSet.push(set);
}
return expandedSet;
};
this.$izip = function(widths, tabs) {
var size = widths.length >= tabs.length ? tabs.length : widths.length;
var expandedSet = [];
for (var i = 0; i < size; i++) {
var set = [ widths[i], tabs[i] ];
expandedSet.push(set);
}
return expandedSet;
};
}).call(ElasticTabstopsLite.prototype);
exports.ElasticTabstopsLite = ElasticTabstopsLite;
var Editor = require("../editor").Editor;
require("../config").defineOptions(Editor.prototype, "editor", {
useElasticTabstops: {
set: function(val) {
if (val) {
if (!this.elasticTabstops)
this.elasticTabstops = new ElasticTabstopsLite(this);
this.commands.on("afterExec", this.elasticTabstops.onAfterExec);
this.commands.on("exec", this.elasticTabstops.onExec);
this.on("change", this.elasticTabstops.onChange);
} else if (this.elasticTabstops) {
this.commands.removeListener("afterExec", this.elasticTabstops.onAfterExec);
this.commands.removeListener("exec", this.elasticTabstops.onExec);
this.removeListener("change", this.elasticTabstops.onChange);
}
}
}
});
});
define('ace/split', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/lib/event_emitter', 'ace/editor', 'ace/virtual_renderer', 'ace/edit_session'], function(require, exports, module) {
var oop = require("./lib/oop");
var lang = require("./lib/lang");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Editor = require("./editor").Editor;
var Renderer = require("./virtual_renderer").VirtualRenderer;
var EditSession = require("./edit_session").EditSession;
var Split = function(container, theme, splits) {
this.BELOW = 1;
this.BESIDE = 0;
this.$container = container;
this.$theme = theme;
this.$splits = 0;
this.$editorCSS = "";
this.$editors = [];
this.$orientation = this.BESIDE;
this.setSplits(splits || 1);
this.$cEditor = this.$editors[0];
this.on("focus", function(editor) {
this.$cEditor = editor;
}.bind(this));
};
(function(){
oop.implement(this, EventEmitter);
this.$createEditor = function() {
var el = document.createElement("div");
el.className = this.$editorCSS;
el.style.cssText = "position: absolute; top:0px; bottom:0px";
this.$container.appendChild(el);
var editor = new Editor(new Renderer(el, this.$theme));
editor.on("focus", function() {
this._emit("focus", editor);
}.bind(this));
this.$editors.push(editor);
editor.setFontSize(this.$fontSize);
return editor;
};
this.setSplits = function(splits) {
var editor;
if (splits < 1) {
throw "The number of splits have to be > 0!";
}
if (splits == this.$splits) {
return;
} else if (splits > this.$splits) {
while (this.$splits < this.$editors.length && this.$splits < splits) {
editor = this.$editors[this.$splits];
this.$container.appendChild(editor.container);
editor.setFontSize(this.$fontSize);
this.$splits ++;
}
while (this.$splits < splits) {
this.$createEditor();
this.$splits ++;
}
} else {
while (this.$splits > splits) {
editor = this.$editors[this.$splits - 1];
this.$container.removeChild(editor.container);
this.$splits --;
}
}
this.resize();
};
this.getSplits = function() {
return this.$splits;
};
this.getEditor = function(idx) {
return this.$editors[idx];
};
this.getCurrentEditor = function() {
return this.$cEditor;
};
this.focus = function() {
this.$cEditor.focus();
};
this.blur = function() {
this.$cEditor.blur();
};
this.setTheme = function(theme) {
this.$editors.forEach(function(editor) {
editor.setTheme(theme);
});
};
this.setKeyboardHandler = function(keybinding) {
this.$editors.forEach(function(editor) {
editor.setKeyboardHandler(keybinding);
});
};
this.forEach = function(callback, scope) {
this.$editors.forEach(callback, scope);
};
this.$fontSize = "";
this.setFontSize = function(size) {
this.$fontSize = size;
this.forEach(function(editor) {
editor.setFontSize(size);
});
};
this.$cloneSession = function(session) {
var s = new EditSession(session.getDocument(), session.getMode());
var undoManager = session.getUndoManager();
if (undoManager) {
var undoManagerProxy = new UndoManagerProxy(undoManager, s);
s.setUndoManager(undoManagerProxy);
}
s.$informUndoManager = lang.delayedCall(function() { s.$deltas = []; });
s.setTabSize(session.getTabSize());
s.setUseSoftTabs(session.getUseSoftTabs());
s.setOverwrite(session.getOverwrite());
s.setBreakpoints(session.getBreakpoints());
s.setUseWrapMode(session.getUseWrapMode());
s.setUseWorker(session.getUseWorker());
s.setWrapLimitRange(session.$wrapLimitRange.min,
session.$wrapLimitRange.max);
s.$foldData = session.$cloneFoldData();
return s;
};
this.setSession = function(session, idx) {
var editor;
if (idx == null) {
editor = this.$cEditor;
} else {
editor = this.$editors[idx];
}
var isUsed = this.$editors.some(function(editor) {
return editor.session === session;
});
if (isUsed) {
session = this.$cloneSession(session);
}
editor.setSession(session);
return session;
};
this.getOrientation = function() {
return this.$orientation;
};
this.setOrientation = function(orientation) {
if (this.$orientation == orientation) {
return;
}
this.$orientation = orientation;
this.resize();
};
this.resize = function() {
var width = this.$container.clientWidth;
var height = this.$container.clientHeight;
var editor;
if (this.$orientation == this.BESIDE) {
var editorWidth = width / this.$splits;
for (var i = 0; i < this.$splits; i++) {
editor = this.$editors[i];
editor.container.style.width = editorWidth + "px";
editor.container.style.top = "0px";
editor.container.style.left = i * editorWidth + "px";
editor.container.style.height = height + "px";
editor.resize();
}
} else {
var editorHeight = height / this.$splits;
for (var i = 0; i < this.$splits; i++) {
editor = this.$editors[i];
editor.container.style.width = width + "px";
editor.container.style.top = i * editorHeight + "px";
editor.container.style.left = "0px";
editor.container.style.height = editorHeight + "px";
editor.resize();
}
}
};
}).call(Split.prototype);
function UndoManagerProxy(undoManager, session) {
this.$u = undoManager;
this.$doc = session;
}
(function() {
this.execute = function(options) {
this.$u.execute(options);
};
this.undo = function() {
var selectionRange = this.$u.undo(true);
if (selectionRange) {
this.$doc.selection.setSelectionRange(selectionRange);
}
};
this.redo = function() {
var selectionRange = this.$u.redo(true);
if (selectionRange) {
this.$doc.selection.setSelectionRange(selectionRange);
}
};
this.reset = function() {
this.$u.reset();
};
this.hasUndo = function() {
return this.$u.hasUndo();
};
this.hasRedo = function() {
return this.$u.hasRedo();
};
}).call(UndoManagerProxy.prototype);
exports.Split = Split;
});
define('ace/keyboard/vim', ['require', 'exports', 'module' , 'ace/keyboard/vim/commands', 'ace/keyboard/vim/maps/util', 'ace/lib/useragent'], function(require, exports, module) {
var cmds = require("./vim/commands");
var coreCommands = cmds.coreCommands;
var util = require("./vim/maps/util");
var useragent = require("../lib/useragent");
var startCommands = {
"i": {
command: coreCommands.start
},
"I": {
command: coreCommands.startBeginning
},
"a": {
command: coreCommands.append
},
"A": {
command: coreCommands.appendEnd
},
"ctrl-f": {
command: "gotopagedown"
},
"ctrl-b": {
command: "gotopageup"
}
};
exports.handler = {
$id: "ace/keyboard/vim",
handleMacRepeat: function(data, hashId, key) {
if (hashId == -1) {
data.inputChar = key;
data.lastEvent = "input";
} else if (data.inputChar && data.$lastHash == hashId && data.$lastKey == key) {
if (data.lastEvent == "input") {
data.lastEvent = "input1";
} else if (data.lastEvent == "input1") {
return true;
}
} else {
data.$lastHash = hashId;
data.$lastKey = key;
data.lastEvent = "keypress";
}
},
updateMacCompositionHandlers: function(editor, enable) {
var onCompositionUpdateOverride = function(text) {
if (util.currentMode !== "insert") {
var el = this.textInput.getElement();
el.blur();
el.focus();
el.value = text;
} else {
this.onCompositionUpdateOrig(text);
}
};
var onCompositionStartOverride = function(text) {
if (util.currentMode === "insert") {
this.onCompositionStartOrig(text);
}
};
if (enable) {
if (!editor.onCompositionUpdateOrig) {
editor.onCompositionUpdateOrig = editor.onCompositionUpdate;
editor.onCompositionUpdate = onCompositionUpdateOverride;
editor.onCompositionStartOrig = editor.onCompositionStart;
editor.onCompositionStart = onCompositionStartOverride;
}
} else {
if (editor.onCompositionUpdateOrig) {
editor.onCompositionUpdate = editor.onCompositionUpdateOrig;
editor.onCompositionUpdateOrig = null;
editor.onCompositionStart = editor.onCompositionStartOrig;
editor.onCompositionStartOrig = null;
}
}
},
handleKeyboard: function(data, hashId, key, keyCode, e) {
if (hashId !== 0 && (!key || keyCode == -1))
return null;
var editor = data.editor;
var vimState = data.vimState || "start";
if (hashId == 1)
key = "ctrl-" + key;
if (key == "ctrl-c") {
if (!useragent.isMac && editor.getCopyText()) {
editor.once("copy", function() {
if (vimState == "start")
coreCommands.stop.exec(editor);
else
editor.selection.clearSelection();
});
return {command: "null", passEvent: true};
}
return {command: coreCommands.stop};
} else if ((key == "esc" && hashId === 0) || key == "ctrl-[") {
return {command: coreCommands.stop};
} else if (vimState == "start") {
if (useragent.isMac && this.handleMacRepeat(data, hashId, key)) {
hashId = -1;
key = data.inputChar;
}
if (hashId == -1 || hashId == 1 || hashId === 0 && key.length > 1) {
if (cmds.inputBuffer.idle && startCommands[key])
return startCommands[key];
var isHandled = cmds.inputBuffer.push(editor, key);
if (!isHandled && hashId !== -1)
return;
return {command: "null", passEvent: !isHandled};
} else if (key == "esc" && hashId === 0) {
return {command: coreCommands.stop};
}
else if (hashId === 0 || hashId == 4) {
return {command: "null", passEvent: true};
}
} else {
if (key == "ctrl-w") {
return {command: "removewordleft"};
}
}
},
attach: function(editor) {
editor.on("click", exports.onCursorMove);
if (util.currentMode !== "insert")
cmds.coreCommands.stop.exec(editor);
editor.$vimModeHandler = this;
this.updateMacCompositionHandlers(editor, true);
},
detach: function(editor) {
editor.removeListener("click", exports.onCursorMove);
util.noMode(editor);
util.currentMode = "normal";
this.updateMacCompositionHandlers(editor, false);
},
actions: cmds.actions,
getStatusText: function() {
if (util.currentMode == "insert")
return "INSERT";
if (util.onVisualMode)
return (util.onVisualLineMode ? "VISUAL LINE " : "VISUAL ") + cmds.inputBuffer.status;
return cmds.inputBuffer.status;
}
};
exports.onCursorMove = function(e) {
cmds.onCursorMove(e.editor, e);
exports.onCursorMove.scheduled = false;
};
});
define('ace/keyboard/vim/commands', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/maps/motions', 'ace/keyboard/vim/maps/operators', 'ace/keyboard/vim/maps/aliases', 'ace/keyboard/vim/registers'], function(require, exports, module) {
"never use strict";
var lang = require("../../lib/lang");
var util = require("./maps/util");
var motions = require("./maps/motions");
var operators = require("./maps/operators");
var alias = require("./maps/aliases");
var registers = require("./registers");
var NUMBER = 1;
var OPERATOR = 2;
var MOTION = 3;
var ACTION = 4;
var HMARGIN = 8; // Minimum amount of line separation between margins;
var repeat = function repeat(fn, count, args) {
while (0 < count--)
fn.apply(this, args);
};
var ensureScrollMargin = function(editor) {
var renderer = editor.renderer;
var pos = renderer.$cursorLayer.getPixelPosition();
var top = pos.top;
var margin = HMARGIN * renderer.layerConfig.lineHeight;
if (2 * margin > renderer.$size.scrollerHeight)
margin = renderer.$size.scrollerHeight / 2;
if (renderer.scrollTop > top - margin) {
renderer.session.setScrollTop(top - margin);
}
if (renderer.scrollTop + renderer.$size.scrollerHeight < top + margin + renderer.lineHeight) {
renderer.session.setScrollTop(top + margin + renderer.lineHeight - renderer.$size.scrollerHeight);
}
};
var actions = exports.actions = {
"z": {
param: true,
fn: function(editor, range, count, param) {
switch (param) {
case "z":
editor.renderer.alignCursor(null, 0.5);
break;
case "t":
editor.renderer.alignCursor(null, 0);
break;
case "b":
editor.renderer.alignCursor(null, 1);
break;
case "c":
editor.session.onFoldWidgetClick(range.start.row, {domEvent:{target :{}}});
break;
case "o":
editor.session.onFoldWidgetClick(range.start.row, {domEvent:{target :{}}});
break;
case "C":
editor.session.foldAll();
break;
case "O":
editor.session.unfold();
break;
}
}
},
"r": {
param: true,
fn: function(editor, range, count, param) {
if (param && param.length) {
if (param.length > 1)
param = param == "return" ? "\n" : param == "tab" ? "\t" : param;
repeat(function() { editor.insert(param); }, count || 1);
editor.navigateLeft();
}
}
},
"R": {
fn: function(editor, range, count, param) {
util.insertMode(editor);
editor.setOverwrite(true);
}
},
"~": {
fn: function(editor, range, count) {
repeat(function() {
var range = editor.selection.getRange();
if (range.isEmpty())
range.end.column++;
var text = editor.session.getTextRange(range);
var toggled = text.toUpperCase();
if (toggled != text)
editor.session.replace(range, toggled);
else if (text.toLowerCase() != text)
editor.session.replace(range, text.toLowerCase())
else
editor.navigateRight();
}, count || 1);
}
},
"*": {
fn: function(editor, range, count, param) {
editor.selection.selectWord();
editor.findNext();
ensureScrollMargin(editor);
var r = editor.selection.getRange();
editor.selection.setSelectionRange(r, true);
}
},
"#": {
fn: function(editor, range, count, param) {
editor.selection.selectWord();
editor.findPrevious();
ensureScrollMargin(editor);
var r = editor.selection.getRange();
editor.selection.setSelectionRange(r, true);
}
},
"m": {
param: true,
fn: function(editor, range, count, param) {
var s = editor.session;
var markers = s.vimMarkers || (s.vimMarkers = {});
var c = editor.getCursorPosition();
if (!markers[param]) {
markers[param] = editor.session.doc.createAnchor(c);
}
markers[param].setPosition(c.row, c.column, true);
}
},
"n": {
fn: function(editor, range, count, param) {
var options = editor.getLastSearchOptions();
options.backwards = false;
options.start = null;
editor.selection.moveCursorRight();
editor.selection.clearSelection();
editor.findNext(options);
ensureScrollMargin(editor);
var r = editor.selection.getRange();
r.end.row = r.start.row;
r.end.column = r.start.column;
editor.selection.setSelectionRange(r, true);
}
},
"N": {
fn: function(editor, range, count, param) {
var options = editor.getLastSearchOptions();
options.backwards = true;
options.start = null;
editor.findPrevious(options);
ensureScrollMargin(editor);
var r = editor.selection.getRange();
r.end.row = r.start.row;
r.end.column = r.start.column;
editor.selection.setSelectionRange(r, true);
}
},
"v": {
fn: function(editor, range, count, param) {
editor.selection.selectRight();
util.visualMode(editor, false);
},
acceptsMotion: true
},
"V": {
fn: function(editor, range, count, param) {
var row = editor.getCursorPosition().row;
editor.selection.moveTo(row, 0);
editor.selection.selectLineEnd();
editor.selection.visualLineStart = row;
util.visualMode(editor, true);
},
acceptsMotion: true
},
"Y": {
fn: function(editor, range, count, param) {
util.copyLine(editor);
}
},
"p": {
fn: function(editor, range, count, param) {
var defaultReg = registers._default;
editor.setOverwrite(false);
if (defaultReg.isLine) {
var pos = editor.getCursorPosition();
pos.column = editor.session.getLine(pos.row).length;
var text = lang.stringRepeat("\n" + defaultReg.text, count || 1);
editor.session.insert(pos, text);
editor.moveCursorTo(pos.row + 1, 0);
}
else {
editor.navigateRight();
editor.insert(lang.stringRepeat(defaultReg.text, count || 1));
editor.navigateLeft();
}
editor.setOverwrite(true);
editor.selection.clearSelection();
}
},
"P": {
fn: function(editor, range, count, param) {
var defaultReg = registers._default;
editor.setOverwrite(false);
if (defaultReg.isLine) {
var pos = editor.getCursorPosition();
pos.column = 0;
var text = lang.stringRepeat(defaultReg.text + "\n", count || 1);
editor.session.insert(pos, text);
editor.moveCursorToPosition(pos);
}
else {
editor.insert(lang.stringRepeat(defaultReg.text, count || 1));
}
editor.setOverwrite(true);
editor.selection.clearSelection();
}
},
"J": {
fn: function(editor, range, count, param) {
var session = editor.session;
range = editor.getSelectionRange();
var pos = {row: range.start.row, column: range.start.column};
count = count || range.end.row - range.start.row;
var maxRow = Math.min(pos.row + (count || 1), session.getLength() - 1);
range.start.column = session.getLine(pos.row).length;
range.end.column = session.getLine(maxRow).length;
range.end.row = maxRow;
var text = "";
for (var i = pos.row; i < maxRow; i++) {
var nextLine = session.getLine(i + 1);
text += " " + /^\s*(.*)$/.exec(nextLine)[1] || "";
}
session.replace(range, text);
editor.moveCursorTo(pos.row, pos.column);
}
},
"u": {
fn: function(editor, range, count, param) {
count = parseInt(count || 1, 10);
for (var i = 0; i < count; i++) {
editor.undo();
}
editor.selection.clearSelection();
}
},
"ctrl-r": {
fn: function(editor, range, count, param) {
count = parseInt(count || 1, 10);
for (var i = 0; i < count; i++) {
editor.redo();
}
editor.selection.clearSelection();
}
},
":": {
fn: function(editor, range, count, param) {
var val = ":";
if (count > 1)
val = ".,.+" + count + val;
if (editor.showCommandLine)
editor.showCommandLine(val);
}
},
"/": {
fn: function(editor, range, count, param) {
if (editor.showCommandLine)
editor.showCommandLine("/");
}
},
"?": {
fn: function(editor, range, count, param) {
if (editor.showCommandLine)
editor.showCommandLine("?");
}
},
".": {
fn: function(editor, range, count, param) {
util.onInsertReplaySequence = inputBuffer.lastInsertCommands;
var previous = inputBuffer.previous;
if (previous) // If there is a previous action
inputBuffer.exec(editor, previous.action, previous.param);
}
},
"ctrl-x": {
fn: function(editor, range, count, param) {
editor.modifyNumber(-(count || 1));
}
},
"ctrl-a": {
fn: function(editor, range, count, param) {
editor.modifyNumber(count || 1);
}
}
};
var inputBuffer = exports.inputBuffer = {
accepting: [NUMBER, OPERATOR, MOTION, ACTION],
currentCmd: null,
currentCount: "",
pendingCount: "",
status: "",
operator: null,
motion: null,
lastInsertCommands: [],
push: function(editor, ch, keyId) {
var status = this.status;
var isKeyHandled = true;
this.idle = false;
var wObj = this.waitingForParam;
if (/^numpad\d+$/i.test(ch))
ch = ch.substr(6);
if (wObj) {
this.exec(editor, wObj, ch);
}
else if (!(ch === "0" && !this.currentCount.length) &&
(/^\d+$/.test(ch) && this.isAccepting(NUMBER))) {
this.currentCount += ch;
this.currentCmd = NUMBER;
this.accepting = [NUMBER, OPERATOR, MOTION, ACTION];
}
else if (!this.operator && this.isAccepting(OPERATOR) && operators[ch]) {
this.operator = {
ch: ch,
count: this.getCount()
};
this.currentCmd = OPERATOR;
this.accepting = [NUMBER, MOTION, ACTION];
this.exec(editor, { operator: this.operator });
}
else if (motions[ch] && this.isAccepting(MOTION)) {
this.currentCmd = MOTION;
var ctx = {
operator: this.operator,
motion: {
ch: ch,
count: this.getCount()
}
};
if (motions[ch].param)
this.waitForParam(ctx);
else
this.exec(editor, ctx);
}
else if (alias[ch] && this.isAccepting(MOTION)) {
alias[ch].operator.count = this.getCount();
this.exec(editor, alias[ch]);
}
else if (actions[ch] && this.isAccepting(ACTION)) {
var actionObj = {
action: {
fn: actions[ch].fn,
count: this.getCount()
}
};
if (actions[ch].param) {
this.waitForParam(actionObj);
}
else {
this.exec(editor, actionObj);
}
if (actions[ch].acceptsMotion)
this.idle = false;
}
else if (this.operator) {
this.operator.count = this.getCount();
this.exec(editor, { operator: this.operator }, ch);
}
else {
isKeyHandled = ch.length == 1;
this.reset();
}
if (this.waitingForParam || this.motion || this.operator) {
this.status += ch;
} else if (this.currentCount) {
this.status = this.currentCount;
} else if (this.status) {
this.status = "";
}
if (this.status != status)
editor._emit("changeStatus");
return isKeyHandled;
},
waitForParam: function(cmd) {
this.waitingForParam = cmd;
},
getCount: function() {
var count = this.currentCount || this.pendingCount;
this.currentCount = "";
this.pendingCount = count;
return count && parseInt(count, 10);
},
exec: function(editor, action, param) {
var m = action.motion;
var o = action.operator;
var a = action.action;
if (!param)
param = action.param;
if (o) {
this.previous = {
action: action,
param: param
};
}
if (o && !editor.selection.isEmpty()) {
if (operators[o.ch].selFn) {
operators[o.ch].selFn(editor, editor.getSelectionRange(), o.count, param);
this.reset();
}
return;
}
else if (!m && !a && o && param) {
operators[o.ch].fn(editor, null, o.count, param);
this.reset();
}
else if (m) {
var run = function(fn) {
if (fn && typeof fn === "function") { // There should always be a motion
if (m.count && !motionObj.handlesCount)
repeat(fn, m.count, [editor, null, m.count, param]);
else
fn(editor, null, m.count, param);
}
};
var motionObj = motions[m.ch];
var selectable = motionObj.sel;
if (!o) {
if ((util.onVisualMode || util.onVisualLineMode) && selectable)
run(motionObj.sel);
else
run(motionObj.nav);
}
else if (selectable) {
repeat(function() {
run(motionObj.sel);
operators[o.ch].fn(editor, editor.getSelectionRange(),
o.count, motionObj.param ? motionObj : param);
}, o.count || 1);
}
this.reset();
}
else if (a) {
a.fn(editor, editor.getSelectionRange(), a.count, param);
this.reset();
}
handleCursorMove(editor);
},
isAccepting: function(type) {
return this.accepting.indexOf(type) !== -1;
},
reset: function() {
this.operator = null;
this.motion = null;
this.currentCount = "";
this.pendingCount = "";
this.status = "";
this.accepting = [NUMBER, OPERATOR, MOTION, ACTION];
this.idle = true;
this.waitingForParam = null;
}
};
function setPreviousCommand(fn) {
inputBuffer.previous = { action: { action: { fn: fn } } };
}
exports.coreCommands = {
start: {
exec: function start(editor) {
util.insertMode(editor);
setPreviousCommand(start);
}
},
startBeginning: {
exec: function startBeginning(editor) {
editor.navigateLineStart();
util.insertMode(editor);
setPreviousCommand(startBeginning);
}
},
stop: {
exec: function stop(editor) {
inputBuffer.reset();
util.onVisualMode = false;
util.onVisualLineMode = false;
inputBuffer.lastInsertCommands = util.normalMode(editor);
}
},
append: {
exec: function append(editor) {
var pos = editor.getCursorPosition();
var lineLen = editor.session.getLine(pos.row).length;
if (lineLen)
editor.navigateRight();
util.insertMode(editor);
setPreviousCommand(append);
}
},
appendEnd: {
exec: function appendEnd(editor) {
editor.navigateLineEnd();
util.insertMode(editor);
setPreviousCommand(appendEnd);
}
}
};
var handleCursorMove = exports.onCursorMove = function(editor, e) {
if (util.currentMode === 'insert' || handleCursorMove.running)
return;
else if(!editor.selection.isEmpty()) {
handleCursorMove.running = true;
if (util.onVisualLineMode) {
var originRow = editor.selection.visualLineStart;
var cursorRow = editor.getCursorPosition().row;
if(originRow <= cursorRow) {
var endLine = editor.session.getLine(cursorRow);
editor.selection.moveTo(originRow, 0);
editor.selection.selectTo(cursorRow, endLine.length);
} else {
var endLine = editor.session.getLine(originRow);
editor.selection.moveTo(originRow, endLine.length);
editor.selection.selectTo(cursorRow, 0);
}
}
handleCursorMove.running = false;
return;
}
else {
if (e && (util.onVisualLineMode || util.onVisualMode)) {
editor.selection.clearSelection();
util.normalMode(editor);
}
handleCursorMove.running = true;
var pos = editor.getCursorPosition();
var lineLen = editor.session.getLine(pos.row).length;
if (lineLen && pos.column === lineLen)
editor.navigateLeft();
handleCursorMove.running = false;
}
};
});
define('ace/keyboard/vim/maps/util', ['require', 'exports', 'module' , 'ace/keyboard/vim/registers', 'ace/lib/dom'], function(require, exports, module) {
var registers = require("../registers");
var dom = require("../../../lib/dom");
dom.importCssString('.insert-mode .ace_cursor{\
border-left: 2px solid #333333;\
}\
.ace_dark.insert-mode .ace_cursor{\
border-left: 2px solid #eeeeee;\
}\
.normal-mode .ace_cursor{\
border: 0!important;\
background-color: red;\
opacity: 0.5;\
}', 'vimMode');
module.exports = {
onVisualMode: false,
onVisualLineMode: false,
currentMode: 'normal',
noMode: function(editor) {
editor.unsetStyle('insert-mode');
editor.unsetStyle('normal-mode');
if (editor.commands.recording)
editor.commands.toggleRecording(editor);
editor.setOverwrite(false);
},
insertMode: function(editor) {
this.currentMode = 'insert';
editor.setStyle('insert-mode');
editor.unsetStyle('normal-mode');
editor.setOverwrite(false);
editor.keyBinding.$data.buffer = "";
editor.keyBinding.$data.vimState = "insertMode";
this.onVisualMode = false;
this.onVisualLineMode = false;
if(this.onInsertReplaySequence) {
editor.commands.macro = this.onInsertReplaySequence;
editor.commands.replay(editor);
this.onInsertReplaySequence = null;
this.normalMode(editor);
} else {
editor._emit("changeStatus");
if(!editor.commands.recording)
editor.commands.toggleRecording(editor);
}
},
normalMode: function(editor) {
this.currentMode = 'normal';
editor.unsetStyle('insert-mode');
editor.setStyle('normal-mode');
editor.clearSelection();
var pos;
if (!editor.getOverwrite()) {
pos = editor.getCursorPosition();
if (pos.column > 0)
editor.navigateLeft();
}
editor.setOverwrite(true);
editor.keyBinding.$data.buffer = "";
editor.keyBinding.$data.vimState = "start";
this.onVisualMode = false;
this.onVisualLineMode = false;
editor._emit("changeStatus");
if (editor.commands.recording) {
editor.commands.toggleRecording(editor);
return editor.commands.macro;
}
else {
return [];
}
},
visualMode: function(editor, lineMode) {
if (
(this.onVisualLineMode && lineMode)
|| (this.onVisualMode && !lineMode)
) {
this.normalMode(editor);
return;
}
editor.setStyle('insert-mode');
editor.unsetStyle('normal-mode');
editor._emit("changeStatus");
if (lineMode) {
this.onVisualLineMode = true;
} else {
this.onVisualMode = true;
this.onVisualLineMode = false;
}
},
getRightNthChar: function(editor, cursor, ch, n) {
var line = editor.getSession().getLine(cursor.row);
var matches = line.substr(cursor.column + 1).split(ch);
return n < matches.length ? matches.slice(0, n).join(ch).length : null;
},
getLeftNthChar: function(editor, cursor, ch, n) {
var line = editor.getSession().getLine(cursor.row);
var matches = line.substr(0, cursor.column).split(ch);
return n < matches.length ? matches.slice(-1 * n).join(ch).length : null;
},
toRealChar: function(ch) {
if (ch.length === 1)
return ch;
if (/^shift-./.test(ch))
return ch[ch.length - 1].toUpperCase();
else
return "";
},
copyLine: function(editor) {
var pos = editor.getCursorPosition();
editor.selection.moveTo(pos.row, pos.column);
editor.selection.selectLine();
registers._default.isLine = true;
registers._default.text = editor.getCopyText().replace(/\n$/, "");
editor.selection.moveTo(pos.row, pos.column);
}
};
});
define('ace/keyboard/vim/registers', ['require', 'exports', 'module' ], function(require, exports, module) {
"never use strict";
module.exports = {
_default: {
text: "",
isLine: false
}
};
});
define('kitchen-sink/util', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/event', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/editor', 'ace/multi_select'], function(require, exports, module) {
var dom = require("ace/lib/dom");
var event = require("ace/lib/event");
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
var Editor = require("ace/editor").Editor;
var MultiSelect = require("ace/multi_select").MultiSelect;
exports.createEditor = function(el) {
return new Editor(new Renderer(el));
};
exports.createSplitEditor = function(el) {
if (typeof(el) == "string")
el = document.getElementById(el);
var e0 = document.createElement("div");
var s = document.createElement("splitter");
var e1 = document.createElement("div");
el.appendChild(e0);
el.appendChild(e1);
el.appendChild(s);
e0.style.position = e1.style.position = s.style.position = "absolute";
el.style.position = "relative";
var split = {$container: el};
split.editor0 = split[0] = new Editor(new Renderer(e0));
split.editor1 = split[1] = new Editor(new Renderer(e1));
split.splitter = s;
s.ratio = 0.5;
split.resize = function resize(){
var height = el.parentNode.clientHeight - el.offsetTop;
var total = el.clientWidth;
var w1 = total * s.ratio;
var w2 = total * (1- s.ratio);
s.style.left = w1 - 1 + "px";
s.style.height = el.style.height = height + "px";
var st0 = split[0].container.style;
var st1 = split[1].container.style;
st0.width = w1 + "px";
st1.width = w2 + "px";
st0.left = 0 + "px";
st1.left = w1 + "px";
st0.top = st1.top = "0px";
st0.height = st1.height = height + "px";
split[0].resize();
split[1].resize();
};
split.onMouseDown = function(e) {
var rect = el.getBoundingClientRect();
var x = e.clientX;
var y = e.clientY;
var button = e.button;
if (button !== 0) {
return;
}
var onMouseMove = function(e) {
x = e.clientX;
y = e.clientY;
};
var onResizeEnd = function(e) {
clearInterval(timerId);
};
var onResizeInterval = function() {
s.ratio = (x - rect.left) / rect.width;
split.resize();
};
event.capture(s, onMouseMove, onResizeEnd);
var timerId = setInterval(onResizeInterval, 40);
return e.preventDefault();
};
event.addListener(s, "mousedown", split.onMouseDown);
event.addListener(window, "resize", split.resize);
split.resize();
return split;
};
exports.stripLeadingComments = function(str) {
if(str.slice(0,2)=='/*') {
var j = str.indexOf('*/')+2;
str = str.substr(j);
}
return str.trim() + "\n";
};
exports.saveOption = function(el, val) {
if (!el.onchange && !el.onclick)
return;
if ("checked" in el) {
if (val !== undefined)
el.checked = val;
localStorage && localStorage.setItem(el.id, el.checked ? 1 : 0);
}
else {
if (val !== undefined)
el.value = val;
localStorage && localStorage.setItem(el.id, el.value);
}
};
exports.bindCheckbox = function(id, callback, noInit) {
if (typeof id == "string")
var el = document.getElementById(id);
else {
var el = id;
id = el.id;
}
var el = document.getElementById(id);
if (localStorage && localStorage.getItem(id))
el.checked = localStorage.getItem(id) == "1";
var onCheck = function() {
callback(!!el.checked);
exports.saveOption(el);
};
el.onclick = onCheck;
noInit || onCheck();
return el;
};
exports.bindDropdown = function(id, callback, noInit) {
if (typeof id == "string")
var el = document.getElementById(id);
else {
var el = id;
id = el.id;
}
if (localStorage && localStorage.getItem(id))
el.value = localStorage.getItem(id);
var onChange = function() {
callback(el.value);
exports.saveOption(el);
};
el.onchange = onChange;
noInit || onChange();
};
exports.fillDropdown = function(el, values) {
if (typeof el == "string")
el = document.getElementById(el);
dropdown(values).forEach(function(e) {
el.appendChild(e);
});
};
function elt(tag, attributes, content) {
var el = dom.createElement(tag);
if (typeof content == "string") {
el.appendChild(document.createTextNode(content));
} else if (content) {
content.forEach(function(ch) {
el.appendChild(ch);
});
}
for (var i in attributes)
el.setAttribute(i, attributes[i]);
return el;
}
function optgroup(values) {
return values.map(function(item) {
if (typeof item == "string")
item = {name: item, caption: item};
return elt("option", {value: item.value || item.name}, item.caption || item.desc);
});
}
function dropdown(values) {
if (Array.isArray(values))
return optgroup(values);
return Object.keys(values).map(function(i) {
return elt("optgroup", {"label": i}, optgroup(values[i]));
});
}
});
define('ace/keyboard/vim/maps/motions', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/search', 'ace/range'], function(require, exports, module) {
var util = require("./util");
var keepScrollPosition = function(editor, fn) {
var scrollTopRow = editor.renderer.getScrollTopRow();
var initialRow = editor.getCursorPosition().row;
var diff = initialRow - scrollTopRow;
fn && fn.call(editor);
editor.renderer.scrollToRow(editor.getCursorPosition().row - diff);
};
function Motion(m) {
if (typeof m == "function") {
var getPos = m;
m = this;
} else {
var getPos = m.getPos;
}
m.nav = function(editor, range, count, param) {
var a = getPos(editor, range, count, param, false);
if (!a)
return;
editor.selection.moveTo(a.row, a.column);
};
m.sel = function(editor, range, count, param) {
var a = getPos(editor, range, count, param, true);
if (!a)
return;
editor.selection.selectTo(a.row, a.column);
};
return m;
}
var nonWordRe = /[\s.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/;
var wordSeparatorRe = /[.\/\\()\"'-:,.;<>~!@#$%^&*|+=\[\]{}`~?]/;
var whiteRe = /\s/;
var StringStream = function(editor, cursor) {
var sel = editor.selection;
this.range = sel.getRange();
cursor = cursor || sel.selectionLead;
this.row = cursor.row;
this.col = cursor.column;
var line = editor.session.getLine(this.row);
var maxRow = editor.session.getLength();
this.ch = line[this.col] || '\n';
this.skippedLines = 0;
this.next = function() {
this.ch = line[++this.col] || this.handleNewLine(1);
return this.ch;
};
this.prev = function() {
this.ch = line[--this.col] || this.handleNewLine(-1);
return this.ch;
};
this.peek = function(dir) {
var ch = line[this.col + dir];
if (ch)
return ch;
if (dir == -1)
return '\n';
if (this.col == line.length - 1)
return '\n';
return editor.session.getLine(this.row + 1)[0] || '\n';
};
this.handleNewLine = function(dir) {
if (dir == 1){
if (this.col == line.length)
return '\n';
if (this.row == maxRow - 1)
return '';
this.col = 0;
this.row ++;
line = editor.session.getLine(this.row);
this.skippedLines++;
return line[0] || '\n';
}
if (dir == -1) {
if (this.row === 0)
return '';
this.row --;
line = editor.session.getLine(this.row);
this.col = line.length;
this.skippedLines--;
return '\n';
}
};
this.debug = function() {
console.log(line.substring(0, this.col)+'|'+this.ch+'\''+this.col+'\''+line.substr(this.col+1));
};
};
var Search = require("../../../search").Search;
var search = new Search();
function find(editor, needle, dir) {
search.$options.needle = needle;
search.$options.backwards = dir == -1;
return search.find(editor.session);
}
var Range = require("../../../range").Range;
var LAST_SEARCH_MOTION = {};
module.exports = {
"w": new Motion(function(editor) {
var str = new StringStream(editor);
if (str.ch && wordSeparatorRe.test(str.ch)) {
while (str.ch && wordSeparatorRe.test(str.ch))
str.next();
} else {
while (str.ch && !nonWordRe.test(str.ch))
str.next();
}
while (str.ch && whiteRe.test(str.ch) && str.skippedLines < 2)
str.next();
str.skippedLines == 2 && str.prev();
return {column: str.col, row: str.row};
}),
"W": new Motion(function(editor) {
var str = new StringStream(editor);
while(str.ch && !(whiteRe.test(str.ch) && !whiteRe.test(str.peek(1))) && str.skippedLines < 2)
str.next();
if (str.skippedLines == 2)
str.prev();
else
str.next();
return {column: str.col, row: str.row};
}),
"b": new Motion(function(editor) {
var str = new StringStream(editor);
str.prev();
while (str.ch && whiteRe.test(str.ch) && str.skippedLines > -2)
str.prev();
if (str.ch && wordSeparatorRe.test(str.ch)) {
while (str.ch && wordSeparatorRe.test(str.ch))
str.prev();
} else {
while (str.ch && !nonWordRe.test(str.ch))
str.prev();
}
str.ch && str.next();
return {column: str.col, row: str.row};
}),
"B": new Motion(function(editor) {
var str = new StringStream(editor);
str.prev();
while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(-1))) && str.skippedLines > -2)
str.prev();
if (str.skippedLines == -2)
str.next();
return {column: str.col, row: str.row};
}),
"e": new Motion(function(editor) {
var str = new StringStream(editor);
str.next();
while (str.ch && whiteRe.test(str.ch))
str.next();
if (str.ch && wordSeparatorRe.test(str.ch)) {
while (str.ch && wordSeparatorRe.test(str.ch))
str.next();
} else {
while (str.ch && !nonWordRe.test(str.ch))
str.next();
}
str.ch && str.prev();
return {column: str.col, row: str.row};
}),
"E": new Motion(function(editor) {
var str = new StringStream(editor);
str.next();
while(str.ch && !(!whiteRe.test(str.ch) && whiteRe.test(str.peek(1))))
str.next();
return {column: str.col, row: str.row};
}),
"l": {
nav: function(editor) {
var pos = editor.getCursorPosition();
var col = pos.column;
var lineLen = editor.session.getLine(pos.row).length;
if (lineLen && col !== lineLen)
editor.navigateRight();
},
sel: function(editor) {
var pos = editor.getCursorPosition();
var col = pos.column;
var lineLen = editor.session.getLine(pos.row).length;
if (lineLen && col !== lineLen) //In selection mode you can select the newline
editor.selection.selectRight();
}
},
"h": {
nav: function(editor) {
var pos = editor.getCursorPosition();
if (pos.column > 0)
editor.navigateLeft();
},
sel: function(editor) {
var pos = editor.getCursorPosition();
if (pos.column > 0)
editor.selection.selectLeft();
}
},
"H": {
nav: function(editor) {
var row = editor.renderer.getScrollTopRow();
editor.moveCursorTo(row);
},
sel: function(editor) {
var row = editor.renderer.getScrollTopRow();
editor.selection.selectTo(row);
}
},
"M": {
nav: function(editor) {
var topRow = editor.renderer.getScrollTopRow();
var bottomRow = editor.renderer.getScrollBottomRow();
var row = topRow + ((bottomRow - topRow) / 2);
editor.moveCursorTo(row);
},
sel: function(editor) {
var topRow = editor.renderer.getScrollTopRow();
var bottomRow = editor.renderer.getScrollBottomRow();
var row = topRow + ((bottomRow - topRow) / 2);
editor.selection.selectTo(row);
}
},
"L": {
nav: function(editor) {
var row = editor.renderer.getScrollBottomRow();
editor.moveCursorTo(row);
},
sel: function(editor) {
var row = editor.renderer.getScrollBottomRow();
editor.selection.selectTo(row);
}
},
"k": {
nav: function(editor) {
editor.navigateUp();
},
sel: function(editor) {
editor.selection.selectUp();
}
},
"j": {
nav: function(editor) {
editor.navigateDown();
},
sel: function(editor) {
editor.selection.selectDown();
}
},
"i": {
param: true,
sel: function(editor, range, count, param) {
switch (param) {
case "w":
editor.selection.selectWord();
break;
case "W":
editor.selection.selectAWord();
break;
case "(":
case "{":
case "[":
var cursor = editor.getCursorPosition();
var end = editor.session.$findClosingBracket(param, cursor, /paren/);
if (!end)
return;
var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/);
if (!start)
return;
start.column ++;
editor.selection.setSelectionRange(Range.fromPoints(start, end));
break;
case "'":
case '"':
case "/":
var end = find(editor, param, 1);
if (!end)
return;
var start = find(editor, param, -1);
if (!start)
return;
editor.selection.setSelectionRange(Range.fromPoints(start.end, end.start));
break;
}
}
},
"a": {
param: true,
sel: function(editor, range, count, param) {
switch (param) {
case "w":
editor.selection.selectAWord();
break;
case "W":
editor.selection.selectAWord();
break;
case ")":
case "}":
case "]":
param = editor.session.$brackets[param];
case "(":
case "{":
case "[":
var cursor = editor.getCursorPosition();
var end = editor.session.$findClosingBracket(param, cursor, /paren/);
if (!end)
return;
var start = editor.session.$findOpeningBracket(editor.session.$brackets[param], cursor, /paren/);
if (!start)
return;
end.column ++;
editor.selection.setSelectionRange(Range.fromPoints(start, end));
break;
case "'":
case "\"":
case "/":
var end = find(editor, param, 1);
if (!end)
return;
var start = find(editor, param, -1);
if (!start)
return;
end.column ++;
editor.selection.setSelectionRange(Range.fromPoints(start.start, end.end));
break;
}
}
},
"f": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel, isRepeat) {
if (param == "space") param = " ";
if (!isRepeat)
LAST_SEARCH_MOTION = {ch: "f", param: param};
var cursor = editor.getCursorPosition();
var column = util.getRightNthChar(editor, cursor, param, count || 1);
if (typeof column === "number") {
cursor.column += column + (isSel ? 2 : 1);
return cursor;
}
}
}),
"F": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel, isRepeat) {
if (param == "space") param = " ";
if (!isRepeat)
LAST_SEARCH_MOTION = {ch: "F", param: param};
var cursor = editor.getCursorPosition();
var column = util.getLeftNthChar(editor, cursor, param, count || 1);
if (typeof column === "number") {
cursor.column -= column + 1;
return cursor;
}
}
}),
"t": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel, isRepeat) {
if (param == "space") param = " ";
if (!isRepeat)
LAST_SEARCH_MOTION = {ch: "t", param: param};
var cursor = editor.getCursorPosition();
var column = util.getRightNthChar(editor, cursor, param, count || 1);
if (isRepeat && column == 0 && !(count > 1))
var column = util.getRightNthChar(editor, cursor, param, 2);
if (typeof column === "number") {
cursor.column += column + (isSel ? 1 : 0);
return cursor;
}
}
}),
"T": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel, isRepeat) {
if (param == "space") param = " ";
if (!isRepeat)
LAST_SEARCH_MOTION = {ch: "T", param: param};
var cursor = editor.getCursorPosition();
var column = util.getLeftNthChar(editor, cursor, param, count || 1);
if (isRepeat && column == 0 && !(count > 1))
var column = util.getLeftNthChar(editor, cursor, param, 2);
if (typeof column === "number") {
cursor.column -= column;
return cursor;
}
}
}),
";": new Motion({
handlesCount: true,
getPos: function(editor, range, count, param, isSel) {
var ch = LAST_SEARCH_MOTION.ch;
if (!ch)
return;
return module.exports[ch].getPos(
editor, range, count, LAST_SEARCH_MOTION.param, isSel, true
);
}
}),
",": new Motion({
handlesCount: true,
getPos: function(editor, range, count, param, isSel) {
var ch = LAST_SEARCH_MOTION.ch;
if (!ch)
return;
var up = ch.toUpperCase();
ch = ch === up ? ch.toLowerCase() : up;
return module.exports[ch].getPos(
editor, range, count, LAST_SEARCH_MOTION.param, isSel, true
);
}
}),
"^": {
nav: function(editor) {
editor.navigateLineStart();
},
sel: function(editor) {
editor.selection.selectLineStart();
}
},
"$": {
handlesCount: true,
nav: function(editor, range, count, param) {
if (count > 1) {
editor.navigateDown(count-1);
}
editor.navigateLineEnd();
},
sel: function(editor, range, count, param) {
if (count > 1) {
editor.selection.moveCursorBy(count-1, 0);
}
editor.selection.selectLineEnd();
}
},
"0": new Motion(function(ed) {
return {row: ed.selection.lead.row, column: 0};
}),
"G": {
nav: function(editor, range, count, param) {
if (!count && count !== 0) { // Stupid JS
count = editor.session.getLength();
}
editor.gotoLine(count);
},
sel: function(editor, range, count, param) {
if (!count && count !== 0) { // Stupid JS
count = editor.session.getLength();
}
editor.selection.selectTo(count, 0);
}
},
"g": {
param: true,
nav: function(editor, range, count, param) {
switch(param) {
case "m":
console.log("Middle line");
break;
case "e":
console.log("End of prev word");
break;
case "g":
editor.gotoLine(count || 0);
case "u":
editor.gotoLine(count || 0);
case "U":
editor.gotoLine(count || 0);
}
},
sel: function(editor, range, count, param) {
switch(param) {
case "m":
console.log("Middle line");
break;
case "e":
console.log("End of prev word");
break;
case "g":
editor.selection.selectTo(count || 0, 0);
}
}
},
"o": {
nav: function(editor, range, count, param) {
count = count || 1;
var content = "";
while (0 < count--)
content += "\n";
if (content.length) {
editor.navigateLineEnd()
editor.insert(content);
util.insertMode(editor);
}
}
},
"O": {
nav: function(editor, range, count, param) {
var row = editor.getCursorPosition().row;
count = count || 1;
var content = "";
while (0 < count--)
content += "\n";
if (content.length) {
if(row > 0) {
editor.navigateUp();
editor.navigateLineEnd()
editor.insert(content);
} else {
editor.session.insert({row: 0, column: 0}, content);
editor.navigateUp();
}
util.insertMode(editor);
}
}
},
"%": new Motion(function(editor){
var brRe = /[\[\]{}()]/g;
var cursor = editor.getCursorPosition();
var ch = editor.session.getLine(cursor.row)[cursor.column];
if (!brRe.test(ch)) {
var range = find(editor, brRe);
if (!range)
return;
cursor = range.start;
}
var match = editor.session.findMatchingBracket({
row: cursor.row,
column: cursor.column + 1
});
return match;
}),
"{": new Motion(function(ed) {
var session = ed.session;
var row = session.selection.lead.row;
while(row > 0 && !/\S/.test(session.getLine(row)))
row--;
while(/\S/.test(session.getLine(row)))
row--;
return {column: 0, row: row};
}),
"}": new Motion(function(ed) {
var session = ed.session;
var l = session.getLength();
var row = session.selection.lead.row;
while(row < l && !/\S/.test(session.getLine(row)))
row++;
while(/\S/.test(session.getLine(row)))
row++;
return {column: 0, row: row};
}),
"ctrl-d": {
nav: function(editor, range, count, param) {
editor.selection.clearSelection();
keepScrollPosition(editor, editor.gotoPageDown);
},
sel: function(editor, range, count, param) {
keepScrollPosition(editor, editor.selectPageDown);
}
},
"ctrl-u": {
nav: function(editor, range, count, param) {
editor.selection.clearSelection();
keepScrollPosition(editor, editor.gotoPageUp);
},
sel: function(editor, range, count, param) {
keepScrollPosition(editor, editor.selectPageUp);
}
},
"`": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel) {
var s = editor.session;
var marker = s.vimMarkers && s.vimMarkers[param];
if (marker) {
return marker.getPosition();
}
}
}),
"'": new Motion({
param: true,
handlesCount: true,
getPos: function(editor, range, count, param, isSel) {
var s = editor.session;
var marker = s.vimMarkers && s.vimMarkers[param];
if (marker) {
var pos = marker.getPosition();
var line = editor.session.getLine(pos.row);
pos.column = line.search(/\S/);
if (pos.column == -1)
pos.column = line.length;
return pos;
}
},
isLine: true
})
};
module.exports.backspace = module.exports.left = module.exports.h;
module.exports.space = module.exports['return'] = module.exports.right = module.exports.l;
module.exports.up = module.exports.k;
module.exports.down = module.exports.j;
module.exports.pagedown = module.exports["ctrl-d"];
module.exports.pageup = module.exports["ctrl-u"];
module.exports.home = module.exports["0"];
module.exports.end = module.exports["$"];
});
define('kitchen-sink/token_tooltip', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/oop', 'ace/lib/event', 'ace/range', 'ace/tooltip'], function(require, exports, module) {
var dom = require("ace/lib/dom");
var oop = require("ace/lib/oop");
var event = require("ace/lib/event");
var Range = require("ace/range").Range;
var Tooltip = require("ace/tooltip").Tooltip;
function TokenTooltip (editor) {
if (editor.tokenTooltip)
return;
Tooltip.call(this, editor.container);
editor.tokenTooltip = this;
this.editor = editor;
this.update = this.update.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onMouseOut = this.onMouseOut.bind(this);
event.addListener(editor.renderer.scroller, "mousemove", this.onMouseMove);
event.addListener(editor.renderer.content, "mouseout", this.onMouseOut);
}
oop.inherits(TokenTooltip, Tooltip);
(function(){
this.token = {};
this.range = new Range();
this.update = function() {
this.$timer = null;
var r = this.editor.renderer;
if (this.lastT - (r.timeStamp || 0) > 1000) {
r.rect = null;
r.timeStamp = this.lastT;
this.maxHeight = window.innerHeight;
this.maxWidth = window.innerWidth;
}
var canvasPos = r.rect || (r.rect = r.scroller.getBoundingClientRect());
var offset = (this.x + r.scrollLeft - canvasPos.left - r.$padding) / r.characterWidth;
var row = Math.floor((this.y + r.scrollTop - canvasPos.top) / r.lineHeight);
var col = Math.round(offset);
var screenPos = {row: row, column: col, side: offset - col > 0 ? 1 : -1};
var session = this.editor.session;
var docPos = session.screenToDocumentPosition(screenPos.row, screenPos.column);
var token = session.getTokenAt(docPos.row, docPos.column);
if (!token && !session.getLine(docPos.row)) {
token = {
type: "",
value: "",
state: session.bgTokenizer.getState(0)
};
}
if (!token) {
session.removeMarker(this.marker);
this.hide();
return;
}
var tokenText = token.type;
if (token.state)
tokenText += "|" + token.state;
if (token.merge)
tokenText += "\n merge";
if (token.stateTransitions)
tokenText += "\n " + token.stateTransitions.join("\n ");
if (this.tokenText != tokenText) {
this.setText(tokenText);
this.width = this.getWidth();
this.height = this.getHeight();
this.tokenText = tokenText;
}
this.show(null, this.x, this.y);
this.token = token;
session.removeMarker(this.marker);
this.range = new Range(docPos.row, token.start, docPos.row, token.start + token.value.length);
this.marker = session.addMarker(this.range, "ace_bracket", "text");
};
this.onMouseMove = function(e) {
this.x = e.clientX;
this.y = e.clientY;
if (this.isOpen) {
this.lastT = e.timeStamp;
this.setPosition(this.x, this.y);
}
if (!this.$timer)
this.$timer = setTimeout(this.update, 100);
};
this.onMouseOut = function(e) {
if (e && e.currentTarget.contains(e.relatedTarget))
return;
this.hide();
this.editor.session.removeMarker(this.marker);
this.$timer = clearTimeout(this.$timer);
};
this.setPosition = function(x, y) {
if (x + 10 + this.width > this.maxWidth)
x = window.innerWidth - this.width - 10;
if (y > window.innerHeight * 0.75 || y + 20 + this.height > this.maxHeight)
y = y - this.height - 30;
Tooltip.prototype.setPosition.call(this, x + 10, y + 20);
};
this.destroy = function() {
this.onMouseOut();
event.removeListener(this.editor.renderer.scroller, "mousemove", this.onMouseMove);
event.removeListener(this.editor.renderer.content, "mouseout", this.onMouseOut);
delete this.editor.tokenTooltip;
};
}).call(TokenTooltip.prototype);
exports.TokenTooltip = TokenTooltip;
});
define('ace/keyboard/vim/maps/operators', ['require', 'exports', 'module' , 'ace/keyboard/vim/maps/util', 'ace/keyboard/vim/registers'], function(require, exports, module) {
var util = require("./util");
var registers = require("../registers");
module.exports = {
"d": {
selFn: function(editor, range, count, param) {
registers._default.text = editor.getCopyText();
registers._default.isLine = util.onVisualLineMode;
if(util.onVisualLineMode)
editor.removeLines();
else
editor.session.remove(range);
util.normalMode(editor);
},
fn: function(editor, range, count, param) {
count = count || 1;
switch (param) {
case "d":
registers._default.text = "";
registers._default.isLine = true;
for (var i = 0; i < count; i++) {
editor.selection.selectLine();
registers._default.text += editor.getCopyText();
var selRange = editor.getSelectionRange();
if (!selRange.isMultiLine()) {
var row = selRange.start.row - 1;
var col = editor.session.getLine(row).length
selRange.setStart(row, col);
editor.session.remove(selRange);
editor.selection.clearSelection();
break;
}
editor.session.remove(selRange);
editor.selection.clearSelection();
}
registers._default.text = registers._default.text.replace(/\n$/, "");
break;
default:
if (range) {
editor.selection.setSelectionRange(range);
registers._default.text = editor.getCopyText();
registers._default.isLine = false;
editor.session.remove(range);
editor.selection.clearSelection();
}
}
}
},
"c": {
selFn: function(editor, range, count, param) {
editor.session.remove(range);
util.insertMode(editor);
},
fn: function(editor, range, count, param) {
count = count || 1;
switch (param) {
case "c":
for (var i = 0; i < count; i++) {
editor.removeLines();
util.insertMode(editor);
}
break;
default:
if (range) {
editor.session.remove(range);
util.insertMode(editor);
}
}
}
},
"y": {
selFn: function(editor, range, count, param) {
registers._default.text = editor.getCopyText();
registers._default.isLine = util.onVisualLineMode;
editor.selection.clearSelection();
util.normalMode(editor);
},
fn: function(editor, range, count, param) {
count = count || 1;
if (param && param.isLine)
param = "y";
switch (param) {
case "y":
var pos = editor.getCursorPosition();
editor.selection.selectLine();
for (var i = 0; i < count - 1; i++) {
editor.selection.moveCursorDown();
}
registers._default.text = editor.getCopyText().replace(/\n$/, "");
editor.selection.clearSelection();
registers._default.isLine = true;
editor.moveCursorToPosition(pos);
break;
default:
if (range) {
var pos = editor.getCursorPosition();
editor.selection.setSelectionRange(range);
registers._default.text = editor.getCopyText();
registers._default.isLine = false;
editor.selection.clearSelection();
editor.moveCursorTo(pos.row, pos.column);
}
}
}
},
">": {
selFn: function(editor, range, count, param) {
count = count || 1;
for (var i = 0; i < count; i++) {
editor.indent();
}
util.normalMode(editor);
},
fn: function(editor, range, count, param) {
count = parseInt(count || 1, 10);
switch (param) {
case ">":
var pos = editor.getCursorPosition();
editor.selection.selectLine();
for (var i = 0; i < count - 1; i++) {
editor.selection.moveCursorDown();
}
editor.indent();
editor.selection.clearSelection();
editor.moveCursorToPosition(pos);
editor.navigateLineEnd();
editor.navigateLineStart();
break;
}
}
},
"<": {
selFn: function(editor, range, count, param) {
count = count || 1;
for (var i = 0; i < count; i++) {
editor.blockOutdent();
}
util.normalMode(editor);
},
fn: function(editor, range, count, param) {
count = count || 1;
switch (param) {
case "<":
var pos = editor.getCursorPosition();
editor.selection.selectLine();
for (var i = 0; i < count - 1; i++) {
editor.selection.moveCursorDown();
}
editor.blockOutdent();
editor.selection.clearSelection();
editor.moveCursorToPosition(pos);
editor.navigateLineEnd();
editor.navigateLineStart();
break;
}
}
}
};
});
define('kitchen-sink/layout', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/event', 'ace/edit_session', 'ace/undomanager', 'ace/virtual_renderer', 'ace/editor', 'ace/multi_select', 'ace/theme/textmate'], function(require, exports, module) {
var dom = require("ace/lib/dom");
var event = require("ace/lib/event");
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
var Editor = require("ace/editor").Editor;
var MultiSelect = require("ace/multi_select").MultiSelect;
dom.importCssString("\
splitter {\
border: 1px solid #C6C6D2;\
width: 0px;\
cursor: ew-resize;\
z-index:10}\
splitter:hover {\
margin-left: -2px;\
width:3px;\
border-color: #B5B4E0;\
}\
", "splitEditor");
exports.edit = function(el) {
if (typeof(el) == "string")
el = document.getElementById(el);
var editor = new Editor(new Renderer(el, require("ace/theme/textmate")));
editor.resize();
event.addListener(window, "resize", function() {
editor.resize();
});
return editor;
};
var SplitRoot = function(el, theme, position, getSize) {
el.style.position = position || "relative";
this.container = el;
this.getSize = getSize || this.getSize;
this.resize = this.$resize.bind(this);
event.addListener(el.ownerDocument.defaultView, "resize", this.resize);
this.editor = this.createEditor();
};
(function(){
this.createEditor = function() {
var el = document.createElement("div");
el.className = this.$editorCSS;
el.style.cssText = "position: absolute; top:0px; bottom:0px";
this.$container.appendChild(el);
var session = new EditSession("");
var editor = new Editor(new Renderer(el, this.$theme));
this.$editors.push(editor);
editor.setFontSize(this.$fontSize);
return editor;
};
this.$resize = function() {
var size = this.getSize(this.container);
this.rect = {
x: size.left,
y: size.top,
w: size.width,
h: size.height
};
this.item.resize(this.rect);
};
this.getSize = function(el) {
return el.getBoundingClientRect();
};
this.destroy = function() {
var win = this.container.ownerDocument.defaultView;
event.removeListener(win, "resize", this.resize);
};
}).call(SplitRoot.prototype);
var Split = function(){
};
(function(){
this.execute = function(options) {
this.$u.execute(options);
};
}).call(Split.prototype);
exports.singleLineEditor = function(el) {
var renderer = new Renderer(el);
el.style.overflow = "hidden";
renderer.screenToTextCoordinates = function(x, y) {
var pos = this.pixelToScreenCoordinates(x, y);
return this.session.screenToDocumentPosition(
Math.min(this.session.getScreenLength() - 1, Math.max(pos.row, 0)),
Math.max(pos.column, 0)
);
};
renderer.$maxLines = 4;
renderer.setStyle("ace_one-line");
var editor = new Editor(renderer);
new MultiSelect(editor);
editor.session.setUndoManager(new UndoManager());
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(false);
editor.renderer.setHighlightGutterLine(false);
editor.$mouseHandler.$focusWaitTimout = 0;
return editor;
};
});
"use strict"
define('ace/keyboard/vim/maps/aliases', ['require', 'exports', 'module' ], function(require, exports, module) {
module.exports = {
"x": {
operator: {
ch: "d",
count: 1
},
motion: {
ch: "l",
count: 1
}
},
"X": {
operator: {
ch: "d",
count: 1
},
motion: {
ch: "h",
count: 1
}
},
"D": {
operator: {
ch: "d",
count: 1
},
motion: {
ch: "$",
count: 1
}
},
"C": {
operator: {
ch: "c",
count: 1
},
motion: {
ch: "$",
count: 1
}
},
"s": {
operator: {
ch: "c",
count: 1
},
motion: {
ch: "l",
count: 1
}
},
"S": {
operator: {
ch: "c",
count: 1
},
param: "c"
}
};
});
define('ace/ext/themelist', ['require', 'exports', 'module' , 'ace/lib/fixoldbrowsers'], function(require, exports, module) {
require("ace/lib/fixoldbrowsers");
var themeData = [
["Chrome" ],
["Clouds" ],
["Crimson Editor" ],
["Dawn" ],
["Dreamweaver" ],
["Eclipse" ],
["GitHub" ],
["Solarized Light"],
["TextMate" ],
["Tomorrow" ],
["XCode" ],
["Kuroir"],
["KatzenMilch"],
["Ambiance" ,"ambiance" , "dark"],
["Chaos" ,"chaos" , "dark"],
["Clouds Midnight" ,"clouds_midnight" , "dark"],
["Cobalt" ,"cobalt" , "dark"],
["idle Fingers" ,"idle_fingers" , "dark"],
["krTheme" ,"kr_theme" , "dark"],
["Merbivore" ,"merbivore" , "dark"],
["Merbivore Soft" ,"merbivore_soft" , "dark"],
["Mono Industrial" ,"mono_industrial" , "dark"],
["Monokai" ,"monokai" , "dark"],
["Pastel on dark" ,"pastel_on_dark" , "dark"],
["Solarized Dark" ,"solarized_dark" , "dark"],
["Terminal" ,"terminal" , "dark"],
["Tomorrow Night" ,"tomorrow_night" , "dark"],
["Tomorrow Night Blue" ,"tomorrow_night_blue" , "dark"],
["Tomorrow Night Bright","tomorrow_night_bright" , "dark"],
["Tomorrow Night 80s" ,"tomorrow_night_eighties" , "dark"],
["Twilight" ,"twilight" , "dark"],
["Vibrant Ink" ,"vibrant_ink" , "dark"]
];
exports.themesByName = {};
exports.themes = themeData.map(function(data) {
var name = data[1] || data[0].replace(/ /g, "_").toLowerCase();
var theme = {
caption: data[0],
theme: "ace/theme/" + name,
isDark: data[2] == "dark",
name: name
};
exports.themesByName[name] = theme;
return theme;
});
});
define('ace/ext/statusbar', ['require', 'exports', 'module' , 'ace/lib/dom', 'ace/lib/lang'], function(require, exports, module) {
var dom = require("ace/lib/dom");
var lang = require("ace/lib/lang");
var StatusBar = function(editor, parentNode) {
this.element = dom.createElement("div");
this.element.className = "ace_status-indicator";
this.element.style.cssText = "display: inline-block;";
parentNode.appendChild(this.element);
var statusUpdate = lang.delayedCall(function(){
this.updateStatus(editor)
}.bind(this));
editor.on("changeStatus", function() {
statusUpdate.schedule(100);
});
editor.on("changeSelection", function() {
statusUpdate.schedule(100);
});
};
(function(){
this.updateStatus = function(editor) {
var status = [];
function add(str, separator) {
str && status.push(str, separator || "|");
}
if (editor.$vimModeHandler)
add(editor.$vimModeHandler.getStatusText());
else if (editor.commands.recording)
add("REC");
var c = editor.selection.lead;
add(c.row + ":" + c.column, " ");
if (!editor.selection.isEmpty()) {
var r = editor.getSelectionRange();
add("(" + (r.end.row - r.start.row) + ":" +(r.end.column - r.start.column) + ")");
}
status.pop();
this.element.textContent = status.join("");
};
}).call(StatusBar.prototype);
exports.StatusBar = StatusBar;
});
define('kitchen-sink/doclist', ['require', 'exports', 'module' , 'ace/edit_session', 'ace/undomanager', 'ace/lib/net', 'ace/ext/modelist'], function(require, exports, module) {
var EditSession = require("ace/edit_session").EditSession;
var UndoManager = require("ace/undomanager").UndoManager;
var net = require("ace/lib/net");
var modelist = require("ace/ext/modelist");
var fileCache = {};
function initDoc(file, path, doc) {
if (doc.prepare)
file = doc.prepare(file);
var session = new EditSession(file);
session.setUndoManager(new UndoManager());
doc.session = session;
doc.path = path;
session.name = doc.name;
if (doc.wrapped) {
session.setUseWrapMode(true);
session.setWrapLimitRange(80, 80);
}
var mode = modelist.getModeForPath(path);
session.modeName = mode.name;
session.setMode(mode.mode);
return session;
}
function makeHuge(txt) {
for (var i = 0; i < 5; i++)
txt += txt;
return txt;
}
var docs = {
"docs/javascript.js": {order: 1, name: "JavaScript"},
"docs/latex.tex": {name: "LaTeX", wrapped: true},
"docs/markdown.md": {name: "Markdown", wrapped: true},
"docs/mushcode.mc": {name: "MUSHCode", wrapped: true},
"docs/pgsql.pgsql": {name: "pgSQL", wrapped: true},
"docs/plaintext.txt": {name: "Plain Text", prepare: makeHuge, wrapped: true},
"docs/sql.sql": {name: "SQL", wrapped: true},
"docs/textile.textile": {name: "Textile", wrapped: true},
"docs/c9search.c9search_results": "C9 Search Results",
"docs/mel.mel": "MEL",
"docs/Nix.nix": "Nix"
};
var ownSource = {
};
var hugeDocs = {
"src/ace.js": "",
"src-min/ace.js": ""
};
modelist.modes.forEach(function(m) {
var ext = m.extensions.split("|")[0];
if (ext[0] === "^") {
path = ext.substr(1);
} else {
var path = m.name + "." + ext;
}
path = "docs/" + path;
if (!docs[path]) {
docs[path] = {name: m.caption};
} else if (typeof docs[path] == "object" && !docs[path].name) {
docs[path].name = m.caption;
}
});
if (window.require && window.require.s) try {
for (var path in window.require.s.contexts._.defined) {
if (path.indexOf("!") != -1)
path = path.split("!").pop();
else
path = path + ".js";
ownSource[path] = "";
}
} catch(e) {}
function sort(list) {
return list.sort(function(a, b) {
var cmp = (b.order || 0) - (a.order || 0);
return cmp || a.name && a.name.localeCompare(b.name);
});
}
function prepareDocList(docs) {
var list = [];
for (var path in docs) {
var doc = docs[path];
if (typeof doc != "object")
doc = {name: doc || path};
doc.path = path;
doc.desc = doc.name.replace(/^(ace|docs|demo|build)\//, "");
if (doc.desc.length > 18)
doc.desc = doc.desc.slice(0, 7) + ".." + doc.desc.slice(-9);
fileCache[doc.name] = doc;
list.push(doc);
}
return list;
}
function loadDoc(name, callback) {
var doc = fileCache[name];
if (!doc)
return callback(null);
if (doc.session)
return callback(doc.session);
var path = doc.path;
var parts = path.split("/");
if (parts[0] == "docs")
path = "kitchen-sink/" + path;
else if (parts[0] == "ace")
path = "lib/" + path;
net.get(path, function(x) {
initDoc(x, path, doc);
callback(doc.session);
});
}
module.exports = {
fileCache: fileCache,
docs: sort(prepareDocList(docs)),
ownSource: prepareDocList(ownSource),
hugeDocs: prepareDocList(hugeDocs),
initDoc: initDoc,
loadDoc: loadDoc
};
module.exports.all = {
"Mode Examples": module.exports.docs,
"Huge documents": module.exports.hugeDocs,
"own source": module.exports.ownSource
};
});
define('ace/ext/emmet', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler', 'ace/editor', 'ace/snippets', 'ace/range', 'ace/config'], function(require, exports, module) {
var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
var Editor = require("ace/editor").Editor;
var snippetManager = require("ace/snippets").snippetManager;
var Range = require("ace/range").Range;
var emmet;
Editor.prototype.indexToPosition = function(index) {
return this.session.doc.indexToPosition(index);
};
Editor.prototype.positionToIndex = function(pos) {
return this.session.doc.positionToIndex(pos);
};
function AceEmmetEditor() {}
AceEmmetEditor.prototype = {
setupContext: function(editor) {
this.ace = editor;
this.indentation = editor.session.getTabString();
if (!emmet)
emmet = window.emmet;
emmet.require("resources").setVariable("indentation", this.indentation);
this.$syntax = null;
this.$syntax = this.getSyntax();
},
getSelectionRange: function() {
var range = this.ace.getSelectionRange();
return {
start: this.ace.positionToIndex(range.start),
end: this.ace.positionToIndex(range.end)
};
},
createSelection: function(start, end) {
this.ace.selection.setRange({
start: this.ace.indexToPosition(start),
end: this.ace.indexToPosition(end)
});
},
getCurrentLineRange: function() {
var row = this.ace.getCursorPosition().row;
var lineLength = this.ace.session.getLine(row).length;
var index = this.ace.positionToIndex({row: row, column: 0});
return {
start: index,
end: index + lineLength
};
},
getCaretPos: function(){
var pos = this.ace.getCursorPosition();
return this.ace.positionToIndex(pos);
},
setCaretPos: function(index){
var pos = this.ace.indexToPosition(index);
this.ace.selection.moveToPosition(pos);
},
getCurrentLine: function() {
var row = this.ace.getCursorPosition().row;
return this.ace.session.getLine(row);
},
replaceContent: function(value, start, end, noIndent) {
if (end == null)
end = start == null ? this.getContent().length : start;
if (start == null)
start = 0;
var editor = this.ace;
var range = Range.fromPoints(editor.indexToPosition(start), editor.indexToPosition(end));
editor.session.remove(range);
range.end = range.start;
value = this.$updateTabstops(value);
snippetManager.insertSnippet(editor, value)
},
getContent: function(){
return this.ace.getValue();
},
getSyntax: function() {
if (this.$syntax)
return this.$syntax;
var syntax = this.ace.session.$modeId.split("/").pop();
if (syntax == "html" || syntax == "php") {
var cursor = this.ace.getCursorPosition();
var state = this.ace.session.getState(cursor.row);
if (typeof state != "string")
state = state[0];
if (state) {
state = state.split("-");
if (state.length > 1)
syntax = state[0];
else if (syntax == "php")
syntax = "html";
}
}
return syntax;
},
getProfileName: function() {
switch(this.getSyntax()) {
case "css": return "css";
case "xml":
case "xsl":
return "xml";
case "html":
var profile = emmet.require("resources").getVariable("profile");
if (!profile)
profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
return profile;
}
return "xhtml";
},
prompt: function(title) {
return prompt(title);
},
getSelection: function() {
return this.ace.session.getTextRange();
},
getFilePath: function() {
return "";
},
$updateTabstops: function(value) {
var base = 1000;
var zeroBase = 0;
var lastZero = null;
var range = emmet.require('range');
var ts = emmet.require('tabStops');
var settings = emmet.require('resources').getVocabulary("user");
var tabstopOptions = {
tabstop: function(data) {
var group = parseInt(data.group, 10);
var isZero = group === 0;
if (isZero)
group = ++zeroBase;
else
group += base;
var placeholder = data.placeholder;
if (placeholder) {
placeholder = ts.processText(placeholder, tabstopOptions);
}
var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
if (isZero) {
lastZero = range.create(data.start, result);
}
return result
},
escape: function(ch) {
if (ch == '$') return '\\$';
if (ch == '\\') return '\\\\';
return ch;
}
};
value = ts.processText(value, tabstopOptions);
if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
value += '${0}';
} else if (lastZero) {
value = emmet.require('utils').replaceSubstring(value, '${0}', lastZero);
}
return value;
}
};
var keymap = {
expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
next_edit_point: "alt+right",
prev_edit_point: "alt+left",
toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
increment_number_by_1: "ctrl+up",
decrement_number_by_1: "ctrl+down",
increment_number_by_01: "alt+up",
decrement_number_by_01: "alt+down",
increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
expand_abbreviation_with_tab: "Tab",
wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
};
var editorProxy = new AceEmmetEditor();
exports.commands = new HashHandler();
exports.runEmmetCommand = function(editor) {
editorProxy.setupContext(editor);
if (editorProxy.getSyntax() == "php")
return false;
var actions = emmet.require("actions");
if (this.action == "expand_abbreviation_with_tab") {
if (!editor.selection.isEmpty())
return false;
}
if (this.action == "wrap_with_abbreviation") {
return setTimeout(function() {
actions.run("wrap_with_abbreviation", editorProxy);
}, 0);
}
try {
var result = actions.run(this.action, editorProxy);
} catch(e) {
editor._signal("changeStatus", typeof e == "string" ? e : e.message);
console.log(e);
result = false
}
return result;
};
for (var command in keymap) {
exports.commands.addCommand({
name: "emmet:" + command,
action: command,
bindKey: keymap[command],
exec: exports.runEmmetCommand,
multiSelectAction: "forEach"
});
}
var onChangeMode = function(e, target) {
var editor = target;
if (!editor)
return;
var modeId = editor.session.$modeId;
var enabled = modeId && /css|less|scss|sass|stylus|html|php/.test(modeId);
if (e.enableEmmet === false)
enabled = false;
if (enabled)
editor.keyBinding.addKeyboardHandler(exports.commands);
else
editor.keyBinding.removeKeyboardHandler(exports.commands);
};
exports.AceEmmetEditor = AceEmmetEditor;
require("ace/config").defineOptions(Editor.prototype, "editor", {
enableEmmet: {
set: function(val) {
this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
onChangeMode({enableEmmet: !!val}, this);
},
value: true
}
});
exports.setCore = function(e) {emmet = e;};
});
define('ace/ext/whitespace', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) {
var lang = require("../lib/lang");
exports.$detectIndentation = function(lines, fallback) {
var stats = [];
var changes = [];
var tabIndents = 0;
var prevSpaces = 0;
var max = Math.min(lines.length, 1000);
for (var i = 0; i < max; i++) {
var line = lines[i];
if (!/^\s*[^*+\-\s]/.test(line))
continue;
var tabs = line.match(/^\t*/)[0].length;
if (line[0] == "\t")
tabIndents++;
var spaces = line.match(/^ */)[0].length;
if (spaces && line[spaces] != "\t") {
var diff = spaces - prevSpaces;
if (diff > 0 && !(prevSpaces%diff) && !(spaces%diff))
changes[diff] = (changes[diff] || 0) + 1;
stats[spaces] = (stats[spaces] || 0) + 1;
}
prevSpaces = spaces;
while (i < max && line[line.length - 1] == "\\")
line = lines[i++];
}
if (!stats.length)
return;
function getScore(indent) {
var score = 0;
for (var i = indent; i < stats.length; i += indent)
score += stats[i] || 0;
return score;
}
var changesTotal = changes.reduce(function(a,b){return a+b}, 0);
var first = {score: 0, length: 0};
var spaceIndents = 0;
for (var i = 1; i < 12; i++) {
if (i == 1) {
spaceIndents = getScore(i);
var score = 1;
} else
var score = getScore(i) / spaceIndents;
if (changes[i])
score += changes[i] / changesTotal;
if (score > first.score)
first = {score: score, length: i};
}
if (first.score && first.score > 1.4)
var tabLength = first.length;
if (tabIndents > spaceIndents + 1)
return {ch: "\t", length: tabLength};
if (spaceIndents + 1 > tabIndents)
return {ch: " ", length: tabLength};
};
exports.detectIndentation = function(session) {
var lines = session.getLines(0, 1000);
var indent = exports.$detectIndentation(lines) || {};
if (indent.ch)
session.setUseSoftTabs(indent.ch == " ");
if (indent.length)
session.setTabSize(indent.length);
return indent;
};
exports.trimTrailingSpace = function(session, trimEmpty) {
var doc = session.getDocument();
var lines = doc.getAllLines();
var min = trimEmpty ? -1 : 0;
for (var i = 0, l=lines.length; i < l; i++) {
var line = lines[i];
var index = line.search(/\s+$/);
if (index > min)
doc.removeInLine(i, index, line.length);
}
};
exports.convertIndentation = function(session, ch, len) {
var oldCh = session.getTabString()[0];
var oldLen = session.getTabSize();
if (!len) len = oldLen;
if (!ch) ch = oldCh;
var tab = ch == "\t" ? ch: lang.stringRepeat(ch, len);
var doc = session.doc;
var lines = doc.getAllLines();
var cache = {};
var spaceCache = {};
for (var i = 0, l=lines.length; i < l; i++) {
var line = lines[i];
var match = line.match(/^\s*/)[0];
if (match) {
var w = session.$getStringScreenWidth(match)[0];
var tabCount = Math.floor(w/oldLen);
var reminder = w%oldLen;
var toInsert = cache[tabCount] || (cache[tabCount] = lang.stringRepeat(tab, tabCount));
toInsert += spaceCache[reminder] || (spaceCache[reminder] = lang.stringRepeat(" ", reminder));
if (toInsert != match) {
doc.removeInLine(i, 0, match.length);
doc.insertInLine({row: i, column: 0}, toInsert);
}
}
}
session.setTabSize(len);
session.setUseSoftTabs(ch == " ");
};
exports.$parseStringArg = function(text) {
var indent = {};
if (/t/.test(text))
indent.ch = "\t";
else if (/s/.test(text))
indent.ch = " ";
var m = text.match(/\d+/);
if (m)
indent.length = parseInt(m[0], 10);
return indent;
};
exports.$parseArg = function(arg) {
if (!arg)
return {};
if (typeof arg == "string")
return exports.$parseStringArg(arg);
if (typeof arg.text == "string")
return exports.$parseStringArg(arg.text);
return arg;
};
exports.commands = [{
name: "detectIndentation",
exec: function(editor) {
exports.detectIndentation(editor.session);
}
}, {
name: "trimTrailingSpace",
exec: function(editor) {
exports.trimTrailingSpace(editor.session);
}
}, {
name: "convertIndentation",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
exports.convertIndentation(editor.session, indent.ch, indent.length);
}
}, {
name: "setIndentation",
exec: function(editor, arg) {
var indent = exports.$parseArg(arg);
indent.length && editor.session.setTabSize(indent.length);
indent.ch && editor.session.setUseSoftTabs(indent.ch == " ");
}
}];
});
define('ace/snippets', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/lib/lang', 'ace/range', 'ace/anchor', 'ace/keyboard/hash_handler', 'ace/tokenizer', 'ace/lib/dom', 'ace/editor'], function(require, exports, module) {
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var lang = require("./lib/lang");
var Range = require("./range").Range;
var Anchor = require("./anchor").Anchor;
var HashHandler = require("./keyboard/hash_handler").HashHandler;
var Tokenizer = require("./tokenizer").Tokenizer;
var comparePoints = Range.comparePoints;
var SnippetManager = function() {
this.snippetMap = {};
this.snippetNameMap = {};
};
(function() {
oop.implement(this, EventEmitter);
this.getTokenizer = function() {
function TabstopToken(str, _, stack) {
str = str.substr(1);
if (/^\d+$/.test(str) && !stack.inFormatString)
return [{tabstopId: parseInt(str, 10)}];
return [{text: str}];
}
function escape(ch) {
return "(?:[^\\\\" + ch + "]|\\\\.)";
}
SnippetManager.$tokenizer = new Tokenizer({
start: [
{regex: /:/, onMatch: function(val, state, stack) {
if (stack.length && stack[0].expectIf) {
stack[0].expectIf = false;
stack[0].elseBranch = stack[0];
return [stack[0]];
}
return ":";
}},
{regex: /\\./, onMatch: function(val, state, stack) {
var ch = val[1];
if (ch == "}" && stack.length) {
val = ch;
}else if ("`$\\".indexOf(ch) != -1) {
val = ch;
} else if (stack.inFormatString) {
if (ch == "n")
val = "\n";
else if (ch == "t")
val = "\n";
else if ("ulULE".indexOf(ch) != -1) {
val = {changeCase: ch, local: ch > "a"};
}
}
return [val];
}},
{regex: /}/, onMatch: function(val, state, stack) {
return [stack.length ? stack.shift() : val];
}},
{regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
{regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
var t = TabstopToken(str.substr(1), state, stack);
stack.unshift(t[0]);
return t;
}, next: "snippetVar"},
{regex: /\n/, token: "newline", merge: false}
],
snippetVar: [
{regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
stack[0].choices = val.slice(1, -1).split(",");
}, next: "start"},
{regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
onMatch: function(val, state, stack) {
var ts = stack[0];
ts.fmtString = val;
val = this.splitRegex.exec(val);
ts.guard = val[1];
ts.fmt = val[2];
ts.flag = val[3];
return "";
}, next: "start"},
{regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
stack[0].code = val.splice(1, -1);
return "";
}, next: "start"},
{regex: "\\?", onMatch: function(val, state, stack) {
if (stack[0])
stack[0].expectIf = true;
}, next: "start"},
{regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
],
formatString: [
{regex: "/(" + escape("/") + "+)/", token: "regex"},
{regex: "", onMatch: function(val, state, stack) {
stack.inFormatString = true;
}, next: "start"}
]
});
SnippetManager.prototype.getTokenizer = function() {
return SnippetManager.$tokenizer;
};
return SnippetManager.$tokenizer;
};
this.tokenizeTmSnippet = function(str, startState) {
return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
return x.value || x;
});
};
this.$getDefaultValue = function(editor, name) {
if (/^[A-Z]\d+$/.test(name)) {
var i = name.substr(1);
return (this.variables[name[0] + "__"] || {})[i];
}
if (/^\d+$/.test(name)) {
return (this.variables.__ || {})[name];
}
name = name.replace(/^TM_/, "");
if (!editor)
return;
var s = editor.session;
switch(name) {
case "CURRENT_WORD":
var r = s.getWordRange();
case "SELECTION":
case "SELECTED_TEXT":
return s.getTextRange(r);
case "CURRENT_LINE":
return s.getLine(editor.getCursorPosition().row);
case "PREV_LINE": // not possible in textmate
return s.getLine(editor.getCursorPosition().row - 1);
case "LINE_INDEX":
return editor.getCursorPosition().column;
case "LINE_NUMBER":
return editor.getCursorPosition().row + 1;
case "SOFT_TABS":
return s.getUseSoftTabs() ? "YES" : "NO";
case "TAB_SIZE":
return s.getTabSize();
case "FILENAME":
case "FILEPATH":
return "";
case "FULLNAME":
return "Ace";
}
};
this.variables = {};
this.getVariableValue = function(editor, varName) {
if (this.variables.hasOwnProperty(varName))
return this.variables[varName](editor, varName) || "";
return this.$getDefaultValue(editor, varName) || "";
};
this.tmStrFormat = function(str, ch, editor) {
var flag = ch.flag || "";
var re = ch.guard;
re = new RegExp(re, flag.replace(/[^gi]/, ""));
var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
var _self = this;
var formatted = str.replace(re, function() {
_self.variables.__ = arguments;
var fmtParts = _self.resolveVariables(fmtTokens, editor);
var gChangeCase = "E";
for (var i = 0; i < fmtParts.length; i++) {
var ch = fmtParts[i];
if (typeof ch == "object") {
fmtParts[i] = "";
if (ch.changeCase && ch.local) {
var next = fmtParts[i + 1];
if (next && typeof next == "string") {
if (ch.changeCase == "u")
fmtParts[i] = next[0].toUpperCase();
else
fmtParts[i] = next[0].toLowerCase();
fmtParts[i + 1] = next.substr(1);
}
} else if (ch.changeCase) {
gChangeCase = ch.changeCase;
}
} else if (gChangeCase == "U") {
fmtParts[i] = ch.toUpperCase();
} else if (gChangeCase == "L") {
fmtParts[i] = ch.toLowerCase();
}
}
return fmtParts.join("");
});
this.variables.__ = null;
return formatted;
};
this.resolveVariables = function(snippet, editor) {
var result = [];
for (var i = 0; i < snippet.length; i++) {
var ch = snippet[i];
if (typeof ch == "string") {
result.push(ch);
} else if (typeof ch != "object") {
continue;
} else if (ch.skip) {
gotoNext(ch);
} else if (ch.processed < i) {
continue;
} else if (ch.text) {
var value = this.getVariableValue(editor, ch.text);
if (value && ch.fmtString)
value = this.tmStrFormat(value, ch);
ch.processed = i;
if (ch.expectIf == null) {
if (value) {
result.push(value);
gotoNext(ch);
}
} else {
if (value) {
ch.skip = ch.elseBranch;
} else
gotoNext(ch);
}
} else if (ch.tabstopId != null) {
result.push(ch);
} else if (ch.changeCase != null) {
result.push(ch);
}
}
function gotoNext(ch) {
var i1 = snippet.indexOf(ch, i + 1);
if (i1 != -1)
i = i1;
}
return result;
};
this.insertSnippetForSelection = function(editor, snippetText) {
var cursor = editor.getCursorPosition();
var line = editor.session.getLine(cursor.row);
var tabString = editor.session.getTabString();
var indentString = line.match(/^\s*/)[0];
if (cursor.column < indentString.length)
indentString = indentString.slice(0, cursor.column);
var tokens = this.tokenizeTmSnippet(snippetText);
tokens = this.resolveVariables(tokens, editor);
tokens = tokens.map(function(x) {
if (x == "\n")
return x + indentString;
if (typeof x == "string")
return x.replace(/\t/g, tabString);
return x;
});
var tabstops = [];
tokens.forEach(function(p, i) {
if (typeof p != "object")
return;
var id = p.tabstopId;
var ts = tabstops[id];
if (!ts) {
ts = tabstops[id] = [];
ts.index = id;
ts.value = "";
}
if (ts.indexOf(p) !== -1)
return;
ts.push(p);
var i1 = tokens.indexOf(p, i + 1);
if (i1 === -1)
return;
var value = tokens.slice(i + 1, i1);
var isNested = value.some(function(t) {return typeof t === "object"});
if (isNested && !ts.value) {
ts.value = value;
} else if (value.length && (!ts.value || typeof ts.value !== "string")) {
ts.value = value.join("");
}
});
tabstops.forEach(function(ts) {ts.length = 0});
var expanding = {};
function copyValue(val) {
var copy = [];
for (var i = 0; i < val.length; i++) {
var p = val[i];
if (typeof p == "object") {
if (expanding[p.tabstopId])
continue;
var j = val.lastIndexOf(p, i - 1);
p = copy[j] || {tabstopId: p.tabstopId};
}
copy[i] = p;
}
return copy;
}
for (var i = 0; i < tokens.length; i++) {
var p = tokens[i];
if (typeof p != "object")
continue;
var id = p.tabstopId;
var i1 = tokens.indexOf(p, i + 1);
if (expanding[id]) {
if (expanding[id] === p)
expanding[id] = null;
continue;
}
var ts = tabstops[id];
var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
arg.unshift(i + 1, Math.max(0, i1 - i));
arg.push(p);
expanding[id] = p;
tokens.splice.apply(tokens, arg);
if (ts.indexOf(p) === -1)
ts.push(p);
}
var row = 0, column = 0;
var text = "";
tokens.forEach(function(t) {
if (typeof t === "string") {
if (t[0] === "\n"){
column = t.length - 1;
row ++;
} else
column += t.length;
text += t;
} else {
if (!t.start)
t.start = {row: row, column: column};
else
t.end = {row: row, column: column};
}
});
var range = editor.getSelectionRange();
var end = editor.session.replace(range, text);
var tabstopManager = new TabstopManager(editor);
var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
};
this.insertSnippet = function(editor, snippetText) {
var self = this;
if (editor.inVirtualSelectionMode)
return self.insertSnippetForSelection(editor, snippetText);
editor.forEachSelection(function() {
self.insertSnippetForSelection(editor, snippetText);
}, null, {keepOrder: true});
if (editor.tabstopManager)
editor.tabstopManager.tabNext();
};
this.$getScope = function(editor) {
var scope = editor.session.$mode.$id || "";
scope = scope.split("/").pop();
if (scope === "html" || scope === "php") {
if (scope === "php" && !editor.session.$mode.inlinePhp)
scope = "html";
var c = editor.getCursorPosition();
var state = editor.session.getState(c.row);
if (typeof state === "object") {
state = state[0];
}
if (state.substring) {
if (state.substring(0, 3) == "js-")
scope = "javascript";
else if (state.substring(0, 4) == "css-")
scope = "css";
else if (state.substring(0, 4) == "php-")
scope = "php";
}
}
return scope;
};
this.getActiveScopes = function(editor) {
var scope = this.$getScope(editor);
var scopes = [scope];
var snippetMap = this.snippetMap;
if (snippetMap[scope] && snippetMap[scope].includeScopes) {
scopes.push.apply(scopes, snippetMap[scope].includeScopes);
}
scopes.push("_");
return scopes;
};
this.expandWithTab = function(editor, options) {
var self = this;
var result = editor.forEachSelection(function() {
return self.expandSnippetForSelection(editor, options);
}, null, {keepOrder: true});
if (result && editor.tabstopManager)
editor.tabstopManager.tabNext();
return result;
};
this.expandSnippetForSelection = function(editor, options) {
var cursor = editor.getCursorPosition();
var line = editor.session.getLine(cursor.row);
var before = line.substring(0, cursor.column);
var after = line.substr(cursor.column);
var snippetMap = this.snippetMap;
var snippet;
this.getActiveScopes(editor).some(function(scope) {
var snippets = snippetMap[scope];
if (snippets)
snippet = this.findMatchingSnippet(snippets, before, after);
return !!snippet;
}, this);
if (!snippet)
return false;
if (options && options.dryRun)
return true;
editor.session.doc.removeInLine(cursor.row,
cursor.column - snippet.replaceBefore.length,
cursor.column + snippet.replaceAfter.length
);
this.variables.M__ = snippet.matchBefore;
this.variables.T__ = snippet.matchAfter;
this.insertSnippetForSelection(editor, snippet.content);
this.variables.M__ = this.variables.T__ = null;
return true;
};
this.findMatchingSnippet = function(snippetList, before, after) {
for (var i = snippetList.length; i--;) {
var s = snippetList[i];
if (s.startRe && !s.startRe.test(before))
continue;
if (s.endRe && !s.endRe.test(after))
continue;
if (!s.startRe && !s.endRe)
continue;
s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
return s;
}
};
this.snippetMap = {};
this.snippetNameMap = {};
this.register = function(snippets, scope) {
var snippetMap = this.snippetMap;
var snippetNameMap = this.snippetNameMap;
var self = this;
function wrapRegexp(src) {
if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
src = "(?:" + src + ")";
return src || "";
}
function guardedRegexp(re, guard, opening) {
re = wrapRegexp(re);
guard = wrapRegexp(guard);
if (opening) {
re = guard + re;
if (re && re[re.length - 1] != "$")
re = re + "$";
} else {
re = re + guard;
if (re && re[0] != "^")
re = "^" + re;
}
return new RegExp(re);
}
function addSnippet(s) {
if (!s.scope)
s.scope = scope || "_";
scope = s.scope;
if (!snippetMap[scope]) {
snippetMap[scope] = [];
snippetNameMap[scope] = {};
}
var map = snippetNameMap[scope];
if (s.name) {
var old = map[s.name];
if (old)
self.unregister(old);
map[s.name] = s;
}
snippetMap[scope].push(s);
if (s.tabTrigger && !s.trigger) {
if (!s.guard && /^\w/.test(s.tabTrigger))
s.guard = "\\b";
s.trigger = lang.escapeRegExp(s.tabTrigger);
}
s.startRe = guardedRegexp(s.trigger, s.guard, true);
s.triggerRe = new RegExp(s.trigger, "", true);
s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
s.endTriggerRe = new RegExp(s.endTrigger, "", true);
}
if (snippets.content)
addSnippet(snippets);
else if (Array.isArray(snippets))
snippets.forEach(addSnippet);
this._signal("registerSnippets", {scope: scope});
};
this.unregister = function(snippets, scope) {
var snippetMap = this.snippetMap;
var snippetNameMap = this.snippetNameMap;
function removeSnippet(s) {
var nameMap = snippetNameMap[s.scope||scope];
if (nameMap && nameMap[s.name]) {
delete nameMap[s.name];
var map = snippetMap[s.scope||scope];
var i = map && map.indexOf(s);
if (i >= 0)
map.splice(i, 1);
}
}
if (snippets.content)
removeSnippet(snippets);
else if (Array.isArray(snippets))
snippets.forEach(removeSnippet);
};
this.parseSnippetFile = function(str) {
str = str.replace(/\r/g, "");
var list = [], snippet = {};
var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
var m;
while (m = re.exec(str)) {
if (m[1]) {
try {
snippet = JSON.parse(m[1]);
list.push(snippet);
} catch (e) {}
} if (m[4]) {
snippet.content = m[4].replace(/^\t/gm, "");
list.push(snippet);
snippet = {};
} else {
var key = m[2], val = m[3];
if (key == "regex") {
var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
snippet.guard = guardRe.exec(val)[1];
snippet.trigger = guardRe.exec(val)[1];
snippet.endTrigger = guardRe.exec(val)[1];
snippet.endGuard = guardRe.exec(val)[1];
} else if (key == "snippet") {
snippet.tabTrigger = val.match(/^\S*/)[0];
if (!snippet.name)
snippet.name = val;
} else {
snippet[key] = val;
}
}
}
return list;
};
this.getSnippetByName = function(name, editor) {
var snippetMap = this.snippetNameMap;
var snippet;
this.getActiveScopes(editor).some(function(scope) {
var snippets = snippetMap[scope];
if (snippets)
snippet = snippets[name];
return !!snippet;
}, this);
return snippet;
};
}).call(SnippetManager.prototype);
var TabstopManager = function(editor) {
if (editor.tabstopManager)
return editor.tabstopManager;
editor.tabstopManager = this;
this.$onChange = this.onChange.bind(this);
this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
this.$onChangeSession = this.onChangeSession.bind(this);
this.$onAfterExec = this.onAfterExec.bind(this);
this.attach(editor);
};
(function() {
this.attach = function(editor) {
this.index = 0;
this.ranges = [];
this.tabstops = [];
this.$openTabstops = null;
this.selectedTabstop = null;
this.editor = editor;
this.editor.on("change", this.$onChange);
this.editor.on("changeSelection", this.$onChangeSelection);
this.editor.on("changeSession", this.$onChangeSession);
this.editor.commands.on("afterExec", this.$onAfterExec);
this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
};
this.detach = function() {
this.tabstops.forEach(this.removeTabstopMarkers, this);
this.ranges = null;
this.tabstops = null;
this.selectedTabstop = null;
this.editor.removeListener("change", this.$onChange);
this.editor.removeListener("changeSelection", this.$onChangeSelection);
this.editor.removeListener("changeSession", this.$onChangeSession);
this.editor.commands.removeListener("afterExec", this.$onAfterExec);
this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
this.editor.tabstopManager = null;
this.editor = null;
};
this.onChange = function(e) {
var changeRange = e.data.range;
var isRemove = e.data.action[0] == "r";
var start = changeRange.start;
var end = changeRange.end;
var startRow = start.row;
var endRow = end.row;
var lineDif = endRow - startRow;
var colDiff = end.column - start.column;
if (isRemove) {
lineDif = -lineDif;
colDiff = -colDiff;
}
if (!this.$inChange && isRemove) {
var ts = this.selectedTabstop;
var changedOutside = ts && !ts.some(function(r) {
return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
});
if (changedOutside)
return this.detach();
}
var ranges = this.ranges;
for (var i = 0; i < ranges.length; i++) {
var r = ranges[i];
if (r.end.row < start.row)
continue;
if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
this.removeRange(r);
i--;
continue;
}
if (r.start.row == startRow && r.start.column > start.column)
r.start.column += colDiff;
if (r.end.row == startRow && r.end.column >= start.column)
r.end.column += colDiff;
if (r.start.row >= startRow)
r.start.row += lineDif;
if (r.end.row >= startRow)
r.end.row += lineDif;
if (comparePoints(r.start, r.end) > 0)
this.removeRange(r);
}
if (!ranges.length)
this.detach();
};
this.updateLinkedFields = function() {
var ts = this.selectedTabstop;
if (!ts || !ts.hasLinkedRanges)
return;
this.$inChange = true;
var session = this.editor.session;
var text = session.getTextRange(ts.firstNonLinked);
for (var i = ts.length; i--;) {
var range = ts[i];
if (!range.linked)
continue;
var fmt = exports.snippetManager.tmStrFormat(text, range.original);
session.replace(range, fmt);
}
this.$inChange = false;
};
this.onAfterExec = function(e) {
if (e.command && !e.command.readOnly)
this.updateLinkedFields();
};
this.onChangeSelection = function() {
if (!this.editor)
return;
var lead = this.editor.selection.lead;
var anchor = this.editor.selection.anchor;
var isEmpty = this.editor.selection.isEmpty();
for (var i = this.ranges.length; i--;) {
if (this.ranges[i].linked)
continue;
var containsLead = this.ranges[i].contains(lead.row, lead.column);
var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
if (containsLead && containsAnchor)
return;
}
this.detach();
};
this.onChangeSession = function() {
this.detach();
};
this.tabNext = function(dir) {
var max = this.tabstops.length;
var index = this.index + (dir || 1);
index = Math.min(Math.max(index, 1), max);
if (index == max)
index = 0;
this.selectTabstop(index);
if (index === 0)
this.detach();
};
this.selectTabstop = function(index) {
this.$openTabstops = null;
var ts = this.tabstops[this.index];
if (ts)
this.addTabstopMarkers(ts);
this.index = index;
ts = this.tabstops[this.index];
if (!ts || !ts.length)
return;
this.selectedTabstop = ts;
if (!this.editor.inVirtualSelectionMode) {
var sel = this.editor.multiSelect;
sel.toSingleRange(ts.firstNonLinked.clone());
for (var i = ts.length; i--;) {
if (ts.hasLinkedRanges && ts[i].linked)
continue;
sel.addRange(ts[i].clone(), true);
}
if (sel.ranges[0])
sel.addRange(sel.ranges[0].clone());
} else {
this.editor.selection.setRange(ts.firstNonLinked);
}
this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
};
this.addTabstops = function(tabstops, start, end) {
if (!this.$openTabstops)
this.$openTabstops = [];
if (!tabstops[0]) {
var p = Range.fromPoints(end, end);
moveRelative(p.start, start);
moveRelative(p.end, start);
tabstops[0] = [p];
tabstops[0].index = 0;
}
var i = this.index;
var arg = [i + 1, 0];
var ranges = this.ranges;
tabstops.forEach(function(ts, index) {
var dest = this.$openTabstops[index] || ts;
for (var i = ts.length; i--;) {
var p = ts[i];
var range = Range.fromPoints(p.start, p.end || p.start);
movePoint(range.start, start);
movePoint(range.end, start);
range.original = p;
range.tabstop = dest;
ranges.push(range);
if (dest != ts)
dest.unshift(range);
else
dest[i] = range;
if (p.fmtString) {
range.linked = true;
dest.hasLinkedRanges = true;
} else if (!dest.firstNonLinked)
dest.firstNonLinked = range;
}
if (!dest.firstNonLinked)
dest.hasLinkedRanges = false;
if (dest === ts) {
arg.push(dest);
this.$openTabstops[index] = dest;
}
this.addTabstopMarkers(dest);
}, this);
if (arg.length > 2) {
if (this.tabstops.length)
arg.push(arg.splice(2, 1)[0]);
this.tabstops.splice.apply(this.tabstops, arg);
}
};
this.addTabstopMarkers = function(ts) {
var session = this.editor.session;
ts.forEach(function(range) {
if (!range.markerId)
range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
});
};
this.removeTabstopMarkers = function(ts) {
var session = this.editor.session;
ts.forEach(function(range) {
session.removeMarker(range.markerId);
range.markerId = null;
});
};
this.removeRange = function(range) {
var i = range.tabstop.indexOf(range);
range.tabstop.splice(i, 1);
i = this.ranges.indexOf(range);
this.ranges.splice(i, 1);
this.editor.session.removeMarker(range.markerId);
if (!range.tabstop.length) {
i = this.tabstops.indexOf(range.tabstop);
if (i != -1)
this.tabstops.splice(i, 1);
if (!this.tabstops.length)
this.detach();
}
};
this.keyboardHandler = new HashHandler();
this.keyboardHandler.bindKeys({
"Tab": function(ed) {
if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
return;
}
ed.tabstopManager.tabNext(1);
},
"Shift-Tab": function(ed) {
ed.tabstopManager.tabNext(-1);
},
"Esc": function(ed) {
ed.tabstopManager.detach();
},
"Return": function(ed) {
return false;
}
});
}).call(TabstopManager.prototype);
var changeTracker = {};
changeTracker.onChange = Anchor.prototype.onChange;
changeTracker.setPosition = function(row, column) {
this.pos.row = row;
this.pos.column = column;
};
changeTracker.update = function(pos, delta, $insertRight) {
this.$insertRight = $insertRight;
this.pos = pos;
this.onChange(delta);
};
var movePoint = function(point, diff) {
if (point.row == 0)
point.column += diff.column;
point.row += diff.row;
};
var moveRelative = function(point, start) {
if (point.row == start.row)
point.column -= start.column;
point.row -= start.row;
};
require("./lib/dom").importCssString("\
.ace_snippet-marker {\
-moz-box-sizing: border-box;\
box-sizing: border-box;\
background: rgba(194, 193, 208, 0.09);\
border: 1px dotted rgba(211, 208, 235, 0.62);\
position: absolute;\
}");
exports.snippetManager = new SnippetManager();
var Editor = require("./editor").Editor;
(function() {
this.insertSnippet = function(content, options) {
return exports.snippetManager.insertSnippet(this, content, options);
};
this.expandSnippet = function(options) {
return exports.snippetManager.expandWithTab(this, options);
};
}).call(Editor.prototype);
});
define('ace/ext/language_tools', ['require', 'exports', 'module' , 'ace/snippets', 'ace/autocomplete', 'ace/config', 'ace/autocomplete/util', 'ace/autocomplete/text_completer', 'ace/editor'], function(require, exports, module) {
var snippetManager = require("../snippets").snippetManager;
var Autocomplete = require("../autocomplete").Autocomplete;
var config = require("../config");
var util = require("../autocomplete/util");
var textCompleter = require("../autocomplete/text_completer");
var keyWordCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var state = editor.session.getState(pos.row);
var completions = session.$mode.getCompletions(state, session, pos, prefix);
callback(null, completions);
}
};
var snippetCompleter = {
getCompletions: function(editor, session, pos, prefix, callback) {
var snippetMap = snippetManager.snippetMap;
var completions = [];
snippetManager.getActiveScopes(editor).forEach(function(scope) {
var snippets = snippetMap[scope] || [];
for (var i = snippets.length; i--;) {
var s = snippets[i];
var caption = s.name || s.tabTrigger;
if (!caption)
continue;
completions.push({
caption: caption,
snippet: s.content,
meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet"
});
}
}, this);
callback(null, completions);
}
};
var completers = [snippetCompleter, textCompleter, keyWordCompleter];
exports.addCompleter = function(completer) {
completers.push(completer);
};
exports.textCompleter = textCompleter;
exports.keyWordCompleter = keyWordCompleter;
exports.snippetCompleter = snippetCompleter;
var expandSnippet = {
name: "expandSnippet",
exec: function(editor) {
var success = snippetManager.expandWithTab(editor);
if (!success)
editor.execCommand("indent");
},
bindKey: "Tab"
};
var onChangeMode = function(e, editor) {
loadSnippetsForMode(editor.session.$mode);
};
var loadSnippetsForMode = function(mode) {
var id = mode.$id;
if (!snippetManager.files)
snippetManager.files = {};
loadSnippetFile(id);
if (mode.modes)
mode.modes.forEach(loadSnippetsForMode);
};
var loadSnippetFile = function(id) {
if (!id || snippetManager.files[id])
return;
var snippetFilePath = id.replace("mode", "snippets");
snippetManager.files[id] = {};
config.loadModule(snippetFilePath, function(m) {
if (m) {
snippetManager.files[id] = m;
if (!m.snippets && m.snippetText)
m.snippets = snippetManager.parseSnippetFile(m.snippetText);
snippetManager.register(m.snippets || [], m.scope);
if (m.includeScopes) {
snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
m.includeScopes.forEach(function(x) {
loadSnippetFile("ace/mode/" + x);
});
}
}
});
};
var doLiveAutocomplete = function(e) {
var editor = e.editor;
var text = e.args || "";
var pos = editor.getCursorPosition();
var line = editor.session.getLine(pos.row);
var hasCompleter = editor.completer && editor.completer.activated;
var prefix = util.retrievePrecedingIdentifier(line, pos.column);
completers.forEach(function(completer) {
if (completer.identifierRegexps) {
completer.identifierRegexps.forEach(function(identifierRegex) {
if (!prefix) {
prefix = util.retrievePrecedingIdentifier(line, pos.column, identifierRegex);
}
});
}
});
if (e.command.name === "backspace" && !prefix) {
if (hasCompleter)
editor.completer.detach();
}
else if (e.command.name === "insertstring") {
if (prefix && !hasCompleter) {
if (!editor.completer) {
editor.completer = new Autocomplete();
editor.completer.autoSelect = false;
editor.completer.autoInsert = false;
}
editor.completer.showPopup(editor);
} else if (!prefix && hasCompleter) {
editor.completer.detach();
}
}
};
var Editor = require("../editor").Editor;
require("../config").defineOptions(Editor.prototype, "editor", {
enableBasicAutocompletion: {
set: function(val) {
if (val) {
this.completers = Array.isArray(val)? val: completers;
this.commands.addCommand(Autocomplete.startCommand);
} else {
this.commands.removeCommand(Autocomplete.startCommand);
}
},
value: false
},
enableLiveAutocompletion: {
set: function(val) {
if (val) {
this.completers = Array.isArray(val)? val: completers;
this.commands.on('afterExec', doLiveAutocomplete);
} else {
this.commands.removeListener('afterExec', doLiveAutocomplete);
}
},
value: false
},
enableSnippets: {
set: function(val) {
if (val) {
this.commands.addCommand(expandSnippet);
this.on("changeMode", onChangeMode);
onChangeMode(null, this);
} else {
this.commands.removeCommand(expandSnippet);
this.off("changeMode", onChangeMode);
}
},
value: false
}
});
});
define('ace/theme/textmate', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-tm";
exports.cssText = ".ace-tm .ace_gutter {\
background: #f0f0f0;\
color: #333;\
}\
.ace-tm .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-tm .ace_fold {\
background-color: #6B72E6;\
}\
.ace-tm {\
background-color: #FFFFFF;\
color: black;\
}\
.ace-tm .ace_cursor {\
color: black;\
}\
.ace-tm .ace_invisible {\
color: rgb(191, 191, 191);\
}\
.ace-tm .ace_storage,\
.ace-tm .ace_keyword {\
color: blue;\
}\
.ace-tm .ace_constant {\
color: rgb(197, 6, 11);\
}\
.ace-tm .ace_constant.ace_buildin {\
color: rgb(88, 72, 246);\
}\
.ace-tm .ace_constant.ace_language {\
color: rgb(88, 92, 246);\
}\
.ace-tm .ace_constant.ace_library {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_invalid {\
background-color: rgba(255, 0, 0, 0.1);\
color: red;\
}\
.ace-tm .ace_support.ace_function {\
color: rgb(60, 76, 114);\
}\
.ace-tm .ace_support.ace_constant {\
color: rgb(6, 150, 14);\
}\
.ace-tm .ace_support.ace_type,\
.ace-tm .ace_support.ace_class {\
color: rgb(109, 121, 222);\
}\
.ace-tm .ace_keyword.ace_operator {\
color: rgb(104, 118, 135);\
}\
.ace-tm .ace_string {\
color: rgb(3, 106, 7);\
}\
.ace-tm .ace_comment {\
color: rgb(76, 136, 107);\
}\
.ace-tm .ace_comment.ace_doc {\
color: rgb(0, 102, 255);\
}\
.ace-tm .ace_comment.ace_doc.ace_tag {\
color: rgb(128, 159, 191);\
}\
.ace-tm .ace_constant.ace_numeric {\
color: rgb(0, 0, 205);\
}\
.ace-tm .ace_variable {\
color: rgb(49, 132, 149);\
}\
.ace-tm .ace_xml-pe {\
color: rgb(104, 104, 91);\
}\
.ace-tm .ace_entity.ace_name.ace_function {\
color: #0000A2;\
}\
.ace-tm .ace_heading {\
color: rgb(12, 7, 255);\
}\
.ace-tm .ace_list {\
color:rgb(185, 6, 144);\
}\
.ace-tm .ace_meta.ace_tag {\
color:rgb(0, 22, 142);\
}\
.ace-tm .ace_string.ace_regex {\
color: rgb(255, 0, 0)\
}\
.ace-tm .ace_marker-layer .ace_selection {\
background: rgb(181, 213, 255);\
}\
.ace-tm.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px white;\
border-radius: 2px;\
}\
.ace-tm .ace_marker-layer .ace_step {\
background: rgb(252, 255, 0);\
}\
.ace-tm .ace_marker-layer .ace_stack {\
background: rgb(164, 229, 101);\
}\
.ace-tm .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgb(192, 192, 192);\
}\
.ace-tm .ace_marker-layer .ace_active-line {\
background: rgba(0, 0, 0, 0.07);\
}\
.ace-tm .ace_gutter-active-line {\
background-color : #dcdcdc;\
}\
.ace-tm .ace_marker-layer .ace_selected-word {\
background: rgb(250, 250, 255);\
border: 1px solid rgb(200, 200, 250);\
}\
.ace-tm .ace_indent-guide {\
background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
}\
";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
define('ace/autocomplete', ['require', 'exports', 'module' , 'ace/keyboard/hash_handler', 'ace/autocomplete/popup', 'ace/autocomplete/util', 'ace/lib/event', 'ace/lib/lang', 'ace/snippets'], function(require, exports, module) {
var HashHandler = require("./keyboard/hash_handler").HashHandler;
var AcePopup = require("./autocomplete/popup").AcePopup;
var util = require("./autocomplete/util");
var event = require("./lib/event");
var lang = require("./lib/lang");
var snippetManager = require("./snippets").snippetManager;
var Autocomplete = function() {
this.autoInsert = true;
this.autoSelect = true;
this.keyboardHandler = new HashHandler();
this.keyboardHandler.bindKeys(this.commands);
this.blurListener = this.blurListener.bind(this);
this.changeListener = this.changeListener.bind(this);
this.mousedownListener = this.mousedownListener.bind(this);
this.mousewheelListener = this.mousewheelListener.bind(this);
this.changeTimer = lang.delayedCall(function() {
this.updateCompletions(true);
}.bind(this));
};
(function() {
this.gatherCompletionsId = 0;
this.$init = function() {
this.popup = new AcePopup(document.body || document.documentElement);
this.popup.on("click", function(e) {
this.insertMatch();
e.stop();
}.bind(this));
this.popup.focus = this.editor.focus.bind(this.editor);
};
this.openPopup = function(editor, prefix, keepPopupPosition) {
if (!this.popup)
this.$init();
this.popup.setData(this.completions.filtered);
var renderer = editor.renderer;
this.popup.setRow(this.autoSelect ? 0 : -1);
if (!keepPopupPosition) {
this.popup.setTheme(editor.getTheme());
this.popup.setFontSize(editor.getFontSize());
var lineHeight = renderer.layerConfig.lineHeight;
var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
pos.left -= this.popup.getTextLeftOffset();
var rect = editor.container.getBoundingClientRect();
pos.top += rect.top - renderer.layerConfig.offset;
pos.left += rect.left - editor.renderer.scrollLeft;
pos.left += renderer.$gutterLayer.gutterWidth;
this.popup.show(pos, lineHeight);
}
};
this.detach = function() {
this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
this.editor.off("changeSelection", this.changeListener);
this.editor.off("blur", this.blurListener);
this.editor.off("mousedown", this.mousedownListener);
this.editor.off("mousewheel", this.mousewheelListener);
this.changeTimer.cancel();
if (this.popup && this.popup.isOpen) {
this.gatherCompletionsId = this.gatherCompletionsId + 1;
}
if (this.popup)
this.popup.hide();
this.activated = false;
this.completions = this.base = null;
};
this.changeListener = function(e) {
var cursor = this.editor.selection.lead;
if (cursor.row != this.base.row || cursor.column < this.base.column) {
this.detach();
}
if (this.activated)
this.changeTimer.schedule();
else
this.detach();
};
this.blurListener = function() {
var el = document.activeElement;
if (el != this.editor.textInput.getElement() && el.parentNode != this.popup.container)
this.detach();
};
this.mousedownListener = function(e) {
this.detach();
};
this.mousewheelListener = function(e) {
this.detach();
};
this.goTo = function(where) {
var row = this.popup.getRow();
var max = this.popup.session.getLength() - 1;
switch(where) {
case "up": row = row <= 0 ? max : row - 1; break;
case "down": row = row >= max ? -1 : row + 1; break;
case "start": row = 0; break;
case "end": row = max; break;
}
this.popup.setRow(row);
};
this.insertMatch = function(data) {
if (!data)
data = this.popup.getData(this.popup.getRow());
if (!data)
return false;
if (data.completer && data.completer.insertMatch) {
data.completer.insertMatch(this.editor);
} else {
if (this.completions.filterText) {
var ranges = this.editor.selection.getAllRanges();
for (var i = 0, range; range = ranges[i]; i++) {
range.start.column -= this.completions.filterText.length;
this.editor.session.remove(range);
}
}
if (data.snippet)
snippetManager.insertSnippet(this.editor, data.snippet);
else
this.editor.execCommand("insertstring", data.value || data);
}
this.detach();
};
this.commands = {
"Up": function(editor) { editor.completer.goTo("up"); },
"Down": function(editor) { editor.completer.goTo("down"); },
"Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
"Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
"Esc": function(editor) { editor.completer.detach(); },
"Space": function(editor) { editor.completer.detach(); editor.insert(" ");},
"Return": function(editor) { return editor.completer.insertMatch(); },
"Shift-Return": function(editor) { editor.completer.insertMatch(true); },
"Tab": function(editor) {
var result = editor.completer.insertMatch();
if (!result && !editor.tabstopManager)
editor.completer.goTo("down");
else
return result;
},
"PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
"PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
};
this.gatherCompletions = function(editor, callback) {
var session = editor.getSession();
var pos = editor.getCursorPosition();
var line = session.getLine(pos.row);
var prefix = util.retrievePrecedingIdentifier(line, pos.column);
this.base = editor.getCursorPosition();
this.base.column -= prefix.length;
var matches = [];
var total = editor.completers.length;
editor.completers.forEach(function(completer, i) {
completer.getCompletions(editor, session, pos, prefix, function(err, results) {
if (!err)
matches = matches.concat(results);
var pos = editor.getCursorPosition();
var line = session.getLine(pos.row);
callback(null, {
prefix: util.retrievePrecedingIdentifier(line, pos.column, results[0] && results[0].identifierRegex),
matches: matches,
finished: (--total === 0)
});
});
});
return true;
};
this.showPopup = function(editor) {
if (this.editor)
this.detach();
this.activated = true;
this.editor = editor;
if (editor.completer != this) {
if (editor.completer)
editor.completer.detach();
editor.completer = this;
}
editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
editor.on("changeSelection", this.changeListener);
editor.on("blur", this.blurListener);
editor.on("mousedown", this.mousedownListener);
editor.on("mousewheel", this.mousewheelListener);
this.updateCompletions();
};
this.updateCompletions = function(keepPopupPosition) {
if (keepPopupPosition && this.base && this.completions) {
var pos = this.editor.getCursorPosition();
var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
if (prefix == this.completions.filterText)
return;
this.completions.setFilter(prefix);
if (!this.completions.filtered.length)
return this.detach();
if (this.completions.filtered.length == 1
&& this.completions.filtered[0].value == prefix
&& !this.completions.filtered[0].snippet)
return this.detach();
this.openPopup(this.editor, prefix, keepPopupPosition);
return;
}
var _id = this.gatherCompletionsId;
this.gatherCompletions(this.editor, function(err, results) {
var detachIfFinished = function() {
if (!results.finished) return;
return this.detach();
}.bind(this);
var prefix = results.prefix;
var matches = results && results.matches;
if (!matches || !matches.length)
return detachIfFinished();
if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
return;
this.completions = new FilteredList(matches);
this.completions.setFilter(prefix);
var filtered = this.completions.filtered;
if (!filtered.length)
return detachIfFinished();
if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
return detachIfFinished();
if (this.autoInsert && filtered.length == 1)
return this.insertMatch(filtered[0]);
this.openPopup(this.editor, prefix, keepPopupPosition);
}.bind(this));
};
this.cancelContextMenu = function() {
var stop = function(e) {
this.editor.off("nativecontextmenu", stop);
if (e && e.domEvent)
event.stopEvent(e.domEvent);
}.bind(this);
setTimeout(stop, 10);
this.editor.on("nativecontextmenu", stop);
};
}).call(Autocomplete.prototype);
Autocomplete.startCommand = {
name: "startAutocomplete",
exec: function(editor) {
if (!editor.completer)
editor.completer = new Autocomplete();
editor.completer.autoInsert =
editor.completer.autoSelect = true;
editor.completer.showPopup(editor);
editor.completer.cancelContextMenu();
},
bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
};
var FilteredList = function(array, filterText, mutateData) {
this.all = array;
this.filtered = array;
this.filterText = filterText || "";
};
(function(){
this.setFilter = function(str) {
if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
var matches = this.filtered;
else
var matches = this.all;
this.filterText = str;
matches = this.filterCompletions(matches, this.filterText);
matches = matches.sort(function(a, b) {
return b.exactMatch - a.exactMatch || b.score - a.score;
});
var prev = null;
matches = matches.filter(function(item){
var caption = item.value || item.caption || item.snippet;
if (caption === prev) return false;
prev = caption;
return true;
});
this.filtered = matches;
};
this.filterCompletions = function(items, needle) {
var results = [];
var upper = needle.toUpperCase();
var lower = needle.toLowerCase();
loop: for (var i = 0, item; item = items[i]; i++) {
var caption = item.value || item.caption || item.snippet;
if (!caption) continue;
var lastIndex = -1;
var matchMask = 0;
var penalty = 0;
var index, distance;
for (var j = 0; j < needle.length; j++) {
var i1 = caption.indexOf(lower[j], lastIndex + 1);
var i2 = caption.indexOf(upper[j], lastIndex + 1);
index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
if (index < 0)
continue loop;
distance = index - lastIndex - 1;
if (distance > 0) {
if (lastIndex === -1)
penalty += 10;
penalty += distance;
}
matchMask = matchMask | (1 << index);
lastIndex = index;
}
item.matchMask = matchMask;
item.exactMatch = penalty ? 0 : 1;
item.score = (item.score || 0) - penalty;
results.push(item);
}
return results;
};
}).call(FilteredList.prototype);
exports.Autocomplete = Autocomplete;
exports.FilteredList = FilteredList;
});
define('ace/ext/modelist', ['require', 'exports', 'module' ], function(require, exports, module) {
var modes = [];
function getModeForPath(path) {
var mode = modesByName.text;
var fileName = path.split(/[\/\\]/).pop();
for (var i = 0; i < modes.length; i++) {
if (modes[i].supportsFile(fileName)) {
mode = modes[i];
break;
}
}
return mode;
}
var Mode = function(name, caption, extensions) {
this.name = name;
this.caption = caption;
this.mode = "ace/mode/" + name;
this.extensions = extensions;
if (/\^/.test(extensions)) {
var re = extensions.replace(/\|(\^)?/g, function(a, b){
return "$|" + (b ? "^" : "^.*\\.");
}) + "$";
} else {
var re = "^.*\\.(" + extensions + ")$";
}
this.extRe = new RegExp(re, "gi");
};
Mode.prototype.supportsFile = function(filename) {
return filename.match(this.extRe);
};
var supportedModes = {
ABAP: ["abap"],
ActionScript:["as"],
ADA: ["ada|adb"],
Apache_Conf: ["^htaccess|^htgroups|^htpasswd|^conf|htaccess|htgroups|htpasswd"],
AsciiDoc: ["asciidoc"],
Assembly_x86:["asm"],
AutoHotKey: ["ahk"],
BatchFile: ["bat|cmd"],
C9Search: ["c9search_results"],
C_Cpp: ["cpp|c|cc|cxx|h|hh|hpp"],
Cirru: ["cirru|cr"],
Clojure: ["clj"],
Cobol: ["CBL|COB"],
coffee: ["coffee|cf|cson|^Cakefile"],
ColdFusion: ["cfm"],
CSharp: ["cs"],
CSS: ["css"],
Curly: ["curly"],
D: ["d|di"],
Dart: ["dart"],
Diff: ["diff|patch"],
Dockerfile: ["^Dockerfile"],
Dot: ["dot"],
Erlang: ["erl|hrl"],
EJS: ["ejs"],
Forth: ["frt|fs|ldr"],
FTL: ["ftl"],
Gherkin: ["feature"],
Glsl: ["glsl|frag|vert"],
golang: ["go"],
Groovy: ["groovy"],
HAML: ["haml"],
Handlebars: ["hbs|handlebars|tpl|mustache"],
Haskell: ["hs"],
haXe: ["hx"],
HTML: ["html|htm|xhtml"],
HTML_Ruby: ["erb|rhtml|html.erb"],
INI: ["ini|conf|cfg|prefs"],
Jack: ["jack"],
Jade: ["jade"],
Java: ["java"],
JavaScript: ["js|jsm"],
JSON: ["json"],
JSONiq: ["jq"],
JSP: ["jsp"],
JSX: ["jsx"],
Julia: ["jl"],
LaTeX: ["tex|latex|ltx|bib"],
LESS: ["less"],
Liquid: ["liquid"],
Lisp: ["lisp"],
LiveScript: ["ls"],
LogiQL: ["logic|lql"],
LSL: ["lsl"],
Lua: ["lua"],
LuaPage: ["lp"],
Lucene: ["lucene"],
Makefile: ["^Makefile|^GNUmakefile|^makefile|^OCamlMakefile|make"],
MATLAB: ["matlab"],
Markdown: ["md|markdown"],
MEL: ["mel"],
MySQL: ["mysql"],
MUSHCode: ["mc|mush"],
Nix: ["nix"],
ObjectiveC: ["m|mm"],
OCaml: ["ml|mli"],
Pascal: ["pas|p"],
Perl: ["pl|pm"],
pgSQL: ["pgsql"],
PHP: ["php|phtml"],
Powershell: ["ps1"],
Prolog: ["plg|prolog"],
Properties: ["properties"],
Protobuf: ["proto"],
Python: ["py"],
R: ["r"],
RDoc: ["Rd"],
RHTML: ["Rhtml"],
Ruby: ["rb|ru|gemspec|rake|^Guardfile|^Rakefile|^Gemfile"],
Rust: ["rs"],
SASS: ["sass"],
SCAD: ["scad"],
Scala: ["scala"],
Smarty: ["smarty|tpl"],
Scheme: ["scm|rkt"],
SCSS: ["scss"],
SH: ["sh|bash|^.bashrc"],
SJS: ["sjs"],
Space: ["space"],
snippets: ["snippets"],
Soy_Template:["soy"],
SQL: ["sql"],
Stylus: ["styl|stylus"],
SVG: ["svg"],
Tcl: ["tcl"],
Tex: ["tex"],
Text: ["txt"],
Textile: ["textile"],
Toml: ["toml"],
Twig: ["twig"],
Typescript: ["ts|typescript|str"],
Vala: ["vala"],
VBScript: ["vbs"],
Velocity: ["vm"],
Verilog: ["v|vh|sv|svh"],
XML: ["xml|rdf|rss|wsdl|xslt|atom|mathml|mml|xul|xbl"],
XQuery: ["xq"],
YAML: ["yaml|yml"]
};
var nameOverrides = {
ObjectiveC: "Objective-C",
CSharp: "C#",
golang: "Go",
C_Cpp: "C/C++",
coffee: "CoffeeScript",
HTML_Ruby: "HTML (Ruby)",
FTL: "FreeMarker"
};
var modesByName = {};
for (var name in supportedModes) {
var data = supportedModes[name];
var displayName = (nameOverrides[name] || name).replace(/_/g, " ");
var filename = name.toLowerCase();
var mode = new Mode(filename, displayName, data[0]);
modesByName[filename] = mode;
modes.push(mode);
}
module.exports = {
getModeForPath: getModeForPath,
modes: modes,
modesByName: modesByName
};
});
define('ace/autocomplete/popup', ['require', 'exports', 'module' , 'ace/edit_session', 'ace/virtual_renderer', 'ace/editor', 'ace/range', 'ace/lib/event', 'ace/lib/lang', 'ace/lib/dom'], function(require, exports, module) {
var EditSession = require("../edit_session").EditSession;
var Renderer = require("../virtual_renderer").VirtualRenderer;
var Editor = require("../editor").Editor;
var Range = require("../range").Range;
var event = require("../lib/event");
var lang = require("../lib/lang");
var dom = require("../lib/dom");
var $singleLineEditor = function(el) {
var renderer = new Renderer(el);
renderer.$maxLines = 4;
var editor = new Editor(renderer);
editor.setHighlightActiveLine(false);
editor.setShowPrintMargin(false);
editor.renderer.setShowGutter(false);
editor.renderer.setHighlightGutterLine(false);
editor.$mouseHandler.$focusWaitTimout = 0;
return editor;
};
var AcePopup = function(parentNode) {
var el = dom.createElement("div");
var popup = new $singleLineEditor(el);
if (parentNode)
parentNode.appendChild(el);
el.style.display = "none";
popup.renderer.content.style.cursor = "default";
popup.renderer.setStyle("ace_autocomplete");
popup.setOption("displayIndentGuides", false);
var noop = function(){};
popup.focus = noop;
popup.$isFocused = true;
popup.renderer.$cursorLayer.restartTimer = noop;
popup.renderer.$cursorLayer.element.style.opacity = 0;
popup.renderer.$maxLines = 8;
popup.renderer.$keepTextAreaAtCursor = false;
popup.setHighlightActiveLine(false);
popup.session.highlight("");
popup.session.$searchHighlight.clazz = "ace_highlight-marker";
popup.on("mousedown", function(e) {
var pos = e.getDocumentPosition();
popup.selection.moveToPosition(pos);
selectionMarker.start.row = selectionMarker.end.row = pos.row;
e.stop();
});
var lastMouseEvent;
var hoverMarker = new Range(-1,0,-1,Infinity);
var selectionMarker = new Range(-1,0,-1,Infinity);
selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
popup.setSelectOnHover = function(val) {
if (!val) {
hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
} else if (hoverMarker.id) {
popup.session.removeMarker(hoverMarker.id);
hoverMarker.id = null;
}
}
popup.setSelectOnHover(false);
popup.on("mousemove", function(e) {
if (!lastMouseEvent) {
lastMouseEvent = e;
return;
}
if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
return;
}
lastMouseEvent = e;
lastMouseEvent.scrollTop = popup.renderer.scrollTop;
var row = lastMouseEvent.getDocumentPosition().row;
if (hoverMarker.start.row != row) {
if (!hoverMarker.id)
popup.setRow(row);
setHoverMarker(row);
}
});
popup.renderer.on("beforeRender", function() {
if (lastMouseEvent && hoverMarker.start.row != -1) {
lastMouseEvent.$pos = null;
var row = lastMouseEvent.getDocumentPosition().row;
if (!hoverMarker.id)
popup.setRow(row);
setHoverMarker(row, true);
}
});
popup.renderer.on("afterRender", function() {
var row = popup.getRow();
var t = popup.renderer.$textLayer;
var selected = t.element.childNodes[row - t.config.firstRow];
if (selected == t.selectedNode)
return;
if (t.selectedNode)
dom.removeCssClass(t.selectedNode, "ace_selected");
t.selectedNode = selected;
if (selected)
dom.addCssClass(selected, "ace_selected");
});
var hideHoverMarker = function() { setHoverMarker(-1) };
var setHoverMarker = function(row, suppressRedraw) {
if (row !== hoverMarker.start.row) {
hoverMarker.start.row = hoverMarker.end.row = row;
if (!suppressRedraw)
popup.session._emit("changeBackMarker");
popup._emit("changeHoverMarker");
}
};
popup.getHoveredRow = function() {
return hoverMarker.start.row;
};
event.addListener(popup.container, "mouseout", hideHoverMarker);
popup.on("hide", hideHoverMarker);
popup.on("changeSelection", hideHoverMarker);
popup.session.doc.getLength = function() {
return popup.data.length;
};
popup.session.doc.getLine = function(i) {
var data = popup.data[i];
if (typeof data == "string")
return data;
return (data && data.value) || "";
};
var bgTokenizer = popup.session.bgTokenizer;
bgTokenizer.$tokenizeRow = function(i) {
var data = popup.data[i];
var tokens = [];
if (!data)
return tokens;
if (typeof data == "string")
data = {value: data};
if (!data.caption)
data.caption = data.value;
var last = -1;
var flag, c;
for (var i = 0; i < data.caption.length; i++) {
c = data.caption[i];
flag = data.matchMask & (1 << i) ? 1 : 0;
if (last !== flag) {
tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c});
last = flag;
} else {
tokens[tokens.length - 1].value += c;
}
}
if (data.meta) {
var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth;
if (data.meta.length + data.caption.length < maxW - 2)
tokens.push({type: "rightAlignedText", value: data.meta});
}
return tokens;
};
bgTokenizer.$updateOnChange = noop;
bgTokenizer.start = noop;
popup.session.$computeWidth = function() {
return this.screenWidth = 0;
}
popup.isOpen = false;
popup.isTopdown = false;
popup.data = [];
popup.setData = function(list) {
popup.data = list || [];
popup.setValue(lang.stringRepeat("\n", list.length), -1);
popup.setRow(0);
};
popup.getData = function(row) {
return popup.data[row];
};
popup.getRow = function() {
return selectionMarker.start.row;
};
popup.setRow = function(line) {
line = Math.max(-1, Math.min(this.data.length, line));
if (selectionMarker.start.row != line) {
popup.selection.clearSelection();
selectionMarker.start.row = selectionMarker.end.row = line || 0;
popup.session._emit("changeBackMarker");
popup.moveCursorTo(line || 0, 0);
if (popup.isOpen)
popup._signal("select");
}
};
popup.on("changeSelection", function() {
if (popup.isOpen)
popup.setRow(popup.selection.lead.row);
});
popup.hide = function() {
this.container.style.display = "none";
this._signal("hide");
popup.isOpen = false;
};
popup.show = function(pos, lineHeight, topdownOnly) {
var el = this.container;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var renderer = this.renderer;
var maxH = renderer.$maxLines * lineHeight * 1.4;
var top = pos.top + this.$borderSize;
if (top + maxH > screenHeight - lineHeight && !topdownOnly) {
el.style.top = "";
el.style.bottom = screenHeight - top + "px";
popup.isTopdown = false;
} else {
top += lineHeight;
el.style.top = top + "px";
el.style.bottom = "";
popup.isTopdown = true;
}
el.style.display = "";
this.renderer.$textLayer.checkForSizeChanges();
var left = pos.left;
if (left + el.offsetWidth > screenWidth)
left = screenWidth - el.offsetWidth;
el.style.left = left + "px";
this._signal("show");
lastMouseEvent = null;
popup.isOpen = true;
};
popup.getTextLeftOffset = function() {
return this.$borderSize + this.renderer.$padding + this.$imageSize;
};
popup.$imageSize = 0;
popup.$borderSize = 1;
return popup;
};
dom.importCssString("\
.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
background-color: #CAD6FA;\
z-index: 1;\
}\
.ace_editor.ace_autocomplete .ace_line-hover {\
border: 1px solid #abbffe;\
margin-top: -1px;\
background: rgba(233,233,253,0.4);\
}\
.ace_editor.ace_autocomplete .ace_line-hover {\
position: absolute;\
z-index: 2;\
}\
.ace_editor.ace_autocomplete .ace_scroller {\
background: none;\
border: none;\
box-shadow: none;\
}\
.ace_rightAlignedText {\
color: gray;\
display: inline-block;\
position: absolute;\
right: 4px;\
text-align: right;\
z-index: -1;\
}\
.ace_editor.ace_autocomplete .ace_completion-highlight{\
color: #000;\
text-shadow: 0 0 0.01em;\
}\
.ace_editor.ace_autocomplete {\
width: 280px;\
z-index: 200000;\
background: #fbfbfb;\
color: #444;\
border: 1px lightgray solid;\
position: fixed;\
box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
line-height: 1.4;\
}");
exports.AcePopup = AcePopup;
});
define('kitchen-sink/file_drop', ['require', 'exports', 'module' , 'ace/config', 'ace/lib/event', 'ace/ext/modelist', 'ace/editor'], function(require, exports, module) {
var config = require("ace/config");
var event = require("ace/lib/event");
var modelist = require("ace/ext/modelist");
module.exports = function(editor) {
event.addListener(editor.container, "dragover", function(e) {
var types = e.dataTransfer.types;
if (types && Array.prototype.indexOf.call(types, 'Files') !== -1)
return event.preventDefault(e);
});
event.addListener(editor.container, "drop", function(e) {
var file;
try {
file = e.dataTransfer.files[0];
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function() {
var mode = modelist.getModeForPath(file.name);
editor.session.doc.setValue(reader.result);
editor.session.setMode(mode.mode);
editor.session.modeName = mode.name;
};
reader.readAsText(file);
}
return event.preventDefault(e);
} catch(err) {
return event.stopEvent(e);
}
});
};
var Editor = require("ace/editor").Editor;
config.defineOptions(Editor.prototype, "editor", {
loadDroppedFile: {
set: function() { module.exports(this); },
value: true
}
});
});
define('ace/autocomplete/util', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.parForEach = function(array, fn, callback) {
var completed = 0;
var arLength = array.length;
if (arLength === 0)
callback();
for (var i = 0; i < arLength; i++) {
fn(array[i], function(result, err) {
completed++;
if (completed === arLength)
callback(result, err);
});
}
};
var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;
exports.retrievePrecedingIdentifier = function(text, pos, regex) {
regex = regex || ID_REGEX;
var buf = [];
for (var i = pos-1; i >= 0; i--) {
if (regex.test(text[i]))
buf.push(text[i]);
else
break;
}
return buf.reverse().join("");
};
exports.retrieveFollowingIdentifier = function(text, pos, regex) {
regex = regex || ID_REGEX;
var buf = [];
for (var i = pos; i < text.length; i++) {
if (regex.test(text[i]))
buf.push(text[i]);
else
break;
}
return buf;
};
});
define('kitchen-sink/dev_util', ['require', 'exports', 'module' ], function(require, exports, module) {
function isStrict() {
try { return !arguments.callee.caller.caller.caller}
catch(e){ return true }
}
function warn() {
if (isStrict()) {
console.error("trying to access to global variable");
}
}
function def(o, key, get) {
try {
Object.defineProperty(o, key, {
configurable: true,
get: get,
set: function(val) {
delete o[key];
o[key] = val;
}
});
} catch(e) {
console.error(e);
}
}
def(window, "ace", function(){ warn(); return window.env.editor });
def(window, "editor", function(){ warn(); return window.env.editor });
def(window, "session", function(){ warn(); return window.env.editor.session });
def(window, "split", function(){ warn(); return window.env.split });
});
define('ace/autocomplete/text_completer', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/;
function getWordIndex(doc, pos) {
var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
return textBefore.split(splitRegex).length - 1;
}
function wordDistance(doc, pos) {
var prefixPos = getWordIndex(doc, pos);
var words = doc.getValue().split(splitRegex);
var wordScores = Object.create(null);
var currentWord = words[prefixPos];
words.forEach(function(word, idx) {
if (!word || word === currentWord) return;
var distance = Math.abs(prefixPos - idx);
var score = words.length - distance;
if (wordScores[word]) {
wordScores[word] = Math.max(score, wordScores[word]);
} else {
wordScores[word] = score;
}
});
return wordScores;
}
exports.getCompletions = function(editor, session, pos, prefix, callback) {
var wordScore = wordDistance(session, pos, prefix);
var wordList = Object.keys(wordScore);
callback(null, wordList.map(function(word) {
return {
name: word,
value: word,
score: wordScore[word],
meta: "local"
};
}));
};
});
define('kitchen-sink/inline_editor', ['require', 'exports', 'module' , 'ace/line_widgets', 'ace/editor', 'ace/virtual_renderer', 'ace/lib/dom', 'ace/commands/default_commands'], function(require, exports, module) {
var LineWidgets = require("ace/line_widgets").LineWidgets;
var Editor = require("ace/editor").Editor;
var Renderer = require("ace/virtual_renderer").VirtualRenderer;
var dom = require("ace/lib/dom");
require("ace/commands/default_commands").commands.push({
name: "openInlineEditor",
bindKey: "F3",
exec: function(editor) {
var split = window.env.split;
var s = editor.session;
var inlineEditor = new Editor(new Renderer());
var splitSession = split.$cloneSession(s);
var row = editor.getCursorPosition().row;
if (editor.session.lineWidgets && editor.session.lineWidgets[row]) {
editor.session.lineWidgets[row].destroy();
return;
}
var rowCount = 10;
var w = {
row: row,
fixedWidth: true,
el: dom.createElement("div"),
editor: editor
};
var el = w.el;
el.appendChild(inlineEditor.container);
if (!editor.session.widgetManager) {
editor.session.widgetManager = new LineWidgets(editor.session);
editor.session.widgetManager.attach(editor);
}
var h = rowCount*editor.renderer.layerConfig.lineHeight;
inlineEditor.container.style.height = h + "px";
el.style.position = "absolute";
el.style.zIndex = "4";
el.style.borderTop = "solid blue 2px";
el.style.borderBottom = "solid blue 2px";
inlineEditor.setSession(splitSession);
editor.session.widgetManager.addLineWidget(w);
var kb = {
handleKeyboard:function(_,hashId, keyString) {
if (hashId === 0 && keyString === "esc") {
w.destroy();
return true;
}
}
};
w.destroy = function() {
editor.keyBinding.removeKeyboardHandler(kb);
s.widgetManager.removeLineWidget(w);
};
editor.keyBinding.addKeyboardHandler(kb);
inlineEditor.keyBinding.addKeyboardHandler(kb);
editor.on("changeSession", function(e) {
w.el.parentNode && w.el.parentNode.removeChild(w.el);
});
inlineEditor.setTheme("ace/theme/solarized_light");
}
});
});
define('ace/ext/beautify', ['require', 'exports', 'module' , 'ace/token_iterator', 'ace/ext/beautify/php_rules'], function(require, exports, module) {
var TokenIterator = require("ace/token_iterator").TokenIterator;
var phpTransform = require("./beautify/php_rules").transform;
exports.beautify = function(session) {
var iterator = new TokenIterator(session, 0, 0);
var token = iterator.getCurrentToken();
var context = session.$modeId.split("/").pop();
var code = phpTransform(iterator, context);
session.doc.setValue(code);
};
exports.commands = [{
name: "beautify",
exec: function(editor) {
exports.beautify(editor.session);
},
bindKey: "Ctrl-Shift-B"
}]
});define('ace/ext/spellcheck', ['require', 'exports', 'module' , 'ace/lib/event', 'ace/editor', 'ace/config'], function(require, exports, module) {
var event = require("../lib/event");
exports.contextMenuHandler = function(e){
var host = e.target;
var text = host.textInput.getElement();
if (!host.selection.isEmpty())
return;
var c = host.getCursorPosition();
var r = host.session.getWordRange(c.row, c.column);
var w = host.session.getTextRange(r);
host.session.tokenRe.lastIndex = 0;
if (!host.session.tokenRe.test(w))
return;
var PLACEHOLDER = "\x01\x01";
var value = w + " " + PLACEHOLDER;
text.value = value;
text.setSelectionRange(w.length, w.length + 1);
text.setSelectionRange(0, 0);
text.setSelectionRange(0, w.length);
var afterKeydown = false;
event.addListener(text, "keydown", function onKeydown() {
event.removeListener(text, "keydown", onKeydown);
afterKeydown = true;
});
host.textInput.setInputHandler(function(newVal) {
console.log(newVal , value, text.selectionStart, text.selectionEnd)
if (newVal == value)
return '';
if (newVal.lastIndexOf(value, 0) === 0)
return newVal.slice(value.length);
if (newVal.substr(text.selectionEnd) == value)
return newVal.slice(0, -value.length);
if (newVal.slice(-2) == PLACEHOLDER) {
var val = newVal.slice(0, -2);
if (val.slice(-1) == " ") {
if (afterKeydown)
return val.substring(0, text.selectionEnd);
val = val.slice(0, -1);
host.session.replace(r, val);
return "";
}
}
return newVal;
});
};
var Editor = require("../editor").Editor;
require("../config").defineOptions(Editor.prototype, "editor", {
spellcheck: {
set: function(val) {
var text = this.textInput.getElement();
text.spellcheck = !!val;
if (!val)
this.removeListener("nativecontextmenu", exports.contextMenuHandler);
else
this.on("nativecontextmenu", exports.contextMenuHandler);
},
value: true
}
});
});
define('ace/ext/beautify/php_rules', ['require', 'exports', 'module' , 'ace/token_iterator'], function(require, exports, module) {
var TokenIterator = require("ace/token_iterator").TokenIterator;
exports.newLines = [{
type: 'support.php_tag',
value: '<?php'
}, {
type: 'support.php_tag',
value: '<?'
}, {
type: 'support.php_tag',
value: '?>'
}, {
type: 'paren.lparen',
value: '{',
indent: true
}, {
type: 'paren.rparen',
breakBefore: true,
value: '}',
indent: false
}, {
type: 'paren.rparen',
breakBefore: true,
value: '})',
indent: false,
dontBreak: true
}, {
type: 'comment'
}, {
type: 'text',
value: ';'
}, {
type: 'text',
value: ':',
context: 'php'
}, {
type: 'keyword',
value: 'case',
indent: true,
dontBreak: true
}, {
type: 'keyword',
value: 'default',
indent: true,
dontBreak: true
}, {
type: 'keyword',
value: 'break',
indent: false,
dontBreak: true
}, {
type: 'punctuation.doctype.end',
value: '>'
}, {
type: 'meta.tag.punctuation.end',
value: '>'
}, {
type: 'meta.tag.punctuation.begin',
value: '<',
blockTag: true,
indent: true,
dontBreak: true
}, {
type: 'meta.tag.punctuation.begin',
value: '</',
indent: false,
breakBefore: true,
dontBreak: true
}, {
type: 'punctuation.operator',
value: ';'
}];
exports.spaces = [{
type: 'xml-pe',
prepend: true
},{
type: 'entity.other.attribute-name',
prepend: true
}, {
type: 'storage.type',
value: 'var',
append: true
}, {
type: 'storage.type',
value: 'function',
append: true
}, {
type: 'keyword.operator',
value: '='
}, {
type: 'keyword',
value: 'as',
prepend: true,
append: true
}, {
type: 'keyword',
value: 'function',
append: true
}, {
type: 'support.function',
next: /[^\(]/,
append: true
}, {
type: 'keyword',
value: 'or',
append: true,
prepend: true
}, {
type: 'keyword',
value: 'and',
append: true,
prepend: true
}, {
type: 'keyword',
value: 'case',
append: true
}, {
type: 'keyword.operator',
value: '||',
append: true,
prepend: true
}, {
type: 'keyword.operator',
value: '&&',
append: true,
prepend: true
}];
exports.singleTags = ['!doctype','area','base','br','hr','input','img','link','meta'];
exports.transform = function(iterator, maxPos, context) {
var token = iterator.getCurrentToken();
var newLines = exports.newLines;
var spaces = exports.spaces;
var singleTags = exports.singleTags;
var code = '';
var indentation = 0;
var dontBreak = false;
var tag;
var lastTag;
var lastToken = {};
var nextTag;
var nextToken = {};
var breakAdded = false;
var value = '';
while (token!==null) {
console.log(token);
if( !token ){
token = iterator.stepForward();
continue;
}
if( token.type == 'support.php_tag' && token.value != '?>' ){
context = 'php';
}
else if( token.type == 'support.php_tag' && token.value == '?>' ){
context = 'html';
}
else if( token.type == 'meta.tag.name.style' && context != 'css' ){
context = 'css';
}
else if( token.type == 'meta.tag.name.style' && context == 'css' ){
context = 'html';
}
else if( token.type == 'meta.tag.name.script' && context != 'js' ){
context = 'js';
}
else if( token.type == 'meta.tag.name.script' && context == 'js' ){
context = 'html';
}
nextToken = iterator.stepForward();
if (nextToken && nextToken.type.indexOf('meta.tag.name') == 0) {
nextTag = nextToken.value;
}
if ( lastToken.type == 'support.php_tag' && lastToken.value == '<?=') {
dontBreak = true;
}
if (token.type == 'meta.tag.name') {
token.value = token.value.toLowerCase();
}
if (token.type == 'text') {
token.value = token.value.trim();
}
if (!token.value) {
token = nextToken;
continue;
}
value = token.value;
for (var i in spaces) {
if (
token.type == spaces[i].type &&
(!spaces[i].value || token.value == spaces[i].value) &&
(
nextToken &&
(!spaces[i].next || spaces[i].next.test(nextToken.value))
)
) {
if (spaces[i].prepend) {
value = ' ' + token.value;
}
if (spaces[i].append) {
value += ' ';
}
}
}
if (token.type.indexOf('meta.tag.name') == 0) {
tag = token.value;
}
breakAdded = false;
for (i in newLines) {
if (
token.type == newLines[i].type &&
(
!newLines[i].value ||
token.value == newLines[i].value
) &&
(
!newLines[i].blockTag ||
singleTags.indexOf(nextTag) === -1
) &&
(
!newLines[i].context ||
newLines[i].context === context
)
) {
if (newLines[i].indent === false) {
indentation--;
}
if (
newLines[i].breakBefore &&
( !newLines[i].prev || newLines[i].prev.test(lastToken.value) )
) {
code += "\n";
breakAdded = true;
for (i = 0; i < indentation; i++) {
code += "\t";
}
}
break;
}
}
if (dontBreak===false) {
for (i in newLines) {
if (
lastToken.type == newLines[i].type &&
(
!newLines[i].value || lastToken.value == newLines[i].value
) &&
(
!newLines[i].blockTag ||
singleTags.indexOf(tag) === -1
) &&
(
!newLines[i].context ||
newLines[i].context === context
)
) {
if (newLines[i].indent === true) {
indentation++;
}
if (!newLines[i].dontBreak && !breakAdded) {
code += "\n";
for (i = 0; i < indentation; i++) {
code += "\t";
}
}
break;
}
}
}
code += value;
if ( lastToken.type == 'support.php_tag' && lastToken.value == '?>' ) {
dontBreak = false;
}
lastTag = tag;
lastToken = token;
token = nextToken;
if (token===null) {
break;
}
}
return code;
};
});
define('ace/occur', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/search', 'ace/edit_session', 'ace/search_highlight', 'ace/lib/dom'], function(require, exports, module) {
var oop = require("./lib/oop");
var Range = require("./range").Range;
var Search = require("./search").Search;
var EditSession = require("./edit_session").EditSession;
var SearchHighlight = require("./search_highlight").SearchHighlight;
function Occur() {}
oop.inherits(Occur, Search);
(function() {
this.enter = function(editor, options) {
if (!options.needle) return false;
var pos = editor.getCursorPosition();
this.displayOccurContent(editor, options);
var translatedPos = this.originalToOccurPosition(editor.session, pos);
editor.moveCursorToPosition(translatedPos);
return true;
}
this.exit = function(editor, options) {
var pos = options.translatePosition && editor.getCursorPosition();
var translatedPos = pos && this.occurToOriginalPosition(editor.session, pos);
this.displayOriginalContent(editor);
if (translatedPos)
editor.moveCursorToPosition(translatedPos);
return true;
}
this.highlight = function(sess, regexp) {
var hl = sess.$occurHighlight = sess.$occurHighlight || sess.addDynamicMarker(
new SearchHighlight(null, "ace_occur-highlight", "text"));
hl.setRegexp(regexp);
sess._emit("changeBackMarker"); // force highlight layer redraw
}
this.displayOccurContent = function(editor, options) {
this.$originalSession = editor.session;
var found = this.matchingLines(editor.session, options);
var lines = found.map(function(foundLine) { return foundLine.content; });
var occurSession = new EditSession(lines.join('\n'));
occurSession.$occur = this;
occurSession.$occurMatchingLines = found;
editor.setSession(occurSession);
this.$useEmacsStyleLineStart = this.$originalSession.$useEmacsStyleLineStart;
occurSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart;
this.highlight(occurSession, options.re);
occurSession._emit('changeBackMarker');
}
this.displayOriginalContent = function(editor) {
editor.setSession(this.$originalSession);
this.$originalSession.$useEmacsStyleLineStart = this.$useEmacsStyleLineStart;
}
this.originalToOccurPosition = function(session, pos) {
var lines = session.$occurMatchingLines;
var nullPos = {row: 0, column: 0};
if (!lines) return nullPos;
for (var i = 0; i < lines.length; i++) {
if (lines[i].row === pos.row)
return {row: i, column: pos.column};
}
return nullPos;
}
this.occurToOriginalPosition = function(session, pos) {
var lines = session.$occurMatchingLines;
if (!lines || !lines[pos.row])
return pos;
return {row: lines[pos.row].row, column: pos.column};
}
this.matchingLines = function(session, options) {
options = oop.mixin({}, options);
if (!session || !options.needle) return [];
var search = new Search();
search.set(options);
return search.findAll(session).reduce(function(lines, range) {
var row = range.start.row;
var last = lines[lines.length-1];
return last && last.row === row ?
lines :
lines.concat({row: row, content: session.getLine(row)});
}, []);
}
}).call(Occur.prototype);
var dom = require('./lib/dom');
dom.importCssString(".ace_occur-highlight {\n\
border-radius: 4px;\n\
background-color: rgba(87, 255, 8, 0.25);\n\
position: absolute;\n\
z-index: 4;\n\
-moz-box-sizing: border-box;\n\
-webkit-box-sizing: border-box;\n\
box-sizing: border-box;\n\
box-shadow: 0 0 4px rgb(91, 255, 50);\n\
}\n\
.ace_dark .ace_occur-highlight {\n\
background-color: rgb(80, 140, 85);\n\
box-shadow: 0 0 4px rgb(60, 120, 70);\n\
}\n", "incremental-occur-highlighting");
exports.Occur = Occur;
});
|
function cos (number) {
return Math.cos(number)
}
module.exports = cos
|
import gulp from 'gulp'
import babel from 'gulp-babel'
import eslint from 'gulp-eslint'
import sequence from 'gulp-sequence'
import rimraf from 'rimraf'
gulp.task('lint', function () {
return gulp.src(['**/*.js', '!node_modules/**', '!dist/**'])
.pipe(eslint())
.pipe(eslint.format())
})
gulp.task('dist:clean', (cb) => {
return rimraf('./dist', cb)
})
gulp.task('dist:build', () => {
return gulp.src('src/**/*.js')
.pipe(babel({ babelrc: './.babelrc' }))
.pipe(gulp.dest('dist'))
})
gulp.task('default', sequence(['lint', 'dist:clean'], 'dist:build'))
|
formatDate = d3.time.format("%b %d");
// parameters
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
},
width = 960 - margin.left - margin.right,
height = 300 - margin.bottom - margin.top;
// scale function
var timeScale = d3.time.scale()
.domain([new Date('2012-01-02'), new Date('2013-01-01')])
.range([0, width])
.clamp(true);
// initial value
var startValue = timeScale(new Date('2012-03-20'));
startingValue = new Date('2012-03-20');
//////////
// defines brush
var brush = d3.svg.brush()
.x(timeScale)
.extent([startingValue, startingValue])
.on("brush", brushed);
var svg = d3.select("#timeslider2").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
// classic transform to position g
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.attr("class", "x axis")
// put in middle of screen
.attr("transform", "translate(0," + height / 2 + ")")
// inroduce axis
.call(d3.svg.axis()
.scale(timeScale)
.orient("bottom")
.tickFormat(function (d) {
return formatDate(d);
})
.tickSize(0)
.tickPadding(12)
.tickValues([timeScale.domain()[0], timeScale.domain()[1]]))
.select(".domain")
.select(function () {
console.log(this);
return this.parentNode.appendChild(this.cloneNode(true));
})
.attr("class", "halo");
var slider = svg.append("g")
.attr("class", "slider")
.call(brush);
slider.selectAll(".extent,.resize")
.remove();
slider.select(".background")
.attr("height", height);
var handle = slider.append("g")
.attr("class", "handle")
handle.append("path")
.attr("transform", "translate(0," + height / 2 + ")")
.attr("d", "M 0 -20 V 20")
handle.append('text')
.text(startingValue)
.attr("transform", "translate(" + (-18) + " ," + (height / 2 - 25) + ")");
slider
.call(brush.event)
function brushed() {
var value = brush.extent()[0];
if (d3.event.sourceEvent) { // not a programmatic event
value = timeScale.invert(d3.mouse(this)[0]);
brush.extent([value, value]);
}
handle.attr("transform", "translate(" + timeScale(value) + ",0)");
handle.select('text').text(formatDate(value));
}
|
var assert = require('assert'),
fs = require('fs'),
http = require('http'),
path = require('path'),
util = require('util'),
base64 = require('flatiron').common.base64,
nock = require('nock'),
helpers = require('./index'),
mock = require('./mock'),
quill = require('../../lib/quill'),
trees = require('system.json/test/fixtures/trees');
//
// ### function shouldQuillOk
//
// Test macro which executes the quill command for
// the current vows context.
//
exports.shouldQuillOk = function () {
var args = Array.prototype.slice.call(arguments),
assertion = "should respond with no error",
assertFn,
setupFn,
mockRequest,
userPrompts;
args.forEach(function (a) {
if (typeof a === 'function' && a.name === 'setup') {
setupFn = a;
}
else if (typeof a === 'function') {
assertFn = a;
}
else if (typeof a === 'string') {
assertion = a;
}
else if (a instanceof Array) {
userPrompts = a;
}
else {
userPrompts = [a];
}
});
var context = {
topic: function () {
var fixturesDir = path.join(__dirname, '..', 'fixtures'),
that = this,
argv;
quill.argv._ = this.args = this.context.name.split(' ');
if (!quill.initialized) {
quill.config.stores.file.file = path.join(fixturesDir, 'dot-quillconf');
quill.config.stores.file.loadSync();
//
// Setup mock directories
//
quill.options.directories['ssh'] = path.join(fixturesDir, 'keys');
quill.options.directories['cache'] = path.join(fixturesDir, 'cache');
quill.options.directories['install'] = path.join(fixturesDir, 'installed');
}
// Pad the output slightly
console.log('');
//
// Execute the target command and assert that no error
// was returned.
//
function startQuill() {
quill.start(function () {
// Pad the output slightly
console.log('');
that.callback.apply(that, arguments);
});
}
//
// If there is a setup function then call it
// and start quill
//
if (setupFn) {
if (setupFn.length) {
return setupFn.apply(this, [startQuill]);
}
setupFn.call(this);
}
startQuill();
}
};
context[assertion] = assertFn
? assertFn
: function (err, _) { assert.isTrue(!err) };
return context;
};
//
// ### function shouldInit(done)
//
// Test macro which initializes quill.
//
exports.shouldInit = function (done) {
return {
"This test requires quill.init()": {
topic: function () {
helpers.init(this.callback);
},
"with no error": function (err) {
assert.isTrue(!err);
if (done) {
done();
}
}
}
};
};
exports.shouldAddOne = function (sourceDir, system) {
var tarball = system.tarball;
return {
topic: function () {
system.tarball = path.join(sourceDir, system.tarball);
quill.composer.cache.addOne(system, this.callback);
},
"should add the system to the cache": function (err, system) {
assert.isNull(err);
assert.isObject(system);
assert.include(system, 'name');
assert.include(system, 'version');
assert.include(system, 'root');
assert.include(system, 'cached');
assert.include(system, 'tarball');
assert.isObject(fs.statSync(system.root));
assert.isObject(fs.statSync(system.cached));
assert.isObject(fs.statSync(system.tarball));
//
// Move the tarball back
//
fs.renameSync(system.tarball, path.join(sourceDir, tarball));
}
};
};
|
'use strict';
var test = require("tap").test;
var ummon = require('..')({pause:true, autoSave:false});
// Stub in some tasks
var collection = {
"collection": "barankay",
"defaults": {
"cwd": "/Users/matt/tmp/"
},
"config": {
"enabled": true
},
"tasks": {
"send-text-messages": {
"command": "sh test.sh",
"cwd": "/Users/matt/tmp",
"trigger": {
"time": "* * * * *"
}
}
}
}
test('Create a collection from an object', function(t){
t.plan(7);
ummon.createCollectionAndTasks(collection, function(err){
t.equal(ummon.defaults.barankay.cwd, '/Users/matt/tmp/', 'Defaults were set')
t.equal(ummon.tasks['barankay.send-text-messages'].command, 'sh test.sh', 'Tasks were set')
t.ok(ummon.timers['barankay.send-text-messages'], 'Timers were setup')
t.equal(ummon.config.collections.barankay.enabled, true, 'Settings were set')
ummon.getTasks(collection.collection, function(err, tasks){
t.equal(tasks[0].collection, 'barankay');
t.equal(tasks[0].defaults.cwd, '/Users/matt/tmp/');
t.equal(tasks[0].config.enabled, true);
})
});
})
test('Try to load an empty collection', function(t){
t.plan(2);
var emptyCollection = {
"collection": "empty",
"config": {
"enabled": false
},
"tasks": {}
}
ummon.createCollectionAndTasks(emptyCollection, function(err){
t.pass('Whew! It did get to the callback')
t.type(err, Error, '... and passed an error to the callback');
});
})
var disabledCollection = {
"collection": "disabledCollection",
"defaults": {
"cwd": "/Users/matt/tmp/"
},
"config": {
"enabled": false
},
"tasks": {
"send-text-messages": {
"command": "sh test.sh",
"cwd": "/Users/matt/tmp",
"trigger": {
"time": "* * * * *"
}
}
}
}
test('Create a collection that is disabled', function(t){
t.plan(7);
ummon.createCollectionAndTasks(disabledCollection, function(err){
t.equal(ummon.defaults.disabledCollection.cwd, '/Users/matt/tmp/', 'Defaults were set')
t.equal(ummon.tasks['disabledCollection.send-text-messages'].command, 'sh test.sh', 'Tasks were set')
t.notOk(ummon.timers['disabledCollection.send-text-messages'], 'Timers were not setup')
t.equal(ummon.config.collections.disabledCollection.enabled, false, 'Settings were set')
ummon.getTasks(disabledCollection.collection, function(err, tasks){
t.equal(tasks[0].collection, 'disabledCollection');
t.equal(tasks[0].defaults.cwd, '/Users/matt/tmp/');
t.equal(tasks[0].config.enabled, false);
})
});
})
test('teardown', function(t){
setImmediate(function() {
process.exit();
});
t.end();
});
|
window.mangopie = angular.module('MangopieApp', ['MangopieControllers', 'MangopieServices', 'chieffancypants.loadingBar']);
// controller
var MangopieControllers = angular.module('MangopieControllers', []);
MangopieControllers.controller('MangopieCtrl', ['$scope', 'MangaFactory', 'ChapterFactory',
function ($scope, MangaFactory, ChapterFactory, cfpLoadingBar) {
$scope.chapters = [];
$scope.cur_chapter = {};
$scope.cur_chapter_images = {};
$scope.cur_image = {};
$scope.cur_image_src = "";
// for now will only support Naruto
MangaFactory.get({ Id: '4e70ea03c092255ef70046f0' }, function (res) {
$scope.chapters = res.chapters;
});
$scope.changeSelected = function () {
ChapterFactory.get({ Id: $scope.cur_chapter[3] }, function (res) {
$scope.cur_chapter_images = res.images.slice().reverse();
$scope.loadImage($scope.cur_chapter_images[0][1]);
})
}
$scope.loadImage = function (param) {
$scope.cur_image_src = "/api/img/" + param.split('.')[0] + "/" + param.slice(-3);
}
}]);
// services
angular.module('MangopieServices', ['ngResource'])
.factory('MangaFactory', function ($resource) {
return $resource('/api/mng/:Id', { Id: '@Id' });
})
.factory('ChapterFactory', function ($resource) {
return $resource('/api/chp/:Id', { Id: '@Id' });
})
|
export default {
selectMatchedName: 'Select a Matching Record'
};
|
var fnode = require('./fnode');
var utils = require('./utils');
var _ = require('underscore');
var formatter = {
plugins: {}
, options: {}
, utils: utils
};
/**
* This function is an alias to setup a list of plugins
* @param {object} plugin [, plugin] [, plugin] ...
* @return {Object} formatter
*/
formatter.use = function () {
var plugins = _.toArray(arguments);
var names = _.pluck(plugins, 'name');
_.each(plugins, _.bind(formatter.addPlugin, formatter));
this.options.plugin_order = names;
return this;
};
/**
* Configures the formatter
* @param {Object} options
* - plugin_order {Array[String]} an array of plugin names in the right order of priority
*/
formatter.setOptions = function (options) {
formatter.options = options;
// so it throws an error if the config is wrong
return formatter.getOptions();
};
/**
* Returns the options object
* @return {Object}
*/
formatter.getOptions = function () {
if (!_.isArray(formatter.options.plugin_order)) {
var plugin_names = _.pluck(formatter.plugins, 'name').join(', ');
throw new Error('Missing plugin_order array. Available plugins: ' + plugin_names);
}
return formatter.options;
};
/**
* Adds a plugin to the formatter
* @param {Object} plugin
* - name {String}
* - parser ? {Function}
* - treeManipulator ? {Function}
* - formatter ? {Function}
*/
formatter.addPlugin = function (plugin) {
if (!plugin.name) {
throw new Error('plugin missing name');
}
this.plugins[plugin.name] = plugin;
};
/**
* Access plugins by name
* @param {String} name
* @return {Object} plugin
*/
formatter.getPlugin = function (name) {
return this.plugins[name];
};
/**
* Returns the plugin objects in the propper order
* @return {Array[Object]}
*/
formatter.getPluginsInOrder = function () {
return _.map(formatter.getOptions().plugin_order, function (name) {
var plugin = formatter.getPlugin(name);
if (!plugin) {
throw new Error('Missing plugin: ' + name);
}
return plugin;
});
};
/**
* Returns an array of curried parsers
* @return {Array[Function]}
*/
formatter.getParserChain = function () {
return _.reduceRight(formatter.getPluginsInOrder(), function (memo, plugin) {
if (plugin.parser) {
memo.unshift(_.partial(plugin.parser, _.first(memo)));
}
return memo;
}, []);
};
/**
* Runs the parser chain on a string
* @param {String} text
* @return {Array[fnode]} ast
*/
formatter.runParsers = function (text) {
return formatter.getParserChain()[0](text);
};
/**
* Runs all the tree manipulators in the correct order
* @param {Array[fnode]} ast
* @return {Array[fnode]}
*/
formatter.runTreeManipulators = function (ast) {
_.each(formatter.getPluginsInOrder(), function (plugin) { // TODO: reverse order?
if (plugin.treeManipulator) {
plugin.treeManipulator(ast);
}
});
return ast;
};
/**
* Runs the formatters on an ast in the right order
* @param {Array[fnode]} ast
* @return {String}
*/
formatter.runformatters = function (ast) {
return _.map(ast, function (node) {
var plugin = formatter.getPlugin(node.type);
return plugin.formatter(node);
}).join('');
};
/**
* Runs the entire formatting process
* @param {String} text
*/
formatter.format = _.compose(formatter.runformatters, formatter.runTreeManipulators, formatter.runParsers);
formatter.fnode = fnode;
module.exports = formatter;
|
import passport from 'passport';
import { BasicStrategy } from 'passport-http';
passport.use(new BasicStrategy((username, password, done) => {
if (username === 'admin' && password === 'password') {
return done(null, { username, password });
}
return done(null, false, { message: 'Who are you again?' });
}));
export default passport.authenticate('basic', { session: false });
|
var assert = require("assert");
/*
This file contains the more basic tests - short sentences, word counts,
sentence counts, and so on. Longer texts are split into their own test
files for convenience.
*/
var TS = require('../index');
var ts = TS();
describe('Test Cleaning of text', function(){
it('testCleaning', function(){
assert.equal('', TS(false).text);
assert.equal('There once was a little sausage named Baldrick. and he lived happily ever after.',
TS('There once was a little sausage named Baldrick. . . . And he lived happily ever after.!! !??').text);
});
});
describe('Test Counts', function(){
it('testCounts', function(){
assert.equal(47, ts.characterCount('There once was a little sausage named Baldrick.'));
assert.equal(47, ts.textLength('There once was a little sausage named Baldrick.'));
assert.equal(39, ts.letterCount('There once was a little sausage named Baldrick.'));
assert.equal(0, ts.letterCount(''));
assert.equal(0, ts.letterCount(' '));
assert.equal(0, ts.wordCount(''));
assert.equal(0, ts.wordCount(' '));
assert.equal(0, ts.sentenceCount(''));
assert.equal(0, ts.sentenceCount(' '));
assert.equal(1, ts.letterCount('a'));
assert.equal(0, ts.letterCount(''));
assert.equal(46, ts.letterCount('this sentence has 30 characters, not including the digits'));
});
});
describe('Test Syllables', function(){
it('testSyllableCountBasicWords', function(){
assert.equal(0, ts.syllableCount('.'));
assert.equal(1, ts.syllableCount('a'));
assert.equal(1, ts.syllableCount('was'));
assert.equal(1, ts.syllableCount('the'));
assert.equal(1, ts.syllableCount('and'));
assert.equal(2, ts.syllableCount('foobar'));
assert.equal(2, ts.syllableCount('hello'));
assert.equal(1, ts.syllableCount('world'));
assert.equal(3, ts.syllableCount('wonderful'));
assert.equal(2, ts.syllableCount('simple'));
assert.equal(2, ts.syllableCount('easy'));
assert.equal(1, ts.syllableCount('hard'));
assert.equal(1, ts.syllableCount('quick'));
assert.equal(1, ts.syllableCount('brown'));
assert.equal(1, ts.syllableCount('fox'));
assert.equal(1, ts.syllableCount('jumped'));
assert.equal(2, ts.syllableCount('over'));
assert.equal(2, ts.syllableCount('lazy'));
assert.equal(1, ts.syllableCount('dog'));
assert.equal(3, ts.syllableCount('camera'));
});
it('testSyllableCountComplexWords', function(){
assert.equal(12, ts.syllableCount('antidisestablishmentarianism'));
assert.equal(14, ts.syllableCount('supercalifragilisticexpialidocious'));
assert.equal(8, ts.syllableCount('chlorofluorocarbonation'));
assert.equal(4, ts.syllableCount('forethoughtfulness'));
assert.equal(4, ts.syllableCount('phosphorescent'));
assert.equal(5, ts.syllableCount('theoretician'));
assert.equal(5, ts.syllableCount('promiscuity'));
assert.equal(4, ts.syllableCount('unbutlering'));
assert.equal(5, ts.syllableCount('continuity'));
assert.equal(1, ts.syllableCount('craunched'));
assert.equal(1, ts.syllableCount('squelched'));
assert.equal(1, ts.syllableCount('scrounge'));
assert.equal(1, ts.syllableCount('coughed'));
assert.equal(1, ts.syllableCount('smile'));
assert.equal(4, ts.syllableCount('monopoly'));
assert.equal(2, ts.syllableCount('doughey'));
assert.equal(3, ts.syllableCount('doughier'));
assert.equal(4, ts.syllableCount('leguminous'));
assert.equal(3, ts.syllableCount('thoroughbreds'));
assert.equal(2, ts.syllableCount('special'));
assert.equal(3, ts.syllableCount('delicious'));
assert.equal(2, ts.syllableCount('spatial'));
assert.equal(4, ts.syllableCount('pacifism'));
assert.equal(4, ts.syllableCount('coagulant'));
assert.equal(2, ts.syllableCount('shouldn\'t'));
assert.equal(3, ts.syllableCount('mcdonald'));
assert.equal(3, ts.syllableCount('audience'));
assert.equal(2, ts.syllableCount('finance'));
assert.equal(3, ts.syllableCount('prevalence'));
assert.equal(5, ts.syllableCount('impropriety'));
assert.equal(3, ts.syllableCount('alien'));
assert.equal(2, ts.syllableCount('dreadnought'));
assert.equal(3, ts.syllableCount('verandah'));
assert.equal(3, ts.syllableCount('similar'));
assert.equal(4, ts.syllableCount('similarly'));
assert.equal(2, ts.syllableCount('central'));
assert.equal(1, ts.syllableCount('cyst'));
assert.equal(1, ts.syllableCount('term'));
assert.equal(2, ts.syllableCount('order'));
assert.equal(1, ts.syllableCount('fur'));
assert.equal(2, ts.syllableCount('sugar'));
assert.equal(2, ts.syllableCount('paper'));
assert.equal(1, ts.syllableCount('make'));
assert.equal(1, ts.syllableCount('gem'));
assert.equal(2, ts.syllableCount('program'));
assert.equal(2, ts.syllableCount('hopeless'));
assert.equal(3, ts.syllableCount('hopelessly'));
assert.equal(2, ts.syllableCount('careful'));
assert.equal(3, ts.syllableCount('carefully'));
assert.equal(2, ts.syllableCount('stuffy'));
assert.equal(2, ts.syllableCount('thistle'));
assert.equal(2, ts.syllableCount('teacher'));
assert.equal(3, ts.syllableCount('unhappy'));
assert.equal(5, ts.syllableCount('ambiguity'));
assert.equal(4, ts.syllableCount('validity'));
assert.equal(4, ts.syllableCount('ambiguous'));
assert.equal(2, ts.syllableCount('deserve'));
assert.equal(2, ts.syllableCount('blooper'));
assert.equal(1, ts.syllableCount('scooped'));
assert.equal(2, ts.syllableCount('deserve'));
assert.equal(1, ts.syllableCount('deal'));
assert.equal(1, ts.syllableCount('death'));
assert.equal(1, ts.syllableCount('dearth'));
assert.equal(1, ts.syllableCount('deign'));
assert.equal(1, ts.syllableCount('reign'));
assert.equal(2, ts.syllableCount('bedsore'));
assert.equal(5, ts.syllableCount('anorexia'));
assert.equal(3, ts.syllableCount('anymore'));
assert.equal(1, ts.syllableCount('cored'));
assert.equal(1, ts.syllableCount('sore'));
assert.equal(2, ts.syllableCount('foremost'));
assert.equal(2, ts.syllableCount('restore'));
assert.equal(2, ts.syllableCount('minute'));
assert.equal(3, ts.syllableCount('manticores'));
assert.equal(4, ts.syllableCount('asparagus'));
assert.equal(3, ts.syllableCount('unexplored'));
assert.equal(4, ts.syllableCount('unexploded'));
assert.equal(3, ts.syllableCount('CAPITALS'));
});
it('testSyllableCountProgrammedExceptions', function(){
assert.equal(3, ts.syllableCount('simile'));
assert.equal(2, ts.syllableCount('shoreline'));
assert.equal(3, ts.syllableCount('forever'));
});
it('testAverageSyllablesPerWord', function(){
assert.equal(1, ts.averageSyllablesPerWord('and then there was one'));
assert.equal(2, ts.averageSyllablesPerWord('because special ducklings deserve rainbows'));
assert.equal(1.5, ts.averageSyllablesPerWord('and then there was one because special ducklings deserve rainbows'));
});
});
describe('Test Words', function(){
it('testWordCount', function(){
assert.equal(9, ts.wordCount('The quick brown fox jumps over the lazy dog'));
assert.equal(9, ts.wordCount('The quick brown fox jumps over the lazy dog.'));
assert.equal(9, ts.wordCount('The quick brown fox jumps over the lazy dog. '));
assert.equal(9, ts.wordCount(' The quick brown fox jumps over the lazy dog. '));
assert.equal(9, ts.wordCount(' The quick brown fox jumps over the lazy dog. '));
assert.equal(2, ts.wordCount('Yes. No.'));
assert.equal(2, ts.wordCount('Yes.No.'));
assert.equal(2, ts.wordCount('Yes.No.'));
assert.equal(2, ts.wordCount('Yes . No.'));
assert.equal(2, ts.wordCount('Yes .No.'));
assert.equal(2, ts.wordCount('Yes - No. '));
});
it('testCheckPercentageWordsWithThreeSyllables', function(){
assert.equal(9, Math.ceil(ts.percentageWordsWithThreeSyllables('there is just one word with three syllables in this sentence')));
assert.equal(9, Math.ceil(ts.percentageWordsWithThreeSyllables('there is just one word with three syllables in this sentence', true)));
assert.equal(0, Math.ceil(ts.percentageWordsWithThreeSyllables('there are no valid words with three Syllables in this sentence', false)));
assert.equal(5, Math.ceil(ts.percentageWordsWithThreeSyllables('there is one and only one word with three or more syllables in this long boring sentence of twenty words')));
assert.equal(10, Math.ceil(ts.percentageWordsWithThreeSyllables('there are two and only two words with three or more syllables in this long sentence of exactly twenty words')));
assert.equal(5, Math.ceil(ts.percentageWordsWithThreeSyllables('there is Actually only one valid word with three or more syllables in this long sentence of Exactly twenty words', false)));
assert.equal(0, Math.ceil(ts.percentageWordsWithThreeSyllables('no long words in this sentence')));
assert.equal(0, Math.ceil(ts.percentageWordsWithThreeSyllables('no long valid words in this sentence because the test ignores proper case words like this Behemoth', false)));
});
});
describe('Test Sentences', function(){
it('testSentenceCount', function(){
assert.equal(1, ts.sentenceCount('This is a sentence'));
assert.equal(1, ts.sentenceCount('This is a sentence.'));
assert.equal(1, ts.sentenceCount('This is a sentence!'));
assert.equal(1, ts.sentenceCount('This is a sentence?'));
assert.equal(1, ts.sentenceCount('This is a sentence..'));
assert.equal(2, ts.sentenceCount('This is a sentence. So is this.'));
assert.equal(2, ts.sentenceCount("This is a sentence. \n\n So is this, but this is multi-line!"));
assert.equal(2, ts.sentenceCount('This is a sentence,. So is this.'));
assert.equal(2, ts.sentenceCount('This is a sentence!? So is this.'));
assert.equal(3, ts.sentenceCount('This is a sentence. So is this. And this one as well.'));
assert.equal(1, ts.sentenceCount('This is a sentence - but just one.'));
assert.equal(1, ts.sentenceCount('This is a sentence (but just one).'));
});
it('testAverageWordsPerSentence', function(){
assert.equal(4, ts.averageWordsPerSentence('This is a sentence'));
assert.equal(4, ts.averageWordsPerSentence('This is a sentence.'));
assert.equal(4, ts.averageWordsPerSentence('This is a sentence. '));
assert.equal(4, ts.averageWordsPerSentence('This is a sentence. This is a sentence'));
assert.equal(4, ts.averageWordsPerSentence('This is a sentence. This is a sentence.'));
assert.equal(4, ts.averageWordsPerSentence('This, is - a sentence . This is a sentence. '));
assert.equal(5.5, ts.averageWordsPerSentence('This is a sentence with extra text. This is a sentence. '));
assert.equal(6, ts.averageWordsPerSentence('This is a sentence with some extra text. This is a sentence. '));
});
});
describe('Test Scores',function(){
it('testFleschKincaidReadingEase', function(){
assert.equal(121.2, ts.fleschKincaidReadingEase('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.')); // Best score possible
assert.equal(94.3, ts.fleschKincaidReadingEase('The quick brown fox jumps over the lazy dog.'));
assert.equal(94.3, ts.fleschKincaidReadingEase('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(94.3, ts.fleschKincaidReadingEase('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(94.3, ts.fleschKincaidReadingEase("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(50.5, ts.fleschKincaidReadingEase('Now it is time for a more complicated sentence, including several longer words.'));
});
it('testFleschKincaidGradeLevel', function(){
assert.equal(-3.4, ts.fleschKincaidGradeLevel('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.')); // Best score possible
assert.equal(2.3, ts.fleschKincaidGradeLevel('The quick brown fox jumps over the lazy dog.'));
assert.equal(2.3, ts.fleschKincaidGradeLevel('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(2.3, ts.fleschKincaidGradeLevel('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(2.3, ts.fleschKincaidGradeLevel("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(9.4, ts.fleschKincaidGradeLevel('Now it is time for a more complicated sentence, including several longer words.'));
});
it('testGunningFogScore', function(){
assert.equal(0.4, ts.gunningFogScore('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.')); // Best possible score
assert.equal(3.6, ts.gunningFogScore('The quick brown fox jumps over the lazy dog.'));
assert.equal(3.6, ts.gunningFogScore('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(3.6, ts.gunningFogScore("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(3.6, ts.gunningFogScore('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(14.4, ts.gunningFogScore('Now it is time for a more complicated sentence, including several longer words.'));
assert.equal(8.3, ts.gunningFogScore('Now it is time for a more Complicated sentence, including Several longer words.')); // Two proper nouns, ignored
});
it('testColemanLiauIndex', function(){
assert.equal(3.0, ts.colemanLiauIndex('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.')); // Best possible score would be if all words were 1 character
assert.equal(7.1, ts.colemanLiauIndex('The quick brown fox jumps over the lazy dog.'));
assert.equal(7.1, ts.colemanLiauIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(7.1, ts.colemanLiauIndex("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(7.1, ts.colemanLiauIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(13.6, ts.colemanLiauIndex('Now it is time for a more complicated sentence, including several longer words.'));
});
it('testSMOGIndex', function(){
assert.equal(1.8, ts.smogIndex('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.')); // Should be 1.8 for any text with no words of 3+ syllables
assert.equal(1.8, ts.smogIndex('The quick brown fox jumps over the lazy dog.'));
assert.equal(1.8, ts.smogIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(1.8, ts.smogIndex("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(1.8, ts.smogIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(10.1, ts.smogIndex('Now it is time for a more complicated sentence, including several longer words.'));
});
it('testAutomatedReadabilityIndex', function(){
assert.equal(-5.6, ts.automatedReadabilityIndex('This. Is. A. Nice. Set. Of. Small. Words. Of. One. Part. Each.'));
assert.equal(1.4, ts.automatedReadabilityIndex('The quick brown fox jumps over the lazy dog.'));
assert.equal(1.4, ts.automatedReadabilityIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.'));
assert.equal(1.4, ts.automatedReadabilityIndex("The quick brown fox jumps over the lazy dog. \n\n The quick brown fox jumps over the lazy dog."));
assert.equal(1.4, ts.automatedReadabilityIndex('The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog'));
assert.equal(8.6, ts.automatedReadabilityIndex('Now it is time for a more complicated sentence, including several longer words.'));
});
});
|
MindMeld = {
export(collectionName, password, callBack) {
Meteor.call('mm_export', collectionName, password, callBack);
},
import(options) {
Meteor.call('mm_import', options);
}
}
|
class ServerData {
constructor() {
this.pendingRequests = new Map(); // map[requestId, res]
this.socketsByBrowser = new Map(); // map[browserId, socket]
this.browserProcessMap = new Map(); // map[browserId, process]
}
purgeBrowserData(deletedBrowserId) {
var purgeList = [];
this.browserProcessMap.delete(deletedBrowserId);
this.socketsByBrowser.delete(deletedBrowserId);
for (let [requestId, res] of this.pendingRequests) {
var browserId = res.req.browserId;
if (browserId === deletedBrowserId) {
purgeList.push(requestId);
}
}
for (let requestId of purgeList) {
console.log('Deleting orphaned request: ', requestId)
this.pendingRequests.delete(requestId);
}
}
fetchPendingCreationData() {
// note: if we do not properly remove entries from 'this.pendingRequests' as appropriate the following code coudl result in picking the wrong browserId
for (let [requestId, res] of this.pendingRequests) {
let browserId = res.req.browserId;
if (!(this.socketsByBrowser.has(browserId)))
return [requestId, browserId];
}
throw new Error('Unable to find a pending browserId');
};
getSocket(browserId) {
return this.socketsByBrowser.get(browserId);
}
getBrowser(browserId) {
return this.browserProcessMap.get(browserId);
}
getPendingRequest(requestId) {
return this.pendingRequests.get(requestId);
}
hasBrowserSocket(browserId) {
return this.socketsByBrowser.has(browserId);
}
hasBrowserProcess(browserId) {
return this.browserProcessMap.has(browserId);
}
setPendingRequest(requestId, res) {
this.pendingRequests.set(requestId, res);
}
setBrowser(browserId, browser) {
this.browserProcessMap.set(browserId, browser);
}
setSocket(browserId, socket) {
this.socketsByBrowser.set(browserId, socket);
}
deletePendingRequest(requestId) {
this.pendingRequests.delete(requestId);
}
}
// only a single instance of this one will exist
module.exports = new ServerData();
|
(function(exports) {
'use strict';
function App(id) {
this.id = id;
}
App.prototype.bow = function() {
if (this.id) {
return 'This is App' + this.id + '.';
}
return 'This does not have id.';
};
exports.App = App;
})(window);
|
module.exports = Data;
function Data(layer, params) {
this.layer = layer;
this.params = params === true ? {} : params;
this.middleware = null;
this.route = null;
this.router = null;
}
|
'use strict';
const core = require('../core');
module.exports = core({
modules: [
require('../modules/state'),
require('../modules/view'),
require('../modules/view.build'),
require('../modules/view.dom'),
require('../modules/router'),
require('../modules/router.fetch'),
require('../modules/router.register-lite'),
require('../modules/primary.router.builder'),
],
options: {
kit: 'lite',
browser: true,
},
});
|
/**
* Created by liulin on 2017/2/27.
*/
ES.Common.Pop.MapMarkerSelect= ES.Common.Pop.Map.extend({
// 加载工具栏
loadMapToolArea: function () {
this.oToolArea = new ES.MapControl.ESMapToolArea(this.oMapMaster, {});
this.oToolBox = new ES.MapControl.ESMapToolBox(this.oMapMaster, {});
this.oToolTile = new ES.MapControl.ESMapTile(this.oMapMaster, {});
new ES.MapControl.ESMapSearch(this.oMapMaster, {});
this.oToolEdit = new ES.MapControl.MapEditPos(this.oMapMaster, {
acParentDivClass: ['ex-layout-maptool', 'ex-theme-maptool', 'ex-map-top', 'ex-map-right','ex-maptool-edit'],
});
},
})
|
import Route from 'ember-route';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Route.extend(AuthenticatedRouteMixin, {
authenticationRoute: 'signin'
});
|
import React from 'react';
import { render } from 'react-dom';
import 'sanitize.css/sanitize.css';
import './style';
import App from 'App';
import registerServiceWorker from './registerServiceWorker';
render(<App />, document.getElementById('root'));
registerServiceWorker();
|
/*!
* DevExtreme (dx.messages.fr.js)
* Version: 19.2.11
* Build date: Mon Dec 14 2020
*
* Copyright (c) 2012 - 2020 Developer Express Inc. ALL RIGHTS RESERVED
* Read about DevExtreme licensing here: https://js.devexpress.com/Licensing/
*/
"use strict";
! function(root, factory) {
if ("function" === typeof define && define.amd) {
define(function(require) {
factory(require("devextreme/localization"))
})
} else {
if ("object" === typeof module && module.exports) {
factory(require("devextreme/localization"))
} else {
factory(DevExpress.localization)
}
}
}(this, function(localization) {
localization.loadMessages({
fr: {
Yes: "Oui",
No: "Non",
Cancel: "Annuler",
Clear: "Vider",
Done: "Termin\xe9",
Loading: "Chargement...",
Select: "S\xe9lection...",
Search: "Recherche",
Back: "Retour",
OK: "OK",
"dxCollectionWidget-noDataText": "Pas de donn\xe9es",
"dxDropDownEditor-selectLabel": "S\xe9lection",
"validation-required": "Obligatoire",
"validation-required-formatted": "{0} est obligatoire",
"validation-numeric": "La valeur doit \xeatre un nombre",
"validation-numeric-formatted": "{0} doit \xeatre un nombre",
"validation-range": "La valeur ne se trouve pas dans la plage valide",
"validation-range-formatted": "{0} ne se trouve pas dans la plage valide",
"validation-stringLength": "La longueur de la valeur est incorrecte",
"validation-stringLength-formatted": "La longueur de {0} est incorrecte",
"validation-custom": "La valeur est invalide",
"validation-custom-formatted": "{0} est invalide",
"validation-async": "La valeur est invalide",
"validation-async-formatted": "{0} est invalide",
"validation-compare": "La valeur est inappropri\xe9e",
"validation-compare-formatted": "{0} est inappropri\xe9e",
"validation-pattern": "La valeur ne correspond pas au mod\xe8le",
"validation-pattern-formatted": "{0} ne correspond pas au mod\xe8le",
"validation-email": "L'adresse email est invalide",
"validation-email-formatted": "{0} est invalide",
"validation-mask": "La valeur est invalide",
"dxLookup-searchPlaceholder": "Nombre minimum de caract\xe8res: {0}",
"dxList-pullingDownText": "Tirez vers le bas pour actualiser...",
"dxList-pulledDownText": "Relacher pour actualiser...",
"dxList-refreshingText": "Actualisation...",
"dxList-pageLoadingText": "Chargement...",
"dxList-nextButtonText": "Suivant",
"dxList-selectAll": "S\xe9lectionner tout",
"dxListEditDecorator-delete": "Supprimer",
"dxListEditDecorator-more": "Plus",
"dxScrollView-pullingDownText": "Tirez vers le bas pour actualiser...",
"dxScrollView-pulledDownText": "Relacher pour actualiser...",
"dxScrollView-refreshingText": "Mise \xe0 jour...",
"dxScrollView-reachBottomText": "Chargement...",
"dxDateBox-simulatedDataPickerTitleTime": "Choisissez l'heure",
"dxDateBox-simulatedDataPickerTitleDate": "Choisissez la date",
"dxDateBox-simulatedDataPickerTitleDateTime": "Choisissez la date et l'heure",
"dxDateBox-validation-datetime": "La valeur doit \xeatre une date ou une heure.",
"dxFileUploader-selectFile": "Choisissez un fichier",
"dxFileUploader-dropFile": "Enlever fichier",
"dxFileUploader-bytes": "Bytes",
"dxFileUploader-kb": "kb",
"dxFileUploader-Mb": "Mb",
"dxFileUploader-Gb": "Gb",
"dxFileUploader-upload": "T\xe9l\xe9charger",
"dxFileUploader-uploaded": "T\xe9l\xe9charg\xe9",
"dxFileUploader-readyToUpload": "Pr\xeat \xe0 t\xe9l\xe9charger",
"dxFileUploader-uploadFailedMessage": "\xc9chec du t\xe9l\xe9chargement",
"dxFileUploader-invalidFileExtension": "Type de fichier non autoris\xe9",
"dxFileUploader-invalidMaxFileSize": "Fichier trop volumineux",
"dxFileUploader-invalidMinFileSize": "Fichier trop petit",
"dxRangeSlider-ariaFrom": "De {0}",
"dxRangeSlider-ariaTill": "\xe0 {0}",
"dxSwitch-switchedOnText": "ON",
"dxSwitch-switchedOffText": "OFF",
"dxForm-optionalMark": "optionnel",
"dxForm-requiredMessage": "{0} est obligatoire",
"dxNumberBox-invalidValueMessage": "La valeur doit \xeatre un nombre",
"dxNumberBox-noDataText": "Pas de donn\xe9es",
"dxDataGrid-columnChooserTitle": "Choisir les colonnes",
"dxDataGrid-columnChooserEmptyText": "Faites glisser une colonne ici pour la cacher",
"dxDataGrid-groupContinuesMessage": "Suite \xe0 la page suivante",
"dxDataGrid-groupContinuedMessage": "Suite de la page pr\xe9c\xe9dente",
"dxDataGrid-groupHeaderText": "Grouper avec cette colonne",
"dxDataGrid-ungroupHeaderText": "D\xe9grouper",
"dxDataGrid-ungroupAllText": "D\xe9grouper tout",
"dxDataGrid-editingEditRow": "Editer",
"dxDataGrid-editingSaveRowChanges": "Sauvegarder",
"dxDataGrid-editingCancelRowChanges": "Annuler",
"dxDataGrid-editingDeleteRow": "Supprimer",
"dxDataGrid-editingUndeleteRow": "Restaurer",
"dxDataGrid-editingConfirmDeleteMessage": "\xcates-vous s\xfbr de vouloir supprimer cet \xe9l\xe9ment ?",
"dxDataGrid-validationCancelChanges": "Annuler les changements",
"dxDataGrid-groupPanelEmptyText": "Faites glisser une colonne ICI pour grouper par celle-ci",
"dxDataGrid-noDataText": "Pas de donn\xe9es",
"dxDataGrid-searchPanelPlaceholder": "Recherche...",
"dxDataGrid-filterRowShowAllText": "(tous)",
"dxDataGrid-filterRowResetOperationText": "R\xe9initialiser",
"dxDataGrid-filterRowOperationEquals": "Egale",
"dxDataGrid-filterRowOperationNotEquals": "Diff\xe9rent de",
"dxDataGrid-filterRowOperationLess": "Plus petit",
"dxDataGrid-filterRowOperationLessOrEquals": "Plus petit ou \xe9gal",
"dxDataGrid-filterRowOperationGreater": "Plus grand",
"dxDataGrid-filterRowOperationGreaterOrEquals": "Plus grand ou \xe9gal",
"dxDataGrid-filterRowOperationStartsWith": "Commence par",
"dxDataGrid-filterRowOperationContains": "Contient",
"dxDataGrid-filterRowOperationNotContains": "Ne contient pas",
"dxDataGrid-filterRowOperationEndsWith": "Termine par",
"dxDataGrid-filterRowOperationBetween": "Entre",
"dxDataGrid-filterRowOperationBetweenStartText": "D\xe9but",
"dxDataGrid-filterRowOperationBetweenEndText": "Fin",
"dxDataGrid-applyFilterText": "Filtrer le texte",
"dxDataGrid-trueText": "Vrai",
"dxDataGrid-falseText": "Faux",
"dxDataGrid-sortingAscendingText": "Tri croissant",
"dxDataGrid-sortingDescendingText": "Tri d\xe9croissant",
"dxDataGrid-sortingClearText": "Supprimer le tri",
"dxDataGrid-editingSaveAllChanges": "Sauvegarder les changements",
"dxDataGrid-editingCancelAllChanges": "Ignorer les changements",
"dxDataGrid-editingAddRow": "Ajouter ligne",
"dxDataGrid-summaryMin": "Min: {0}",
"dxDataGrid-summaryMinOtherColumn": "Minimum de {1} est {0}",
"dxDataGrid-summaryMax": "Max: {0}",
"dxDataGrid-summaryMaxOtherColumn": "Maximum de {1} est {0}",
"dxDataGrid-summaryAvg": "Moy: {0}",
"dxDataGrid-summaryAvgOtherColumn": "Moyenne de {1} est {0}",
"dxDataGrid-summarySum": "Somme: {0}",
"dxDataGrid-summarySumOtherColumn": "Somme de {1} est {0}",
"dxDataGrid-summaryCount": "Total: {0}",
"dxDataGrid-columnFixingFix": "Fixer",
"dxDataGrid-columnFixingUnfix": "D\xe9tacher",
"dxDataGrid-columnFixingLeftPosition": "A gauche",
"dxDataGrid-columnFixingRightPosition": "A droite",
"dxDataGrid-exportTo": "Exporter",
"dxDataGrid-exportToExcel": "Exporter sous Excel",
"dxDataGrid-exporting": "Exporter...",
"dxDataGrid-excelFormat": "Fichier Excel",
"dxDataGrid-selectedRows": "Lignes s\xe9lectionn\xe9es",
"dxDataGrid-exportSelectedRows": "Exporter les lignes s\xe9lectionn\xe9es",
"dxDataGrid-exportAll": "Exporter tout",
"dxDataGrid-headerFilterEmptyValue": "(aucune valeur)",
"dxDataGrid-headerFilterOK": "OK",
"dxDataGrid-headerFilterCancel": "Annuler",
"dxDataGrid-ariaColumn": "Colonne",
"dxDataGrid-ariaValue": "Valeur",
"dxDataGrid-ariaFilterCell": "Filtre de cellule",
"dxDataGrid-ariaCollapse": "R\xe9duire",
"dxDataGrid-ariaExpand": "Etendre",
"dxDataGrid-ariaDataGrid": "Grille",
"dxDataGrid-ariaSearchInGrid": "Rechercher dans la grille",
"dxDataGrid-ariaSelectAll": "S\xe9lectionner tout",
"dxDataGrid-ariaSelectRow": "S\xe9lectionner ligne",
"dxDataGrid-filterBuilderPopupTitle": "Cr\xe9ation de filtre",
"dxDataGrid-filterPanelCreateFilter": "Cr\xe9er un filtre",
"dxDataGrid-filterPanelClearFilter": "Supprimer",
"dxDataGrid-filterPanelFilterEnabledHint": "Activer le filtre",
"dxTreeList-ariaTreeList": "Liste arborescente",
"dxTreeList-editingAddRowToNode": "Ajouter",
"dxPager-infoText": "Page {0} sur {1} ({2} \xe9lements)",
"dxPager-pagesCountText": "sur",
"dxPivotGrid-grandTotal": "Total g\xe9n\xe9ral",
"dxPivotGrid-total": "Total {0}",
"dxPivotGrid-fieldChooserTitle": "Liste des champs",
"dxPivotGrid-showFieldChooser": "Afficher la liste des champs",
"dxPivotGrid-expandAll": "Etendre tout",
"dxPivotGrid-collapseAll": "R\xe9duire tout",
"dxPivotGrid-sortColumnBySummary": 'Trier par colonne "{0}"',
"dxPivotGrid-sortRowBySummary": 'Trier par ligne "{0}"',
"dxPivotGrid-removeAllSorting": "Supprimer les tris",
"dxPivotGrid-dataNotAvailable": "ND",
"dxPivotGrid-rowFields": "Lignes",
"dxPivotGrid-columnFields": "Colonnes",
"dxPivotGrid-dataFields": "Valeurs",
"dxPivotGrid-filterFields": "Filtres",
"dxPivotGrid-allFields": "Tous les champs",
"dxPivotGrid-columnFieldArea": "D\xe9poser les champs de colonne ici",
"dxPivotGrid-dataFieldArea": "D\xe9poser les champs de donn\xe9es ici",
"dxPivotGrid-rowFieldArea": "D\xe9poser les champs de ligne ici",
"dxPivotGrid-filterFieldArea": "D\xe9poser les champs de filtre ici",
"dxScheduler-editorLabelTitle": "Titre",
"dxScheduler-editorLabelStartDate": "Date de d\xe9but",
"dxScheduler-editorLabelEndDate": "Date de fin",
"dxScheduler-editorLabelDescription": "Description",
"dxScheduler-editorLabelRecurrence": "R\xe9currence",
"dxScheduler-openAppointment": "D\xe9finir un \xe9venement",
"dxScheduler-recurrenceNever": "Jamais",
"dxScheduler-recurrenceDaily": "Quotidien",
"dxScheduler-recurrenceWeekly": "Hebdomadaire",
"dxScheduler-recurrenceMonthly": "Mensuel",
"dxScheduler-recurrenceYearly": "Annuel",
"dxScheduler-recurrenceRepeatEvery": "Chaque",
"dxScheduler-recurrenceRepeatOn": "Repeat On",
"dxScheduler-recurrenceEnd": "Jusqu'\xe0",
"dxScheduler-recurrenceAfter": "Apr\xe8s",
"dxScheduler-recurrenceOn": "Le",
"dxScheduler-recurrenceRepeatDaily": "Jour(s)",
"dxScheduler-recurrenceRepeatWeekly": "Semaine(s)",
"dxScheduler-recurrenceRepeatMonthly": "Mois(s)",
"dxScheduler-recurrenceRepeatYearly": "Ann\xe9e(s)",
"dxScheduler-switcherDay": "Jour",
"dxScheduler-switcherWeek": "Semaine",
"dxScheduler-switcherWorkWeek": "Semaine de travail",
"dxScheduler-switcherMonth": "Mois",
"dxScheduler-switcherAgenda": "Agenda",
"dxScheduler-switcherTimelineDay": "Timeline Jour",
"dxScheduler-switcherTimelineWeek": "Timeline Semaine",
"dxScheduler-switcherTimelineWorkWeek": "Timeline Semaine de travail",
"dxScheduler-switcherTimelineMonth": "Timeline Mois",
"dxScheduler-recurrenceRepeatOnDate": "le",
"dxScheduler-recurrenceRepeatCount": "occurence(s)",
"dxScheduler-allDay": "Temps plein",
"dxScheduler-confirmRecurrenceEditMessage": "Voulez-vous \xe9diter cet \xe9venement ou la s\xe9rie enti\xe8re ?",
"dxScheduler-confirmRecurrenceDeleteMessage": "Voulez-vous supprimer cet \xe9venement ou la s\xe9rie enti\xe8re ?",
"dxScheduler-confirmRecurrenceEditSeries": "Editer serie",
"dxScheduler-confirmRecurrenceDeleteSeries": "Supprimer serie",
"dxScheduler-confirmRecurrenceEditOccurrence": "Editer \xe9venement",
"dxScheduler-confirmRecurrenceDeleteOccurrence": "Supprimer \xe9venement",
"dxScheduler-noTimezoneTitle": "Pas de fuseau horaire",
"dxScheduler-moreAppointments": "{0} en plus",
"dxCalendar-todayButtonText": "Aujourd'hui",
"dxCalendar-ariaWidgetName": "Calendrier",
"dxColorView-ariaRed": "Rouge",
"dxColorView-ariaGreen": "Vert",
"dxColorView-ariaBlue": "Bleu",
"dxColorView-ariaAlpha": "Transparence",
"dxColorView-ariaHex": "Code couleur",
"dxTagBox-selected": "{0} selectionn\xe9s",
"dxTagBox-allSelected": "Tous s\xe9lectionn\xe9s ({0})",
"dxTagBox-moreSelected": "{0} en plus",
"vizExport-printingButtonText": "Imprimer",
"vizExport-titleMenuText": "Exporter/Imprimer",
"vizExport-exportButtonText": "{0} fichier",
"dxFilterBuilder-and": "Et",
"dxFilterBuilder-or": "Ou",
"dxFilterBuilder-notAnd": "Non Et",
"dxFilterBuilder-notOr": "Non Ou",
"dxFilterBuilder-addCondition": "Ajouter une condition",
"dxFilterBuilder-addGroup": "Ajouter un groupe",
"dxFilterBuilder-enterValueText": "<entrer une valeur>",
"dxFilterBuilder-filterOperationEquals": "Est \xe9gal \xe0",
"dxFilterBuilder-filterOperationNotEquals": "Est diff\xe9rent de",
"dxFilterBuilder-filterOperationLess": "Est plus petit que",
"dxFilterBuilder-filterOperationLessOrEquals": "Est plus petit ou \xe9gal \xe0",
"dxFilterBuilder-filterOperationGreater": "Est plus grand que",
"dxFilterBuilder-filterOperationGreaterOrEquals": "Est plus grand ou \xe9gal \xe0",
"dxFilterBuilder-filterOperationStartsWith": "Commence par",
"dxFilterBuilder-filterOperationContains": "Contient",
"dxFilterBuilder-filterOperationNotContains": "Ne contient pas",
"dxFilterBuilder-filterOperationEndsWith": "Finit par",
"dxFilterBuilder-filterOperationIsBlank": "Est vide",
"dxFilterBuilder-filterOperationIsNotBlank": "N'est pas vide",
"dxFilterBuilder-filterOperationBetween": "Entre",
"dxFilterBuilder-filterOperationAnyOf": "Est parmi",
"dxFilterBuilder-filterOperationNoneOf": "N'est pas parmi",
"dxHtmlEditor-dialogColorCaption": "Changer couleur police",
"dxHtmlEditor-dialogBackgroundCaption": "Changer couleur fond",
"dxHtmlEditor-dialogLinkCaption": "Ajouter un hyperlien",
"dxHtmlEditor-dialogLinkUrlField": "URL",
"dxHtmlEditor-dialogLinkTextField": "Texte",
"dxHtmlEditor-dialogLinkTargetField": "Ouvrir le lien dans une nouvelle fen\xeatre",
"dxHtmlEditor-dialogImageCaption": "Ajouter image",
"dxHtmlEditor-dialogImageUrlField": "URL",
"dxHtmlEditor-dialogImageAltField": "Texte alternatif",
"dxHtmlEditor-dialogImageWidthField": "Largeur (px)",
"dxHtmlEditor-dialogImageHeightField": "Hauteur (px)",
"dxHtmlEditor-heading": "Titre",
"dxHtmlEditor-normalText": "Texte normal",
"dxFileManager-newDirectoryName": "R\xe9pertoire sans titre",
"dxFileManager-rootDirectoryName": "Fichiers",
"dxFileManager-errorNoAccess": "Acc\xe8s interdit. L'op\xe9ration ne peut se terminer.",
"dxFileManager-errorDirectoryExistsFormat": "R\xe9pertoire '{0}' existe d\xe9j\xe0.",
"dxFileManager-errorFileExistsFormat": "Fichier '{0}' existe d\xe9j\xe0.",
"dxFileManager-errorFileNotFoundFormat": "Impossible de trouver le fichier '{0}.'",
"dxFileManager-errorDirectoryNotFoundFormat": "Impossible de trouver le r\xe9pertoire '{0}.'",
"dxFileManager-errorWrongFileExtension": "Extension de fichier non permise.",
"dxFileManager-errorMaxFileSizeExceeded": "Taille du fichier d\xe9passe la limite maximum permise.",
"dxFileManager-errorInvalidSymbols": "Ce nom contient des caract\xe8res invalides.",
"dxFileManager-errorDefault": "Erreur non sp\xe9cifi\xe9.",
"dxFileManager-commandCreate": "Nouveau r\xe9pertoire",
"dxFileManager-commandRename": "Renommer",
"dxFileManager-commandMove": "D\xe9placer",
"dxFileManager-commandCopy": "Copier",
"dxFileManager-commandDelete": "Supprimer",
"dxFileManager-commandDownload": "T\xe9l\xe9charger",
"dxFileManager-commandUpload": "T\xe9l\xe9verser des fichiers",
"dxFileManager-commandRefresh": "Rafra\xeechir",
"dxFileManager-commandThumbnails": "Mode vignette",
"dxFileManager-commandDetails": "Mode d\xe9tails",
"dxFileManager-commandClear": "Vider s\xe9lection",
"dxFileManager-dialogDirectoryChooserTitle": "S\xe9lectionner r\xe9pertoire de destination",
"dxFileManager-dialogDirectoryChooserButtonText": "S\xe9lectionner",
"dxFileManager-dialogRenameItemTitle": "Renommer",
"dxFileManager-dialogRenameItemButtonText": "Sauvegarder",
"dxFileManager-dialogCreateDirectoryTitle": "Nouveau r\xe9pertoire",
"dxFileManager-dialogCreateDirectoryButtonText": "Cr\xe9er",
"dxFileManager-editingCreateSingleItemProcessingMessage": "Cr\xe9er un r\xe9pertoire dans {0}",
"dxFileManager-editingCreateSingleItemSuccessMessage": "R\xe9pertoire cr\xe9\xe9 dans {0}",
"dxFileManager-editingCreateSingleItemErrorMessage": "R\xe9pertoire n'est pas cr\xe9\xe9",
"dxFileManager-editingCreateCommonErrorMessage": "R\xe9pertoire n'est pas cr\xe9\xe9",
"dxFileManager-editingRenameSingleItemProcessingMessage": "Renommer un item dans {0}",
"dxFileManager-editingRenameSingleItemSuccessMessage": "Item renomm\xe9 dans {0}",
"dxFileManager-editingRenameSingleItemErrorMessage": "Item non renomm\xe9",
"dxFileManager-editingRenameCommonErrorMessage": "Item non renomm\xe9",
"dxFileManager-editingDeleteSingleItemProcessingMessage": "Supprimer un item de {0}",
"dxFileManager-editingDeleteMultipleItemsProcessingMessage": "Supprimer {0} items de {1}",
"dxFileManager-editingDeleteSingleItemSuccessMessage": "Item supprim\xe9 de {0}",
"dxFileManager-editingDeleteMultipleItemsSuccessMessage": "{0} items supprim\xe9s de {1}",
"dxFileManager-editingDeleteSingleItemErrorMessage": "Item non suprim\xe9",
"dxFileManager-editingDeleteMultipleItemsErrorMessage": "{0} items non supprim\xe9s",
"dxFileManager-editingDeleteCommonErrorMessage": "Des items ne sont pas supprim\xe9s",
"dxFileManager-editingMoveSingleItemProcessingMessage": "En train de d\xe9placer un item vers {0}",
"dxFileManager-editingMoveMultipleItemsProcessingMessage": "En train de d\xe9placer {0} items vers {1}",
"dxFileManager-editingMoveSingleItemSuccessMessage": "Item d\xe9plac\xe9 vers {0}",
"dxFileManager-editingMoveMultipleItemsSuccessMessage": "{0} items d\xe9plac\xe9s vers {1}",
"dxFileManager-editingMoveSingleItemErrorMessage": "Item non d\xe9plac\xe9",
"dxFileManager-editingMoveMultipleItemsErrorMessage": "{0} items non d\xe9plac\xe9s",
"dxFileManager-editingMoveCommonErrorMessage": "Des items ne sont pas d\xe9plac\xe9s",
"dxFileManager-editingCopySingleItemProcessingMessage": "En train de copier un item vers {0}",
"dxFileManager-editingCopyMultipleItemsProcessingMessage": "En train de copier {0} items vers {1}",
"dxFileManager-editingCopySingleItemSuccessMessage": "Item copi\xe9 vers {0}",
"dxFileManager-editingCopyMultipleItemsSuccessMessage": "{0} items copi\xe9s vers {1}",
"dxFileManager-editingCopySingleItemErrorMessage": "Item non copi\xe9",
"dxFileManager-editingCopyMultipleItemsErrorMessage": "{0} items non copi\xe9s",
"dxFileManager-editingCopyCommonErrorMessage": "Des items ne sont pas copi\xe9s",
"dxFileManager-editingUploadSingleItemProcessingMessage": "En train de t\xe9l\xe9verser un item vers {0}",
"dxFileManager-editingUploadMultipleItemsProcessingMessage": "En train de t\xe9l\xe9verser {0} items vers {1}",
"dxFileManager-editingUploadSingleItemSuccessMessage": "Item t\xe9l\xe9vers\xe9 vers {0}",
"dxFileManager-editingUploadMultipleItemsSuccessMessage": "{0} items t\xe9l\xe9vers\xe9s vers {1}",
"dxFileManager-editingUploadSingleItemErrorMessage": "Item non t\xe9l\xe9vers\xe9",
"dxFileManager-editingUploadMultipleItemsErrorMessage": "{0} items non t\xe9l\xe9vers\xe9s",
"dxFileManager-editingUploadCanceledMessage": "Annul\xe9",
"dxFileManager-listDetailsColumnCaptionName": "Nom",
"dxFileManager-listDetailsColumnCaptionDateModified": "Date modifi\xe9",
"dxFileManager-listDetailsColumnCaptionFileSize": "Taille de fichier",
"dxFileManager-listThumbnailsTooltipTextSize": "Taille",
"dxFileManager-listThumbnailsTooltipTextDateModified": "Date modifi\xe9",
"dxFileManager-notificationProgressPanelTitle": "En cours",
"dxFileManager-notificationProgressPanelEmptyListText": "Aucune op\xe9ration",
"dxFileManager-notificationProgressPanelOperationCanceled": "Annul\xe9",
"dxDiagram-categoryGeneral": "G\xe9n\xe9ral",
"dxDiagram-categoryFlowchart": "Organigramme",
"dxDiagram-categoryOrgChart": "Structure organisationnelle",
"dxDiagram-categoryContainers": "Conteneurs",
"dxDiagram-categoryCustom": "Personnalis\xe9",
"dxDiagram-commandProperties": "Propri\xe9t\xe9s",
"dxDiagram-commandExport": "Exporter",
"dxDiagram-commandExportToSvg": "Exporter en SVG",
"dxDiagram-commandExportToPng": "Exporter en PNG",
"dxDiagram-commandExportToJpg": "Exporter en JPEG",
"dxDiagram-commandUndo": "Annuler",
"dxDiagram-commandRedo": "Refaire",
"dxDiagram-commandFontName": "Nom de la police",
"dxDiagram-commandFontSize": "Taille de la police",
"dxDiagram-commandBold": "Gras",
"dxDiagram-commandItalic": "Italique",
"dxDiagram-commandUnderline": "Souligner",
"dxDiagram-commandTextColor": "Couleur texte",
"dxDiagram-commandLineColor": "Couleur ligne",
"dxDiagram-commandFillColor": "Couleur remplissage",
"dxDiagram-commandAlignLeft": "Aligner \xe0 gauche",
"dxDiagram-commandAlignCenter": "Centrer",
"dxDiagram-commandAlignRight": "Aligner \xe0 droite",
"dxDiagram-commandConnectorLineType": "Type de ligne de connexion",
"dxDiagram-commandConnectorLineStraight": "Droit",
"dxDiagram-commandConnectorLineOrthogonal": "Orthogonal",
"dxDiagram-commandConnectorLineStart": "D\xe9but de la ligne de connexion",
"dxDiagram-commandConnectorLineEnd": "Fin de la ligne de connexion",
"dxDiagram-commandConnectorLineNone": "Aucun",
"dxDiagram-commandConnectorLineArrow": "Fl\xe8che",
"dxDiagram-commandAutoLayout": "Mise en page automatique",
"dxDiagram-commandAutoLayoutTree": "Arbre",
"dxDiagram-commandAutoLayoutLayered": "Par couches",
"dxDiagram-commandAutoLayoutHorizontal": "Horizontal",
"dxDiagram-commandAutoLayoutVertical": "Vertical",
"dxDiagram-commandFullscreen": "Plein \xe9cran",
"dxDiagram-commandUnits": "Unit\xe9s",
"dxDiagram-commandPageSize": "Taille de la page",
"dxDiagram-commandPageOrientation": "Orientation de la page",
"dxDiagram-commandPageOrientationLandscape": "Paysage",
"dxDiagram-commandPageOrientationPortrait": "Portrait",
"dxDiagram-commandPageColor": "Couleur de la page",
"dxDiagram-commandShowGrid": "Afficher la grille",
"dxDiagram-commandSnapToGrid": "Aligner sur la grille",
"dxDiagram-commandGridSize": "Taille de la grille",
"dxDiagram-commandZoomLevel": "Niveau de zoom",
"dxDiagram-commandAutoZoom": "Zoom automatique",
"dxDiagram-commandSimpleView": "Vue simple",
"dxDiagram-commandCut": "Couper",
"dxDiagram-commandCopy": "Copier",
"dxDiagram-commandPaste": "Coller",
"dxDiagram-commandSelectAll": "Tout s\xe9lectionner",
"dxDiagram-commandDelete": "Supprimer",
"dxDiagram-commandBringToFront": "Amener au premier plan",
"dxDiagram-commandSendToBack": "Envoyer \xe0 l'arri\xe8re",
"dxDiagram-commandLock": "Verrouiller",
"dxDiagram-commandUnlock": "D\xe9verrouiller",
"dxDiagram-commandInsertShapeImage": "Ins\xe9rer une image...",
"dxDiagram-commandEditShapeImage": "Changer image...",
"dxDiagram-commandDeleteShapeImage": "Supprimer image",
"dxDiagram-unitIn": "po",
"dxDiagram-unitCm": "cm",
"dxDiagram-unitPx": "px",
"dxDiagram-dialogButtonOK": "OK",
"dxDiagram-dialogButtonCancel": "Annuler",
"dxDiagram-dialogInsertShapeImageTitle": "Ins\xe9rer une image",
"dxDiagram-dialogEditShapeImageTitle": "Changer image",
"dxDiagram-dialogEditShapeImageSelectButton": "S\xe9lectionner une image",
"dxDiagram-dialogEditShapeImageLabelText": "ou d\xe9poser le fichier ici"
}
})
});
|
!function(){var n;jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd&&(n=jQuery.fn.select2.amd),n.define("select2/i18n/pl",[],function(){function e(n,e){return 1===n?e[0]:1<n&&n<=4?e[1]:5<=n?e[2]:void 0}var r=["znak","znaki","znaków"],t=["element","elementy","elementów"];return{errorLoading:function(){return"Nie można załadować wyników."},inputTooLong:function(n){n=n.input.length-n.maximum;return"Usuń "+n+" "+e(n,r)},inputTooShort:function(n){n=n.minimum-n.input.length;return"Podaj przynajmniej "+n+" "+e(n,r)},loadingMore:function(){return"Trwa ładowanie…"},maximumSelected:function(n){return"Możesz zaznaczyć tylko "+n.maximum+" "+e(n.maximum,t)},noResults:function(){return"Brak wyników"},searching:function(){return"Trwa wyszukiwanie…"},removeAllItems:function(){return"Usuń wszystkie przedmioty"}}}),n.define,n.require}();
|
/**
* Copyright (C) 2011-2012 Pavel Shramov
* Copyright (C) 2013-2017 Maxime Petazzoni <maxime.petazzoni@bulix.org>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Thanks to Pavel Shramov who provided the initial implementation and Leaflet
* integration. Original code was at https://github.com/shramov/leaflet-plugins.
*
* It was then cleaned-up and modified to record and make available more
* information about the GPX track while it is being parsed so that the result
* can be used to display additional information about the track that is
* rendered on the Leaflet map.
*/
var L = L || require('leaflet');
var _MAX_POINT_INTERVAL_MS = 15000;
var _SECOND_IN_MILLIS = 1000;
var _MINUTE_IN_MILLIS = 60 * _SECOND_IN_MILLIS;
var _HOUR_IN_MILLIS = 60 * _MINUTE_IN_MILLIS;
var _DAY_IN_MILLIS = 24 * _HOUR_IN_MILLIS;
var _GPX_STYLE_NS = 'http://www.topografix.com/GPX/gpx_style/0/2';
var _DEFAULT_MARKER_OPTS = {
startIconUrl: 'pin-icon-start.png',
endIconUrl: 'pin-icon-end.png',
shadowUrl: 'pin-shadow.png',
wptIcons: [],
wptIconsType: [],
wptIconUrls : {
'': 'pin-icon-wpt.png',
},
wptIconTypeUrls : {
'': 'pin-icon-wpt.png',
},
pointMatchers: [],
iconSize: [33, 45],
shadowSize: [50, 50],
iconAnchor: [16, 45],
shadowAnchor: [16, 47],
clickable: false
};
var _DEFAULT_POLYLINE_OPTS = {
color: 'blue'
};
var _DEFAULT_GPX_OPTS = {
parseElements: ['track', 'route', 'waypoint'],
joinTrackSegments: true
};
L.GPX = L.FeatureGroup.extend({
initialize: function(gpx, options) {
options.max_point_interval = options.max_point_interval || _MAX_POINT_INTERVAL_MS;
options.marker_options = this._merge_objs(
_DEFAULT_MARKER_OPTS,
options.marker_options || {});
options.polyline_options = options.polyline_options || {};
options.gpx_options = this._merge_objs(
_DEFAULT_GPX_OPTS,
options.gpx_options || {});
L.Util.setOptions(this, options);
// Base icon class for track pins.
L.GPXTrackIcon = L.Icon.extend({ options: options.marker_options });
this._gpx = gpx;
this._layers = {};
this._init_info();
if (gpx) {
this._parse(gpx, options, this.options.async);
}
},
get_duration_string: function(duration, hidems) {
var s = '';
if (duration >= _DAY_IN_MILLIS) {
s += Math.floor(duration / _DAY_IN_MILLIS) + 'd ';
duration = duration % _DAY_IN_MILLIS;
}
if (duration >= _HOUR_IN_MILLIS) {
s += Math.floor(duration / _HOUR_IN_MILLIS) + ':';
duration = duration % _HOUR_IN_MILLIS;
}
var mins = Math.floor(duration / _MINUTE_IN_MILLIS);
duration = duration % _MINUTE_IN_MILLIS;
if (mins < 10) s += '0';
s += mins + '\'';
var secs = Math.floor(duration / _SECOND_IN_MILLIS);
duration = duration % _SECOND_IN_MILLIS;
if (secs < 10) s += '0';
s += secs;
if (!hidems && duration > 0) s += '.' + Math.round(Math.floor(duration)*1000)/1000;
else s += '"';
return s;
},
get_duration_string_iso: function(duration, hidems) {
var s = this.get_duration_string(duration, hidems);
return s.replace("'",':').replace('"','');
},
// Public methods
to_miles: function(v) { return v / 1.60934; },
to_ft: function(v) { return v * 3.28084; },
m_to_km: function(v) { return v / 1000; },
m_to_mi: function(v) { return v / 1609.34; },
ms_to_kmh: function(v) { return v * 3.6; },
ms_to_mih: function(v) { return v / 1609.34 * 3600; },
get_name: function() { return this._info.name; },
get_desc: function() { return this._info.desc; },
get_author: function() { return this._info.author; },
get_copyright: function() { return this._info.copyright; },
get_distance: function() { return this._info.length; },
get_distance_imp: function() { return this.to_miles(this.m_to_km(this.get_distance())); },
get_start_time: function() { return this._info.duration.start; },
get_end_time: function() { return this._info.duration.end; },
get_moving_time: function() { return this._info.duration.moving; },
get_total_time: function() { return this._info.duration.total; },
get_moving_pace: function() { return this.get_moving_time() / this.m_to_km(this.get_distance()); },
get_moving_pace_imp: function() { return this.get_moving_time() / this.get_distance_imp(); },
get_moving_speed: function() { return this.m_to_km(this.get_distance()) / (this.get_moving_time() / (3600 * 1000)) ; },
get_moving_speed_imp:function() { return this.to_miles(this.m_to_km(this.get_distance())) / (this.get_moving_time() / (3600 * 1000)) ; },
get_total_speed: function() { return this.m_to_km(this.get_distance()) / (this.get_total_time() / (3600 * 1000)); },
get_total_speed_imp: function() { return this.to_miles(this.m_to_km(this.get_distance())) / (this.get_total_time() / (3600 * 1000)); },
get_elevation_gain: function() { return this._info.elevation.gain; },
get_elevation_loss: function() { return this._info.elevation.loss; },
get_elevation_gain_imp: function() { return this.to_ft(this.get_elevation_gain()); },
get_elevation_loss_imp: function() { return this.to_ft(this.get_elevation_loss()); },
get_elevation_data: function() {
var _this = this;
return this._info.elevation._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return a.toFixed(2) + ' km, ' + b.toFixed(0) + ' m'; });
});
},
get_elevation_data_imp: function() {
var _this = this;
return this._info.elevation._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, _this.to_ft,
function(a, b) { return a.toFixed(2) + ' mi, ' + b.toFixed(0) + ' ft'; });
});
},
get_elevation_max: function() { return this._info.elevation.max; },
get_elevation_min: function() { return this._info.elevation.min; },
get_elevation_max_imp: function() { return this.to_ft(this.get_elevation_max()); },
get_elevation_min_imp: function() { return this.to_ft(this.get_elevation_min()); },
get_speed_data: function() {
var _this = this;
return this._info.speed._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, _this.ms_to_kmh,
function(a, b) { return a.toFixed(2) + ' km, ' + b.toFixed(2) + ' km/h'; });
});
},
get_speed_data_imp: function() {
var _this = this;
return this._info.elevation._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, _this.ms_to_mih,
function(a, b) { return a.toFixed(2) + ' mi, ' + b.toFixed(2) + ' mi/h'; });
});
},
get_speed_max: function() { return this.m_to_km(this._info.speed.max) * 3600; },
get_speed_max_imp: function() { return this.to_miles(this.get_speed_max()); },
get_average_hr: function() { return this._info.hr.avg; },
get_average_temp: function() { return this._info.atemp.avg; },
get_average_cadence: function() { return this._info.cad.avg; },
get_heartrate_data: function() {
var _this = this;
return this._info.hr._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return a.toFixed(2) + ' km, ' + b.toFixed(0) + ' bpm'; });
});
},
get_heartrate_data_imp: function() {
var _this = this;
return this._info.hr._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return a.toFixed(2) + ' mi, ' + b.toFixed(0) + ' bpm'; });
});
},
get_cadence_data: function() {
var _this = this;
return this._info.cad._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return a.toFixed(2) + ' km, ' + b.toFixed(0) + ' rpm'; });
});
},
get_temp_data: function() {
var _this = this;
return this._info.atemp._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_km, null,
function(a, b) { return a.toFixed(2) + ' km, ' + b.toFixed(0) + ' degrees'; });
});
},
get_cadence_data_imp: function() {
var _this = this;
return this._info.cad._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return a.toFixed(2) + ' mi, ' + b.toFixed(0) + ' rpm'; });
});
},
get_temp_data_imp: function() {
var _this = this;
return this._info.atemp._points.map(
function(p) { return _this._prepare_data_point(p, _this.m_to_mi, null,
function(a, b) { return a.toFixed(2) + ' mi, ' + b.toFixed(0) + ' degrees'; });
});
},
reload: function() {
this._init_info();
this.clearLayers();
this._parse(this._gpx, this.options, this.options.async);
},
// Private methods
_merge_objs: function(a, b) {
var _ = {};
for (var attr in a) { _[attr] = a[attr]; }
for (var attr in b) { _[attr] = b[attr]; }
return _;
},
_prepare_data_point: function(p, trans1, trans2, trans_tooltip) {
var r = [trans1 && trans1(p[0]) || p[0], trans2 && trans2(p[1]) || p[1]];
r.push(trans_tooltip && trans_tooltip(r[0], r[1]) || (r[0] + ': ' + r[1]));
return r;
},
_init_info: function() {
this._info = {
name: null,
length: 0.0,
elevation: {gain: 0.0, loss: 0.0, max: 0.0, min: Infinity, _points: []},
speed : {max: 0.0, _points: []},
hr: {avg: 0, _total: 0, _points: []},
duration: {start: null, end: null, moving: 0, total: 0},
atemp: {avg: 0, _total: 0, _points: []},
cad: {avg: 0, _total: 0, _points: []}
};
},
_load_xml: function(url, cb, options, async) {
if (async == undefined) async = this.options.async;
if (options == undefined) options = this.options;
var req = new window.XMLHttpRequest();
req.open('GET', url, async);
try {
req.overrideMimeType('text/xml'); // unsupported by IE
} catch(e) {}
req.onreadystatechange = function() {
if (req.readyState != 4) return;
if(req.status == 200) cb(req.responseXML, options);
};
req.send(null);
},
_parse: function(input, options, async) {
var _this = this;
var cb = function(gpx, options) {
var layers = _this._parse_gpx_data(gpx, options);
if (!layers) {
_this.fire('error', { err: 'No parseable layers of type(s) ' + JSON.stringify(options.gpx_options.parseElements) });
return;
}
_this.addLayer(layers);
_this.fire('loaded', { layers: layers, element: gpx });
}
if (input.substr(0,1)==='<') { // direct XML has to start with a <
var parser = new DOMParser();
if (async) {
setTimeout(function() {
cb(parser.parseFromString(input, "text/xml"), options);
});
} else {
cb(parser.parseFromString(input, "text/xml"), options);
}
} else {
this._load_xml(input, cb, options, async);
}
},
_parse_gpx_data: function(xml, options) {
var i, t, l, el, layers = [];
var name = xml.getElementsByTagName('name');
if (name.length > 0) {
this._info.name = name[0].textContent;
}
var desc = xml.getElementsByTagName('desc');
if (desc.length > 0) {
this._info.desc = desc[0].textContent;
}
var author = xml.getElementsByTagName('author');
if (author.length > 0) {
this._info.author = author[0].textContent;
}
var copyright = xml.getElementsByTagName('copyright');
if (copyright.length > 0) {
this._info.copyright = copyright[0].textContent;
}
var parseElements = options.gpx_options.parseElements;
if (parseElements.indexOf('route') > -1) {
// routes are <rtept> tags inside <rte> sections
var routes = xml.getElementsByTagName('rte');
for (i = 0; i < routes.length; i++) {
layers = layers.concat(this._parse_segment(routes[i], options, {}, 'rtept'));
}
}
if (parseElements.indexOf('track') > -1) {
// tracks are <trkpt> tags in one or more <trkseg> sections in each <trk>
var tracks = xml.getElementsByTagName('trk');
for (i = 0; i < tracks.length; i++) {
var track = tracks[i];
var polyline_options = this._extract_styling(track);
if (options.gpx_options.joinTrackSegments) {
layers = layers.concat(this._parse_segment(track, options, polyline_options, 'trkpt'));
} else {
var segments = track.getElementsByTagName('trkseg');
for (j = 0; j < segments.length; j++) {
layers = layers.concat(this._parse_segment(segments[j], options, polyline_options, 'trkpt'));
}
}
}
}
this._info.hr.avg = Math.round(this._info.hr._total / this._info.hr._points.length);
this._info.cad.avg = Math.round(this._info.cad._total / this._info.cad._points.length);
this._info.atemp.avg = Math.round(this._info.atemp._total / this._info.atemp._points.length);
// parse waypoints and add markers for each of them
if (parseElements.indexOf('waypoint') > -1) {
el = xml.getElementsByTagName('wpt');
for (i = 0; i < el.length; i++) {
var ll = new L.LatLng(
el[i].getAttribute('lat'),
el[i].getAttribute('lon'));
var nameEl = el[i].getElementsByTagName('name');
var name = nameEl.length > 0 ? nameEl[0].textContent : '';
var descEl = el[i].getElementsByTagName('desc');
var desc = descEl.length > 0 ? descEl[0].textContent : '';
var symEl = el[i].getElementsByTagName('sym');
var symKey = symEl.length > 0 ? symEl[0].textContent : null;
var typeEl = el[i].getElementsByTagName('type');
var typeKey = typeEl.length > 0 ? typeEl[0].textContent : null;
/*
* Add waypoint marker based on the waypoint symbol key.
*
* First look for a configured icon for that symKey. If not found, look
* for a configured icon URL for that symKey and build an icon from it.
* If none of those match, look through the point matchers for a match
* on the waypoint's name.
*
* Otherwise, fall back to the default icon if one was configured, or
* finally to the default icon URL, if one was configured.
*/
var wptIcons = options.marker_options.wptIcons;
var wptIconUrls = options.marker_options.wptIconUrls;
var wptIconsType = options.marker_options.wptIconsType;
var wptIconTypeUrls = options.marker_options.wptIconTypeUrls;
var ptMatchers = options.marker_options.pointMatchers || [];
var symIcon;
if (wptIcons && symKey && wptIcons[symKey]) {
symIcon = wptIcons[symKey];
} else if (wptIconsType && typeKey && wptIconsType[typeKey]) {
symIcon = wptIconsType[typeKey];
} else if (wptIconUrls && symKey && wptIconUrls[symKey]) {
symIcon = new L.GPXTrackIcon({iconUrl: wptIconUrls[symKey]});
} else if (wptIconTypeUrls && typeKey && wptIconTypeUrls[typeKey]) {
symIcon = new L.GPXTrackIcon({iconUrl: wptIconTypeUrls[typeKey]});
} else if (ptMatchers.length > 0) {
for (var j = 0; j < ptMatchers.length; j++) {
if (ptMatchers[j].regex.test(name)) {
symIcon = ptMatchers[j].icon;
break;
}
}
} else if (wptIcons && wptIcons['']) {
symIcon = wptIcons[''];
} else if (wptIconUrls && wptIconUrls['']) {
symIcon = new L.GPXTrackIcon({iconUrl: wptIconUrls['']});
}
if (!symIcon) {
console.log(
'No waypoint icon could be matched for symKey=%s,typeKey=%s,name=%s on waypoint %o',
symKey, typeKey, name, el[i]);
continue;
}
var marker = new L.Marker(ll, {
clickable: options.marker_options.clickable,
title: name,
icon: symIcon,
type: 'waypoint'
});
marker.bindPopup("<b>" + name + "</b>" + (desc.length > 0 ? '<br>' + desc : '')).openPopup();
this.fire('addpoint', { point: marker, point_type: 'waypoint', element: el[i] });
layers.push(marker);
}
}
if (layers.length > 1) {
return new L.FeatureGroup(layers);
} else if (layers.length == 1) {
return layers[0];
}
},
_parse_segment: function(line, options, polyline_options, tag) {
var el = line.getElementsByTagName(tag);
if (!el.length) return [];
var coords = [];
var markers = [];
var layers = [];
var last = null;
for (var i = 0; i < el.length; i++) {
var _, ll = new L.LatLng(
el[i].getAttribute('lat'),
el[i].getAttribute('lon'));
ll.meta = { time: null, ele: null, hr: null, cad: null, atemp: null, speed: null };
_ = el[i].getElementsByTagName('time');
if (_.length > 0) {
ll.meta.time = new Date(Date.parse(_[0].textContent));
} else {
ll.meta.time = new Date('1970-01-01T00:00:00');
}
var time_diff = last != null ? Math.abs(ll.meta.time - last.meta.time) : 0;
_ = el[i].getElementsByTagName('ele');
if (_.length > 0) {
ll.meta.ele = parseFloat(_[0].textContent);
} else {
// If the point doesn't have an <ele> tag, assume it has the same
// elevation as the point before it (if it had one).
ll.meta.ele = last.meta.ele;
}
var ele_diff = last != null ? ll.meta.ele - last.meta.ele : 0;
var dist_3d = last != null ? this._dist3d(last, ll) : 0;
_ = el[i].getElementsByTagName('speed');
if (_.length > 0) {
ll.meta.speed = parseFloat(_[0].textContent);
} else {
// speed in meter per second
ll.meta.speed = time_diff > 0 ? 1000.0 * dist_3d / time_diff : 0;
}
_ = el[i].getElementsByTagName('name');
if (_.length > 0) {
var name = _[0].textContent;
var ptMatchers = options.marker_options.pointMatchers || [];
for (var j = 0; j < ptMatchers.length; j++) {
if (ptMatchers[j].regex.test(name)) {
markers.push({ label: name, coords: ll, icon: ptMatchers[j].icon, element: el[i] });
break;
}
}
}
_ = el[i].getElementsByTagNameNS('*', 'hr');
if (_.length > 0) {
ll.meta.hr = parseInt(_[0].textContent);
this._info.hr._points.push([this._info.length, ll.meta.hr]);
this._info.hr._total += ll.meta.hr;
}
_ = el[i].getElementsByTagNameNS('*', 'cad');
if (_.length > 0) {
ll.meta.cad = parseInt(_[0].textContent);
this._info.cad._points.push([this._info.length, ll.meta.cad]);
this._info.cad._total += ll.meta.cad;
}
_ = el[i].getElementsByTagNameNS('*', 'atemp');
if (_.length > 0) {
ll.meta.atemp = parseInt(_[0].textContent);
this._info.atemp._points.push([this._info.length, ll.meta.atemp]);
this._info.atemp._total += ll.meta.atemp;
}
if (ll.meta.ele > this._info.elevation.max) {
this._info.elevation.max = ll.meta.ele;
}
if (ll.meta.ele < this._info.elevation.min) {
this._info.elevation.min = ll.meta.ele;
}
this._info.elevation._points.push([this._info.length, ll.meta.ele]);
if (ll.meta.speed > this._info.speed.max) {
this._info.speed.max = ll.meta.speed;
}
this._info.speed._points.push([this._info.length, ll.meta.speed]);
if ((last == null) && (this._info.duration.start == null)) {
this._info.duration.start = ll.meta.time;
}
this._info.duration.end = ll.meta.time;
this._info.duration.total += time_diff;
if (time_diff < options.max_point_interval) {
this._info.duration.moving += time_diff;
}
this._info.length += dist_3d;
if (ele_diff > 0) {
this._info.elevation.gain += ele_diff;
} else {
this._info.elevation.loss += Math.abs(ele_diff);
}
last = ll;
coords.push(ll);
}
// add track
var l = new L.Polyline(coords, this._extract_styling(line, polyline_options, options.polyline_options));
this.fire('addline', { line: l, element: line });
layers.push(l);
if (options.marker_options.startIcon || options.marker_options.startIconUrl) {
// add start pin
var marker = new L.Marker(coords[0], {
clickable: options.marker_options.clickable,
icon: options.marker_options.startIcon || new L.GPXTrackIcon({iconUrl: options.marker_options.startIconUrl})
});
this.fire('addpoint', { point: marker, point_type: 'start', element: el[0] });
layers.push(marker);
}
if (options.marker_options.endIcon || options.marker_options.endIconUrl) {
// add end pin
var marker = new L.Marker(coords[coords.length-1], {
clickable: options.marker_options.clickable,
icon: options.marker_options.endIcon || new L.GPXTrackIcon({iconUrl: options.marker_options.endIconUrl})
});
this.fire('addpoint', { point: marker, point_type: 'end', element: el[el.length-1] });
layers.push(marker);
}
// add named markers
for (var i = 0; i < markers.length; i++) {
var marker = new L.Marker(markers[i].coords, {
clickable: options.marker_options.clickable,
title: markers[i].label,
icon: markers[i].icon
});
this.fire('addpoint', { point: marker, point_type: 'label', element: markers[i].element });
layers.push(marker);
}
return layers;
},
_extract_styling: function(el, base, overrides) {
var style = this._merge_objs(_DEFAULT_POLYLINE_OPTS, base);
var e = el.getElementsByTagNameNS(_GPX_STYLE_NS, 'line');
if (e.length > 0) {
var _ = e[0].getElementsByTagName('color');
if (_.length > 0) style.color = '#' + _[0].textContent;
var _ = e[0].getElementsByTagName('opacity');
if (_.length > 0) style.opacity = _[0].textContent;
var _ = e[0].getElementsByTagName('weight');
if (_.length > 0) style.weight = _[0].textContent;
var _ = e[0].getElementsByTagName('linecap');
if (_.length > 0) style.lineCap = _[0].textContent;
var _ = e[0].getElementsByTagName('linejoin');
if (_.length > 0) style.lineJoin = _[0].textContent;
var _ = e[0].getElementsByTagName('dasharray');
if (_.length > 0) style.dashArray = _[0].textContent;
var _ = e[0].getElementsByTagName('dashoffset');
if (_.length > 0) style.dashOffset = _[0].textContent;
}
return this._merge_objs(style, overrides)
},
_dist2d: function(a, b) {
var R = 6371000;
var dLat = this._deg2rad(b.lat - a.lat);
var dLon = this._deg2rad(b.lng - a.lng);
var r = Math.sin(dLat/2) *
Math.sin(dLat/2) +
Math.cos(this._deg2rad(a.lat)) *
Math.cos(this._deg2rad(b.lat)) *
Math.sin(dLon/2) *
Math.sin(dLon/2);
var c = 2 * Math.atan2(Math.sqrt(r), Math.sqrt(1-r));
var d = R * c;
return d;
},
_dist3d: function(a, b) {
var planar = this._dist2d(a, b);
var height = Math.abs(b.meta.ele - a.meta.ele);
return Math.sqrt(Math.pow(planar, 2) + Math.pow(height, 2));
},
_deg2rad: function(deg) {
return deg * Math.PI / 180;
}
});
if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = L;
} else if (typeof define === 'function' && define.amd) {
define(L);
}
|
import './chunk-2452e3d3.js';
import { merge } from './helpers.js';
import { V as VueInstance } from './chunk-8ed29c41.js';
import { r as registerComponent, a as registerComponentProgrammatic, u as use } from './chunk-cca88db8.js';
import './chunk-b9bdb0e4.js';
import { L as Loading } from './chunk-c9c58d0c.js';
export { L as BLoading } from './chunk-c9c58d0c.js';
var localVueInstance;
var LoadingProgrammatic = {
open: function open(params) {
var defaultParam = {
programmatic: true
};
var propsData = merge(defaultParam, params);
var vm = typeof window !== 'undefined' && window.Vue ? window.Vue : localVueInstance || VueInstance;
var LoadingComponent = vm.extend(Loading);
return new LoadingComponent({
el: document.createElement('div'),
propsData: propsData
});
}
};
var Plugin = {
install: function install(Vue) {
localVueInstance = Vue;
registerComponent(Vue, Loading);
registerComponentProgrammatic(Vue, 'loading', LoadingProgrammatic);
}
};
use(Plugin);
export default Plugin;
export { LoadingProgrammatic };
|
/**
* @license Highcharts JS v10.0.0 (2022-03-07)
* @module highcharts/modules/windbarb
* @requires highcharts
*
* Wind barb series module
*
* (c) 2010-2021 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../Series/Windbarb/WindbarbSeries.js';
|
/*!
* Bootstrap-select v1.13.17 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2020 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'No hay selección',
noneResultsText: 'No hay resultados {0}',
countSelectedText: 'Seleccionados {0} de {1}',
maxOptionsText: ['Límite alcanzado ({n} {var} max)', 'Límite del grupo alcanzado({n} {var} max)', ['elementos', 'element']],
multipleSeparator: ', ',
selectAllText: 'Seleccionar Todos',
deselectAllText: 'Desmarcar Todos'
};
})(jQuery);
}));
//# sourceMappingURL=defaults-es_ES.js.map
|
;(function (window) {
if (window.VueDemi) {
return
}
var VueDemi = {}
var Vue = window.Vue
if (Vue) {
if (Vue.version.slice(0, 2) === '2.') {
var VueCompositionAPI = window.VueCompositionAPI
if (VueCompositionAPI) {
for (var key in VueCompositionAPI) {
VueDemi[key] = VueCompositionAPI[key]
}
VueDemi.isVue2 = true
VueDemi.isVue3 = false
VueDemi.install = function (){}
VueDemi.Vue = Vue
VueDemi.Vue2 = Vue
VueDemi.version = Vue.version
} else {
console.error(
'[vue-demi] no VueCompositionAPI instance found, please be sure to import `@vue/composition-api` before `vue-demi`.'
)
}
} else if (Vue.version.slice(0, 2) === '3.') {
for (var key in Vue) {
VueDemi[key] = Vue[key]
}
VueDemi.isVue2 = false
VueDemi.isVue3 = true
VueDemi.install = function (){}
VueDemi.Vue = Vue
VueDemi.Vue2 = undefined
VueDemi.version = Vue.version
VueDemi.set = function(target, key, val) {
if (Array.isArray(target)) {
target.length = Math.max(target.length, key)
target.splice(key, 1, val)
return val
}
target[key] = val
return val
}
VueDemi.del = function(target, key) {
if (Array.isArray(target)) {
target.splice(key, 1)
return
}
delete target[key]
}
} else {
console.error('[vue-demi] Vue version ' + Vue.version + ' is unsupported.')
}
} else {
console.error(
'[vue-demi] no Vue instance found, please be sure to import `vue` before `vue-demi`.'
)
}
window.VueDemi = VueDemi
})(window)
;
;
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('echarts'), require('vue-demi'), require('echarts/core')) :
typeof define === 'function' && define.amd ? define(['echarts', 'vue-demi', 'echarts/core'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.VueECharts = factory(global.echarts, global.VueDemi, global.echarts));
}(this, (function (echarts, vueDemi, core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var METHOD_NAMES = [
"getWidth",
"getHeight",
"getDom",
"getOption",
"resize",
"dispatchAction",
"convertToPixel",
"convertFromPixel",
"containPixel",
"getDataURL",
"getConnectedDataURL",
"appendData",
"clear",
"isDisposed",
"dispose"
];
function usePublicAPI(chart, init) {
function makePublicMethod(name) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (!chart.value) {
init();
}
if (!chart.value) {
throw new Error("ECharts is not initialized yet.");
}
return chart.value[name].apply(chart.value, args);
};
}
function makeAnyMethod(name) {
return makePublicMethod(name);
}
function makePublicMethods() {
var methods = Object.create(null);
METHOD_NAMES.forEach(function (name) {
methods[name] = makePublicMethod(name);
});
return methods;
}
return __assign(__assign({}, makePublicMethods()), { dispatchAction: makeAnyMethod("dispatchAction"), getDataURL: makeAnyMethod("getDataURL"), getConnectedDataURL: makeAnyMethod("getConnectedDataURL") });
}
var raf = null;
function requestAnimationFrame (callback) {
if (!raf) {
raf = (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
function (callback) {
return setTimeout(callback, 16)
}
).bind(window);
}
return raf(callback)
}
var caf = null;
function cancelAnimationFrame (id) {
if (!caf) {
caf = (
window.cancelAnimationFrame ||
window.webkitCancelAnimationFrame ||
window.mozCancelAnimationFrame ||
function (id) {
clearTimeout(id);
}
).bind(window);
}
caf(id);
}
function createStyles (styleText) {
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = styleText;
} else {
style.appendChild(document.createTextNode(styleText));
}
(document.querySelector('head') || document.body).appendChild(style);
return style
}
function createElement (tagName, props) {
if ( props === void 0 ) props = {};
var elem = document.createElement(tagName);
Object.keys(props).forEach(function (key) {
elem[key] = props[key];
});
return elem
}
function getComputedStyle (elem, prop, pseudo) {
// for older versions of Firefox, `getComputedStyle` required
// the second argument and may return `null` for some elements
// when `display: none`
var computedStyle = window.getComputedStyle(elem, pseudo || null) || {
display: 'none'
};
return computedStyle[prop]
}
function getRenderInfo (elem) {
if (!document.documentElement.contains(elem)) {
return {
detached: true,
rendered: false
}
}
var current = elem;
while (current !== document) {
if (getComputedStyle(current, 'display') === 'none') {
return {
detached: false,
rendered: false
}
}
current = current.parentNode;
}
return {
detached: false,
rendered: true
}
}
var css_248z$1 = ".resize-triggers{visibility:hidden;opacity:0;pointer-events:none}.resize-contract-trigger,.resize-contract-trigger:before,.resize-expand-trigger,.resize-triggers{content:\"\";position:absolute;top:0;left:0;height:100%;width:100%;overflow:hidden}.resize-contract-trigger,.resize-expand-trigger{background:#eee;overflow:auto}.resize-contract-trigger:before{width:200%;height:200%}";
var total = 0;
var style = null;
function addListener (elem, callback) {
if (!elem.__resize_mutation_handler__) {
elem.__resize_mutation_handler__ = handleMutation.bind(elem);
}
var listeners = elem.__resize_listeners__;
if (!listeners) {
elem.__resize_listeners__ = [];
if (window.ResizeObserver) {
var offsetWidth = elem.offsetWidth;
var offsetHeight = elem.offsetHeight;
var ro = new ResizeObserver(function () {
if (!elem.__resize_observer_triggered__) {
elem.__resize_observer_triggered__ = true;
if (elem.offsetWidth === offsetWidth && elem.offsetHeight === offsetHeight) {
return
}
}
runCallbacks(elem);
});
// initially display none won't trigger ResizeObserver callback
var ref = getRenderInfo(elem);
var detached = ref.detached;
var rendered = ref.rendered;
elem.__resize_observer_triggered__ = detached === false && rendered === false;
elem.__resize_observer__ = ro;
ro.observe(elem);
} else if (elem.attachEvent && elem.addEventListener) {
// targeting IE9/10
elem.__resize_legacy_resize_handler__ = function handleLegacyResize () {
runCallbacks(elem);
};
elem.attachEvent('onresize', elem.__resize_legacy_resize_handler__);
document.addEventListener('DOMSubtreeModified', elem.__resize_mutation_handler__);
} else {
if (!total) {
style = createStyles(css_248z$1);
}
initTriggers(elem);
elem.__resize_rendered__ = getRenderInfo(elem).rendered;
if (window.MutationObserver) {
var mo = new MutationObserver(elem.__resize_mutation_handler__);
mo.observe(document, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
elem.__resize_mutation_observer__ = mo;
}
}
}
elem.__resize_listeners__.push(callback);
total++;
}
function removeListener (elem, callback) {
var listeners = elem.__resize_listeners__;
if (!listeners) {
return
}
if (callback) {
listeners.splice(listeners.indexOf(callback), 1);
}
// no listeners exist, or removing all listeners
if (!listeners.length || !callback) {
// targeting IE9/10
if (elem.detachEvent && elem.removeEventListener) {
elem.detachEvent('onresize', elem.__resize_legacy_resize_handler__);
document.removeEventListener('DOMSubtreeModified', elem.__resize_mutation_handler__);
return
}
if (elem.__resize_observer__) {
elem.__resize_observer__.unobserve(elem);
elem.__resize_observer__.disconnect();
elem.__resize_observer__ = null;
} else {
if (elem.__resize_mutation_observer__) {
elem.__resize_mutation_observer__.disconnect();
elem.__resize_mutation_observer__ = null;
}
elem.removeEventListener('scroll', handleScroll);
elem.removeChild(elem.__resize_triggers__.triggers);
elem.__resize_triggers__ = null;
}
elem.__resize_listeners__ = null;
}
if (!--total && style) {
style.parentNode.removeChild(style);
}
}
function getUpdatedSize (elem) {
var ref = elem.__resize_last__;
var width = ref.width;
var height = ref.height;
var offsetWidth = elem.offsetWidth;
var offsetHeight = elem.offsetHeight;
if (offsetWidth !== width || offsetHeight !== height) {
return {
width: offsetWidth,
height: offsetHeight
}
}
return null
}
function handleMutation () {
// `this` denotes the scrolling element
var ref = getRenderInfo(this);
var rendered = ref.rendered;
var detached = ref.detached;
if (rendered !== this.__resize_rendered__) {
if (!detached && this.__resize_triggers__) {
resetTriggers(this);
this.addEventListener('scroll', handleScroll, true);
}
this.__resize_rendered__ = rendered;
runCallbacks(this);
}
}
function handleScroll () {
var this$1 = this;
// `this` denotes the scrolling element
resetTriggers(this);
if (this.__resize_raf__) {
cancelAnimationFrame(this.__resize_raf__);
}
this.__resize_raf__ = requestAnimationFrame(function () {
var updated = getUpdatedSize(this$1);
if (updated) {
this$1.__resize_last__ = updated;
runCallbacks(this$1);
}
});
}
function runCallbacks (elem) {
if (!elem || !elem.__resize_listeners__) {
return
}
elem.__resize_listeners__.forEach(function (callback) {
callback.call(elem, elem);
});
}
function initTriggers (elem) {
var position = getComputedStyle(elem, 'position');
if (!position || position === 'static') {
elem.style.position = 'relative';
}
elem.__resize_old_position__ = position;
elem.__resize_last__ = {};
var triggers = createElement('div', {
className: 'resize-triggers'
});
var expand = createElement('div', {
className: 'resize-expand-trigger'
});
var expandChild = createElement('div');
var contract = createElement('div', {
className: 'resize-contract-trigger'
});
expand.appendChild(expandChild);
triggers.appendChild(expand);
triggers.appendChild(contract);
elem.appendChild(triggers);
elem.__resize_triggers__ = {
triggers: triggers,
expand: expand,
expandChild: expandChild,
contract: contract
};
resetTriggers(elem);
elem.addEventListener('scroll', handleScroll, true);
elem.__resize_last__ = {
width: elem.offsetWidth,
height: elem.offsetHeight
};
}
function resetTriggers (elem) {
var ref = elem.__resize_triggers__;
var expand = ref.expand;
var expandChild = ref.expandChild;
var contract = ref.contract;
// batch read
var csw = contract.scrollWidth;
var csh = contract.scrollHeight;
var eow = expand.offsetWidth;
var eoh = expand.offsetHeight;
var esw = expand.scrollWidth;
var esh = expand.scrollHeight;
// batch write
contract.scrollLeft = csw;
contract.scrollTop = csh;
expandChild.style.width = eow + 1 + 'px';
expandChild.style.height = eoh + 1 + 'px';
expand.scrollLeft = esw;
expand.scrollTop = esh;
}
function useAutoresize(chart, autoresize, root, option) {
var resizeListener = null;
var lastArea = 0;
function getArea() {
var el = root.value;
if (!el) {
return 0;
}
return el.offsetWidth * el.offsetHeight;
}
vueDemi.watch([root, chart, autoresize], function (_a, _, cleanup) {
var root = _a[0], chart = _a[1], autoresize = _a[2];
if (root && chart && autoresize) {
lastArea = getArea();
resizeListener = core.throttle(function () {
if (lastArea === 0) {
chart.setOption(Object.create(null), true);
chart.resize();
chart.setOption(option.value, true);
}
else {
chart.resize();
}
lastArea = getArea();
}, 100);
addListener(root, resizeListener);
}
cleanup(function () {
if (resizeListener && root) {
lastArea = 0;
removeListener(root, resizeListener);
}
});
});
}
var autoresizeProps = {
autoresize: Boolean
};
var LOADING_OPTIONS_KEY = "ecLoadingOptions";
function useLoading(chart, loading, loadingOptions) {
var defaultLoadingOptions = vueDemi.inject(LOADING_OPTIONS_KEY, {});
var realLoadingOptions = vueDemi.computed(function () { return (__assign(__assign({}, vueDemi.unref(defaultLoadingOptions)), loadingOptions === null || loadingOptions === void 0 ? void 0 : loadingOptions.value)); });
vueDemi.watchEffect(function () {
var instance = chart.value;
if (!instance) {
return;
}
if (loading.value) {
instance.showLoading(realLoadingOptions.value);
}
else {
instance.hideLoading();
}
});
}
var loadingProps = {
loading: Boolean,
loadingOptions: Object
};
function styleInject(css, ref) {
if ( ref === void 0 ) ref = {};
var insertAt = ref.insertAt;
if (!css || typeof document === 'undefined') { return; }
var head = document.head || document.getElementsByTagName('head')[0];
var style = document.createElement('style');
style.type = 'text/css';
if (insertAt === 'top') {
if (head.firstChild) {
head.insertBefore(style, head.firstChild);
} else {
head.appendChild(style);
}
} else {
head.appendChild(style);
}
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
}
var css_248z = "x-vue-echarts{display:block;width:100%;height:100%}";
styleInject(css_248z);
var onRE = /^on[^a-z]/;
var isOn = function (key) { return onRE.test(key); };
function omitOn(attrs) {
var result = {};
for (var key in attrs) {
if (!isOn(key)) {
result[key] = attrs[key];
}
}
return result;
}
vueDemi.install();
var TAG_NAME = "x-vue-echarts";
if (vueDemi.Vue2) {
vueDemi.Vue2.config.ignoredElements.push(TAG_NAME);
}
var THEME_KEY = "ecTheme";
var INIT_OPTIONS_KEY = "ecInitOptions";
var UPDATE_OPTIONS_KEY = "ecUpdateOptions";
var ECharts = vueDemi.defineComponent({
name: "echarts",
props: __assign(__assign({ option: Object, theme: {
type: [Object, String]
}, initOptions: Object, updateOptions: Object, group: String, manualUpdate: Boolean }, autoresizeProps), loadingProps),
inheritAttrs: false,
setup: function (props, _a) {
var attrs = _a.attrs, listeners = _a.listeners;
var root = vueDemi.ref();
var chart = vueDemi.shallowRef();
var manualOption = vueDemi.shallowRef();
var defaultTheme = vueDemi.inject(THEME_KEY, null);
var defaultInitOptions = vueDemi.inject(INIT_OPTIONS_KEY, null);
var defaultUpdateOptions = vueDemi.inject(UPDATE_OPTIONS_KEY, null);
var realOption = vueDemi.computed(function () { return manualOption.value || props.option || Object.create(null); });
var realTheme = vueDemi.computed(function () { return props.theme || vueDemi.unref(defaultTheme) || {}; });
var realInitOptions = vueDemi.computed(function () { return props.initOptions || vueDemi.unref(defaultInitOptions) || {}; });
var realUpdateOptions = vueDemi.computed(function () { return props.updateOptions || vueDemi.unref(defaultUpdateOptions) || {}; });
var _b = vueDemi.toRefs(props), autoresize = _b.autoresize, manualUpdate = _b.manualUpdate, loading = _b.loading;
var theme = vueDemi.toRef(props, "theme");
var initOptions = vueDemi.toRef(props, "initOptions");
var loadingOptions = vueDemi.toRef(props, "loadingOptions");
var nonEventAttrs = vueDemi.computed(function () { return omitOn(attrs); });
function init(option) {
if (chart.value || !root.value) {
return;
}
var instance = (chart.value = core.init(root.value, realTheme.value, realInitOptions.value));
if (props.group) {
instance.group = props.group;
}
var realListeners = listeners;
if (!realListeners) {
realListeners = {};
Object.keys(attrs)
.filter(function (key) { return key.indexOf("on") === 0 && key.length > 2; })
.forEach(function (key) {
var event = key.charAt(2).toLowerCase() + key.slice(3);
realListeners[event] = attrs[key];
});
}
Object.keys(realListeners).forEach(function (key) {
var handler = realListeners[key];
if (!handler) {
return;
}
if (key.indexOf("zr:") === 0) {
instance.getZr().on(key.slice(3).toLowerCase(), handler);
}
else {
instance.on(key.toLowerCase(), handler);
}
});
instance.setOption(option || realOption.value, realUpdateOptions.value);
setTimeout(function () {
instance.resize();
});
}
function setOption(option, updateOptions) {
if (props.manualUpdate) {
manualOption.value = option;
}
if (!chart.value) {
init(option);
}
else {
chart.value.setOption(option, __assign(__assign({}, realUpdateOptions.value), updateOptions));
}
}
function cleanup() {
if (chart.value) {
chart.value.dispose();
chart.value = undefined;
}
}
var unwatchOption = null;
vueDemi.watch(manualUpdate, function (manualUpdate) {
if (typeof unwatchOption === "function") {
unwatchOption();
unwatchOption = null;
}
if (!manualUpdate) {
unwatchOption = vueDemi.watch(function () { return props.option; }, function (option) {
if (!option) {
return;
}
if (!chart.value) {
init();
}
else {
chart.value.setOption(option, props.updateOptions);
}
}, { deep: true });
}
}, {
immediate: true
});
vueDemi.watch([theme, initOptions], function () {
cleanup();
init();
}, {
deep: true
});
vueDemi.watchEffect(function () {
if (props.group && chart.value) {
chart.value.group = props.group;
}
});
var publicApi = usePublicAPI(chart, init);
useLoading(chart, loading, loadingOptions);
useAutoresize(chart, autoresize, root, realOption);
vueDemi.onMounted(function () {
if (props.option) {
init();
}
});
vueDemi.onUnmounted(cleanup);
var exposed = __assign({ root: root,
setOption: setOption,
nonEventAttrs: nonEventAttrs }, publicApi);
Object.defineProperty(exposed, "chart", {
get: function () {
return vueDemi.unref(chart);
}
});
return exposed;
},
render: function () {
var attrs = __assign({}, this.nonEventAttrs);
attrs.ref = "root";
attrs.class = attrs.class ? ["echarts"].concat(attrs.class) : "echarts";
return vueDemi.h(TAG_NAME, attrs);
}
});
var exported = /*#__PURE__*/Object.freeze({
__proto__: null,
'default': ECharts,
LOADING_OPTIONS_KEY: LOADING_OPTIONS_KEY,
THEME_KEY: THEME_KEY,
INIT_OPTIONS_KEY: INIT_OPTIONS_KEY,
UPDATE_OPTIONS_KEY: UPDATE_OPTIONS_KEY
});
var global = __assign(__assign({}, ECharts), exported);
return global;
})));
//# sourceMappingURL=index.umd.js.map
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import { getThemeProps, useTheme } from '@material-ui/styles';
import { elementAcceptingRef, HTMLElementType } from '@material-ui/utils';
import ownerDocument from '../utils/ownerDocument';
import Portal from '../Portal';
import createChainedFunction from '../utils/createChainedFunction';
import useForkRef from '../utils/useForkRef';
import useEventCallback from '../utils/useEventCallback';
import zIndex from '../styles/zIndex';
import ModalManager, { ariaHidden } from './ModalManager';
import TrapFocus from '../Unstable_TrapFocus';
import SimpleBackdrop from './SimpleBackdrop';
function getContainer(container) {
return typeof container === 'function' ? container() : container;
}
function getHasTransition(props) {
return props.children ? props.children.props.hasOwnProperty('in') : false;
} // A modal manager used to track and manage the state of open Modals.
// Modals don't open on the server so this won't conflict with concurrent requests.
const defaultManager = new ModalManager();
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
position: 'fixed',
zIndex: theme.zIndex.modal,
right: 0,
bottom: 0,
top: 0,
left: 0
},
/* Styles applied to the root element if the `Modal` has exited. */
hidden: {
visibility: 'hidden'
}
});
/**
* Modal is a lower-level construct that is leveraged by the following components:
*
* - [Dialog](/api/dialog/)
* - [Drawer](/api/drawer/)
* - [Menu](/api/menu/)
* - [Popover](/api/popover/)
*
* If you are creating a modal dialog, you probably want to use the [Dialog](/api/dialog/) component
* rather than directly using Modal.
*
* This component shares many concepts with [react-overlays](https://react-bootstrap.github.io/react-overlays/#modals).
*/
const Modal = /*#__PURE__*/React.forwardRef(function Modal(inProps, ref) {
const theme = useTheme();
const props = getThemeProps({
name: 'MuiModal',
props: _extends({}, inProps),
theme
});
const {
BackdropComponent = SimpleBackdrop,
BackdropProps,
children,
closeAfterTransition = false,
container,
disableAutoFocus = false,
disableBackdropClick = false,
disableEnforceFocus = false,
disableEscapeKeyDown = false,
disablePortal = false,
disableRestoreFocus = false,
disableScrollLock = false,
hideBackdrop = false,
keepMounted = false,
// private
// eslint-disable-next-line react/prop-types
manager = defaultManager,
onBackdropClick,
onClose,
onEscapeKeyDown,
onRendered,
open
} = props,
other = _objectWithoutPropertiesLoose(props, ["BackdropComponent", "BackdropProps", "children", "closeAfterTransition", "container", "disableAutoFocus", "disableBackdropClick", "disableEnforceFocus", "disableEscapeKeyDown", "disablePortal", "disableRestoreFocus", "disableScrollLock", "hideBackdrop", "keepMounted", "manager", "onBackdropClick", "onClose", "onEscapeKeyDown", "onRendered", "open"]);
const [exited, setExited] = React.useState(true);
const modal = React.useRef({});
const mountNodeRef = React.useRef(null);
const modalRef = React.useRef(null);
const handleRef = useForkRef(modalRef, ref);
const hasTransition = getHasTransition(props);
const getDoc = () => ownerDocument(mountNodeRef.current);
const getModal = () => {
modal.current.modalRef = modalRef.current;
modal.current.mountNode = mountNodeRef.current;
return modal.current;
};
const handleMounted = () => {
manager.mount(getModal(), {
disableScrollLock
}); // Fix a bug on Chrome where the scroll isn't initially 0.
modalRef.current.scrollTop = 0;
};
const handleOpen = useEventCallback(() => {
const resolvedContainer = getContainer(container) || getDoc().body;
manager.add(getModal(), resolvedContainer); // The element was already mounted.
if (modalRef.current) {
handleMounted();
}
});
const isTopModal = React.useCallback(() => manager.isTopModal(getModal()), [manager]);
const handlePortalRef = useEventCallback(node => {
mountNodeRef.current = node;
if (!node) {
return;
}
if (onRendered) {
onRendered();
}
if (open && isTopModal()) {
handleMounted();
} else {
ariaHidden(modalRef.current, true);
}
});
const handleClose = React.useCallback(() => {
manager.remove(getModal());
}, [manager]);
React.useEffect(() => {
return () => {
handleClose();
};
}, [handleClose]);
React.useEffect(() => {
if (open) {
handleOpen();
} else if (!hasTransition || !closeAfterTransition) {
handleClose();
}
}, [open, handleClose, hasTransition, closeAfterTransition, handleOpen]);
if (!keepMounted && !open && (!hasTransition || exited)) {
return null;
}
const handleEnter = () => {
setExited(false);
};
const handleExited = () => {
setExited(true);
if (closeAfterTransition) {
handleClose();
}
};
const handleBackdropClick = event => {
if (event.target !== event.currentTarget) {
return;
}
if (onBackdropClick) {
onBackdropClick(event);
}
if (!disableBackdropClick && onClose) {
onClose(event, 'backdropClick');
}
};
const handleKeyDown = event => {
// The handler doesn't take event.defaultPrevented into account:
//
// event.preventDefault() is meant to stop default behaviours like
// clicking a checkbox to check it, hitting a button to submit a form,
// and hitting left arrow to move the cursor in a text input etc.
// Only special HTML elements have these default behaviors.
if (event.key !== 'Escape' || !isTopModal()) {
return;
}
if (onEscapeKeyDown) {
onEscapeKeyDown(event);
}
if (!disableEscapeKeyDown) {
// Swallow the event, in case someone is listening for the escape key on the body.
event.stopPropagation();
if (onClose) {
onClose(event, 'escapeKeyDown');
}
}
};
const inlineStyle = styles(theme || {
zIndex
});
const childProps = {};
if (children.props.tabIndex === undefined) {
childProps.tabIndex = children.props.tabIndex || '-1';
} // It's a Transition like component
if (hasTransition) {
childProps.onEnter = createChainedFunction(handleEnter, children.props.onEnter);
childProps.onExited = createChainedFunction(handleExited, children.props.onExited);
}
return /*#__PURE__*/React.createElement(Portal, {
ref: handlePortalRef,
container: container,
disablePortal: disablePortal
}, /*#__PURE__*/React.createElement("div", _extends({
ref: handleRef,
onKeyDown: handleKeyDown,
role: "presentation"
}, other, {
style: _extends({}, inlineStyle.root, !open && exited ? inlineStyle.hidden : {}, other.style)
}), hideBackdrop ? null : /*#__PURE__*/React.createElement(BackdropComponent, _extends({
open: open,
onClick: handleBackdropClick
}, BackdropProps)), /*#__PURE__*/React.createElement(TrapFocus, {
disableEnforceFocus: disableEnforceFocus,
disableAutoFocus: disableAutoFocus,
disableRestoreFocus: disableRestoreFocus,
getDoc: getDoc,
isEnabled: isTopModal,
open: open
}, /*#__PURE__*/React.cloneElement(children, childProps))));
});
process.env.NODE_ENV !== "production" ? Modal.propTypes = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* A backdrop component. This prop enables custom backdrop rendering.
*/
BackdropComponent: PropTypes.elementType,
/**
* Props applied to the [`Backdrop`](/api/backdrop/) element.
*/
BackdropProps: PropTypes.object,
/**
* A single child content element.
*/
children: elementAcceptingRef.isRequired,
/**
* When set to true the Modal waits until a nested Transition is completed before closing.
*/
closeAfterTransition: PropTypes.bool,
/**
* A HTML element, component instance, or function that returns either.
* The `container` will have the portal children appended to it.
*
* By default, it uses the body of the top-level document object,
* so it's simply `document.body` most of the time.
*/
container: PropTypes
/* @typescript-to-proptypes-ignore */
.oneOfType([HTMLElementType, PropTypes.instanceOf(React.Component), PropTypes.func]),
/**
* If `true`, the modal will not automatically shift focus to itself when it opens, and
* replace it to the last focused element when it closes.
* This also works correctly with any modal children that have the `disableAutoFocus` prop.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableAutoFocus: PropTypes.bool,
/**
* If `true`, clicking the backdrop will not fire `onClose`.
*/
disableBackdropClick: PropTypes.bool,
/**
* If `true`, the modal will not prevent focus from leaving the modal while open.
*
* Generally this should never be set to `true` as it makes the modal less
* accessible to assistive technologies, like screen readers.
*/
disableEnforceFocus: PropTypes.bool,
/**
* If `true`, hitting escape will not fire `onClose`.
*/
disableEscapeKeyDown: PropTypes.bool,
/**
* The `children` will be inside the DOM hierarchy of the parent component.
*/
disablePortal: PropTypes.bool,
/**
* If `true`, the modal will not restore focus to previously focused element once
* modal is hidden.
*/
disableRestoreFocus: PropTypes.bool,
/**
* Disable the scroll lock behavior.
*/
disableScrollLock: PropTypes.bool,
/**
* If `true`, the backdrop is not rendered.
*/
hideBackdrop: PropTypes.bool,
/**
* Always keep the children in the DOM.
* This prop can be useful in SEO situation or
* when you want to maximize the responsiveness of the Modal.
*/
keepMounted: PropTypes.bool,
/**
* Callback fired when the backdrop is clicked.
*/
onBackdropClick: PropTypes.func,
/**
* Callback fired when the component requests to be closed.
* The `reason` parameter can optionally be used to control the response to `onClose`.
*
* @param {object} event The event source of the callback.
* @param {string} reason Can be: `"escapeKeyDown"`, `"backdropClick"`.
*/
onClose: PropTypes.func,
/**
* Callback fired when the escape key is pressed,
* `disableEscapeKeyDown` is false and the modal is in focus.
*/
onEscapeKeyDown: PropTypes.func,
/**
* Callback fired once the children has been mounted into the `container`.
* It signals that the `open={true}` prop took effect.
*
* This prop will be deprecated and removed in v5, the ref can be used instead.
*/
onRendered: PropTypes.func,
/**
* If `true`, the modal is open.
*/
open: PropTypes.bool.isRequired
} : void 0;
export default Modal;
|
/**
* @license Highcharts JS v8.1.2 (2020-06-16)
* @module highcharts/modules/accessibility
* @requires highcharts
*
* Accessibility module
*
* (c) 2010-2019 Highsoft AS
* Author: Oystein Moseng
*
* License: www.highcharts.com/license
*/
'use strict';
import '../../modules/accessibility/accessibility.js';
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.VueFlowForm = {}, global.Vue));
})(this, (function (exports, vue) { 'use strict';
/*!
Copyright (c) 2020 - present, DITDOT Ltd. - MIT Licence
https://github.com/ditdot-dev/vue-flow-form
https://www.ditdot.hr/en
*/
// Language data store
var LanguageModel = function LanguageModel(options) {
this.enterKey = 'Enter';
this.shiftKey = 'Shift';
this.ok = 'OK';
this.continue = 'Continue';
this.skip = 'Skip';
this.pressEnter = 'Press :enterKey';
this.multipleChoiceHelpText = 'Choose as many as you like';
this.multipleChoiceHelpTextSingle = 'Choose only one answer';
this.otherPrompt = 'Other';
this.placeholder = 'Type your answer here...';
this.submitText = 'Submit';
this.longTextHelpText = ':shiftKey + :enterKey to make a line break.';
this.prev = 'Prev';
this.next = 'Next';
this.percentCompleted = ':percent% completed';
this.invalidPrompt = 'Please fill out the field correctly';
this.thankYouText = 'Thank you!';
this.successText = 'Your submission has been sent.';
this.ariaOk = 'Press to continue';
this.ariaRequired = 'This step is required';
this.ariaPrev = 'Previous step';
this.ariaNext = 'Next step';
this.ariaSubmitText = 'Press to submit';
this.ariaMultipleChoice = 'Press :letter to select';
this.ariaTypeAnswer = 'Type your answer here';
this.errorAllowedFileTypes = 'Invalid file type. Allowed file types: :fileTypes.';
this.errorMaxFileSize = 'File(s) too large. Maximum allowed file size: :size.';
this.errorMinFiles = 'Too few files added. Minimum allowed files: :min.';
this.errorMaxFiles = 'Too many files added. Maximum allowed files: :max.';
Object.assign(this, options || {});
};
/**
* Inserts a new CSS class into the language model string to format the :string
* Use it in a component's v-html directive: v-html="language.formatString(language.languageString)"
*/
LanguageModel.prototype.formatString = function formatString (string, replacements) {
var this$1$1 = this;
return string.replace(/:(\w+)/g, function (match, word) {
if (this$1$1[word]) {
return '<span class="f-string-em">' + this$1$1[word] + '</span>'
} else if (replacements && replacements[word]) {
return replacements[word]
}
return match
})
};
LanguageModel.prototype.formatFileSize = function formatFileSize (bytes) {
var
units = ['B', 'kB', 'MB', 'GB', 'TB'],
i = bytes > 0 ? Math.floor(Math.log(bytes) / Math.log(1024)) : 0;
return (bytes / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + units[i];
};
/*
Copyright (c) 2020 - present, DITDOT Ltd. - MIT Licence
https://github.com/ditdot-dev/vue-flow-form
https://www.ditdot.hr/en
*/
// Global data store
var QuestionType = Object.freeze({
Date: 'FlowFormDateType',
Dropdown: 'FlowFormDropdownType',
Email: 'FlowFormEmailType',
File: 'FlowFormFileType',
LongText: 'FlowFormLongTextType',
MultipleChoice: 'FlowFormMultipleChoiceType',
MultiplePictureChoice: 'FlowFormMultiplePictureChoiceType',
Number: 'FlowFormNumberType',
Password: 'FlowFormPasswordType',
Phone: 'FlowFormPhoneType',
SectionBreak: 'FlowFormSectionBreakType',
Text: 'FlowFormTextType',
Url: 'FlowFormUrlType',
Matrix: 'FlowFormMatrixType'
});
Object.freeze({
label: '',
value: '',
disabled: true
});
var MaskPresets = Object.freeze({
Date: '##/##/####',
DateIso: '####-##-##',
PhoneUs: '(###) ###-####'
});
var ChoiceOption = function ChoiceOption(options) {
this.label = '';
this.value = null;
this.selected = false;
this.imageSrc = null;
this.imageAlt = null;
Object.assign(this, options);
};
ChoiceOption.prototype.choiceLabel = function choiceLabel () {
return this.label || this.value
};
ChoiceOption.prototype.choiceValue = function choiceValue () {
// Returns the value if it's anything other than the default (null).
if (this.value !== null) {
return this.value
}
// Returns any other non-empty property if the value has not been set.
return this.label || this.imageAlt || this.imageSrc
};
ChoiceOption.prototype.toggle = function toggle () {
this.selected = !this.selected;
};
var LinkOption = function LinkOption(options) {
this.url = '';
this.text = '';
this.target = '_blank';
Object.assign(this, options);
};
var QuestionModel = function QuestionModel(options) {
// Make sure the options variable is an object
options = options || {};
this.id = null;
this.answer = null;
this.answered = false;
this.index = 0;
this.options = [];
this.description = '';
this.className = '';
this.type = null;
this.html = null;
this.required = false;
this.jump = null;
this.placeholder = null;
this.mask = '';
this.multiple = false;
this.allowOther = false;
this.other = null;
this.language = null;
this.tagline = null;
this.title = null;
this.subtitle = null;
this.content = null;
this.inline = false;
this.helpText = null;
this.helpTextShow = true;
this.descriptionLink = [];
this.min = null;
this.max = null;
this.maxLength = null;
this.nextStepOnAnswer = false;
this.accept = null;
this.maxSize = null;
this.rows = [];
this.columns = [];
Object.assign(this, options);
// Sets default mask and placeholder value on PhoneType question
if (this.type === QuestionType.Phone) {
if (!this.mask) {
this.mask = MaskPresets.Phone;
}
if (!this.placeholder) {
this.placeholder = this.mask;
}
}
if (this.type === QuestionType.Url) {
this.mask = null;
}
if (this.type === QuestionType.Date && !this.placeholder) {
this.placeholder = 'yyyy-mm-dd';
}
if (this.type !== QuestionType.Matrix && this.multiple && !Array.isArray(this.answer)) {
this.answer = this.answer ? [this.answer] : [];
}
// Check if we have an answer already (when we have a pre-filled form)
// and set the answered property accordingly
if (!this.required && typeof options.answer !== 'undefined') {
this.answered = true;
} else if (this.answer && (!this.multiple || this.answer.length)) {
this.answered = true;
}
this.resetOptions();
};
QuestionModel.prototype.getJumpId = function getJumpId () {
var nextId = null;
if (typeof this.jump === 'function') {
nextId = this.jump.call(this);
} else if (this.jump[this.answer]) {
nextId = this.jump[this.answer];
} else if (this.jump['_other']) {
nextId = this.jump['_other'];
}
return nextId
};
QuestionModel.prototype.setAnswer = function setAnswer (answer) {
if (this.type === QuestionType.Number && answer !== '' && !isNaN(+answer)) {
answer = +answer;
}
this.answer = answer;
};
QuestionModel.prototype.setIndex = function setIndex (index) {
if (!this.id) {
this.id = 'q_' + index;
}
this.index = index;
};
QuestionModel.prototype.resetOptions = function resetOptions () {
var this$1$1 = this;
if (this.options) {
var isArray = Array.isArray(this.answer);
var numSelected = 0;
this.options.forEach(function (o) {
var optionValue = o.choiceValue();
if (this$1$1.answer === optionValue || (isArray && this$1$1.answer.indexOf(optionValue) !== -1)) {
o.selected = true;
++numSelected;
} else {
o.selected = false;
}
});
if (this.allowOther) {
var otherAnswer = null;
if (isArray) {
if (this.answer.length && this.answer.length !== numSelected) {
otherAnswer = this.answer[this.answer.length - 1];
}
} else if (this.options.map(function (o) { return o.choiceValue(); }).indexOf(this.answer) === -1) {
otherAnswer = this.answer;
}
if (otherAnswer !== null) {
this.other = otherAnswer;
}
}
}
};
QuestionModel.prototype.resetAnswer = function resetAnswer () {
this.answered = false;
this.answer = this.multiple ? [] : null;
this.other = null;
this.resetOptions();
};
QuestionModel.prototype.isMultipleChoiceType = function isMultipleChoiceType () {
return [QuestionType.MultipleChoice, QuestionType.MultiplePictureChoice].includes(this.type)
};
/*
Copyright (c) 2020 - present, DITDOT Ltd. - MIT Licence
https://github.com/ditdot-dev/vue-flow-form
https://www.ditdot.hr/en
*/
var
isIos = false,
isMobile = false;
if (typeof navigator !== 'undefined' && typeof document !== 'undefined') {
// Simple mobile device/tablet detection
isIos = navigator.userAgent.match(/iphone|ipad|ipod/i) || (navigator.userAgent.indexOf('Mac') !== -1 && 'ontouchend' in document);
isMobile = isIos || navigator.userAgent.match(/android/i);
}
// Mixin that adds `isMobile` and `isIos` data variables
var IsMobile = {
data: function data() {
return {
isIos: isIos,
isMobile: isMobile
}
}
};
var script$j = {
name: 'FlowFormBaseType',
props: {
language: LanguageModel,
question: QuestionModel,
active: Boolean,
disabled: Boolean,
modelValue: [String, Array, Boolean, Number, Object]
},
mixins: [
IsMobile ],
data: function data() {
return {
dirty: false,
dataValue: null,
answer: null,
enterPressed: false,
allowedChars: null,
alwaysAllowedKeys: ['ArrowLeft', 'ArrowRight', 'Delete', 'Backspace'],
focused: false,
canReceiveFocus: false,
errorMessage: null
}
},
mounted: function mounted() {
if (this.question.answer) {
this.dataValue = this.answer = this.question.answer;
} else if (this.question.multiple) {
this.dataValue = [];
}
},
methods: {
/**
* This method can be overriden in custom components to
* change the answer before going through validation.
*/
fixAnswer: function fixAnswer(answer) {
return answer
},
getElement: function getElement() {
var el = this.$refs.input;
// Sometimes the input is nested so we need to find it
while (el && el.$el) {
el = el.$el;
}
return el
},
setFocus: function setFocus() {
this.focused = true;
},
// eslint-disable-next-line no-unused-vars
unsetFocus: function unsetFocus($event) {
this.focused = false;
},
focus: function focus() {
if (!this.focused) {
var el = this.getElement();
el && el.focus();
}
},
blur: function blur() {
var el = this.getElement();
el && el.blur();
},
onKeyDown: function onKeyDown($event) {
this.enterPressed = false;
clearTimeout(this.timeoutId);
if ($event) {
if ($event.key === 'Enter' && !$event.shiftKey) {
this.unsetFocus();
}
if (this.allowedChars !== null) {
// Check if the entered character is allowed.
// We always allow keys from the alwaysAllowedKeys array.
if (this.alwaysAllowedKeys.indexOf($event.key) === -1 && this.allowedChars.indexOf($event.key) === -1) {
$event.preventDefault();
}
}
}
},
onChange: function onChange($event) {
this.dirty = true;
this.dataValue = $event.target.value;
this.onKeyDown();
this.setAnswer(this.dataValue);
},
onEnter: function onEnter() {
this._onEnter();
},
_onEnter: function _onEnter() {
this.enterPressed = true;
this.dataValue = this.fixAnswer(this.dataValue);
this.setAnswer(this.dataValue);
this.isValid() ? this.blur() : this.focus();
},
setAnswer: function setAnswer(answer) {
this.question.setAnswer(answer);
this.answer = this.question.answer;
this.question.answered = this.isValid();
this.$emit('update:modelValue', this.answer);
},
showInvalid: function showInvalid() {
return this.dirty && this.enterPressed && !this.isValid()
},
isValid: function isValid() {
if (!this.question.required && !this.hasValue && this.dirty) {
return true
}
if (this.validate()) {
return true
}
return false
},
/**
* This method validates the input and is meant to be overriden
* in custom question types.
*/
validate: function validate() {
return !this.question.required || this.hasValue
}
},
computed: {
placeholder: function placeholder() {
return this.question.placeholder || this.language.placeholder
},
hasValue: function hasValue() {
if (this.dataValue !== null) {
var v = this.dataValue;
if (v.trim) {
// Don't allow empty strings
return v.trim().length > 0
}
if (Array.isArray(v)) {
// Don't allow empty arrays
return v.length > 0
}
// All other non-null values are allowed to pass through
return true
}
return false
}
}
};
script$j.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/BaseType.vue";
var script$i = {
extends: script$j,
name: QuestionType.Dropdown,
computed: {
answerLabel: function answerLabel() {
for (var i = 0; i < this.question.options.length; i++) {
var option = this.question.options[i];
if (option.choiceValue() === this.dataValue) {
return option.choiceLabel()
}
}
return this.question.placeholder
}
},
methods: {
onKeyDownListener: function onKeyDownListener($event) {
if ($event.key === 'ArrowDown' || $event.key === 'ArrowUp') {
this.setAnswer(this.dataValue);
} else if ($event.key === 'Enter' && this.hasValue) {
this.focused = false;
this.blur();
}
},
onKeyUpListener: function onKeyUpListener($event) {
if ($event.key === 'Enter' && this.isValid() && !this.disabled) {
$event.stopPropagation();
this._onEnter();
this.$emit('next');
}
}
}
};
var _hoisted_1$8 = { class: "faux-form" };
var _hoisted_2$6 = ["value", "required"];
var _hoisted_3$4 = {
key: 0,
label: " ",
value: "",
disabled: "",
selected: "",
hidden: ""
};
var _hoisted_4$4 = ["disabled", "value"];
var _hoisted_5$4 = /*#__PURE__*/vue.createElementVNode("span", { class: "f-arrow-down" }, [
/*#__PURE__*/vue.createElementVNode("svg", {
version: "1.1",
id: "Capa_1",
xmlns: "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
x: "0px",
y: "0px",
viewBox: "-163 254.1 284.9 284.9",
style: "",
"xml:space": "preserve"
}, [
/*#__PURE__*/vue.createElementVNode("g", null, [
/*#__PURE__*/vue.createElementVNode("path", { d: "M119.1,330.6l-14.3-14.3c-1.9-1.9-4.1-2.9-6.6-2.9c-2.5,0-4.7,1-6.6,2.9L-20.5,428.5l-112.2-112.2c-1.9-1.9-4.1-2.9-6.6-2.9c-2.5,0-4.7,0.9-6.6,2.9l-14.3,14.3c-1.9,1.9-2.9,4.1-2.9,6.6c0,2.5,1,4.7,2.9,6.6l133,133c1.9,1.9,4.1,2.9,6.6,2.9s4.7-1,6.6-2.9l133.1-133c1.9-1.9,2.8-4.1,2.8-6.6C121.9,334.7,121,332.5,119.1,330.6z" })
])
])
], -1 /* HOISTED */);
function render$a(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createElementBlock("span", _hoisted_1$8, [
vue.createElementVNode("select", {
ref: "input",
class: "",
value: _ctx.dataValue,
onChange: _cache[0] || (_cache[0] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onChange && _ctx.onChange.apply(_ctx, args));
}),
onKeydown: _cache[1] || (_cache[1] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onKeyDownListener && $options.onKeyDownListener.apply($options, args));
}),
onKeyup: _cache[2] || (_cache[2] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onKeyUpListener && $options.onKeyUpListener.apply($options, args));
}),
required: _ctx.question.required
}, [
(_ctx.question.required)
? (vue.openBlock(), vue.createElementBlock("option", _hoisted_3$4, " "))
: vue.createCommentVNode("v-if", true),
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.question.options, function (option, index) {
return (vue.openBlock(), vue.createElementBlock("option", {
disabled: option.disabled,
value: option.choiceValue(),
key: 'o' + index
}, vue.toDisplayString(option.choiceLabel()), 9 /* TEXT, PROPS */, _hoisted_4$4))
}), 128 /* KEYED_FRAGMENT */))
], 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_2$6),
vue.createElementVNode("span", null, [
vue.createElementVNode("span", {
class: vue.normalizeClass(["f-empty", {'f-answered': this.question.answer && this.question.answered}])
}, vue.toDisplayString($options.answerLabel), 3 /* TEXT, CLASS */),
_hoisted_5$4
])
]))
}
script$i.render = render$a;
script$i.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/DropdownType.vue";
function maskit (value, mask, masked, tokens) {
if ( masked === void 0 ) masked = true;
value = value || '';
mask = mask || '';
var iMask = 0;
var iValue = 0;
var output = '';
while (iMask < mask.length && iValue < value.length) {
var cMask = mask[iMask];
var masker = tokens[cMask];
var cValue = value[iValue];
if (masker && !masker.escape) {
if (masker.pattern.test(cValue)) {
output += masker.transform ? masker.transform(cValue) : cValue;
iMask++;
}
iValue++;
} else {
if (masker && masker.escape) {
iMask++; // take the next mask char and treat it as char
cMask = mask[iMask];
}
if (masked) { output += cMask; }
if (cValue === cMask) { iValue++; } // user typed the same char
iMask++;
}
}
// fix mask that ends with a char: (#)
var restOutput = '';
while (iMask < mask.length && masked) {
var cMask = mask[iMask];
if (tokens[cMask]) {
restOutput = '';
break
}
restOutput += cMask;
iMask++;
}
return output + restOutput
}
function dynamicMask (maskit, masks, tokens) {
masks = masks.sort(function (a, b) { return a.length - b.length; });
return function (value, mask, masked) {
if ( masked === void 0 ) masked = true;
var i = 0;
while (i < masks.length) {
var currentMask = masks[i];
i++;
var nextMask = masks[i];
if (! (nextMask && maskit(value, nextMask, true, tokens).length > currentMask.length) ) {
return maskit(value, currentMask, masked, tokens)
}
}
return '' // empty masks
}
}
// Facade to maskit/dynamicMask when mask is String or Array
function masker (value, mask, masked, tokens) {
if ( masked === void 0 ) masked = true;
return Array.isArray(mask)
? dynamicMask(maskit, mask, tokens)(value, mask, masked, tokens)
: maskit(value, mask, masked, tokens)
}
var tokens = {
'#': {pattern: /\d/},
'X': {pattern: /[0-9a-zA-Z]/},
'S': {pattern: /[a-zA-Z]/},
'A': {pattern: /[a-zA-Z]/, transform: function (v) { return v.toLocaleUpperCase(); }},
'a': {pattern: /[a-zA-Z]/, transform: function (v) { return v.toLocaleLowerCase(); }},
'!': {escape: true}
};
// https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events#The_old-fashioned_way
function event (name) {
var evt = document.createEvent('Event');
evt.initEvent(name, true, true);
return evt
}
function mask (el, binding) {
var config = binding.value;
if (Array.isArray(config) || typeof config === 'string') {
config = {
mask: config,
tokens: tokens
};
}
if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
var els = el.getElementsByTagName('input');
if (els.length !== 1) {
throw new Error("v-mask directive requires 1 input, found " + els.length)
} else {
el = els[0];
}
}
el.oninput = function (evt) {
if (!evt.isTrusted) { return } // avoid infinite loop
/* other properties to try to diferentiate InputEvent of Event (custom)
InputEvent (native)
cancelable: false
isTrusted: true
composed: true
isComposing: false
which: 0
Event (custom)
cancelable: true
isTrusted: false
*/
// by default, keep cursor at same position as before the mask
var position = el.selectionEnd;
// save the character just inserted
var digit = el.value[position-1];
el.value = masker(el.value, config.mask, true, config.tokens);
// if the digit was changed, increment position until find the digit again
while (position < el.value.length && el.value.charAt(position-1) !== digit) {
position++;
}
if (el === document.activeElement) {
el.setSelectionRange(position, position);
setTimeout(function () {
el.setSelectionRange(position, position);
}, 0);
}
el.dispatchEvent(event('input'));
};
var newDisplay = masker(el.value, config.mask, true, config.tokens);
if (newDisplay !== el.value) {
el.value = newDisplay;
el.dispatchEvent(event('input'));
}
}
var script$h = {
name: 'TheMask',
props: {
value: [String, Number],
mask: {
type: [String, Array],
required: true
},
masked: { // by default emits the value unformatted, change to true to format with the mask
type: Boolean,
default: false // raw
},
tokens: {
type: Object,
default: function () { return tokens; }
}
},
directives: {mask: mask},
data: function data () {
return {
lastValue: null, // avoid unecessary emit when has no change
display: this.value
}
},
watch : {
value: function value (newValue) {
if (newValue !== this.lastValue) {
this.display = newValue;
}
},
masked: function masked () {
this.refresh(this.display);
}
},
computed: {
config: function config () {
return {
mask: this.mask,
tokens: this.tokens,
masked: this.masked
}
}
},
methods: {
onInput: function onInput (e) {
if (e.isTrusted) { return } // ignore native event
this.refresh(e.target.value);
},
refresh: function refresh (value) {
this.display = value;
var value = masker(value, this.mask, this.masked, this.tokens);
if (value !== this.lastValue) {
this.lastValue = value;
this.$emit('input', value);
}
}
}
};
var _hoisted_1$7 = ["value"];
function render$9(_ctx, _cache, $props, $setup, $data, $options) {
var _directive_mask = vue.resolveDirective("mask");
return vue.withDirectives((vue.openBlock(), vue.createElementBlock("input", {
type: "text",
value: $data.display,
onInput: _cache[0] || (_cache[0] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onInput && $options.onInput.apply($options, args));
})
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_1$7)), [
[_directive_mask, $options.config]
])
}
script$h.render = render$9;
script$h.__file = "//HAL9000/work/_open source/_vff/_git - phre/node_modules/vue-the-mask/src/component.vue";
var script$g = {
extends: script$j,
name: QuestionType.Text,
components: {
TheMask: script$h
},
data: function data() {
return {
inputType: 'text',
canReceiveFocus: true
}
},
methods: {
validate: function validate() {
if (this.question.mask && this.hasValue) {
return this.validateMask()
}
return !this.question.required || this.hasValue
},
validateMask: function validateMask() {
var this$1$1 = this;
if (Array.isArray(this.question.mask)) {
return this.question.mask.some(function (mask) { return mask.length === this$1$1.dataValue.length; })
}
return this.dataValue.length === this.question.mask.length
}
}
};
var _hoisted_1$6 = ["data-placeholder"];
var _hoisted_2$5 = ["type", "value", "required", "min", "max", "placeholder", "maxlength"];
function render$8(_ctx, _cache, $props, $setup, $data, $options) {
var _component_the_mask = vue.resolveComponent("the-mask");
return (vue.openBlock(), vue.createElementBlock("span", {
"data-placeholder": $data.inputType === 'date' ? _ctx.placeholder : null
}, [
(_ctx.question.mask)
? (vue.openBlock(), vue.createBlock(_component_the_mask, {
key: 0,
ref: "input",
mask: _ctx.question.mask,
masked: false,
type: $data.inputType,
value: _ctx.modelValue,
required: _ctx.question.required,
onKeydown: _ctx.onKeyDown,
onKeyup: [
_ctx.onChange,
vue.withKeys(vue.withModifiers(_ctx.onEnter, ["prevent"]), ["enter"]),
vue.withKeys(vue.withModifiers(_ctx.onEnter, ["prevent"]), ["tab"])
],
onFocus: _ctx.setFocus,
onBlur: _ctx.unsetFocus,
placeholder: _ctx.placeholder,
min: _ctx.question.min,
max: _ctx.question.max,
onChange: _ctx.onChange
}, null, 8 /* PROPS */, ["mask", "type", "value", "required", "onKeydown", "onKeyup", "onFocus", "onBlur", "placeholder", "min", "max", "onChange"]))
: (vue.openBlock(), vue.createElementBlock("input", {
key: 1,
ref: "input",
type: $data.inputType,
value: _ctx.modelValue,
required: _ctx.question.required,
onKeydown: _cache[0] || (_cache[0] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onKeyDown && _ctx.onKeyDown.apply(_ctx, args));
}),
onKeyup: [
_cache[1] || (_cache[1] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onChange && _ctx.onChange.apply(_ctx, args));
}),
_cache[2] || (_cache[2] = vue.withKeys(vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onEnter && _ctx.onEnter.apply(_ctx, args));
}, ["prevent"]), ["enter"])),
_cache[3] || (_cache[3] = vue.withKeys(vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onEnter && _ctx.onEnter.apply(_ctx, args));
}, ["prevent"]), ["tab"]))
],
onFocus: _cache[4] || (_cache[4] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.setFocus && _ctx.setFocus.apply(_ctx, args));
}),
onBlur: _cache[5] || (_cache[5] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.unsetFocus && _ctx.unsetFocus.apply(_ctx, args));
}),
min: _ctx.question.min,
max: _ctx.question.max,
onChange: _cache[6] || (_cache[6] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onChange && _ctx.onChange.apply(_ctx, args));
}),
placeholder: _ctx.placeholder,
maxlength: _ctx.question.maxLength
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_2$5))
], 8 /* PROPS */, _hoisted_1$6))
}
script$g.render = render$8;
script$g.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/TextType.vue";
var script$f = {
extends: script$g,
name: QuestionType.Email,
data: function data() {
return {
inputType: 'email'
}
},
methods: {
validate: function validate() {
if (this.hasValue) {
return /^[^@]+@.+[^.]$/.test(this.dataValue)
}
return !this.question.required
}
}
};
script$f.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/EmailType.vue";
var script$e = {
name: 'TextareaAutosize',
props: {
value: {
type: [String, Number],
default: ''
},
autosize: {
type: Boolean,
default: true
},
minHeight: {
type: [Number],
'default': null
},
maxHeight: {
type: [Number],
'default': null
},
/*
* Force !important for style properties
*/
important: {
type: [Boolean, Array],
default: false
}
},
data: function data () {
return {
// data property for v-model binding with real textarea tag
val: null,
// works when content height becomes more then value of the maxHeight property
maxHeightScroll: false,
height: 'auto'
}
},
computed: {
computedStyles: function computedStyles () {
if (!this.autosize) { return {} }
return {
resize: !this.isResizeImportant ? 'none' : 'none !important',
height: this.height,
overflow: this.maxHeightScroll ? 'auto' : (!this.isOverflowImportant ? 'hidden' : 'hidden !important')
}
},
isResizeImportant: function isResizeImportant () {
var imp = this.important;
return imp === true || (Array.isArray(imp) && imp.includes('resize'))
},
isOverflowImportant: function isOverflowImportant () {
var imp = this.important;
return imp === true || (Array.isArray(imp) && imp.includes('overflow'))
},
isHeightImportant: function isHeightImportant () {
var imp = this.important;
return imp === true || (Array.isArray(imp) && imp.includes('height'))
}
},
watch: {
value: function value (val) {
this.val = val;
},
val: function val (val$1) {
this.$nextTick(this.resize);
this.$emit('input', val$1);
},
minHeight: function minHeight () {
this.$nextTick(this.resize);
},
maxHeight: function maxHeight () {
this.$nextTick(this.resize);
},
autosize: function autosize (val) {
if (val) { this.resize(); }
}
},
methods: {
resize: function resize () {
var this$1$1 = this;
var important = this.isHeightImportant ? 'important' : '';
this.height = "auto" + (important ? ' !important' : '');
this.$nextTick(function () {
var contentHeight = this$1$1.$el.scrollHeight + 1;
if (this$1$1.minHeight) {
contentHeight = contentHeight < this$1$1.minHeight ? this$1$1.minHeight : contentHeight;
}
if (this$1$1.maxHeight) {
if (contentHeight > this$1$1.maxHeight) {
contentHeight = this$1$1.maxHeight;
this$1$1.maxHeightScroll = true;
} else {
this$1$1.maxHeightScroll = false;
}
}
var heightVal = contentHeight + 'px';
this$1$1.height = "" + heightVal + (important ? ' !important' : '');
});
return this
}
},
created: function created () {
this.val = this.value;
},
mounted: function mounted () {
this.resize();
}
};
function render$7(_ctx, _cache, $props, $setup, $data, $options) {
return vue.withDirectives((vue.openBlock(), vue.createElementBlock("textarea", {
style: vue.normalizeStyle($options.computedStyles),
"onUpdate:modelValue": _cache[0] || (_cache[0] = function ($event) { return (($data.val) = $event); }),
onFocus: _cache[1] || (_cache[1] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.resize && $options.resize.apply($options, args));
})
}, null, 36 /* STYLE, HYDRATE_EVENTS */)), [
[vue.vModelText, $data.val]
])
}
script$e.render = render$7;
script$e.__file = "//HAL9000/work/_open source/_vff/_git - phre/node_modules/vue-textarea-autosize/src/components/TextareaAutosize.vue";
var script$d = {
extends: script$j,
name: QuestionType.LongText,
components: {
TextareaAutosize: script$e
},
data: function data () {
return {
canReceiveFocus: true
}
},
mounted: function mounted() {
window.addEventListener('resize', this.onResizeListener);
},
beforeUnmount: function beforeUnmount() {
window.removeEventListener('resize', this.onResizeListener);
},
methods: {
onResizeListener: function onResizeListener() {
this.$refs.input.resize();
},
unsetFocus: function unsetFocus($event) {
if ($event || !this.isMobile) {
this.focused = false;
}
},
onEnterDown: function onEnterDown($event) {
if (!this.isMobile) {
$event.preventDefault();
}
},
onEnter: function onEnter() {
this._onEnter();
if (this.isMobile) {
this.focus();
}
}
}
};
function render$6(_ctx, _cache, $props, $setup, $data, $options) {
var _component_textarea_autosize = vue.resolveComponent("textarea-autosize");
return (vue.openBlock(), vue.createElementBlock("span", null, [
vue.createVNode(_component_textarea_autosize, {
ref: "input",
rows: "1",
value: _ctx.modelValue,
required: _ctx.question.required,
onKeydown: [
_ctx.onKeyDown,
vue.withKeys(vue.withModifiers($options.onEnterDown, ["exact"]), ["enter"])
],
onKeyup: [
_ctx.onChange,
vue.withKeys(vue.withModifiers($options.onEnter, ["exact","prevent"]), ["enter"]),
vue.withKeys(vue.withModifiers($options.onEnter, ["prevent"]), ["tab"])
],
onFocus: _ctx.setFocus,
onBlur: $options.unsetFocus,
placeholder: _ctx.placeholder,
maxlength: _ctx.question.maxLength
}, null, 8 /* PROPS */, ["value", "required", "onKeydown", "onKeyup", "onFocus", "onBlur", "placeholder", "maxlength"])
]))
}
script$d.render = render$6;
script$d.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/LongTextType.vue";
var script$c = {
extends: script$j,
name: QuestionType.MultipleChoice,
data: function data() {
return {
editingOther: false,
hasImages: false
}
},
mounted: function mounted() {
this.addKeyListener();
},
beforeUnmount: function beforeUnmount() {
this.removeKeyListener();
},
watch: {
active: function active(value) {
if (value) {
this.addKeyListener();
if (this.question.multiple && this.question.answered) {
this.enterPressed = false;
}
} else {
this.removeKeyListener();
}
}
},
methods: {
addKeyListener: function addKeyListener() {
this.removeKeyListener();
document.addEventListener('keyup', this.onKeyListener);
},
removeKeyListener: function removeKeyListener() {
document.removeEventListener('keyup', this.onKeyListener);
},
/**
* Listens for keyboard events (A, B, C, ...)
*/
onKeyListener: function onKeyListener($event) {
if (this.active && !this.editingOther && $event.key && $event.key.length === 1) {
var keyCode = $event.key.toUpperCase().charCodeAt(0);
if (keyCode >= 65 && keyCode <= 90) {
var index = keyCode - 65;
if (index > -1) {
var option = this.question.options[index];
if (option) {
this.toggleAnswer(option);
} else if (this.question.allowOther && index === this.question.options.length) {
this.startEditOther();
}
}
}
}
},
getLabel: function getLabel(index) {
return this.language.ariaMultipleChoice.replace(':letter', this.getToggleKey(index))
},
getToggleKey: function getToggleKey(index) {
var key = 65 + index;
if (key <= 90) {
return String.fromCharCode(key)
}
return ''
},
toggleAnswer: function toggleAnswer(option) {
if (!this.question.multiple) {
if (this.question.allowOther) {
this.question.other = this.dataValue = null;
this.setAnswer(this.dataValue);
}
for (var i = 0; i < this.question.options.length; i++) {
var o = this.question.options[i];
if (o.selected) {
this._toggleAnswer(o);
}
}
}
this._toggleAnswer(option);
},
_toggleAnswer: function _toggleAnswer(option) {
var optionValue = option.choiceValue();
option.toggle();
if (this.question.multiple) {
this.enterPressed = false;
if (!option.selected) {
this._removeAnswer(optionValue);
} else if (this.dataValue.indexOf(optionValue) === -1) {
this.dataValue.push(optionValue);
}
} else {
this.dataValue = option.selected ? optionValue : null;
}
if (this.isValid() && this.question.nextStepOnAnswer && !this.question.multiple && !this.disabled) {
this.$emit('next');
}
this.setAnswer(this.dataValue);
},
_removeAnswer: function _removeAnswer(value) {
var index = this.dataValue.indexOf(value);
if (index !== -1) {
this.dataValue.splice(index, 1);
}
},
startEditOther: function startEditOther() {
var this$1$1 = this;
this.editingOther = true;
this.enterPressed = false;
this.$nextTick(function () {
this$1$1.$refs.otherInput.focus();
});
},
onChangeOther: function onChangeOther() {
if (this.editingOther) {
var
value = [],
self = this;
this.question.options.forEach(function(option) {
if (option.selected) {
if (self.question.multiple) {
value.push(option.choiceValue());
} else {
option.toggle();
}
}
});
if (this.question.other && this.question.multiple) {
value.push(this.question.other);
} else if (!this.question.multiple) {
value = this.question.other;
}
this.dataValue = value;
this.setAnswer(this.dataValue);
}
},
stopEditOther: function stopEditOther() {
this.editingOther = false;
}
},
computed: {
hasValue: function hasValue() {
if (this.question.options.filter(function (o) { return o.selected; }).length) {
return true
}
if (this.question.allowOther) {
return this.question.other && this.question.other.trim().length > 0
}
return false
}
}
};
var _hoisted_1$5 = { class: "f-radios-wrap" };
var _hoisted_2$4 = ["onClick", "aria-label"];
var _hoisted_3$3 = {
key: 0,
class: "f-image"
};
var _hoisted_4$3 = ["src", "alt"];
var _hoisted_5$3 = { class: "f-label-wrap" };
var _hoisted_6$3 = { class: "f-key" };
var _hoisted_7$3 = {
key: 0,
class: "f-label"
};
var _hoisted_8$3 = ["aria-label"];
var _hoisted_9$3 = { class: "f-label-wrap" };
var _hoisted_10$3 = {
key: 0,
class: "f-key"
};
var _hoisted_11$3 = {
key: 2,
class: "f-selected"
};
var _hoisted_12$3 = { class: "f-label" };
var _hoisted_13$3 = {
key: 3,
class: "f-label"
};
function render$5(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createElementBlock("div", _hoisted_1$5, [
vue.createElementVNode("ul", {
class: vue.normalizeClass(["f-radios", {'f-multiple': _ctx.question.multiple}]),
role: "listbox"
}, [
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.question.options, function (option, index) {
return (vue.openBlock(), vue.createElementBlock("li", {
onClick: vue.withModifiers(function ($event) { return ($options.toggleAnswer(option)); }, ["prevent"]),
class: vue.normalizeClass({'f-selected': option.selected}),
key: 'm' + index,
"aria-label": $options.getLabel(index),
role: "option"
}, [
($data.hasImages && option.imageSrc)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_3$3, [
vue.createElementVNode("img", {
src: option.imageSrc,
alt: option.imageAlt
}, null, 8 /* PROPS */, _hoisted_4$3)
]))
: vue.createCommentVNode("v-if", true),
vue.createElementVNode("div", _hoisted_5$3, [
vue.createElementVNode("span", _hoisted_6$3, vue.toDisplayString($options.getToggleKey(index)), 1 /* TEXT */),
(option.choiceLabel())
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_7$3, vue.toDisplayString(option.choiceLabel()), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true)
])
], 10 /* CLASS, PROPS */, _hoisted_2$4))
}), 128 /* KEYED_FRAGMENT */)),
(!$data.hasImages && _ctx.question.allowOther)
? (vue.openBlock(), vue.createElementBlock("li", {
key: 0,
class: vue.normalizeClass(["f-other", {'f-selected': _ctx.question.other, 'f-focus': $data.editingOther}]),
onClick: _cache[5] || (_cache[5] = vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.startEditOther && $options.startEditOther.apply($options, args));
}, ["prevent"])),
"aria-label": _ctx.language.ariaTypeAnswer,
role: "option"
}, [
vue.createElementVNode("div", _hoisted_9$3, [
(!$data.editingOther)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_10$3, vue.toDisplayString($options.getToggleKey(_ctx.question.options.length)), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true),
($data.editingOther)
? vue.withDirectives((vue.openBlock(), vue.createElementBlock("input", {
key: 1,
"onUpdate:modelValue": _cache[0] || (_cache[0] = function ($event) { return ((_ctx.question.other) = $event); }),
type: "text",
ref: "otherInput",
onBlur: _cache[1] || (_cache[1] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.stopEditOther && $options.stopEditOther.apply($options, args));
}),
onKeyup: [
_cache[2] || (_cache[2] = vue.withKeys(vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.stopEditOther && $options.stopEditOther.apply($options, args));
}, ["prevent"]), ["enter"])),
_cache[3] || (_cache[3] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onChangeOther && $options.onChangeOther.apply($options, args));
})
],
onChange: _cache[4] || (_cache[4] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onChangeOther && $options.onChangeOther.apply($options, args));
}),
maxlength: "256"
}, null, 544 /* HYDRATE_EVENTS, NEED_PATCH */)), [
[vue.vModelText, _ctx.question.other]
])
: (_ctx.question.other)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_11$3, [
vue.createElementVNode("span", _hoisted_12$3, vue.toDisplayString(_ctx.question.other), 1 /* TEXT */)
]))
: (vue.openBlock(), vue.createElementBlock("span", _hoisted_13$3, vue.toDisplayString(_ctx.language.otherPrompt), 1 /* TEXT */))
])
], 10 /* CLASS, PROPS */, _hoisted_8$3))
: vue.createCommentVNode("v-if", true)
], 2 /* CLASS */)
]))
}
script$c.render = render$5;
script$c.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/MultipleChoiceType.vue";
var script$b = {
extends: script$c,
name: QuestionType.MultiplePictureChoice,
data: function data() {
return {
hasImages: true
}
}
};
script$b.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/MultiplePictureChoiceType.vue";
var script$a = {
extends: script$g,
name: QuestionType.Number,
data: function data() {
return {
inputType: 'tel',
allowedChars: '-0123456789.'
}
},
methods: {
validate: function validate() {
if (this.question.min !== null && !isNaN(this.question.min) && +this.dataValue < +this.question.min) {
return false
}
if (this.question.max !== null && !isNaN(this.question.max) && +this.dataValue > +this.question.max) {
return false
}
if (this.hasValue) {
if (this.question.mask) {
return this.validateMask()
}
return !isNaN(+this.dataValue)
}
return !this.question.required || this.hasValue
}
}
};
script$a.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/NumberType.vue";
var script$9 = {
extends: script$g,
name: QuestionType.Password,
data: function data() {
return {
inputType: 'password'
}
}
};
script$9.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/PasswordType.vue";
var script$8 = {
extends: script$g,
name: QuestionType.Phone,
data: function data() {
return {
inputType: 'tel',
canReceiveFocus: true
}
}
};
script$8.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/PhoneType.vue";
var script$7 = {
extends: script$j,
name: QuestionType.SectionBreak,
methods: {
onEnter: function onEnter() {
this.dirty = true;
this._onEnter();
},
isValid: function isValid() {
return true
}
}
};
var _hoisted_1$4 = {
key: 0,
class: "f-content"
};
var _hoisted_2$3 = { class: "f-section-text" };
function render$4(_ctx, _cache, $props, $setup, $data, $options) {
return (_ctx.question.content)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_1$4, [
vue.createElementVNode("span", _hoisted_2$3, vue.toDisplayString(_ctx.question.content), 1 /* TEXT */)
]))
: vue.createCommentVNode("v-if", true)
}
script$7.render = render$4;
script$7.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/SectionBreakType.vue";
var script$6 = {
extends: script$g,
name: QuestionType.Url,
data: function data() {
return {
inputType: 'url'
}
},
methods: {
fixAnswer: function fixAnswer(answer) {
if (answer && answer.indexOf('://') === -1) {
// Insert https protocol to make it easier to enter
// correct URLs
answer = 'https://' + answer;
}
return answer
},
validate: function validate() {
if (this.hasValue) {
try {
new URL(this.fixAnswer(this.dataValue));
return true
} catch(_) {
// Invalid URL
return false
}
}
return !this.question.required
}
}
};
script$6.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/UrlType.vue";
var script$5 = {
extends: script$g,
name: QuestionType.Date,
data: function data() {
return {
inputType: 'date'
}
},
methods: {
validate: function validate() {
if (this.question.min && this.dataValue < this.question.min) {
return false
}
if (this.question.max && this.dataValue > this.question.max) {
return false
}
return !this.question.required || this.hasValue
}
}
};
script$5.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/DateType.vue";
var script$4 = {
extends: script$g,
name: QuestionType.File,
mounted: function mounted() {
if (this.question.accept) {
this.mimeTypeRegex = new RegExp(this.question.accept.replace('*', '[^\\/,]+'));
}
},
methods: {
setAnswer: function setAnswer(answer) {
this.question.setAnswer(this.files);
this.answer = answer;
this.question.answered = this.isValid();
this.$emit('update:modelValue', answer);
},
showInvalid: function showInvalid() {
return this.errorMessage !== null
},
validate: function validate() {
var this$1$1 = this;
this.errorMessage = null;
if (this.question.required && !this.hasValue) {
return false
}
if (this.question.accept) {
if (!Array.from(this.files).every(function (file) { return this$1$1.mimeTypeRegex.test(file.type); })) {
this.errorMessage = this.language.formatString(this.language.errorAllowedFileTypes, {
fileTypes: this.question.accept
});
return false
}
}
if (this.question.multiple) {
var fileCount = this.files.length;
if (this.question.min !== null && fileCount < +this.question.min) {
this.errorMessage = this.language.formatString(this.language.errorMinFiles, {
min: this.question.min
});
return false
}
if (this.question.max !== null && fileCount > +this.question.max) {
this.errorMessage = this.language.formatString(this.language.errorMaxFiles, {
max: this.question.max
});
return false
}
}
if (this.question.maxSize !== null) {
var fileSize =
Array.from(this.files).reduce(function (current, file) { return current + file.size; }, 0);
if (fileSize > +this.question.maxSize) {
this.errorMessage = this.language.formatString(this.language.errorMaxFileSize, {
size: this.language.formatFileSize(this.question.maxSize)
});
return false
}
}
return this.$refs.input.checkValidity()
}
},
computed: {
files: function files() {
return this.$refs.input.files
}
}
};
var _hoisted_1$3 = ["accept", "multiple", "value", "required"];
function render$3(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createElementBlock("input", {
ref: "input",
type: "file",
accept: _ctx.question.accept,
multiple: _ctx.question.multiple,
value: _ctx.modelValue,
required: _ctx.question.required,
onKeyup: [
_cache[0] || (_cache[0] = vue.withKeys(vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onEnter && _ctx.onEnter.apply(_ctx, args));
}, ["prevent"]), ["enter"])),
_cache[1] || (_cache[1] = vue.withKeys(vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onEnter && _ctx.onEnter.apply(_ctx, args));
}, ["prevent"]), ["tab"]))
],
onFocus: _cache[2] || (_cache[2] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.setFocus && _ctx.setFocus.apply(_ctx, args));
}),
onBlur: _cache[3] || (_cache[3] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.unsetFocus && _ctx.unsetFocus.apply(_ctx, args));
}),
onChange: _cache[4] || (_cache[4] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return (_ctx.onChange && _ctx.onChange.apply(_ctx, args));
})
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_1$3))
}
script$4.render = render$3;
script$4.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/FileType.vue";
var script$3 = {
extends: script$j,
name: QuestionType.Matrix,
data: function data() {
return {
selected: {},
inputList: []
}
},
beforeMount: function beforeMount() {
// Pre-fill the form if there is a predefined answer
if (this.question.multiple) {
for (var i = 0, list = this.question.rows; i < list.length; i += 1) {
var row = list[i];
this.selected[row.id] = this.question.answer && this.question.answer[row.id] ? [].concat( this.question.answer[row.id] ) : [];
}
} else if (this.question.answer) {
this.selected = Object.assign({}, this.question.answer);
}
},
beforeUpdate: function beforeUpdate() {
this.inputList = [];
},
methods: {
onChange: function onChange($event) {
this.dirty = true;
this.dataValue = this.selected;
this.onKeyDown();
this.setAnswer(this.dataValue);
},
validate: function validate() {
if (!this.question.required) {
return true
}
var checked = function (inputs) { return inputs.some(function (input) { return input.checked; }); };
if (!Object.values(this.inputGroups).every(function (value) { return checked(value); })) {
return false
}
return true
},
getElement: function getElement() {
return this.inputList[0]
},
},
computed: {
inputGroups: function inputGroups() {
var inputGroups = {};
// Setting input list for validation
for (var i = 0, list = this.question.rows; i < list.length; i += 1) {
var row = list[i];
inputGroups[row.id] = [];
}
this.inputList.forEach(function (input) {
inputGroups[input.dataset.id].push(input);
});
return inputGroups
}
}
};
var _hoisted_1$2 = { class: "f-matrix-wrap" };
var _hoisted_2$2 = /*#__PURE__*/vue.createElementVNode("td", null, null, -1 /* HOISTED */);
var _hoisted_3$2 = { class: "f-table-string" };
var _hoisted_4$2 = { class: "f-table-cell f-row-cell" };
var _hoisted_5$2 = { class: "f-table-string" };
var _hoisted_6$2 = ["title"];
var _hoisted_7$2 = {
key: 0,
class: "f-field-wrap"
};
var _hoisted_8$2 = { class: "f-matrix-field f-matrix-radio" };
var _hoisted_9$2 = ["name", "id", "aria-label", "data-id", "value", "onUpdate:modelValue"];
var _hoisted_10$2 = /*#__PURE__*/vue.createElementVNode("span", { class: "f-field-mask f-radio-mask" }, [
/*#__PURE__*/vue.createElementVNode("svg", {
viewBox: "0 0 24 24",
class: "f-field-svg f-radio-svg"
}, [
/*#__PURE__*/vue.createElementVNode("circle", {
r: "6",
cx: "12",
cy: "12"
})
])
], -1 /* HOISTED */);
var _hoisted_11$2 = {
key: 1,
class: "f-field-wrap"
};
var _hoisted_12$2 = { class: "f-matrix-field f-matrix-checkbox" };
var _hoisted_13$2 = ["id", "aria-label", "data-id", "value", "onUpdate:modelValue"];
var _hoisted_14$2 = /*#__PURE__*/vue.createElementVNode("span", { class: "f-field-mask f-checkbox-mask" }, [
/*#__PURE__*/vue.createElementVNode("svg", {
viewBox: "0 0 24 24",
class: "f-field-svg f-checkbox-svg"
}, [
/*#__PURE__*/vue.createElementVNode("rect", {
width: "12",
height: "12",
x: "6",
y: "6"
})
])
], -1 /* HOISTED */);
function render$2(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createElementBlock("div", _hoisted_1$2, [
vue.createElementVNode("table", {
class: vue.normalizeClass(["f-matrix-table", { 'f-matrix-multiple': _ctx.question.multiple }])
}, [
vue.createElementVNode("thead", null, [
vue.createElementVNode("tr", null, [
_hoisted_2$2,
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.question.columns, function (column, index) {
return (vue.openBlock(), vue.createElementBlock("th", {
key: 'c' + index,
class: "f-table-cell f-column-cell"
}, [
vue.createElementVNode("span", _hoisted_3$2, vue.toDisplayString(column.label), 1 /* TEXT */)
]))
}), 128 /* KEYED_FRAGMENT */))
])
]),
vue.createElementVNode("tbody", null, [
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.question.rows, function (row, index) {
return (vue.openBlock(), vue.createElementBlock("tr", {
key: 'r' + index,
class: "f-table-row"
}, [
vue.createElementVNode("td", _hoisted_4$2, [
vue.createElementVNode("span", _hoisted_5$2, vue.toDisplayString(row.label), 1 /* TEXT */)
]),
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList(_ctx.question.columns, function (column, index) {
return (vue.openBlock(), vue.createElementBlock("td", {
key: 'l' + index,
title: column.label,
class: "f-table-cell f-matrix-cell"
}, [
(!_ctx.question.multiple)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_7$2, [
vue.createElementVNode("label", _hoisted_8$2, [
vue.withDirectives(vue.createElementVNode("input", {
type: "radio",
ref: function (el) { return $data.inputList.push(el); },
name: row.id,
id: 'c' + index + '-' + row.id,
"aria-label": row.label,
"data-id": row.id,
value: column.value,
"onUpdate:modelValue": function ($event) { return (($data.selected[row.id]) = $event); },
class: "f-field-control f-radio-control",
onChange: _cache[0] || (_cache[0] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onChange && $options.onChange.apply($options, args));
})
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_9$2), [
[vue.vModelRadio, $data.selected[row.id]]
]),
_hoisted_10$2
])
]))
: (vue.openBlock(), vue.createElementBlock("div", _hoisted_11$2, [
vue.createElementVNode("label", _hoisted_12$2, [
vue.withDirectives(vue.createElementVNode("input", {
type: "checkbox",
ref: function (el) { return $data.inputList.push(el); },
id: 'c' + index + '-' + row.id,
"aria-label": row.label,
"data-id": row.id,
value: column.value,
class: "f-field-control f-checkbox-control",
"onUpdate:modelValue": function ($event) { return (($data.selected[row.id]) = $event); },
onChange: _cache[1] || (_cache[1] = function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onChange && $options.onChange.apply($options, args));
})
}, null, 40 /* PROPS, HYDRATE_EVENTS */, _hoisted_13$2), [
[vue.vModelCheckbox, $data.selected[row.id]]
]),
_hoisted_14$2
])
]))
], 8 /* PROPS */, _hoisted_6$2))
}), 128 /* KEYED_FRAGMENT */))
]))
}), 128 /* KEYED_FRAGMENT */))
])
], 2 /* CLASS */)
]))
}
script$3.render = render$2;
script$3.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/QuestionTypes/MatrixType.vue";
var script$2 = {
name: 'FlowFormQuestion',
components: {
FlowFormDateType: script$5,
FlowFormDropdownType: script$i,
FlowFormEmailType: script$f,
FlowFormLongTextType: script$d,
FlowFormMultipleChoiceType: script$c,
FlowFormMultiplePictureChoiceType: script$b,
FlowFormNumberType: script$a,
FlowFormPasswordType: script$9,
FlowFormPhoneType: script$8,
FlowFormSectionBreakType: script$7,
FlowFormTextType: script$g,
FlowFormFileType: script$4,
FlowFormUrlType: script$6,
FlowFormMatrixType: script$3
},
props: {
question: QuestionModel,
language: LanguageModel,
value: [String, Array, Boolean, Number, Object],
active: {
type: Boolean,
default: false
},
reverse: {
type: Boolean,
default: false
},
disabled: {
type: Boolean,
default: false
},
autofocus: {
type: Boolean,
default: true
}
},
mixins: [
IsMobile
],
data: function data() {
return {
QuestionType: QuestionType,
dataValue: null,
debounced: false
}
},
mounted: function mounted() {
this.autofocus && this.focusField();
this.dataValue = this.question.answer;
this.$refs.qanimate.addEventListener('animationend', this.onAnimationEnd);
},
beforeUnmount: function beforeUnmount() {
this.$refs.qanimate.removeEventListener('animationend', this.onAnimationEnd);
},
methods: {
/**
* Autofocus the input box of the current question
*/
focusField: function focusField() {
var el = this.$refs.questionComponent;
el && el.focus();
},
onAnimationEnd: function onAnimationEnd() {
this.autofocus && this.focusField();
},
shouldFocus: function shouldFocus() {
var q = this.$refs.questionComponent;
return q && q.canReceiveFocus && !q.focused
},
returnFocus: function returnFocus() {
this.$refs.questionComponent;
if (this.shouldFocus()) {
this.focusField();
}
},
/**
* Emits "answer" event and calls "onEnter" method on Enter press
*/
onEnter: function onEnter($event) {
this.checkAnswer(this.emitAnswer);
},
onTab: function onTab($event) {
this.checkAnswer(this.emitAnswerTab);
},
checkAnswer: function checkAnswer(fn) {
var this$1$1 = this;
var q = this.$refs.questionComponent;
if (q.isValid() && this.question.isMultipleChoiceType() && this.question.nextStepOnAnswer && !this.question.multiple) {
this.$emit('disable', true);
this.debounce(function () {
fn(q);
this$1$1.$emit('disable', false);
}, 350);
} else {
fn(q);
}
},
emitAnswer: function emitAnswer(q) {
if (q) {
if (!q.focused) {
this.$emit('answer', q);
}
q.onEnter();
}
},
emitAnswerTab: function emitAnswerTab(q) {
if (q && this.question.type !== QuestionType.Date) {
this.returnFocus();
this.$emit('answer', q);
q.onEnter();
}
},
debounce: function debounce(fn, delay) {
var debounceTimer;
this.debounced = true;
return (function () {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(fn, delay);
})()
},
/**
* Check if the "OK" button should be shown.
*/
showOkButton: function showOkButton() {
var q = this.$refs.questionComponent;
if (this.question.type === QuestionType.SectionBreak) {
return this.active
}
if (!this.question.required) {
return true
}
if (this.question.allowOther && this.question.other) {
return true
}
if (this.question.isMultipleChoiceType() && !this.question.multiple && this.question.nextStepOnAnswer) {
return false
}
// If there is no question referenced, or dataValue is still set to its default (null).
// This allows a ChoiceOption value of false, but will not allow you to use null as a value.
if (!q || this.dataValue === null) {
return false
}
return q.hasValue && q.isValid()
},
showSkip: function showSkip() {
var q = this.$refs.questionComponent;
// We might not have a reference to the question component at first
// but we know that if we don't, it's definitely empty
return !this.question.required && (!q || !q.hasValue)
},
/**
* Determins if the invalid message should be shown.
*/
showInvalid: function showInvalid() {
var q = this.$refs.questionComponent;
if (!q || this.dataValue === null) {
return false
}
return q.showInvalid()
}
},
computed: {
mainClasses: {
cache: false,
get: function get() {
var classes = {
'q-is-active': this.active,
'q-is-inactive': !this.active,
'f-fade-in-down': this.reverse,
'f-fade-in-up': !this.reverse,
'f-focused': this.$refs.questionComponent && this.$refs.questionComponent.focused,
'f-has-value': this.$refs.questionComponent && this.$refs.questionComponent.hasValue
};
classes['field-' + this.question.type.toLowerCase().substring(8, this.question.type.length - 4)] = true;
return classes
}
},
showHelperText: function showHelperText() {
if (this.question.subtitle) {
return true
}
if (this.question.type === QuestionType.LongText || this.question.type === QuestionType.MultipleChoice) {
return this.question.helpTextShow
}
return false
},
errorMessage: function errorMessage() {
var q = this.$refs.questionComponent;
if (q && q.errorMessage) {
return q.errorMessage
}
return this.language.invalidPrompt
}
}
};
var _hoisted_1$1 = { class: "q-inner" };
var _hoisted_2$1 = {
key: 0,
class: "f-tagline"
};
var _hoisted_3$1 = {
key: 0,
class: "fh2"
};
var _hoisted_4$1 = {
key: 1,
class: "f-text"
};
var _hoisted_5$1 = ["aria-label"];
var _hoisted_6$1 = /*#__PURE__*/vue.createElementVNode("span", { "aria-hidden": "true" }, "*", -1 /* HOISTED */);
var _hoisted_7$1 = [
_hoisted_6$1
];
var _hoisted_8$1 = {
key: 1,
class: "f-answer"
};
var _hoisted_9$1 = {
key: 2,
class: "f-sub"
};
var _hoisted_10$1 = { key: 0 };
var _hoisted_11$1 = ["innerHTML"];
var _hoisted_12$1 = {
key: 2,
class: "f-help"
};
var _hoisted_13$1 = {
key: 3,
class: "f-help"
};
var _hoisted_14$1 = {
key: 3,
class: "f-answer f-full-width"
};
var _hoisted_15$1 = {
key: 0,
class: "f-description"
};
var _hoisted_16$1 = { key: 0 };
var _hoisted_17$1 = ["href", "target"];
var _hoisted_18$1 = {
key: 0,
class: "vff-animate f-fade-in f-enter"
};
var _hoisted_19$1 = ["aria-label"];
var _hoisted_20 = { key: 0 };
var _hoisted_21 = { key: 1 };
var _hoisted_22 = { key: 2 };
var _hoisted_23 = ["innerHTML"];
var _hoisted_24 = {
key: 1,
class: "f-invalid",
role: "alert",
"aria-live": "assertive"
};
function render$1(_ctx, _cache, $props, $setup, $data, $options) {
return (vue.openBlock(), vue.createElementBlock("div", {
class: vue.normalizeClass(["vff-animate q-form", $options.mainClasses]),
ref: "qanimate"
}, [
vue.createElementVNode("div", _hoisted_1$1, [
vue.createElementVNode("div", {
class: vue.normalizeClass({'f-section-wrap': $props.question.type === $data.QuestionType.SectionBreak})
}, [
vue.createElementVNode("div", {
class: vue.normalizeClass({'fh2': $props.question.type !== $data.QuestionType.SectionBreak})
}, [
($props.question.tagline)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_2$1, vue.toDisplayString($props.question.tagline), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true),
($props.question.title)
? (vue.openBlock(), vue.createElementBlock(vue.Fragment, { key: 1 }, [
($props.question.type === $data.QuestionType.SectionBreak)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_3$1, vue.toDisplayString($props.question.title), 1 /* TEXT */))
: (vue.openBlock(), vue.createElementBlock("span", _hoisted_4$1, [
vue.createTextVNode(vue.toDisplayString($props.question.title) + " ", 1 /* TEXT */),
vue.createCommentVNode(" Required questions are marked by an asterisk (*) "),
($props.question.required)
? (vue.openBlock(), vue.createElementBlock("span", {
key: 0,
class: "f-required",
"aria-label": $props.language.ariaRequired,
role: "note"
}, _hoisted_7$1, 8 /* PROPS */, _hoisted_5$1))
: vue.createCommentVNode("v-if", true),
($props.question.inline)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_8$1, [
(vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent($props.question.type), {
ref: "questionComponent",
question: $props.question,
language: $props.language,
modelValue: $data.dataValue,
"onUpdate:modelValue": _cache[0] || (_cache[0] = function ($event) { return (($data.dataValue) = $event); }),
active: $props.active,
disabled: $props.disabled,
onNext: $options.onEnter
}, null, 8 /* PROPS */, ["question", "language", "modelValue", "active", "disabled", "onNext"]))
]))
: vue.createCommentVNode("v-if", true)
]))
], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */))
: vue.createCommentVNode("v-if", true),
($options.showHelperText)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_9$1, [
($props.question.subtitle)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_10$1, vue.toDisplayString($props.question.subtitle), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true),
($props.question.type === $data.QuestionType.LongText && !_ctx.isMobile)
? (vue.openBlock(), vue.createElementBlock("span", {
key: 1,
class: "f-help",
innerHTML: $props.question.helpText || $props.language.formatString($props.language.longTextHelpText)
}, null, 8 /* PROPS */, _hoisted_11$1))
: vue.createCommentVNode("v-if", true),
($props.question.type === $data.QuestionType.MultipleChoice && $props.question.multiple)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_12$1, vue.toDisplayString($props.question.helpText || $props.language.multipleChoiceHelpText), 1 /* TEXT */))
: ($props.question.type === $data.QuestionType.MultipleChoice)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_13$1, vue.toDisplayString($props.question.helpText || $props.language.multipleChoiceHelpTextSingle), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true)
]))
: vue.createCommentVNode("v-if", true),
(!$props.question.inline)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_14$1, [
(vue.openBlock(), vue.createBlock(vue.resolveDynamicComponent($props.question.type), {
ref: "questionComponent",
question: $props.question,
language: $props.language,
modelValue: $data.dataValue,
"onUpdate:modelValue": _cache[1] || (_cache[1] = function ($event) { return (($data.dataValue) = $event); }),
active: $props.active,
disabled: $props.disabled,
onNext: $options.onEnter
}, null, 8 /* PROPS */, ["question", "language", "modelValue", "active", "disabled", "onNext"]))
]))
: vue.createCommentVNode("v-if", true)
], 2 /* CLASS */),
($props.question.description || $props.question.descriptionLink.length !== 0)
? (vue.openBlock(), vue.createElementBlock("p", _hoisted_15$1, [
($props.question.description)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_16$1, vue.toDisplayString($props.question.description), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true),
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList($props.question.descriptionLink, function (link, index) {
return (vue.openBlock(), vue.createElementBlock("a", {
class: "f-link",
key: 'm' + index,
href: link.url,
target: link.target
}, vue.toDisplayString(link.text || link.url), 9 /* TEXT, PROPS */, _hoisted_17$1))
}), 128 /* KEYED_FRAGMENT */))
]))
: vue.createCommentVNode("v-if", true)
], 2 /* CLASS */),
($options.showOkButton())
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_18$1, [
vue.createElementVNode("button", {
class: "o-btn-action",
type: "button",
ref: "button",
href: "#",
onClick: _cache[2] || (_cache[2] = vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onEnter && $options.onEnter.apply($options, args));
}, ["prevent"])),
"aria-label": $props.language.ariaOk
}, [
($props.question.type === $data.QuestionType.SectionBreak)
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_20, vue.toDisplayString($props.language.continue), 1 /* TEXT */))
: ($options.showSkip())
? (vue.openBlock(), vue.createElementBlock("span", _hoisted_21, vue.toDisplayString($props.language.skip), 1 /* TEXT */))
: (vue.openBlock(), vue.createElementBlock("span", _hoisted_22, vue.toDisplayString($props.language.ok), 1 /* TEXT */))
], 8 /* PROPS */, _hoisted_19$1),
($props.question.type !== $data.QuestionType.LongText || !_ctx.isMobile)
? (vue.openBlock(), vue.createElementBlock("a", {
key: 0,
class: "f-enter-desc",
href: "#",
onClick: _cache[3] || (_cache[3] = vue.withModifiers(function () {
var args = [], len = arguments.length;
while ( len-- ) args[ len ] = arguments[ len ];
return ($options.onEnter && $options.onEnter.apply($options, args));
}, ["prevent"])),
innerHTML: $props.language.formatString($props.language.pressEnter)
}, null, 8 /* PROPS */, _hoisted_23))
: vue.createCommentVNode("v-if", true)
]))
: vue.createCommentVNode("v-if", true),
($options.showInvalid())
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_24, vue.toDisplayString($options.errorMessage), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true)
])
], 2 /* CLASS */))
}
script$2.render = render$1;
script$2.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/FlowFormQuestion.vue";
/*
Copyright (c) 2020 - present, DITDOT Ltd. - MIT Licence
https://github.com/ditdot-dev/vue-flow-form
https://www.ditdot.hr/en
*/
var instances = {};
var ComponentInstance = {
methods: {
getInstance: function getInstance(id) {
return instances[id]
},
setInstance: function setInstance() {
instances[this.id] = this;
}
}
};
var script$1 = {
name: 'FlowForm',
components: {
FlowFormQuestion: script$2
},
props: {
questions: {
type: Array,
validator: function (value) { return value.every(function (q) { return q instanceof QuestionModel; }); }
},
language: {
type: LanguageModel,
default: function () { return new LanguageModel(); }
},
progressbar: {
type: Boolean,
default: true
},
standalone: {
type: Boolean,
default: true
},
navigation: {
type: Boolean,
default: true
},
timer: {
type: Boolean,
default: false
},
timerStartStep: [String, Number],
timerStopStep: [String, Number],
autofocus: {
type: Boolean,
default: true
}
},
mixins: [
IsMobile,
ComponentInstance
],
data: function data() {
return {
questionRefs: [],
completed: false,
submitted: false,
activeQuestionIndex: 0,
questionList: [],
questionListActivePath: [],
reverse: false,
timerOn: false,
timerInterval: null,
time: 0,
disabled: false
}
},
mounted: function mounted() {
document.addEventListener('keydown', this.onKeyDownListener);
document.addEventListener('keyup', this.onKeyUpListener, true);
window.addEventListener('beforeunload', this.onBeforeUnload);
this.setQuestions();
this.checkTimer();
},
beforeUnmount: function beforeUnmount() {
document.removeEventListener('keydown', this.onKeyDownListener);
document.removeEventListener('keyup', this.onKeyUpListener, true);
window.removeEventListener('beforeunload', this.onBeforeUnload);
this.stopTimer();
},
beforeUpdate: function beforeUpdate() {
this.questionRefs = [];
},
computed: {
numActiveQuestions: function numActiveQuestions() {
return this.questionListActivePath.length
},
activeQuestion: function activeQuestion() {
return this.questionListActivePath[this.activeQuestionIndex]
},
activeQuestionId: function activeQuestionId() {
var question = this.questionModels[this.activeQuestionIndex];
if (this.isOnLastStep) {
return '_submit'
}
if (question && question.id) {
return question.id
}
return null
},
numCompletedQuestions: function numCompletedQuestions() {
var num = 0;
this.questionListActivePath.forEach(function (question) {
if (question.answered) {
++num;
}
});
return num
},
percentCompleted: function percentCompleted() {
if (!this.numActiveQuestions) {
return 0
}
return Math.floor((this.numCompletedQuestions / this.numActiveQuestions) * 100)
},
isOnLastStep: function isOnLastStep() {
return this.numActiveQuestions > 0 && this.activeQuestionIndex === this.questionListActivePath.length
},
isOnTimerStartStep: function isOnTimerStartStep() {
if (this.activeQuestionId === this.timerStartStep) {
return true
}
if (!this.timerOn && !this.timerStartStep && this.activeQuestionIndex === 0) {
return true
}
return false
},
isOnTimerStopStep: function isOnTimerStopStep() {
if (this.submitted) {
return true
}
if (this.activeQuestionId === this.timerStopStep) {
return true
}
return false
},
questionModels: {
cache: false,
get: function get() {
var this$1$1 = this;
if (this.questions && this.questions.length) {
return this.questions
}
var questions = [];
if (!this.questions) {
var classMap = {
options: ChoiceOption,
descriptionLink: LinkOption
};
var defaultSlot = this.$slots.default();
var children = null;
if (defaultSlot && defaultSlot.length) {
children = defaultSlot[0].children;
if (!children) {
children = defaultSlot;
}
}
if (children) {
children
.filter(function (q) { return q.type && q.type.name.indexOf('Question') !== -1; })
.forEach(function (q) {
var props = q.props;
var componentInstance = this$1$1.getInstance(props.id);
var model = new QuestionModel();
if (componentInstance.question !== null) {
model = componentInstance.question;
}
if (props.modelValue) {
model.answer = props.modelValue;
}
Object.keys(model).forEach(function (key) {
if (props[key] !== undefined) {
if (typeof model[key] === 'boolean') {
model[key] = props[key] !== false;
} else if (key in classMap) {
var
classReference = classMap[key],
options = [];
props[key].forEach(function (option) {
var instance = new classReference();
Object.keys(instance).forEach(function (instanceKey) {
if (option[instanceKey] !== undefined) {
instance[instanceKey] = option[instanceKey];
}
});
options.push(instance);
});
model[key] = options;
} else {
switch(key) {
case 'type':
if (Object.values(QuestionType).indexOf(props[key]) !== -1) {
model[key] = props[key];
} else {
for (var questionTypeKey in QuestionType) {
if (questionTypeKey.toLowerCase() === props[key].toLowerCase()) {
model[key] = QuestionType[questionTypeKey];
break
}
}
}
break
default:
model[key] = props[key];
break
}
}
}
});
componentInstance.question = model;
model.resetOptions();
questions.push(model);
});
}
}
return questions
}
}
},
methods: {
setQuestionRef: function setQuestionRef(el) {
this.questionRefs.push(el);
},
/**
* Returns currently active question component (if any).
*/
activeQuestionComponent: function activeQuestionComponent() {
return this.questionRefs[this.activeQuestionIndex]
},
setQuestions: function setQuestions() {
this.setQuestionListActivePath();
this.setQuestionList();
},
/**
* This method goes through all questions and sets the ones
* that are in the current path (taking note of logic jumps)
*/
setQuestionListActivePath: function setQuestionListActivePath() {
var this$1$1 = this;
var questions = [];
if (!this.questionModels.length) {
return
}
var
index = 0,
serialIndex = 0,
nextId,
activeIndex = this.activeQuestionIndex;
var loop = function () {
var question = this$1$1.questionModels[index];
if (questions.some(function (q) { return q === question; })) {
return 'break'
}
question.setIndex(serialIndex);
question.language = this$1$1.language;
questions.push(question);
if (!question.jump) {
++index;
} else if (question.answered) {
nextId = question.getJumpId();
if (nextId) {
if (nextId === '_submit') {
index = this$1$1.questionModels.length;
} else {
var loop$1 = function ( i ) {
if (this$1$1.questionModels[i].id === nextId) {
if (i < index && questions.some(function (q) { return q === this$1$1.questionModels[i]; })) {
question.answered = false;
activeIndex = i;
++index;
} else {
index = i;
}
return 'break'
}
};
for (var i = 0; i < this$1$1.questionModels.length; i++) {
var returned$1 = loop$1( i );
if ( returned$1 === 'break' ) break;
}
}
} else {
++index;
}
} else {
index = this$1$1.questionModels.length;
}
++serialIndex;
};
do {
var returned = loop();
if ( returned === 'break' ) break;
} while (index < this$1$1.questionModels.length)
this.questionListActivePath = questions;
this.goToQuestion(activeIndex);
},
/**
* Sets the question list array
* (all questions up to, and including, the current one)
*/
setQuestionList: function setQuestionList() {
var questions = [];
for (var index = 0; index < this.questionListActivePath.length; index++) {
var question = this.questionListActivePath[index];
questions.push(question);
if (!question.answered) {
if (this.completed) {
// The "completed" status changed - user probably changed an
// already entered answer.
this.completed = false;
}
break
}
}
this.questionList = questions;
},
/**
* If we have any answered questions, notify user before leaving
* the page.
*/
onBeforeUnload: function onBeforeUnload(event) {
if (this.activeQuestionIndex > 0 && !this.submitted) {
event.preventDefault();
event.returnValue = '';
}
},
/**
* Global key listeners, listen for Enter or Tab key events.
*/
onKeyDownListener: function onKeyDownListener(e) {
if (e.key !== 'Tab' || this.submitted) {
return
}
if (e.shiftKey) {
e.stopPropagation();
e.preventDefault();
if (this.navigation) {
this.goToPreviousQuestion();
}
} else {
var q = this.activeQuestionComponent();
if (q.shouldFocus()) {
e.preventDefault();
q.focusField();
} else {
e.stopPropagation();
this.emitTab();
this.reverse = false;
}
}
},
onKeyUpListener: function onKeyUpListener(e) {
if (e.shiftKey || ['Tab', 'Enter'].indexOf(e.key) === -1 || this.submitted) {
return
}
var q = this.activeQuestionComponent();
if (e.key === 'Tab' && q.shouldFocus()) {
q.focusField();
} else {
if (e.key === 'Enter') {
this.emitEnter();
}
e.stopPropagation();
this.reverse = false;
}
},
emitEnter: function emitEnter() {
if (this.disabled) {
return
}
var q = this.activeQuestionComponent();
if (q) {
// Send enter event to the current question component
q.onEnter();
} else if (this.completed && this.isOnLastStep) {
// We're finished - submit form
this.submit();
}
},
emitTab: function emitTab() {
var q = this.activeQuestionComponent();
if (q) {
// Send tab event to the current question component
q.onTab();
} else {
this.emitEnter();
}
},
submit: function submit() {
this.emitSubmit();
this.submitted = true;
},
emitComplete: function emitComplete() {
this.$emit('complete', this.completed, this.questionList);
},
emitSubmit: function emitSubmit() {
this.$emit('submit', this.questionList);
},
/**
* Checks if we have another question and if we
* can jump to it.
*/
isNextQuestionAvailable: function isNextQuestionAvailable() {
if (this.submitted) {
return false
}
var q = this.activeQuestion;
if (q && !q.required) {
return true
}
if (this.completed && !this.isOnLastStep) {
return true
}
return this.activeQuestionIndex < this.questionList.length - 1
},
/**
* Triggered by the "answer" event in the Question component
*/
onQuestionAnswered: function onQuestionAnswered(question) {
var this$1$1 = this;
if (question.isValid()) {
this.$emit('answer', question.question);
if (this.activeQuestionIndex < this.questionListActivePath.length) {
++this.activeQuestionIndex;
}
this.$nextTick(function () {
this$1$1.reverse = false;
this$1$1.setQuestions();
this$1$1.checkTimer();
// Nested $nextTick so we're 100% sure that setQuestions
// actually updated the question array
this$1$1.$nextTick(function () {
var q = this$1$1.activeQuestionComponent();
if (q) {
this$1$1.autofocus && q.focusField();
this$1$1.activeQuestionIndex = q.question.index;
} else if (this$1$1.isOnLastStep) {
// No more questions left - set "completed" to true
this$1$1.completed = true;
this$1$1.activeQuestionIndex = this$1$1.questionListActivePath.length;
this$1$1.$refs.button && this$1$1.$refs.button.focus();
}
this$1$1.$emit('step', this$1$1.activeQuestionId, this$1$1.activeQuestion);
});
});
} else if (this.completed) {
this.completed = false;
}
},
/**
* Jumps to previous question.
*/
goToPreviousQuestion: function goToPreviousQuestion() {
this.blurFocus();
if (this.activeQuestionIndex > 0 && !this.submitted) {
if (this.isOnTimerStopStep) {
this.startTimer();
}
--this.activeQuestionIndex;
this.reverse = true;
this.checkTimer();
}
},
/**
* Jumps to next question.
*/
goToNextQuestion: function goToNextQuestion() {
this.blurFocus();
if (this.isNextQuestionAvailable()) {
this.emitEnter();
}
this.reverse = false;
},
/**
* Jumps to question with specific index.
*/
goToQuestion: function goToQuestion(index) {
if (isNaN(+index)) {
var questionIndex = this.activeQuestionIndex;
this.questionListActivePath.forEach(function (question, _index) {
if (question.id === index) {
questionIndex = _index;
}
});
index = questionIndex;
}
if (index !== this.activeQuestionIndex) {
this.blurFocus();
if (!this.submitted && index <= this.questionListActivePath.length - 1) {
// Check if we can actually jump to the wanted question.
do {
var previousQuestionsAnswered =
this
.questionListActivePath
.slice(0, index)
.every(function (q) { return q.answered; });
if (previousQuestionsAnswered) {
break
}
--index;
} while (index > 0)
this.reverse = index < this.activeQuestionIndex;
this.activeQuestionIndex = index;
this.checkTimer();
}
}
},
/**
* Removes focus from the currently focused DOM element.
*/
blurFocus: function blurFocus() {
document.activeElement && document.activeElement.blur && document.activeElement.blur();
},
checkTimer: function checkTimer() {
if (this.timer) {
if (this.isOnTimerStartStep) {
this.startTimer();
} else if (this.isOnTimerStopStep) {
this.stopTimer();
}
}
},
startTimer: function startTimer() {
if (this.timer && !this.timerOn) {
this.timerInterval = setInterval(this.incrementTime, 1000);
this.timerOn = true;
}
},
stopTimer: function stopTimer() {
if (this.timerOn) {
clearInterval(this.timerInterval);
}
this.timerOn = false;
},
incrementTime: function incrementTime() {
++this.time;
this.$emit('timer', this.time, this.formatTime(this.time));
},
formatTime: function formatTime(seconds) {
var
startIndex = 14,
length = 5;
if (seconds >= 60 * 60) {
startIndex = 11;
length = 8;
}
return new Date(1000 * seconds).toISOString().substr(startIndex, length)
},
setDisabled: function setDisabled(state) {
this.disabled = state;
},
reset: function reset() {
this.questionModels.forEach(function (question) { return question.resetAnswer(); });
this.goToQuestion(0);
}
},
watch: {
completed: function completed() {
this.emitComplete();
},
submitted: function submitted() {
this.stopTimer();
}
}
};
var _hoisted_1 = { class: "f-container" };
var _hoisted_2 = { class: "f-form-wrap" };
var _hoisted_3 = {
key: 0,
class: "vff-animate f-fade-in-up field-submittype"
};
var _hoisted_4 = { class: "f-section-wrap" };
var _hoisted_5 = { class: "fh2" };
var _hoisted_6 = ["aria-label"];
var _hoisted_7 = ["innerHTML"];
var _hoisted_8 = {
key: 2,
class: "text-success"
};
var _hoisted_9 = { class: "vff-footer" };
var _hoisted_10 = { class: "footer-inner-wrap" };
var _hoisted_11 = { class: "f-progress-bar" };
var _hoisted_12 = {
key: 1,
class: "f-nav"
};
var _hoisted_13 = ["aria-label"];
var _hoisted_14 = /*#__PURE__*/vue.createElementVNode("svg", {
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
x: "0px",
y: "0px",
width: "42.333px",
height: "28.334px",
viewBox: "78.833 5.5 42.333 28.334",
"aria-hidden": "true"
}, [
/*#__PURE__*/vue.createElementVNode("path", { d: "M82.039,31.971L100,11.442l17.959,20.529L120,30.187L101.02,8.492c-0.258-0.295-0.629-0.463-1.02-0.463c-0.39,0-0.764,0.168-1.02,0.463L80,30.187L82.039,31.971z" })
], -1 /* HOISTED */);
var _hoisted_15 = {
class: "f-nav-text",
"aria-hidden": "true"
};
var _hoisted_16 = ["aria-label"];
var _hoisted_17 = /*#__PURE__*/vue.createElementVNode("svg", {
version: "1.1",
xmlns: "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
x: "0px",
y: "0px",
width: "42.333px",
height: "28.334px",
viewBox: "78.833 5.5 42.333 28.334",
"aria-hidden": "true"
}, [
/*#__PURE__*/vue.createElementVNode("path", { d: "M117.963,8.031l-17.961,20.529L82.042,8.031l-2.041,1.784l18.98,21.695c0.258,0.295,0.629,0.463,1.02,0.463c0.39,0,0.764-0.168,1.02-0.463l18.98-21.695L117.963,8.031z" })
], -1 /* HOISTED */);
var _hoisted_18 = {
class: "f-nav-text",
"aria-hidden": "true"
};
var _hoisted_19 = {
key: 2,
class: "f-timer"
};
function render(_ctx, _cache, $props, $setup, $data, $options) {
var _component_flow_form_question = vue.resolveComponent("flow-form-question");
return (vue.openBlock(), vue.createElementBlock("div", {
class: vue.normalizeClass(["vff", {'vff-not-standalone': !$props.standalone, 'vff-is-mobile': _ctx.isMobile, 'vff-is-ios': _ctx.isIos}])
}, [
vue.createElementVNode("div", _hoisted_1, [
vue.createElementVNode("div", _hoisted_2, [
(vue.openBlock(true), vue.createElementBlock(vue.Fragment, null, vue.renderList($data.questionList, function (q, index) {
return (vue.openBlock(), vue.createBlock(_component_flow_form_question, {
ref: $options.setQuestionRef,
question: q,
language: $props.language,
key: 'q' + index,
active: q.index === $data.activeQuestionIndex,
modelValue: q.answer,
"onUpdate:modelValue": function ($event) { return ((q.answer) = $event); },
onAnswer: $options.onQuestionAnswered,
reverse: $data.reverse,
disabled: $data.disabled,
onDisable: $options.setDisabled,
autofocus: $props.autofocus
}, null, 8 /* PROPS */, ["question", "language", "active", "modelValue", "onUpdate:modelValue", "onAnswer", "reverse", "disabled", "onDisable", "autofocus"]))
}), 128 /* KEYED_FRAGMENT */)),
vue.renderSlot(_ctx.$slots, "default"),
vue.createCommentVNode(" Complete/Submit screen slots "),
($options.isOnLastStep)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_3, [
vue.renderSlot(_ctx.$slots, "complete", {}, function () { return [
vue.createCommentVNode(" Default content for the \"complete\" slot "),
vue.createElementVNode("div", _hoisted_4, [
vue.createElementVNode("p", null, [
vue.createElementVNode("span", _hoisted_5, vue.toDisplayString($props.language.thankYouText), 1 /* TEXT */)
])
])
]; }),
vue.renderSlot(_ctx.$slots, "completeButton", {}, function () { return [
vue.createCommentVNode(" Default content for the \"completeButton\" slot "),
(!$data.submitted)
? (vue.openBlock(), vue.createElementBlock("button", {
key: 0,
class: "o-btn-action",
ref: "button",
type: "button",
href: "#",
onClick: _cache[0] || (_cache[0] = vue.withModifiers(function ($event) { return ($options.submit()); }, ["prevent"])),
"aria-label": $props.language.ariaSubmitText
}, [
vue.createElementVNode("span", null, vue.toDisplayString($props.language.submitText), 1 /* TEXT */)
], 8 /* PROPS */, _hoisted_6))
: vue.createCommentVNode("v-if", true),
(!$data.submitted)
? (vue.openBlock(), vue.createElementBlock("a", {
key: 1,
class: "f-enter-desc",
href: "#",
onClick: _cache[1] || (_cache[1] = vue.withModifiers(function ($event) { return ($options.submit()); }, ["prevent"])),
innerHTML: $props.language.formatString($props.language.pressEnter)
}, null, 8 /* PROPS */, _hoisted_7))
: vue.createCommentVNode("v-if", true),
($data.submitted)
? (vue.openBlock(), vue.createElementBlock("p", _hoisted_8, vue.toDisplayString($props.language.successText), 1 /* TEXT */))
: vue.createCommentVNode("v-if", true)
]; })
]))
: vue.createCommentVNode("v-if", true)
])
]),
vue.createElementVNode("div", _hoisted_9, [
vue.createElementVNode("div", _hoisted_10, [
($props.progressbar)
? (vue.openBlock(), vue.createElementBlock("div", {
key: 0,
class: vue.normalizeClass(["f-progress", {'not-started': $options.percentCompleted === 0, 'completed': $options.percentCompleted === 100}])
}, [
vue.createElementVNode("div", _hoisted_11, [
vue.createElementVNode("div", {
class: "f-progress-bar-inner",
style: vue.normalizeStyle('width: ' + $options.percentCompleted + '%;')
}, null, 4 /* STYLE */)
]),
vue.createTextVNode(" " + vue.toDisplayString($props.language.percentCompleted.replace(':percent', $options.percentCompleted)), 1 /* TEXT */)
], 2 /* CLASS */))
: vue.createCommentVNode("v-if", true),
($props.navigation)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_12, [
vue.createElementVNode("a", {
class: vue.normalizeClass(["f-prev", {'f-disabled': $data.activeQuestionIndex === 0 || $data.submitted}]),
href: "#",
onClick: _cache[2] || (_cache[2] = vue.withModifiers(function ($event) { return ($options.goToPreviousQuestion()); }, ["prevent"])),
role: "button",
"aria-label": $props.language.ariaPrev
}, [
_hoisted_14,
vue.createElementVNode("span", _hoisted_15, vue.toDisplayString($props.language.prev), 1 /* TEXT */)
], 10 /* CLASS, PROPS */, _hoisted_13),
vue.createElementVNode("a", {
class: vue.normalizeClass(["f-next", {'f-disabled': !$options.isNextQuestionAvailable()}]),
href: "#",
onClick: _cache[3] || (_cache[3] = vue.withModifiers(function ($event) { return ($options.goToNextQuestion()); }, ["prevent"])),
role: "button",
"aria-label": $props.language.ariaNext
}, [
_hoisted_17,
vue.createElementVNode("span", _hoisted_18, vue.toDisplayString($props.language.next), 1 /* TEXT */)
], 10 /* CLASS, PROPS */, _hoisted_16)
]))
: vue.createCommentVNode("v-if", true),
($props.timer)
? (vue.openBlock(), vue.createElementBlock("div", _hoisted_19, [
vue.createElementVNode("span", null, vue.toDisplayString($options.formatTime($data.time)), 1 /* TEXT */)
]))
: vue.createCommentVNode("v-if", true)
])
])
], 2 /* CLASS */))
}
script$1.render = render;
script$1.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/FlowForm.vue";
var script = {
name: 'Question',
mixins: [
ComponentInstance
],
props: {
id: null,
modelValue: [String, Array, Boolean, Number, Object]
},
data: function data() {
return {
question: null
}
},
mounted: function mounted() {
this.setInstance();
},
render: function render() {
return null
},
watch: {
'question.answer': function question_answer(val) {
this.$emit('update:modelValue', val);
}
}
};
script.__file = "//HAL9000/work/_open source/_vff/_git - phre/src/components/Question.vue";
exports.ChoiceOption = ChoiceOption;
exports.FlowForm = script$1;
exports.LanguageModel = LanguageModel;
exports.LinkOption = LinkOption;
exports.MaskPresets = MaskPresets;
exports.Question = script;
exports.QuestionModel = QuestionModel;
exports.QuestionType = QuestionType;
Object.defineProperty(exports, '__esModule', { value: true });
}));
|
/**
* @module jsdoc/opts/args
* @requires jsdoc/opts/argparser
*/
const ArgParser = require('jsdoc/opts/argparser');
const cast = require('jsdoc/util/cast').cast;
const querystring = require('querystring');
let ourOptions;
const argParser = new ArgParser();
const hasOwnProp = Object.prototype.hasOwnProperty;
function parseQuery(str) {
return cast( querystring.parse(str) );
}
/* eslint-disable no-multi-spaces */
argParser.addOption('a', 'access', true, 'Only display symbols with the given access: "package", public", "protected", "private" or "undefined", or "all" for all access levels. Default: all except "private"', true);
argParser.addOption('c', 'configure', true, 'The path to the configuration file. Default: path/to/jsdoc/conf.json');
argParser.addOption('d', 'destination', true, 'The path to the output folder. Default: ./out/');
argParser.addOption('', 'debug', false, 'Log information for debugging JSDoc.');
argParser.addOption('e', 'encoding', true, 'Assume this encoding when reading all source files. Default: utf8');
argParser.addOption('h', 'help', false, 'Print this message and quit.');
argParser.addOption('', 'match', true, 'When running tests, only use specs whose names contain <value>.', true);
argParser.addOption('', 'nocolor', false, 'When running tests, do not use color in console output.');
argParser.addOption('p', 'private', false, 'Display symbols marked with the @private tag. Equivalent to "--access all". Default: false');
argParser.addOption('P', 'package', true, 'The path to the project\'s package file. Default: path/to/sourcefiles/package.json');
argParser.addOption('', 'pedantic', false, 'Treat errors as fatal errors, and treat warnings as errors. Default: false');
argParser.addOption('q', 'query', true, 'A query string to parse and store in jsdoc.env.opts.query. Example: foo=bar&baz=true', false, parseQuery);
argParser.addOption('r', 'recurse', false, 'Recurse into subdirectories when scanning for source files and tutorials.');
argParser.addOption('R', 'readme', true, 'The path to the project\'s README file. Default: path/to/sourcefiles/README.md');
argParser.addOption('t', 'template', true, 'The path to the template to use. Default: path/to/jsdoc/templates/default');
argParser.addOption('T', 'test', false, 'Run all tests and quit.');
argParser.addOption('u', 'tutorials', true, 'Directory in which JSDoc should search for tutorials.');
argParser.addOption('v', 'version', false, 'Display the version number and quit.');
argParser.addOption('', 'verbose', false, 'Log detailed information to the console as JSDoc runs.');
argParser.addOption('X', 'explain', false, 'Dump all found doclet internals to console and quit.');
/* eslint-enable no-multi-spaces */
// Options that are no longer supported and should be ignored
argParser.addIgnoredOption('l', 'lenient'); // removed in JSDoc 3.3.0
/**
* Set the options for this app.
* @throws {Error} Illegal arguments will throw errors.
* @param {string|String[]} args The command line arguments for this app.
*/
exports.parse = (args = []) => {
if (typeof args === 'string' || args.constructor === String) {
args = String(args).split(/\s+/g);
}
ourOptions = argParser.parse(args);
return ourOptions;
};
/**
* Retrieve help message for options.
*/
exports.help = () => argParser.help();
/**
* Get a named option.
* @variation name
* @param {string} name The name of the option.
* @return {string} The value associated with the given name.
*//**
* Get all the options for this app.
* @return {Object} A collection of key/values representing all the options.
*/
exports.get = name => {
if (typeof name === 'undefined') {
return ourOptions;
}
else if ( hasOwnProp.call(ourOptions, name) ) {
return ourOptions[name];
}
return undefined;
};
|
const Container = require('./')
const Graph = require('./Graph')
const Parser = require('./Parser')
const {
MainDependencyError,
NoExistingContainerError
} = require('./errors')
describe('Container', () => {
describe('.module', () => {
it('returns an instance of a Container', () => {
expect(Container.module('test')).to.be.instanceof(Container)
})
})
describe('.resolve', () => {
describe('when the container exists', () => {
let moduleName
beforeEach(() => {
moduleName = 'test'
Container
.module(moduleName)
.main(() => {})
})
describe('when the main dependency is defined', () => {
let spy
beforeEach(() => {
spy = sinon.spy(Container.module(moduleName), 'resolve')
})
afterEach(() => {
Container.module(moduleName).resolve.restore()
})
it('resolves the container', () => {
Container.module(moduleName).resolve()
expect(spy.called).to.eql(true)
})
})
describe('when the main dependency is not defined', () => {
let moduleName
beforeEach(() => {
moduleName = 'test2'
})
it('throws MainDependencyError', () => {
Container.module(moduleName)
expect(() => {
Container.module(moduleName).resolve()
}).to.throw(MainDependencyError)
})
})
})
describe('when the container does not exist', () => {
let moduleName
beforeEach(() => {
moduleName = 'test3'
})
it('throws NoExistingContainerError', () => {
expect(() => {
Container.resolve(moduleName)
}).to.throw(NoExistingContainerError)
})
})
})
describe('#define', () => {
let container, spy, depName
beforeEach(() => {
container = new Container()
depName = 'test'
spy = sinon.spy(container.graph, 'add')
})
it('calls graph#add', () => {
container.define(function test() {})
expect(spy.called).to.eql(true)
})
})
describe('#main', () => {
let container, main
beforeEach(() => {
container = new Container()
main = () => {}
})
it('sets the main property', () => {
container.main(main)
expect(container._main).to.eql({ deps: [], fn: main})
})
})
describe('#resolve', () => {
describe('when main is set', () => {
let container, main, resolveAllSpy, resolveNodeSpy
beforeEach(() => {
container = new Container()
main = () => {}
container.main(main)
resolveAllSpy = sinon.spy(container.graph, 'resolveAllNodes')
resolveNodeSpy = sinon.spy(container.graph, 'resolveNode')
})
it('calls graph#resolveAllNodes', () => {
container.resolve()
expect(resolveAllSpy.called).to.eql(true)
})
it('calls graph#resolveNode', () => {
container.resolve()
expect(resolveNodeSpy.called).to.eql(true)
})
})
describe('when main is not set', () => {
let container
beforeEach(() => {
container = new Container()
})
it('throws MainDependencyError', () => {
expect(() => {
container.resolve()
}).to.throw(MainDependencyError)
})
})
})
describe('#reset', () => {
let container, graph, parser
beforeEach(() => {
container = new Container()
graph = container.graph
parser = container.parse
container.reset()
})
it('sets the main injector to null', () => {
expect(container._main).to.eql(null)
})
it('sets external dependencies to empty array', () => {
expect(container.external).to.eql([])
})
it('sets a new graph instance', () => {
expect(container.graph).not.to.equal(graph)
expect(container.graph).to.be.an.instanceof(Graph)
})
it('sets a new parser instance', () => {
expect(container.parse).not.to.equal(parser)
expect(container.parse).to.be.an.instanceof(Parser)
})
})
})
|
// TODO list
// Use functions as keyFrames
// Test metronomic on real animation
// Create jquery FX like queue
var ease = require("ease-component"),
Emitter = require("events").EventEmitter,
util = require("util"),
__ = require("./fn"),
temporal;
Animation.DEFAULTS = {
cuePoints: [0, 1],
duration: 1000,
easing: "linear",
loop: false,
loopback: 0,
metronomic: false,
currentSpeed: 1,
progress: 0,
fps: 60,
rate: 1000 / 60,
paused: false,
segments: [],
onstart: null,
onpause: null,
onstop: null,
oncomplete: null,
onloop: null
};
/**
* Placeholders for Symbol
*/
Animation.normalize = "@@normalize";
Animation.render = "@@render";
/**
* Temporal will run up the CPU. temporalFallback is used
* for long running animations.
*/
function TemporalFallback(animation) {
this.interval = setInterval(function() {
animation.loopFunction({
calledAt: Date.now()
});
}, animation.rate);
}
TemporalFallback.prototype.stop = function() {
if (this.interval) {
clearInterval(this.interval);
}
};
/**
* Animation
* @constructor
*
* @param {target} A Servo or Servo.Collection to be animated
*
* Animating a single servo
*
* var servo = new five.Servo(10);
* var animation = new five.Animation(servo);
* animation.enqueue({
* cuePoints: [0, 0.25, 0.75, 1],
* keyFrames: [{degrees: 90}, 60, -120, {degrees: 90}],
* duration: 2000
* });
*
*
* Animating a servo array
*
* var a = new five.Servo(9),
* b = new five.Servo(10);
* var servos = new five.Servo.Collection([a, b]);
* var animation = new five.Animation(servos);
* animation.enqueue({
* cuePoints: [0, 0.25, 0.75, 1],
* keyFrames: [
* [{degrees: 90}, 60, -120, {degrees: 90}],
* [{degrees: 180}, -120, 90, {degrees: 180}],
* ],
* duration: 2000
* });
*
*/
function Animation(target) {
// Necessary to avoid loading temporal unless necessary
if (!temporal) {
temporal = require("temporal");
}
if (!(this instanceof Animation)) {
return new Animation(target);
}
this.defaultTarget = target;
Object.assign(this, Animation.DEFAULTS);
}
util.inherits(Animation, Emitter);
/**
* Add an animation segment to the animation queue
* @param {Object} opts Options: cuePoints, keyFrames, duration,
* easing, loop, metronomic, progress, fps, onstart, onpause,
* onstop, oncomplete, onloop
*/
Animation.prototype.enqueue = function(opts) {
if (typeof opts.target === "undefined") {
opts.target = this.defaultTarget;
}
opts = Object.assign({}, Animation.DEFAULTS, opts);
this.segments.push(opts);
if (!this.paused) {
this.next();
}
return this;
};
/**
* Plays next segment in queue
* Users need not call this. It's automatic
*/
Animation.prototype.next = function() {
if (this.segments.length > 0) {
Object.assign(this, this.segments.shift());
if (this.onstart) {
this.onstart();
}
this.normalizeKeyframes();
if (this.reverse) {
this.currentSpeed *= -1;
}
if (this.currentSpeed !== 0) {
this.play();
} else {
this.paused = true;
}
} else {
this.playLoop.stop();
}
};
/**
* pause
*
* Pause animation while maintaining progress, speed and segment queue
*
*/
Animation.prototype.pause = function() {
this.emit("animation:pause");
if (this.playLoop) {
this.playLoop.stop();
}
this.paused = true;
if (this.onpause) {
this.onpause();
}
};
/**
* stop
*
* Stop all animations
*
*/
Animation.prototype.stop = function() {
this.emit("animation:stop");
this.segments = [];
if (this.playLoop) {
this.playLoop.stop();
}
if (this.onstop) {
this.onstop();
}
};
/**
* speed
*
* Get or set the current playback speed
*
* @param {Number} speed
*
*/
Animation.prototype.speed = function(speed) {
if (typeof speed === "undefined") {
return this.currentSpeed;
} else {
this.currentSpeed = speed;
// Find our timeline endpoints and refresh rate
this.scaledDuration = this.duration / Math.abs(this.currentSpeed);
this.startTime = Date.now() - this.scaledDuration * this.progress;
this.endTime = this.startTime + this.scaledDuration;
return this;
}
};
/**
* This function is called in each frame of our animation
* Users need not call this. It's automatic
*/
Animation.prototype.loopFunction = function(loop) {
// Find the current timeline progress
var progress = this.calculateProgress(loop.calledAt);
// Find the left and right cuePoints/keyFrames;
var indices = this.findIndices(progress);
// Get tweened value
var val = this.tweenedValue(indices, progress);
// call render function
this.target[Animation.render](val);
// If this animation has been running for more than 5 seconds
if (loop.calledAt > this.fallBackTime) {
this.fallBackTime = Infinity;
if (this.playLoop) {
this.playLoop.stop();
}
this.playLoop = new TemporalFallback(this);
}
// See if we have reached the end of the animation
if ((progress === 1 && !this.reverse) || (progress === this.loopback && this.reverse)) {
if (this.loop || (this.metronomic && !this.reverse)) {
if (this.onloop) {
this.onloop();
}
if (this.metronomic) {
this.reverse = this.reverse ? false : true;
}
this.normalizeKeyframes();
this.progress = this.loopback;
this.startTime = Date.now() - this.scaledDuration * this.progress;
this.endTime = this.startTime + this.scaledDuration;
} else {
this.stop();
if (this.oncomplete) {
this.oncomplete();
}
this.next();
}
}
};
/**
* play
*
* Start a segment
*/
Animation.prototype.play = function() {
var now = Date.now();
if (this.playLoop) {
this.playLoop.stop();
}
this.paused = false;
// Find our timeline endpoints and refresh rate
this.scaledDuration = this.duration / Math.abs(this.currentSpeed);
this.startTime = now - this.scaledDuration * this.progress;
this.endTime = this.startTime + this.scaledDuration;
// If our animation runs for more than 5 seconds switch to setTimeout
this.fallBackTime = now + 5000;
this.frameCount = 0;
if (this.fps) {
this.rate = 1000 / this.fps;
}
this.rate = this.rate | 0;
this.playLoop = temporal.loop(this.rate, this.loopFunction.bind(this));
};
Animation.prototype.findIndices = function(progress) {
var indices = {
left: null,
right: null
};
// Find our current before and after cuePoints
indices.right = this.cuePoints.findIndex(function(point) {
return point >= progress;
});
indices.left = indices.right === 0 ? 0 : indices.right - 1;
return indices;
};
Animation.prototype.calculateProgress = function(calledAt) {
var progress = (calledAt - this.startTime) / this.scaledDuration;
if (progress > 1) {
progress = 1;
}
this.progress = progress;
if (this.reverse) {
progress = 1 - progress;
}
// Ease the timeline
// to do: When reverse replace inFoo with outFoo and vice versa. skip inOutFoo
progress = ease[this.easing](progress);
progress = __.constrain(progress, 0, 1);
return progress;
};
Animation.prototype.tweenedValue = function(indices, progress) {
var tween = {
duration: null,
progress: null
};
var result = this.normalizedKeyFrames.map(function(keyFrame) {
// Note: "this" is bound to the animation object
var memberIndices = {
left: null,
right: null
};
// If the keyframe at indices.left is null, move left
for (memberIndices.left = indices.left; memberIndices.left > -1; memberIndices.left--) {
if (keyFrame[memberIndices.left] !== null) {
break;
}
}
// If the keyframe at indices.right is null, move right
memberIndices.right = keyFrame.findIndex(function(frame, index) {
return index >= indices.right && frame !== null;
});
// Find our progress for the current tween
tween.duration = this.cuePoints[memberIndices.right] - this.cuePoints[memberIndices.left];
tween.progress = (progress - this.cuePoints[memberIndices.left]) / tween.duration;
// Catch divide by zero
if (!Number.isFinite(tween.progress)) {
tween.progress = this.reverse ? 0 : 1;
}
var left = keyFrame[memberIndices.left],
right = keyFrame[memberIndices.right];
// Apply tween easing to tween.progress
// to do: When reverse replace inFoo with outFoo and vice versa. skip inOutFoo
tween.progress = ease[right.easing](tween.progress);
// Calculate this tween value
var calcValue;
if (right.position) {
// This is a tuple
calcValue = right.position.map(function(value, index) {
return (value - left.position[index]) *
tween.progress + left.position[index];
});
} else {
calcValue = (right.value - left.value) *
tween.progress + left.value;
}
return calcValue;
}, this);
return result;
};
// Make sure our keyframes conform to a standard
Animation.prototype.normalizeKeyframes = function() {
var previousVal,
keyFrameSet = __.cloneDeep(this.keyFrames),
cuePoints = this.cuePoints;
// Run through the target's normalization
keyFrameSet = this.target[Animation.normalize](keyFrameSet);
// keyFrames can be passed as a single dimensional array if
// there is just one servo/device. If the first element is not an
// array, nest keyFrameSet so we only have to deal with one format
if (!Array.isArray(keyFrameSet[0])) {
keyFrameSet = [keyFrameSet];
}
keyFrameSet.forEach(function(keyFrames) {
// Pad the right side of keyFrames arrays with null
for (var i = keyFrames.length; i < cuePoints.length; i++) {
keyFrames.push(null);
}
keyFrames.forEach(function(keyFrame, i, source) {
if (keyFrame !== null) {
// keyFrames need to be converted to objects
if (typeof keyFrame !== "object") {
keyFrame = {
step: keyFrame,
easing: "linear"
};
}
// Replace step values
if (typeof keyFrame.step !== "undefined") {
keyFrame.value = keyFrame.step === false ?
previousVal : previousVal + keyFrame.step;
}
// Set a default easing function
if (!keyFrame.easing) {
keyFrame.easing = "linear";
}
// Copy value from another frame
if (typeof keyFrame.copyValue !== "undefined") {
keyFrame.value = source[keyFrame.copyValue].value;
}
// Copy everything from another keyframe in this array
if (keyFrame.copyFrame) {
keyFrame = source[keyFrame.copyFrame];
}
previousVal = keyFrame.value;
} else {
if (i === source.length - 1) {
keyFrame = {
value: previousVal,
easing: "linear"
};
} else {
keyFrame = null;
}
}
source[i] = keyFrame;
}, this);
});
this.normalizedKeyFrames = keyFrameSet;
return this;
};
module.exports = Animation;
|
(window.webpackJsonp=window.webpackJsonp||[]).push([[5],{572:function(n,o){},573:function(n,o){},574:function(n,o){},575:function(n,o){}}]);
//# sourceMappingURL=vega.bundle.js.map
|
import Accounts from '../../models/accounts';
import Alerts from '../../models/alerts';
import { asyncErr, KError } from '../../helpers';
import { checkAlert } from '../../shared/validators';
export async function loadAlert(req, res, next, alertId) {
try {
let { id: userId } = req.user;
let alert = await Alerts.find(userId, alertId);
if (!alert) {
throw new KError('bank alert not found', 404);
}
req.preloaded = req.preloaded || {};
req.preloaded.alert = alert;
return next();
} catch (err) {
return asyncErr(res, err, 'when preloading alert');
}
}
export async function create(req, res) {
try {
let { id: userId } = req.user;
let newAlert = req.body;
if (
!newAlert ||
typeof newAlert.accountId !== 'string' ||
typeof newAlert.type !== 'string'
) {
throw new KError('missing parameters', 400);
}
let validationError = checkAlert(newAlert);
if (validationError) {
throw new KError(validationError, 400);
}
let account = await Accounts.find(userId, newAlert.accountId);
if (!account) {
throw new KError('bank account not found', 404);
}
let alert = await Alerts.create(userId, newAlert);
res.status(201).json(alert);
} catch (err) {
return asyncErr(res, err, 'when creating an alert');
}
}
export async function destroy(req, res) {
try {
let { id: userId } = req.user;
await Alerts.destroy(userId, req.preloaded.alert.id);
res.status(204).end();
} catch (err) {
return asyncErr(res, err, 'when deleting a bank alert');
}
}
export async function update(req, res) {
try {
let { id: userId } = req.user;
let { alert } = req.preloaded;
let newAlert = req.body;
if (typeof newAlert.type !== 'undefined') {
throw new KError("can't update an alert type", 400);
}
newAlert = Object.assign({}, alert, newAlert);
let validationError = checkAlert(newAlert);
if (validationError) {
throw new KError(validationError, 400);
}
newAlert = await Alerts.update(userId, alert.id, req.body);
res.status(200).json(newAlert);
} catch (err) {
return asyncErr(res, err, 'when updating a bank alert');
}
}
|
/**
* @ngdoc service
* @name merchelloListViewHelper
* @description Handles list view configurations.
**/
angular.module('merchello.services').service('merchelloListViewHelper',
['$filter',
function() {
var configs = {
product: {
columns: [
{ name: 'name', localizeKey: 'merchelloVariant_product' },
{ name: 'sku', localizeKey: 'merchelloVariant_sku' },
{ name: 'available', localizeKey: 'merchelloProducts_available' },
{ name: 'shippable', localizeKey: 'merchelloProducts_shippable' },
{ name: 'taxable', localizeKey: 'merchelloProducts_taxable' },
{ name: 'totalInventory', localizeKey: 'merchelloGeneral_quantity', resultColumn: true },
{ name: 'onSale', localizeKey: 'merchelloVariant_productOnSale', resultColumn: true },
{ name: 'price', localizeKey: 'merchelloGeneral_price' }
]
},
// TODO remove this
productoption: {
columns: [
{ name: 'name', localizeKey: 'merchelloTableCaptions_optionName' },
{ name: 'uiOption', localizeKey: 'merchelloTableCaptions_optionUi' },
{ name: 'choices', localizeKey: 'merchelloTableCaptions_optionValues', resultColumn: true },
{ name: 'shared', localizeKey: 'merchelloTableCaptions_shared' },
{ name: 'sharedCount', localizeKey: 'merchelloTableCaptions_sharedCount' }
],
pageSize: 10,
orderBy: 'name',
orderDirection: 'asc'
},
customer: {
columns: [
{ name: 'loginName', localizeKey: 'merchelloCustomers_loginName' },
{ name: 'firstName', localizeKey: 'general_name' },
{ name: 'location', localizeKey: 'merchelloCustomers_location', resultColumn: true },
{ name: 'lastInvoiceTotal', localizeKey: 'merchelloCustomers_lastInvoiceTotal', resultColumn: true }
]
},
invoice: {
columns: [
{ name: 'invoiceNumber', localizeKey: 'merchelloSales_invoiceNumber' },
{ name: 'invoiceDate', localizeKey: 'general_date' },
{ name: 'billToName', localizeKey: 'merchelloGeneral_customer' },
{ name: 'paymentStatus', localizeKey: 'merchelloSales_paymentStatus', resultColumn: true },
{ name: 'fulfillmentStatus', localizeKey: 'merchelloOrder_fulfillmentStatus', resultColumn: true },
{ name: 'total', localizeKey: 'merchelloGeneral_total' }
],
pageSize: 10,
orderBy: 'invoiceNumber',
orderDirection: 'desc'
},
saleshistory: {
columns: [
{ name: 'invoiceNumber', localizeKey: 'merchelloSales_invoiceNumber' },
{ name: 'invoiceDate', localizeKey: 'general_date' },
{ name: 'paymentStatus', localizeKey: 'merchelloSales_paymentStatus', resultColumn: true },
{ name: 'fulfillmentStatus', localizeKey: 'merchelloOrder_fulfillmentStatus', resultColumn: true },
{ name: 'total', localizeKey: 'merchelloGeneral_total' }
],
orderBy: 'invoiceNumber',
orderDirection: 'desc'
},
offer: {
columns: [
{ name: 'name', localizeKey: 'merchelloTableCaptions_name' },
{ name: 'offerCode', localizeKey: 'merchelloMarketing_offerCode' },
{ name: 'offerType', localizeKey: 'merchelloMarketing_offerType' },
{ name: 'rewards', localizeKey: 'merchelloMarketing_offerRewardsInfo', resultColumn: true },
{ name: 'offerStartDate', localizeKey: 'merchelloTableCaptions_startDate' },
{ name: 'offerEndDate', localizeKey: 'merchelloTableCaptions_endDate' },
{ name: 'active', localizeKey: 'merchelloTableCaptions_active' }
]
},
customerbaskets: {
columns: [
{ name: 'loginName', localizeKey: 'merchelloCustomers_loginName' },
{ name: 'firstName', localizeKey: 'general_name' },
{ name: 'lastActivityDate', localizeKey: 'merchelloCustomers_lastActivityDate' },
{ name: 'items', localizeKey: 'merchelloCustomers_basket' }
],
pageSize: 10,
orderBy: 'lastActivityDate',
orderDirection: 'desc'
}
};
this.getConfig = function(listViewType) {
var ensure = listViewType.toLowerCase();
return configs[ensure];
};
}]);
|
describe("callFunc", function(){
var rt = wdFrp,
TestScheduler = rt.TestScheduler,
next = TestScheduler.next,
completed = TestScheduler.completed;
var scheduler = null;
var sandbox = null;
beforeEach(function(){
sandbox = sinon.sandbox.create();
scheduler = TestScheduler.create();
});
afterEach(function(){
sandbox.restore();
});
it("invoke function in the specific context", function(){
var context = {
a: 1
};
var result = [];
rt.callFunc(function(){
this.a++;
return this.a;
}, context)
.subscribe(function(a){
result.push(a);
});
expect(result).toEqual([2]);
expect(context.a).toEqual(2);
});
it("default context is window", function() {
rt.callFunc(function () {
this.a = 1;
return this.a;
})
.subscribe(function (a) {
});
expect(window.a).toEqual(1);
delete window.a;
});
it("if error, pass to errorHandler", function(){
var err = new Error("err");
var result = null;
rt.callFunc(function () {
throw err;
})
.subscribe(function () {
}, function(e){
result = e;
});
expect(result).toEqual(err);
});
it("multi operator", function(){
var result = [];
rt.fromArray([1, 2])
.concat(rt.callFunc(function(){
return 10;
}))
.subscribe(function(data){
result.push(data);
});
expect(result).toEqual([1, 2, 10]);
});
});
|
var ob = ob || {}
;(function(namespace, undefined) {
namespace.fusion = function(api_key, table_id) {
return {
key: api_key,
table: table_id,
url: function(hierarchy, sum) {
/* quote columns */
var columns = hierarchy.map(function(x) { return "'" + x + "'"; });
/* build query */
var query = 'SELECT ' + columns.join(',');
if (sum) { query += ',Sum(' + sum + ')'; }
query += ' FROM ' + this.table + ' GROUP BY ' + columns.join(',');
/* encode query */
query = encodeURIComponent(query);
/* build url */
var url = 'https://www.googleapis.com/fusiontables/v1/';
url += 'query?sql=' + query;
url += '&key=' + this.key;
return url;
},
};
}
})(ob);
/* test
var x = ob.fusion(
'AIzaSyCnWo1USrkSKnN6oy02tNeWfg6aFSg0OI8',
'1V2R7lsdg-GTbGOZ_h_DrGOa-Gfqk1PGA9h_n5zwU'
);
console.log(
x.url(
['Fund Description', 'Department', 'Division'],
'Amount'
)
);
x.key = 'xxxxx'
console.log(
x.url(
['Fund Description', 'Department', 'Division'],
'Amount'
)
);
*/
|
import { Agent } from 'http';
import net from 'net';
import assert from 'assert';
import log from 'book';
import Debug from 'debug';
const DEFAULT_MAX_SOCKETS = 10;
// Implements an http.Agent interface to a pool of tunnel sockets
// A tunnel socket is a connection _from_ a client that will
// service http requests. This agent is usable wherever one can use an http.Agent
class TunnelAgent extends Agent {
constructor(options = {}) {
super({
keepAlive: true,
// only allow keepalive to hold on to one socket
// this prevents it from holding on to all the sockets so they can be used for upgrades
maxFreeSockets: 1,
});
// sockets we can hand out via createConnection
this.availableSockets = [];
// when a createConnection cannot return a socket, it goes into a queue
// once a socket is available it is handed out to the next callback
this.waitingCreateConn = [];
this.debug = Debug(`lt:TunnelAgent[${options.clientId}]`);
// track maximum allowed sockets
this.connectedSockets = 0;
this.maxTcpSockets = options.maxTcpSockets || DEFAULT_MAX_SOCKETS;
// new tcp server to service requests for this client
this.server = net.createServer();
// flag to avoid double starts
this.started = false;
this.closed = false;
}
stats() {
return {
connectedSockets: this.connectedSockets,
};
}
listen() {
const server = this.server;
if (this.started) {
throw new Error('already started');
}
this.started = true;
server.on('close', this._onClose.bind(this));
server.on('connection', this._onConnection.bind(this));
server.on('error', (err) => {
// These errors happen from killed connections, we don't worry about them
if (err.code == 'ECONNRESET' || err.code == 'ETIMEDOUT') {
return;
}
log.error(err);
});
return new Promise((resolve) => {
server.listen(() => {
const port = server.address().port;
this.debug('tcp server listening on port: %d', port);
resolve({
// port for lt client tcp connections
port: port,
});
});
});
}
_onClose() {
this.closed = true;
this.debug('closed tcp socket');
// flush any waiting connections
for (const conn of this.waitingCreateConn) {
conn(new Error('closed'), null);
}
this.waitingCreateConn = [];
this.emit('end');
}
// new socket connection from client for tunneling requests to client
_onConnection(socket) {
// no more socket connections allowed
if (this.connectedSockets >= this.maxTcpSockets) {
this.debug('no more sockets allowed');
socket.destroy();
return false;
}
socket.once('close', (hadError) => {
this.debug('closed socket (error: %s)', hadError);
this.connectedSockets -= 1;
// remove the socket from available list
const idx = this.availableSockets.indexOf(socket);
if (idx >= 0) {
this.availableSockets.splice(idx, 1);
}
this.debug('connected sockets: %s', this.connectedSockets);
if (this.connectedSockets <= 0) {
this.debug('all sockets disconnected');
this.emit('offline');
}
});
// close will be emitted after this
socket.once('error', (err) => {
// we do not log these errors, sessions can drop from clients for many reasons
// these are not actionable errors for our server
socket.destroy();
});
if (this.connectedSockets === 0) {
this.emit('online');
}
this.connectedSockets += 1;
this.debug('new connection from: %s:%s', socket.address().address, socket.address().port);
// if there are queued callbacks, give this socket now and don't queue into available
const fn = this.waitingCreateConn.shift();
if (fn) {
this.debug('giving socket to queued conn request');
setTimeout(() => {
fn(null, socket);
}, 0);
return;
}
// make socket available for those waiting on sockets
this.availableSockets.push(socket);
}
// fetch a socket from the available socket pool for the agent
// if no socket is available, queue
// cb(err, socket)
createConnection(options, cb) {
if (this.closed) {
cb(new Error('closed'));
return;
}
this.debug('create connection');
// socket is a tcp connection back to the user hosting the site
const sock = this.availableSockets.shift();
// no available sockets
// wait until we have one
if (!sock) {
this.waitingCreateConn.push(cb);
this.debug('waiting connected: %s', this.connectedSockets);
this.debug('waiting available: %s', this.availableSockets.length);
return;
}
this.debug('socket given');
cb(null, sock);
}
destroy() {
this.server.close();
super.destroy();
}
}
export default TunnelAgent;
|
define({
name: 'Ball',
state: {
x: 0,
y: 0,
dx: 0,
dy: 1,
r: 10,
speed: 2,
radius: 11, // px
}
});
|
"use strict";
/**
* @module template/publish
* @type {*}
*/
/*global env: true */
var template = require( 'jsdoc/template' ),
fs = require( 'jsdoc/fs' ),
_ = require( 'underscore' ),
path = require( 'jsdoc/path' ),
taffy = require( 'taffydb' ).taffy,
handle = require( 'jsdoc/util/error' ).handle,
helper = require( 'jsdoc/util/templateHelper' ),
htmlsafe = helper.htmlsafe,
linkto = helper.linkto,
resolveAuthorLinks = helper.resolveAuthorLinks,
scopeToPunc = helper.scopeToPunc,
hasOwnProp = Object.prototype.hasOwnProperty,
conf = env.conf.tsdoc || {},
data,
view,
outdir = env.opts.destination;
var globalUrl = helper.getUniqueFilename( 'global' );
var indexUrl = helper.getUniqueFilename( 'index' );
var navOptions = {
systemName : conf.systemName || "Documentation",
navType : "vertical",
footer : conf.footer || "",
copyright : conf.copyright || "",
theme : "cerulean",
linenums : false,
collapseSymbols : true,
inverseNav : false
};
/**
* Check whether a symbol is a function and is the only symbol exported by a module (as in
* `module.exports = function() {};`).
*
* @private
* @param {module:jsdoc/doclet.Doclet} doclet - The doclet for the symbol.
* @return {boolean} `true` if the symbol is a function and is the only symbol exported by a module;
* otherwise, `false`.
*/
function isModuleFunction2(doclet) {
return doclet.longname && doclet.longname === doclet.name &&
doclet.longname.indexOf('module:') === 0 && doclet.kind === 'function';
}
/**
* Retrieve all of the following types of members from a set of doclets:
*
* + Classes
* + Externals
* + Globals
* + Mixins
* + Modules
* + Namespaces
* + Events
* @param {TAFFY} data The TaffyDB database to search.
* @return {object} An object with `classes`, `externals`, `globals`, `mixins`, `modules`,
* `events`, and `namespaces` properties. Each property contains an array of objects.
*/
function getMembers2(data) {
var find = function(data, spec) {
return data(spec).get();
};
var members = {
classes: find( data, {kind: 'class'} ),
externals: find( data, {kind: 'external'} ),
events: find( data, {kind: 'event'} ),
globals: find(data, {
kind: ['member', 'function', 'constant', 'typedef'],
memberof: { isUndefined: true }
}),
mixins: find( data, {kind: 'mixin'} ),
modules: find( data, {kind: 'module'} ),
namespaces: find( data, {kind: 'namespace'}),
typedef: find( data, {kind: 'typedef', isTSEnum:{is:true} }),
callbacks: find( data, {kind: 'typedef', isTSEnum:{isUndefined:true} })
};
// functions that are also modules (as in "module.exports = function() {};") are not globals
members.globals = members.globals.filter(function(doclet) {
if ( isModuleFunction2(doclet) ) {
return false;
}
return true;
});
return members;
};
var navigationMaster = {
index : {
title : navOptions.systemName,
link : indexUrl,
members : []
},
tutorial : {
title : "Tutorials",
link : helper.getUniqueFilename( "tutorials.list" ),
members : []
},
namespace : {
title : "Namespaces",
link : helper.getUniqueFilename( "namespaces.list" ),
members : []
},
module : {
title : "Modules",
link : helper.getUniqueFilename( "modules.list" ),
members : []
},
interface : {
title : "Interfaces",
link : helper.getUniqueFilename( 'classes.list' ),
members : []
},
class : {
title : "Classes",
link : helper.getUniqueFilename( 'classes.list' ),
members : []
},
mixin : {
title : "Mixins",
link : helper.getUniqueFilename( "mixins.list" ),
members : []
},
event : {
title : "Events",
link : helper.getUniqueFilename( "events.list" ),
members : []
},
global : {
title : "Global",
link : globalUrl,
members : []
},
external : {
title : "Externals",
link : helper.getUniqueFilename( "externals.list" ),
members : []
},
typedef : {
title : "Enums",
link : helper.getUniqueFilename( "enums.list" ),
members : []
},
callbacks : {
title : "Callbacks",
link : helper.getUniqueFilename( "namespaces.list" ),
members : []
}
};
function find( spec ) {
return helper.find( data, spec );
}
function tutoriallink( tutorial ) {
return helper.toTutorial( tutorial, null, { tag : 'em', classname : 'disabled', prefix : 'Tutorial: ' } );
}
function getAncestorLinks( doclet ) {
return helper.getAncestorLinks( data, doclet );
}
function hashToLink( doclet, hash ) {
if ( !/^(#.+)/.test( hash ) ) { return hash; }
var url = helper.createLink( doclet );
url = url.replace( /(#.+|$)/, hash );
return '<a href="' + url + '">' + hash + '</a>';
}
function needsSignature( doclet ) {
var needsSig = false;
// function and class definitions always get a signature
if ( doclet.kind === 'function' || doclet.kind === 'class' ) {
needsSig = true;
}
// typedefs that contain functions get a signature, too
else if ( doclet.kind === 'typedef' && doclet.type && doclet.type.names &&
doclet.type.names.length ) {
for ( var i = 0, l = doclet.type.names.length; i < l; i++ ) {
if ( doclet.type.names[i].toLowerCase() === 'function' ) {
needsSig = true;
break;
}
}
}
return needsSig;
}
function addSignatureParams( f ) {
var params = helper.getSignatureParams( f, 'optional' );
f.signature = (f.signature || '') + '(' + params.join( ', ' ) + ')';
}
function addSignatureReturns( f ) {
var returnTypes = helper.getSignatureReturns( f );
f.signature = '<span class="signature">' + (f.signature || '') + '</span>' + '<span class="type-signature">' + (returnTypes.length ? ' → {' + returnTypes.join( '|' ) + '}' : '') + '</span>';
}
function addSignatureTypes( f ) {
var types = helper.getSignatureTypes( f );
f.signature = (f.signature || '') + '<span class="type-signature">' + (types.length ? ' :' + types.join( '|' ) : '') + '</span>';
}
function addAttribs( f ) {
var attribs = helper.getAttribs( f );
f.attribs = '<span class="type-signature">' + htmlsafe( attribs.length ? '<' + attribs.join( ', ' ) + '> ' : '' ) + '</span>';
}
function shortenPaths( files, commonPrefix ) {
// always use forward slashes
var regexp = new RegExp( '\\\\', 'g' );
Object.keys( files ).forEach( function ( file ) {
files[file].shortened = files[file].resolved.replace( commonPrefix, '' )
.replace( regexp, '/' );
} );
return files;
}
function resolveSourcePath( filepath ) {
return path.resolve( process.cwd(), filepath );
}
function getPathFromDoclet( doclet ) {
if ( !doclet.meta ) {
return;
}
var filepath = doclet.meta.path && doclet.meta.path !== 'null' ?
doclet.meta.path + '/' + doclet.meta.filename :
doclet.meta.filename;
return filepath;
}
function generate( docType, title, docs, filename, resolveLinks ) {
resolveLinks = resolveLinks === false ? false : true;
var docData = {
title : title,
docs : docs,
docType : docType
};
var outpath = path.join( outdir, filename ),
html = view.render( 'container.tmpl', docData );
if ( resolveLinks ) {
html = helper.resolveLinks( html ); // turn {@link foo} into <a href="foodoc.html">foo</a>
}
fs.writeFileSync( outpath, html, 'utf8' );
}
function generateSourceFiles( sourceFiles ) {
Object.keys( sourceFiles ).forEach( function ( file ) {
var source;
// links are keyed to the shortened path in each doclet's `meta.filename` property
var sourceOutfile = helper.getUniqueFilename( sourceFiles[file].shortened );
helper.registerLink( sourceFiles[file].shortened, sourceOutfile );
try {
source = {
kind : 'source',
code : helper.htmlsafe( fs.readFileSync( sourceFiles[file].resolved, 'utf8' ) )
};
}
catch ( e ) {
handle( e );
}
generate( 'source', 'Source: ' + sourceFiles[file].shortened, [source], sourceOutfile,
false );
} );
}
/**
* Look for classes or functions with the same name as modules (which indicates that the module
* exports only that class or function), then attach the classes or functions to the `module`
* property of the appropriate module doclets. The name of each class or function is also updated
* for display purposes. This function mutates the original arrays.
*
* @private
* @param {Array.<module:jsdoc/doclet.Doclet>} doclets - The array of classes and functions to
* check.
* @param {Array.<module:jsdoc/doclet.Doclet>} modules - The array of module doclets to search.
*/
function attachModuleSymbols( doclets, modules ) {
var symbols = {};
// build a lookup table
doclets.forEach( function ( symbol ) {
symbols[symbol.longname] = symbol;
} );
return modules.map( function ( module ) {
if ( symbols[module.longname] ) {
module.module = symbols[module.longname];
module.module.name = module.module.name.replace( 'module:', 'require("' ) + '")';
}
} );
}
/*xperiments*/
var sort_by = function(field, reverse, primer){
var key = function (x) {return primer ? primer(x[field]) : x[field]};
return function (a,b) {
var A = key(a), B = key(b);
return ( (A < B) ? -1 : ((A > B) ? 1 : 0) ) * [-1,1][+!!reverse];
}
}
/**
* Create the navigation sidebar.
* @param {object} members The members that will be used to create the sidebar.
* @param {array<object>} members.classes
* @param {array<object>} members.externals
* @param {array<object>} members.globals
* @param {array<object>} members.mixins
* @param {array<object>} members.modules
* @param {array<object>} members.namespaces
* @param {array<object>} members.tutorials
* @param {array<object>} members.events
* @return {string} The HTML for the navigation sidebar.
*/
function buildNav( members ) {
var seen = {};
var nav = navigationMaster;
if ( members.modules.length ) {
members.modules.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.modules.forEach( function ( m ) {
if ( !hasOwnProp.call( seen, m.longname ) ) {
nav.module.members.push( linkto( m.longname, m.name ) );
}
seen[m.longname] = true;
} );
}
if ( members.externals.length ) {
members.externals.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.externals.forEach( function ( e ) {
if ( !hasOwnProp.call( seen, e.longname ) ) {
nav.external.members.push( linkto( e.longname, e.name.replace( /(^"|"$)/g, '' ) ) );
}
seen[e.longname] = true;
} );
}
if ( members.classes.length ) {
members.classes.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.classes.forEach( function ( c ) {
if ( !hasOwnProp.call( seen, c.longname ) ) {
nav.class.members.push( { link: linkto( c.longname, c.longname ), namespace:c} );
}
seen[c.longname] = true;
} );
}
/*
if ( members.events.length ) {
members.events.forEach( function ( e ) {
if ( !hasOwnProp.call( seen, e.longname ) ) {
nav.event.members.push( linkto( e.longname, e.name ) );
}
seen[e.longname] = true;
} );
}*/
if ( members.typedef.length ) {
members.typedef.forEach( function ( td ) {
if ( !hasOwnProp.call( seen, td.longname ) ) {
nav.typedef.members.push( {link:linkto( td.name, td.name ), namespace:{ longname:td.longname } });
}
seen[td.longname] = true;
} );
}
if ( members.callbacks.length ) {
members.callbacks.forEach( function ( cb ) {
if ( !hasOwnProp.call( seen, cb.longname ) ) {
nav.callbacks.members.push( {link:linkto( cb.longname, cb.longname.split('#')[0] ), namespace:{ longname:cb.longname } });
}
seen[cb.longname] = true;
} );
}
if ( members.namespaces.length ) {
members.namespaces.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.namespaces.forEach( function ( n ) {
if ( !hasOwnProp.call( seen, n.longname ))
{
nav.namespace.members.push( { link: linkto( n.longname, n.longname ), namespace:n} );
}
seen[n.longname] = true;
} );
}
if ( members.mixins.length ) {
members.mixins.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.mixins.forEach( function ( m ) {
if ( !hasOwnProp.call( seen, m.longname ) ) {
nav.mixin.members.push( linkto( m.longname, m.longname ) );
}
seen[m.longname] = true;
} );
}
if ( members.tutorials.length ) {
members.tutorials.sort(sort_by('name', true, function(a){return a.toUpperCase()}));
members.tutorials.forEach( function ( t ) {
nav.tutorial.members.push( tutoriallink( t.name ) );
} );
}
if ( members.globals.length ) {
members.globals.sort(sort_by('longname', true, function(a){return a.toUpperCase()}));
members.globals.forEach( function ( g ) {
if ( g.kind !== 'typedef' && !hasOwnProp.call( seen, g.longname ) ) {
nav.global.members.push( linkto( g.longname, g.longname ) );
}
seen[g.longname] = true;
} );
}
var topLevelNav = [];
_.each( nav, function ( entry, name ) {
if ( entry.members.length > 0 && name !== "index" ) {
topLevelNav.push( {
title : entry.title,
link : entry.link,
members : entry.members
} );
}
} );
nav.topLevelNav = topLevelNav;
}
/**
@param {TAFFY} taffyData See <http://taffydb.com/>.
@param {object} opts
@param {Tutorial} tutorials
*/
exports.publish = function ( taffyData, opts, tutorials ) {
data = taffyData;
conf['default'] = conf['default'] || {};
var templatePath = opts.template;
view = new template.Template( templatePath + '/tmpl' );
// claim some special filenames in advance, so the All-Powerful Overseer of Filename Uniqueness
// doesn't try to hand them out later
// var indexUrl = helper.getUniqueFilename( 'index' );
// don't call registerLink() on this one! 'index' is also a valid longname
// var globalUrl = helper.getUniqueFilename( 'global' );
helper.registerLink( 'global', globalUrl );
// set up templating
view.layout = 'layout.tmpl';
// set up tutorials for helper
helper.setTutorials( tutorials );
data = helper.prune( data );
data.sort( 'longname, version, since' );
helper.addEventListeners( data );
var sourceFiles = {};
var sourceFilePaths = [];
data().each( function ( doclet ) {
doclet.attribs = '';
if ( doclet.examples ) {
doclet.examples = doclet.examples.map( function ( example ) {
var caption, code;
if ( example.match( /^\s*<caption>([\s\S]+?)<\/caption>(\s*[\n\r])([\s\S]+)$/i ) ) {
caption = RegExp.$1;
code = RegExp.$3;
}
return {
caption : caption || '',
code : code || example
};
} );
}
if ( doclet.see ) {
doclet.see.forEach( function ( seeItem, i ) {
doclet.see[i] = hashToLink( doclet, seeItem );
} );
}
// build a list of source files
var sourcePath;
var resolvedSourcePath;
if ( doclet.meta ) {
sourcePath = getPathFromDoclet( doclet );
resolvedSourcePath = resolveSourcePath( sourcePath );
sourceFiles[sourcePath] = {
resolved : resolvedSourcePath,
shortened : null
};
sourceFilePaths.push( resolvedSourcePath );
}
} );
// update outdir if necessary, then create outdir
var packageInfo = ( find( {kind : 'package'} ) || [] ) [0];
if ( packageInfo && packageInfo.name ) {
outdir = path.join( outdir, packageInfo.name, packageInfo.version );
}
fs.mkPath( outdir );
// copy static files to outdir
var fromDir = path.join( templatePath, 'static' ),
staticFiles = fs.ls( fromDir, 3 );
staticFiles.forEach( function ( fileName ) {
var toDir = fs.toDir( fileName.replace( fromDir, outdir ) );
fs.mkPath( toDir );
fs.copyFileSync( fileName, toDir );
} );
if ( sourceFilePaths.length ) {
sourceFiles = shortenPaths( sourceFiles, path.commonPrefix( sourceFilePaths ) );
}
data().each( function ( doclet ) {
var url = helper.createLink( doclet );
helper.registerLink( doclet.longname, url );
// replace the filename with a shortened version of the full path
var docletPath;
if ( doclet.meta ) {
docletPath = getPathFromDoclet( doclet );
docletPath = sourceFiles[docletPath].shortened;
if ( docletPath ) {
doclet.meta.filename = docletPath;
}
}
} );
data().each( function ( doclet ) {
var url = helper.longnameToUrl[doclet.longname];
if ( url.indexOf( '#' ) > -1 ) {
doclet.id = helper.longnameToUrl[doclet.longname].split( /#/ ).pop();
}
else {
doclet.id = doclet.name;
}
if ( needsSignature( doclet ) ) {
addSignatureParams( doclet );
addSignatureReturns( doclet );
addAttribs( doclet );
}
} );
// do this after the urls have all been generated
data().each( function ( doclet ) {
doclet.ancestors = getAncestorLinks( doclet );
if ( doclet.kind === 'member' ) {
addSignatureTypes( doclet );
addAttribs( doclet );
}
if ( doclet.kind === 'constant' ) {
addSignatureTypes( doclet );
addAttribs( doclet );
doclet.kind = 'member';
}
} );
var members = getMembers2( data );
members.tutorials = tutorials.children;
// add template helpers
view.find = find;
view.linkto = linkto;
view.resolveAuthorLinks = resolveAuthorLinks;
view.tutoriallink = tutoriallink;
view.htmlsafe = htmlsafe;
// once for all
buildNav( members );
view.nav = navigationMaster;
view.navOptions = navOptions;
attachModuleSymbols( find( { kind : ['class', 'function'], longname : {left : 'module:'} } ),
members.modules );
// only output pretty-printed source files if requested; do this before generating any other
// pages, so the other pages can link to the source files
if ( conf.outputSourceFiles ) {
generateSourceFiles( sourceFiles );
}
if ( members.globals.length ) {
generate( 'global', 'Global', [
{kind : 'globalobj'}
], globalUrl );
}
// some browsers can't make the dropdown work
if ( view.nav.module && view.nav.module.members.length ) {
generate( 'module', view.nav.module.title, [
{kind : 'sectionIndex', contents : view.nav.module}
], navigationMaster.module.link );
}
if ( view.nav.class && view.nav.class.members.length ) {
generate( 'class', view.nav.class.title, [
{kind : 'sectionIndex', contents : view.nav.class}
], navigationMaster.class.link );
}
if ( view.nav.namespace && view.nav.namespace.members.length ) {
generate( 'namespace', view.nav.namespace.title, [
{kind : 'sectionIndex', contents : view.nav.namespace}
], navigationMaster.namespace.link );
}
if ( view.nav.mixin && view.nav.mixin.members.length ) {
generate( 'mixin', view.nav.mixin.title, [
{kind : 'sectionIndex', contents : view.nav.mixin}
], navigationMaster.mixin.link );
}
if ( view.nav.external && view.nav.external.members.length ) {
generate( 'external', view.nav.external.title, [
{kind : 'sectionIndex', contents : view.nav.external}
], navigationMaster.external.link );
}
if ( view.nav.tutorial && view.nav.tutorial.members.length ) {
generate( 'tutorial', view.nav.tutorial.title, [
{kind : 'sectionIndex', contents : view.nav.tutorial}
], navigationMaster.tutorial.link );
}
if ( view.nav.typedef && view.nav.typedef.members.length ) {
generate( 'typedef', view.nav.typedef.title, [
{kind : 'sectionIndex', contents : view.nav.typedef}
], navigationMaster.typedef.link );
}
if ( view.nav.callbacks && view.nav.callbacks.members.length ) {
generate( 'callbacks', view.nav.callbacks.title, [
{kind : 'sectionIndex', contents : view.nav.callbacks}
], navigationMaster.callbacks.link );
}
// index page displays information from package.json and lists files
var files = find( {kind : 'file'} ),
packages = find( {kind : 'package'} );
generate( 'index', 'Index',
packages.concat(
[
{kind : 'mainpage', readme : opts.readme, longname : (opts.mainpagetitle) ? opts.mainpagetitle : 'Main Page'}
]
).concat( files ),
indexUrl );
// set up the lists that we'll use to generate pages
var classes = taffy( members.classes );
var modules = taffy( members.modules );
var namespaces = taffy( members.namespaces );
var mixins = taffy( members.mixins );
var externals = taffy( members.externals );
var typedefs = taffy( members.typedef );
var callbacks = taffy( members.callbacks );
for ( var longname in helper.longnameToUrl ) {
if ( hasOwnProp.call( helper.longnameToUrl, longname ) ) {
var myClasses = helper.find( classes, {longname : longname} );
if ( myClasses.length )
{
var dta = myClasses[0];
if( dta && dta.tags )
{
var isInterface = false;
for( var i=0; i<dta.tags.length; i++ )
{
if( dta.tags[i].title=="interface")
{
isInterface = true;
}
}
if( isInterface )
{
generate( 'class', 'Interface: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname] );
}
else
{
generate( 'class', 'Class: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname] );
}
}
else
{
generate( 'class', 'Class: ' + myClasses[0].name, myClasses, helper.longnameToUrl[longname] );
}
}
var myModules = helper.find( modules, {longname : longname} );
if ( myModules.length ) {
generate( 'module', 'Module: ' + myModules[0].name, myModules, helper.longnameToUrl[longname] );
}
/*xperiments*/
var myNamespaces = helper.find( namespaces, {longname : longname} );
if ( myNamespaces.length ) {
//group repeated namespaces
var outNS = [];
var namesNS = [];
for( var ns = 0, total = myNamespaces.length; ns<total; ns++ )
{
if( namesNS.indexOf( myNamespaces[ns].longname)==-1 )
{
outNS.push( myNamespaces[ns]);
namesNS.push( myNamespaces[ns].longname );
}
}
generate( 'namespace', 'Namespace: ' + outNS[0].longname, outNS, helper.longnameToUrl[longname] );
}
var myMixins = helper.find( mixins, {longname : longname} );
if ( myMixins.length ) {
generate( 'mixin', 'Mixin: ' + myMixins[0].name, myMixins, helper.longnameToUrl[longname] );
}
var myExternals = helper.find( externals, {longname : longname} );
if ( myExternals.length ) {
generate( 'external', 'External: ' + myExternals[0].name, myExternals, helper.longnameToUrl[longname] );
}
var myTypedefs = helper.find( typedefs, {longname : longname} );
if ( myTypedefs.length ) {
generate( 'typedef', 'Enums: ' + myTypedefs[0].name, myTypedefs, helper.longnameToUrl[longname] );
}
var myCallbacks = helper.find( callbacks, {longname : longname} );
if ( myCallbacks.length ) {
if( longname.indexOf('#')==-1)
{
generate( 'callbacks', 'Callbacks: ' + myCallbacks[0].name, myCallbacks, helper.longnameToUrl[longname] );
}
else
{
generate( 'callbacks', 'Callbacks: ' + myCallbacks[0].name, myCallbacks, longname.split('#')[0] );
}
}
}
}
// TODO: move the tutorial functions to templateHelper.js
function generateTutorial( title, tutorial, filename ) {
var tutorialData = {
title : title,
header : tutorial.title,
content : tutorial.parse(),
children : tutorial.children,
docs : null
};
var tutorialPath = path.join( outdir, filename ),
html = view.render( 'tutorial.tmpl', tutorialData );
// yes, you can use {@link} in tutorials too!
html = helper.resolveLinks( html ); // turn {@link foo} into <a href="foodoc.html">foo</a>
fs.writeFileSync( tutorialPath, html, 'utf8' );
}
// tutorials can have only one parent so there is no risk for loops
function saveChildren( node ) {
node.children.forEach( function ( child ) {
generateTutorial( 'tutorial' + child.title, child, helper.tutorialToUrl( child.name ) );
saveChildren( child );
} );
}
if( tutorials && tutorials.length>0) saveChildren( tutorials );
};
|
/*jslint node: true, indent: 2 */
'use strict';
var config = require('./config.js');
// Utility functions
// getip function copied from Morgan (private there)
var getip = function (req) {
/*jslint nomen: true */
return req.ip
|| req._remoteAddress
|| (req.connection && req.connection.remoteAddress)
|| undefined;
};
var ipZeroedLastOctet = function (ipStr) {
var octets, zeroed;
octets = ipStr.split(/\./).map(function (m) {
return parseInt(m, 10);
});
octets[3] = 0;
zeroed = octets.join('.');
return zeroed;
};
module.exports.reqIpZeroedLastOctet = function (req) {
var beforeAnon, afterAnon, remoteIpHeader;
beforeAnon = '';
remoteIpHeader = config.get('remoteIpHeader');
if (remoteIpHeader && (typeof remoteIpHeader === 'string') && (remoteIpHeader.length > 0)
&& req.get(remoteIpHeader)) {
beforeAnon = req.get(remoteIpHeader);
} else {
beforeAnon = getip(req);
}
afterAnon = ipZeroedLastOctet(beforeAnon);
return afterAnon;
};
|
/**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'uploadwidget', 'uk', {
abort: 'Завантаження перервано користувачем.',
doneOne: 'Файл цілком завантажено.',
doneMany: 'Цілком завантажено %1 файлів.',
uploadOne: 'Завантаження файлу ({percentage}%)...',
uploadMany: 'Завантажено {current} із {max} файлів завершено на ({percentage}%)...'
} );
|
import Ember from 'ember';
import { test } from 'qunit';
import PagedArray from 'ember-cli-pagination/local/paged-array';
import equalArray from '../../../helpers/equal-array';
//module("PagedArray abc");
var paramTest = function(name,ops,f) {
if (ops.content) {
ops.content = Ember.A(ops.content);
}
test(name, function(assert) {
var subject = null;
Ember.run(function() {
subject = PagedArray.create(ops);
});
f(subject,assert);
});
};
paramTest("smoke", {page: 1, perPage: 2, content: [1,2,3,4,5]}, function(s,assert) {
assert.equal(s.get('totalPages'),3);
equalArray(assert,s,[1,2]);
s.set('page',2);
equalArray(assert,s,[3,4]);
});
paramTest("page out of range should give empty array", {page: 20, perPage: 2, content: [1,2,3,4,5]}, function(s,assert) {
equalArray(assert,s,[]);
});
paramTest("working then method", {page: 1, perPage: 2, content: [1,2,3,4,5]}, function(s,assert) {
equalArray(assert,s,[1,2]);
s.set('page',2);
s.then(function(res) {
equalArray(assert,s,[3,4]);
equalArray(assert,res,[3,4]);
});
});
paramTest("page oob event test", {page: 1, perPage: 2, content: [1,2,3,4,5]}, function(s,assert) {
var events = [];
s.on('invalidPage', function(page) {
events.push(page);
});
Ember.run(function() {
s.set('page',20);
});
assert.equal(events.length,1);
assert.equal(events[0].page,20);
Ember.run(function() {
s.set('page',2);
});
assert.equal(events.length,1);
});
import LockToRange from 'ember-cli-pagination/watch/lock-to-range';
paramTest("LockToRange", {page: 1, perPage: 2, content: [1,2,3,4,5]}, function(s,assert) {
LockToRange.watch(s);
Ember.run(function() {
s.set('page',20);
});
equalArray(assert,s,[5]);
Ember.run(function() {
s.set('page',-10);
});
equalArray(assert,s,[1,2]);
});
|
define([
'backbone',
'app/views/Sidebar',
'app/views/Canvas',
'app/models/settings',
'text!app/tpl/App.html'
], function(Backbone, SidebarView, CanvasView, Settings, Tpl) {
'use strict';
return Backbone.View.extend({
el: '.app',
initialize: function() {
// Compile Template
this.template = _.template(Tpl);
// Global Settings
// Save it in localstorage
this.settings = new Settings({id: 1});
this.settings.fetch({
error: function(model) {
model.save();
}
});
// Save all changes
this.settings.on('change', function() {
this.save();
});
// Add Other Views
this.sidebarView = new SidebarView({appView: this});
this.canvasView = new CanvasView({appView: this});
},
render: function() {
// Render Main Layout
this.$el.html(this.template());
// Render Attached Views
this.$('.app__sidebar').append(this.sidebarView.render().el);
this.$('.app__canvas').append(this.canvasView.render().el);
// Chain
return this;
}
});
});
|
/**
* @module zrender/graphic/Style
*/
var STYLE_COMMON_PROPS = [
['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
];
// var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
// var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
var Style = function (opts) {
this.extendFrom(opts);
};
function createLinearGradient(ctx, obj, rect) {
// var size =
var x = obj.x;
var x2 = obj.x2;
var y = obj.y;
var y2 = obj.y2;
if (!obj.global) {
x = x * rect.width + rect.x;
x2 = x2 * rect.width + rect.x;
y = y * rect.height + rect.y;
y2 = y2 * rect.height + rect.y;
}
var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
return canvasGradient;
}
function createRadialGradient(ctx, obj, rect) {
var width = rect.width;
var height = rect.height;
var min = Math.min(width, height);
var x = obj.x;
var y = obj.y;
var r = obj.r;
if (!obj.global) {
x = x * width + rect.x;
y = y * height + rect.y;
r = r * min;
}
var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
return canvasGradient;
}
Style.prototype = {
constructor: Style,
/**
* @type {string}
*/
fill: '#000000',
/**
* @type {string}
*/
stroke: null,
/**
* @type {number}
*/
opacity: 1,
/**
* @type {Array.<number>}
*/
lineDash: null,
/**
* @type {number}
*/
lineDashOffset: 0,
/**
* @type {number}
*/
shadowBlur: 0,
/**
* @type {number}
*/
shadowOffsetX: 0,
/**
* @type {number}
*/
shadowOffsetY: 0,
/**
* @type {number}
*/
lineWidth: 1,
/**
* If stroke ignore scale
* @type {Boolean}
*/
strokeNoScale: false,
// Bounding rect text configuration
// Not affected by element transform
/**
* @type {string}
*/
text: null,
/**
* @type {string}
*/
textFill: '#000',
/**
* @type {string}
*/
textStroke: null,
/**
* 'inside', 'left', 'right', 'top', 'bottom'
* [x, y]
* @type {string|Array.<number>}
* @default 'inside'
*/
textPosition: 'inside',
/**
* [x, y]
* @type {Array.<number>}
*/
textOffset: null,
/**
* @type {string}
*/
textBaseline: null,
/**
* @type {string}
*/
textAlign: null,
/**
* @type {string}
*/
textVerticalAlign: null,
/**
* Only useful in Path and Image element
* @type {number}
*/
textDistance: 5,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowBlur: 0,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowOffsetX: 0,
/**
* Only useful in Path and Image element
* @type {number}
*/
textShadowOffsetY: 0,
/**
* If transform text
* Only useful in Path and Image element
* @type {boolean}
*/
textTransform: false,
/**
* Text rotate around position of Path or Image
* Only useful in Path and Image element and textTransform is false.
*/
textRotation: 0,
/**
* @type {string}
* https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
*/
blend: null,
/**
* @param {CanvasRenderingContext2D} ctx
*/
bind: function (ctx, el, prevEl) {
var style = this;
var prevStyle = prevEl && prevEl.style;
var firstDraw = !prevStyle;
for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
var prop = STYLE_COMMON_PROPS[i];
var styleName = prop[0];
if (firstDraw || style[styleName] !== prevStyle[styleName]) {
// FIXME Invalid property value will cause style leak from previous element.
ctx[styleName] = style[styleName] || prop[1];
}
}
if ((firstDraw || style.fill !== prevStyle.fill)) {
ctx.fillStyle = style.fill;
}
if ((firstDraw || style.stroke !== prevStyle.stroke)) {
ctx.strokeStyle = style.stroke;
}
if ((firstDraw || style.opacity !== prevStyle.opacity)) {
ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
}
if ((firstDraw || style.blend !== prevStyle.blend)) {
ctx.globalCompositeOperation = style.blend || 'source-over';
}
if (this.hasStroke()) {
var lineWidth = style.lineWidth;
ctx.lineWidth = lineWidth / (
(this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
);
}
},
hasFill: function () {
var fill = this.fill;
return fill != null && fill !== 'none';
},
hasStroke: function () {
var stroke = this.stroke;
return stroke != null && stroke !== 'none' && this.lineWidth > 0;
},
/**
* Extend from other style
* @param {zrender/graphic/Style} otherStyle
* @param {boolean} overwrite
*/
extendFrom: function (otherStyle, overwrite) {
if (otherStyle) {
var target = this;
for (var name in otherStyle) {
if (otherStyle.hasOwnProperty(name)
&& (overwrite || ! target.hasOwnProperty(name))
) {
target[name] = otherStyle[name];
}
}
}
},
/**
* Batch setting style with a given object
* @param {Object|string} obj
* @param {*} [obj]
*/
set: function (obj, value) {
if (typeof obj === 'string') {
this[obj] = value;
}
else {
this.extendFrom(obj, true);
}
},
/**
* Clone
* @return {zrender/graphic/Style} [description]
*/
clone: function () {
var newStyle = new this.constructor();
newStyle.extendFrom(this, true);
return newStyle;
},
getGradient: function (ctx, obj, rect) {
var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
var canvasGradient = method(ctx, obj, rect);
var colorStops = obj.colorStops;
for (var i = 0; i < colorStops.length; i++) {
canvasGradient.addColorStop(
colorStops[i].offset, colorStops[i].color
);
}
return canvasGradient;
}
};
var styleProto = Style.prototype;
for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
var prop = STYLE_COMMON_PROPS[i];
if (!(prop[0] in styleProto)) {
styleProto[prop[0]] = prop[1];
}
}
// Provide for others
Style.getGradient = styleProto.getGradient;
module.exports = Style;
|
'use strict';
const obj = {
myFirstKey : 'foo',
mySecondKey : 'bar',
mythirdKey : 'baz'
};
obj;
|
/* Integral Code JS manifest */
$(document).ready(function(){
(function() {
// Parallax scrolling
parallax.init();
})();
});
|
// Example:
//
// export const CLEAR_FORM_ERRORS = 'CLEAR_FORM_ERRORS'
export const REHYDRATE = 'persist/REHYDRATE'
|
/*
* angular-marked v0.0.1
* (c) 2013 J. Harshbarger
* License: MIT
*/
/* jshint undef: true, unused: true */
/* global angular:true */
/* global marked:true */
(function () {
'use strict';
var app = angular.module('hc.marked', []);
app.constant('marked', window.marked);
// TODO: filter tests */
//app.filter('marked', ['marked', function(marked) {
// return marked;
//}]);
app.directive('marked', ['marked', function (marked) {
return {
restrict: 'AE',
replace: true,
scope: {
opts: '=',
marked: '='
},
link: function (scope, element, attrs) {
var value = scope.marked || element.text() || '';
set(value);
function set(val) {
element.html(marked(val || '', scope.opts || null));
}
if (attrs.marked) {
scope.$watch('marked', set);
}
}
};
}]);
}());
|
var util = require('util');
var Model = require('../model');
var _ = require('underscore');
function Profile(db) {
this.tableName = 'Profile';
//Call constructor of parent (Model)
Profile.super_.call(this, db);
}
util.inherits(Profile, Model);
Profile.prototype.getByJoined = function(column, search, callback){
var self = this;
var conn = this.db.connection;
var statement = util.format('SELECT Profile.id as id, ' +
'profile_name, magento_path, excluded_tables, tables, ' +
'Client.id as client_id, client_name, client_code, ' +
'Server.id as server_id, server_name, ssh_host, ssh_username ' +
'FROM Profile ' +
'INNER JOIN Server ON Profile.server_id = Server.id ' +
'INNER JOIN Client ON Server.client_id = Client.id ' +
'WHERE %s = ?',
column
);
search = this.sanitize(search);
conn.all(statement, [search], function(err, rows){
if (err) throw err;
callback(self.afterGetJoined(rows));
});
};
Profile.prototype.getAllJoined = function(callback){
var self = this;
var conn = this.db.connection;
var statement = 'SELECT Profile.id as id, ' +
'profile_name, magento_path, excluded_tables, tables, ' +
'Client.id as client_id, client_color, client_name, client_code, ' +
'Server.id as server_id, server_name, ssh_host, ssh_username ' +
'FROM Profile ' +
'INNER JOIN Server ON Profile.server_id = Server.id ' +
'INNER JOIN Client ON Server.client_id = Client.id';
conn.all(statement, function(err, rows){
if (err) throw err;
callback(self.afterGetJoined(rows));
});
};
Profile.prototype.afterGetJoined = function(rows) {
_.each(rows, function(row, i){
if (rows[i]['excluded_tables']) {
rows[i]['excluded_tables'] = JSON.parse(rows[i]['excluded_tables']);
}
if (rows[i]['tables']) {
rows[i]['tables'] = JSON.parse(rows[i]['tables']);
}
});
return rows;
};
module.exports = Profile;
|
'use strict';
const Stream = require('stream');
const Stringify = require('fast-safe-stringify');
class SafeJson extends Stream.Transform {
constructor(options, stringify) {
options = Object.assign({}, options, {
objectMode: true
});
super(options);
this._stringify = Object.assign({}, {
separator: '\n'
}, stringify);
}
_transform(data, enc, next) {
next(null, `${Stringify(data)}${this._stringify.separator}`);
}
}
module.exports = SafeJson;
|
module.exports = function (config) {
config.set({
frameworks: ['jasmine'],
logLevel: config.LOG_INFO,
loggers: [{ type: 'console' }],
reporters: ['dots'],
browsers: ['PhantomJS'],
autoWatch: false,
singleRun: true,
files: [
'lib/jquery/impl/jquery-1.9.1.js',
'lib/angular/impl/angular.js',
'lib/angular/impl/angular-mocks.js',
'build/angular-routing.js',
'build/angular-routing.legacy.js',
'build/test/**/*.js'
],
});
};
|
var searchData=
[
['findcritter',['findCritter',['../class_critter_wave.html#a1244e59ebd702edd2530e6256779ace0',1,'CritterWave']]]
];
|
angular.module('myApp').run(function ($rootScope) {
$rootScope.dt1 = new Date("yyyy-MM-dd HH:mm:ss");
$rootScope.dt2 = new Date("yyyy-MM-dd HH:mm:ss");
$rootScope.today = function () {
$rootScope.dt1 = new Date();
$rootScope.dt2 = new Date();
};
$rootScope.today();
$rootScope.clear = function () {
$rootScope.dt1 = null;
$rootScope.dt2 = null;
};
$rootScope.inlineOptions = {
customClass: getDayClass,
minDate: new Date(),
showWeeks: true
};
$rootScope.dateOptions = {
//dateDisabled: disabled,
formatYear: 'yyyy',
maxDate: new Date(),
minDate: new Date(),
startingDay: 1
};
$rootScope.toggleMin = function () {
$rootScope.inlineOptions.minDate = $rootScope.inlineOptions.minDate ? null : new Date();
$rootScope.dateOptions.minDate = $rootScope.inlineOptions.minDate;
};
$rootScope.toggleMin();
$rootScope.open1 = function () {
$rootScope.popup1.opened = true;
};
$rootScope.open2 = function () {
$rootScope.popup2.opened = true;
};
$rootScope.setDate = function (year, month, day) {
$rootScope.dt1 = new Date(year, month, day);
$rootScope.dt2 = new Date(year, month, day);
};
$rootScope.formats = ['yyyy-MM-dd', 'small'];
$rootScope.format = $rootScope.formats[0];
$rootScope.altInputFormats = ['yyyy!/MM!/yyyy'];
$rootScope.popup1 = {
opened: false
};
$rootScope.popup2 = {
opened: false
};
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
var afterTomorrow = new Date();
afterTomorrow.setDate(tomorrow.getDate() + 1);
$rootScope.events = [
{
date: tomorrow,
status: 'full'
},
{
date: afterTomorrow,
status: 'partially'
}];
function getDayClass(data) {
var date = data.date,
mode = data.mode;
if (mode === 'day') {
var dayToCheck = new Date(date).setHours(0, 0, 0, 0);
for (var i = 0; i < $rootScope.events.length; i++) {
var currentDay = new Date($rootScope.events[i].date).setHours(0, 0, 0, 0);
if (dayToCheck === currentDay) {
return $rootScope.events[i].status;
}
}
}
return '';
}
$rootScope.notify = function (type, text) {
var notify = $.notify('<strong>Loading...</strong>', {
type: type,
allow_dismiss: false,
showProgressbar: true,
delay: 1000,
time: 1000
});
setTimeout(function () {
notify.update('message', '<strong>' + text + '</strong>');
}, 1000);
};
});
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Ivan Kopeykin @vankop
*/
"use strict";
const WebpackError = require("./WebpackError");
const CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
/**
* @param {string=} method method name
* @returns {string} message
*/
function createMessage(method) {
return `Abstract method${method ? " " + method : ""}. Must be overridden.`;
}
/**
* @constructor
*/
function Message() {
this.stack = undefined;
Error.captureStackTrace(this);
/** @type {RegExpMatchArray} */
const match = this.stack.split("\n")[3].match(CURRENT_METHOD_REGEXP);
this.message = match && match[1] ? createMessage(match[1]) : createMessage();
}
/**
* Error for abstract method
* @example
* class FooClass {
* abstractMethod() {
* throw new AbstractMethodError(); // error message: Abstract method FooClass.abstractMethod. Must be overriden.
* }
* }
*
*/
class AbstractMethodError extends WebpackError {
constructor() {
super(new Message().message);
this.name = "AbstractMethodError";
}
}
module.exports = AbstractMethodError;
|
var merge = require('lodash.merge');
var env = process.env.TRAVIS && process.env._BROWSER !== 'phantomjs' ? 'travis-ci' : 'local';
var defaults = require('./defaults.js');
var asked = require('./' + env + '.js');
if(process.env._ENV === 'mobile') {
var mobile = require('./mobile');
asked = merge(asked,mobile);
}
module.exports = merge(defaults, asked);
|
(function (angular) {
// Create all modules and define dependencies to make sure they exist
// and are loaded in the correct order to satisfy dependency injection
// before all nested files are concatenated by Gulp
// Config
angular.module('angularUserSettings.config', [])
.value('angularUserSettings.config', {
debug: true
});
// Modules
angular.module('angularUserSettings.directives', []);
angular.module('angularUserSettings.controllers', []);
angular.module('angularUserSettings.services', []);
angular.module('angularUserSettings',
[
'angularUserSettings.config',
'angularUserSettings.controllers',
'angularUserSettings.directives',
'angularUserSettings.services'
]);
})(angular);
(function (angular) {
angular
.module('angularUserSettings.controllers')
.controller('angularUserSettings.UserSettingController', UserSettingController);
function UserSettingController($attrs, $userSettings){
this._key = null;
this.getKey = function(){
if(!this._key){
this._key = ($attrs.userSetting || 'global');
}
return this._key;
};
this.get = function(){
return $userSettings.get(this.getKey());
};
this.set = function(value){
return $userSettings.set(this.getKey(), value);
};
this.enable = function(){
return $userSettings.enable(this.getKey());
};
this.disable = function(){
return $userSettings.disable(this.getKey());
};
this.enabled = function(){
return $userSettings.enabled(this.getKey());
};
this.disabled = function(){
return $userSettings.disabled(this.getKey());
};
}
UserSettingController.$inject = ['$attrs', '$userSettings'];
})(angular);
(function (angular) {
angular
.module('angularUserSettings.controllers')
.controller('angularUserSettings.UserSettingsController', UserSettingsController);
function UserSettingsController($attrs, $scope, $userSettings){
this._name = ($attrs.settings || '$userSettings');
$scope[this._name] = $userSettings;
}
UserSettingsController.$inject = ['$attrs', '$scope', '$userSettings'];
})(angular);
(function (angular) {
var localStoragePrefix = 'angularUserSettings:';
angular
.module('angularUserSettings.services')
.factory('angularUserSettings.storage', storageFactory);
function storageFactory($window, $log){
if(!$window.localStorage){
$log.debug('angular-user-settings: localStorage not available');
}
return new StorageService($window.localStorage);
}
storageFactory.$inject = ['$window', '$log'];
function StorageService(localStorage){
/**
* Placeholder for internal data
*
* @type {{}}
* @private
*/
this._settings = {};
this._getLocalStorageKey = function(key){
return localStoragePrefix + key;
};
this.setItem = function(key, value){
this._settings[key] = value;
if(localStorage && localStorage.setItem){
localStorage.setItem(this._getLocalStorageKey(key), JSON.stringify(value));
}
return this;
};
this.getItem = function(key){
if(localStorage && localStorage.getItem){
this._settings[key] = JSON.parse(localStorage.getItem(this._getLocalStorageKey(key)));
}
return this._settings[key];
};
}
})(angular);
(function (angular) {
angular
.module('angularUserSettings.services')
.provider('$userSettings', userSettingsServiceProvider);
/**
* Default options
*/
var options = {
storageServiceName: 'angularUserSettings.storage'
};
function userSettingsServiceProvider(){
/**
* Set options
*
* @param opts
*/
this.setOptions = function(opts){
angular.merge(options, opts);
};
/**
* Get options
*
* @returns {{showWhenUnknown: boolean}}
*/
this.getOptions = function(){
return options;
};
this.$get = userSettingsServiceFactory;
}
/**
* Settings service factory
*
* @returns {SettingsService}
*/
function userSettingsServiceFactory(storage){
return new SettingsService(storage);
}
// Inject dependencies
userSettingsServiceFactory.$inject = [options.storageServiceName];
/**
* Settings service constructor
*
* @param storage
* @constructor
*/
function SettingsService(storage){
/**
* Get value for key
*
* @param key
* @returns {*}
*/
this.get = function(key){
return storage.getItem(key);
};
/**
* Set value for key
*
* @param key
* @param value
*/
this.set = function(key, value){
storage.setItem(key, value);
return this;
};
/**
* Set value for key to true
*
* @param key
*/
this.enable = function(key){
return this.set(key, true);
};
/**
* Set value for key to false
*
* @param key
*/
this.disable = function(key){
return this.set(key, false);
};
/**
* Return whether value for key is truthy
*
* @param key
* @returns {boolean}
*/
this.enabled = function(key){
return !!this.get(key);
};
/**
* Return whether value for key is falsy
*
* @param key
* @returns {boolean}
*/
this.disabled = function(key){
return !this.enabled(key);
};
}
})(angular);
(function (angular) {
angular
.module('angularUserSettings.directives')
.directive('userSetting', createDirectiveDDO);
function createDirectiveDDO(){
return {
restrict: 'A',
scope: true,
controller: 'angularUserSettings.UserSettingController',
controllerAs: '$userSetting'
};
}
})(angular);
(function (angular) {
angular
.module('angularUserSettings.directives')
.directive('userSettings', createDirectiveDDO);
function createDirectiveDDO(){
return {
restrict: 'A',
controller: 'angularUserSettings.UserSettingsController'
};
}
})(angular);
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "M21 10V4c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2L1 16c0 1.1.9 2 2 2h11v-5c0-1.66 1.34-3 3-3h4zm-9.47.67c-.32.2-.74.2-1.06 0L3.4 6.25c-.25-.16-.4-.43-.4-.72 0-.67.73-1.07 1.3-.72L11 9l6.7-4.19c.57-.35 1.3.05 1.3.72 0 .29-.15.56-.4.72l-7.07 4.42z"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "M22 14c-.55 0-1 .45-1 1v3c0 1.1-.9 2-2 2s-2-.9-2-2v-4.5c0-.28.22-.5.5-.5s.5.22.5.5V17c0 .55.45 1 1 1s1-.45 1-1v-3.5c0-1.38-1.12-2.5-2.5-2.5S15 12.12 15 13.5V18c0 2.21 1.79 4 4 4s4-1.79 4-4v-3c0-.55-.45-1-1-1z"
}, "1")], 'AttachEmailRounded');
|
/* eslint no-unused-vars: 0 */
/* globals language_names: 1 */
language_names = {
'af': ['Afrikaans', 'Afrikaans'],
'ak': ['Akan', 'Akan'],
'sq': ['Albanian', 'Shqip'],
'am': ['Amharic', 'አማርኛ'],
'ar': ['Arabic', 'العربية'],
'hy': ['Armenian', 'Հայերեն'],
'rup': ['Aromanian', 'Armãneashce'],
'as': ['Assamese', 'অসমীয়া'],
'az': ['Azerbaijani', 'Azərbaycan dili'],
'az-TR': ['Azerbaijani (Turkey)', 'Azərbaycan Türkcəsi'],
'ba': ['Bashkir', 'башҡорт теле'],
'eu': ['Basque', 'Euskara'],
'bel': ['Belarusian', 'Беларуская мова'],
'bn': ['Bengali', 'বাংলা'],
'bs': ['Bosnian', 'Bosanski'],
'bg': ['Bulgarian', 'Български'],
'mya': ['Burmese', 'ဗမာစာ'],
'ca': ['Catalan', 'Català'],
'bal': ['Catalan (Balear)', 'Català (Balear)'],
'zh': ['Chinese', '中文'],
'zh-CN': ['Chinese (China)', '简体中文'],
'zh-HK': ['Chinese (Hong Kong)', '繁體中文(香港)'],
'zh-TW': ['Chinese (Taiwan)', '繁體中文(台灣)'],
'co': ['Corsican', 'corsu'],
'hr': ['Croatian', 'Hrvatski'],
'cs': ['Czech', 'čeština'],
'da': ['Danish', 'Dansk'],
'nl': ['Dutch', 'Nederlands'],
'nl-BE': ['Dutch (Belgium)', 'Nederlands (België)'],
'en': ['English', 'English'],
'en-AU': ['English (Australia)', 'English (Australia)'],
'en-CA': ['English (Canada)', 'English (Canada)'],
'en-GB': ['English (UK)', 'English (UK)'],
'eo': ['Esperanto', 'Esperanto'],
'et': ['Estonian', 'Eesti'],
'fo': ['Faroese', 'føroyskt'],
'fi': ['Finnish', 'Suomi'],
'fr-BE': ['French (Belgium)', 'Français de Belgique'],
'fr': ['French (France)', 'Français'],
'fy': ['Frisian', 'Frysk'],
'fuc': ['Fulah', 'Pulaar'],
'gl': ['Galician', 'Galego'],
'ka': ['Georgian', 'ქართული'],
'de': ['German', 'Deutsch'],
'el': ['Greek', 'Ελληνικά'],
'gn': ['Guaraní', 'Avañe\'ẽ'],
'haw': ['Hawaiian', 'Ōlelo Hawaiʻi'],
'haz': ['Hazaragi', 'هزاره گی'],
'he': ['Hebrew', 'עברית'],
'hi': ['Hindi', 'हिन्दी'],
'hu': ['Hungarian', 'Magyar'],
'is': ['Icelandic', 'Íslenska'],
'id': ['Indonesian', 'Bahasa Indonesia'],
'ga': ['Irish', 'Gaelige'],
'it': ['Italian', 'Italiano'],
'ja': ['Japanese', '日本語'],
'jv': ['Javanese', 'Basa Jawa'],
'kn': ['Kannada', 'ಕನ್ನಡ'],
'kk': ['Kazakh', 'Қазақ тілі'],
'km': ['Khmer', 'ភាសាខ្មែរ'],
'rw': ['Kinyarwanda', 'Kinyarwanda'],
'ky': ['Kirghiz', 'кыргыз тили'],
'ko': ['Korean', '한국어'],
'ckb': ['Kurdish (Sorani)', 'كوردی'],
'lo': ['Lao', 'ພາສາລາວ'],
'lv': ['Latvian', 'latviešu valoda'],
'li': ['Limburgish', 'Limburgs'],
'lt': ['Lithuanian', 'Lietuvių kalba'],
'lb': ['Luxembourgish', 'Lëtzebuergesch'],
'mk': ['Macedonian', 'македонски јазик'],
'mg': ['Malagasy', 'Malagasy'],
'ms': ['Malay', 'Bahasa Melayu'],
'ml': ['Malayalam', 'മലയാളം'],
'mr': ['Marathi', 'मराठी'],
'xmf': ['Mingrelian', 'მარგალური ნინა'],
'mn': ['Mongolian', 'Монгол'],
'me': ['Montenegrin', 'Crnogorski jezik'],
'ne': ['Nepali', 'नेपाली'],
'nb': ['Norwegian (Bokmål)', 'Norsk bokmål'],
'nn': ['Norwegian (Nynorsk)', 'Norsk nynorsk'],
'os': ['Ossetic', 'Ирон'],
'ps': ['Pashto', 'پښتو'],
'fa': ['Persian', 'فارسی'],
'fa-AF': ['Persian (Afghanistan)', 'فارسی (افغانستان'],
'pl': ['Polish', 'Polski'],
'pt-BR': ['Portuguese (Brazil)', 'Português do Brasil'],
'pt': ['Portuguese (Portugal)', 'Português'],
'pa': ['Punjabi', 'ਪੰਜਾਬੀ'],
'rhg': ['Rohingya', 'Rohingya'],
'ro': ['Romanian', 'Română'],
'ru': ['Russian', 'Русский'],
'rue': ['Rusyn', 'Русиньскый'],
'sah': ['Sakha', 'Sakha'],
'sa-IN': ['Sanskrit', 'भारतम्'],
'srd': ['Sardinian', 'sardu'],
'gd': ['Scottish Gaelic', 'Gàidhlig'],
'sr': ['Serbian', 'Српски језик'],
'sd': ['Sindhi', 'سندھ'],
'si': ['Sinhala', 'සිංහල'],
'sk': ['Slovak', 'Slovenčina'],
'sl': ['Slovenian', 'slovenščina'],
'so': ['Somali', 'Afsoomaali'],
'azb': ['South Azerbaijani', 'گؤنئی آذربایجان'],
'es-AR': ['Spanish (Argentina)', 'Español de Argentina'],
'es-CL': ['Spanish (Chile)', 'Español de Chile'],
'es-CO': ['Spanish (Colombia)', 'Español de Colombia'],
'es-MX': ['Spanish (Mexico)', 'Español de México'],
'es-PE': ['Spanish (Peru)', 'Español de Perú'],
'es-PR': ['Spanish (Puerto Rico)', 'Español de Puerto Rico'],
'es': ['Spanish (Spain)', 'Español'],
'es-VE': ['Spanish (Venezuela)', 'Español de Venezuela'],
'su': ['Sundanese', 'Basa Sunda'],
'sw': ['Swahili', 'Kiswahili'],
'sv': ['Swedish', 'Svenska'],
'gsw': ['Swiss German', 'Schwyzerdütsch'],
'tl': ['Tagalog', 'Tagalog'],
'tg': ['Tajik', 'тоҷикӣ'],
'ta': ['Tamil', 'தமிழ்'],
'ta-LK': ['Tamil (Sri Lanka)', 'தமிழ்'],
'tt': ['Tatar', 'Татар теле'],
'te': ['Telugu', 'తెలుగు'],
'th': ['Thai', 'ไทย'],
'bo': ['Tibetan', 'བོད་སྐད'],
'tir': ['Tigrinya', 'ትግርኛ'],
'tr': ['Turkish', 'Türkçe'],
'tuk': ['Turkmen', 'Türkmençe'],
'ua': ['Ukrainian', 'Українська'],
'ug': ['Uighur', 'Uyƣurqə'],
'uk': ['Ukrainian', 'Українська'],
'ur': ['Urdu', 'اردو'],
'uz': ['Uzbek', 'O‘zbekcha'],
'vi': ['Vietnamese', 'Tiếng Việt'],
'wa': ['Walloon', 'Walon'],
'cy': ['Welsh', 'Cymraeg']
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.