code
stringlengths 2
1.05M
|
---|
/**
* Global config setters/getters. Chainable ;)
*
* @usage
* config.duration(500) //
* config.duration() // => 500
* config.duration(600).duration() // 600
*/
// Number of millseconds for each message to last
var _duration = 10000;
/**
* (s|g)etter for the duration
*
* @parmam {int} ms
* @return {this|int}
*/
export default {
duration: function (ms) {
if ( ms ) {
// We'll parse it as int just in case a
// dumb consumer tries to provide a string
_duration = parseInt(ms, 10);
return this;
} else {
return _duration;
}
}
};
|
/**
* This method start authentication workflow.
* It should be called by application which require authentication.
*
* Author: Yuriy Movchan Date: 11/06/2013
*/
var uuid = require('uuid');
var async = require('async');
var oxutil = require('../util/util.js');
var state = require('../shared/state.js');
var push = require('../push/push.js');
exports.rest_api = function(req, res, authenticationStore, applicationService, deviceService) {
console.log("Authenticate: '" + req.params.deployment_id + "'", "user: '" + req.params.user_name + "'");
// Load device and application entries
async.series([ function(done) {
deviceService.getDeviceById(req.params.deployment_id, function(found_deployment_entry) {
deployment_entry = found_deployment_entry;
done();
});
}, function(done) {
if (deployment_entry) {
applicationService.getApplication(deployment_entry.oxPushApplication, function(found_application_entry) {
application_entry = found_application_entry;
done();
});
} else {
console.warn("Failed to find deployment entry: '%s'", req.params.deployment_id);
oxutil.sendFailedJsonResponse(res);
done();
}
} ], function() {
if (application_entry && deployment_entry) {
var application_configuration = JSON.parse(application_entry.oxPushApplicationConf);
// TODO: Validate application_ip and req.ip
var authentication_id = uuid.v1();
var authentication_entry = {
'authentication_id' : authentication_id,
'authentication_time' : Date.now(),
'expires_in' : 60,
'expires_at' : Date.now() + 60 * 1000,
'clean_up_at' : Date.now() + 180 * 1000,
'application_id' : application_entry.oxId,
'application_name' : application_configuration.name,
'application_description' : application_configuration.description,
'application_ip' : req.ip,
'user_name' : req.params.user_name,
'authentication_status' : state.PENDING,
};
authenticationStore.set(authentication_id, authentication_entry);
// Send message to device
var device_configuration = JSON.parse(deployment_entry.oxPushDeviceConf);
try {
push.sendAuthenticationMessageToDevice(device_configuration, authentication_id);
} catch (err) {
console.log("Failed to send notification message to device: '" + device_configuration.device_uuid);
}
console.log("Initialized authentication process: '" + authentication_id + "' for application: '"
+ authentication_entry.application_name + "'");
oxutil.sendJsonResponse(res, {
authentication_id : authentication_entry.authentication_id,
expires_in : authentication_entry.expires_in,
result : true,
});
} else {
console.warn("Failed to find application entry: '%s'", deployment_entry.oxPushApplication);
oxutil.sendFailedJsonResponse(res);
}
});
};
|
const { yellow, cyan, gray } = require('chalk');
const EslintCLI = require('eslint').CLIEngine;
const eslintConfig = require('../config/eslint/eslintConfig');
const runESLint = ({ fix = false, paths }) =>
new Promise((resolve, reject) => {
console.log(cyan(`${fix ? 'Fixing' : 'Checking'} code with ESLint`));
const cli = new EslintCLI({
baseConfig: eslintConfig,
extensions: ['.ts', '.tsx', '.js', '.jsx'],
useEslintrc: false,
fix,
});
const checkAll = typeof paths === 'undefined';
/* Whitelist the file extensions that our ESLint setup currently supports */
const filteredFilePaths = checkAll
? ['.']
: paths.filter(
(filePath) =>
filePath.endsWith('.ts') ||
filePath.endsWith('.tsx') ||
filePath.endsWith('.js') ||
filePath.endsWith('.jsx') ||
filePath.endsWith('.json'),
);
if (filteredFilePaths.length === 0) {
console.log(gray(`No JS files to lint`));
} else {
console.log(gray(`Paths: ${filteredFilePaths.join(' ')}`));
try {
const report = cli.executeOnFiles(filteredFilePaths);
if (fix) {
EslintCLI.outputFixes(report);
} else {
const { errorCount, warningCount, results } = report;
if (errorCount || warningCount) {
const formatter = cli.getFormatter();
console.log(formatter(results));
}
if (errorCount > 0) {
reject();
}
}
} catch (e) {
if (e && e.message && e.message.includes('No files matching')) {
console.warn(yellow(`Warning: ${e.message}`));
} else {
reject(e);
}
}
}
resolve();
});
module.exports = {
check: (paths) => runESLint({ paths }),
fix: (paths) => runESLint({ fix: true, paths }),
};
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
root.ng.common.locales['nl-sr'] = [
'nl-SR',
[['a.m.', 'p.m.'], u, u],
u,
[
['Z', 'M', 'D', 'W', 'D', 'V', 'Z'], ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'jan.', 'feb.', 'mrt.', 'apr.', 'mei', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.',
'dec.'
],
[
'januari', 'februari', 'maart', 'april', 'mei', 'juni', 'juli', 'augustus', 'september',
'oktober', 'november', 'december'
]
],
u,
[['v.C.', 'n.C.'], ['v.Chr.', 'n.Chr.'], ['voor Christus', 'na Christus']],
1,
[6, 0],
['dd-MM-y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', u, '{1} \'om\' {0}', u],
[',', '.', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤ #,##0.00;¤ -#,##0.00', '#E0'],
'$',
'Surinaamse dollar',
{
'AUD': ['AU$', '$'],
'CAD': ['C$', '$'],
'FJD': ['FJ$', '$'],
'JPY': ['JP¥', '¥'],
'SBD': ['SI$', '$'],
'SRD': ['$'],
'THB': ['฿'],
'TWD': ['NT$'],
'USD': ['US$', '$'],
'XPF': [],
'XXX': []
},
plural,
[
[['middernacht', '’s ochtends', '’s middags', '’s avonds', '’s nachts'], u, u],
[['middernacht', 'ochtend', 'middag', 'avond', 'nacht'], u, u],
['00:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'], ['00:00', '06:00']]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
import NumeralFieldComponent from './Numeral'
const numeral = global.numeral
if (!numeral) {
throw new Error('Numeral is required in global variable')
}
export default class MoneyComponent extends NumeralFieldComponent {
unformatValue(label) {
return label === '' ? undefined : numeral._.stringToNumber(label)
}
formatValue(real) {
return numeral(real) ? numeral(real).format('$0,0.[000000000000000000000]') : ''
}
}
|
var gulp = require("gulp");
var util = require("gulp-util");
var config = require("../config")
gulp.task("watch", () => {
gulp.watch(`${config.src.ts}`, ["compile:ts"]).on("change", reportChange).on("error", swallowError);
gulp.watch(`${config.test.files}`, ["compile:test"]).on("change", reportChange).on("error", swallowError);
});
function reportChange(event) {
console.log(`File ${event.path} was ${event.type}, running tasks...`);
}
function swallowError(error) {
console.log(util.colors.red(`Error occurred while running watched task...`));
} |
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserify = require('gulp-browserify'),
concat = require('gulp-concat'),
gulpif = require('gulp-if'),
uglify = require('gulp-uglify'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
sequence = require('run-sequence'),
less = require('gulp-less'),
zip = require('gulp-zip'),
rev = require('gulp-rev-append'),
gutil = require('gulp-util');
var production = gutil.env.type === "production";
var game_name = gutil.env.name || 'fp'
var paths = {
source: {
canvas_js: './app/js/' + game_name + '/canvas.js',
web_js: './app/js/' + game_name + '/web.js',
canvas_css: './app/less/' + game_name + '/canvas.less',
web_css: './app/less/' + game_name + '/web.less',
baseJsDir: './app/js/**',
js: './app/js/**/*.js',
css: './app/less/**/*.less',
libs: [
'./bower_components/phaser/build/phaser.js'
]
},
dest: {
base: './public/' + game_name + '/',
html: './public/' + game_name + '/index.html',
js: './public/' + game_name + '/js',
css: './public/' + game_name + '/css'
}
};
gulp.task('rev', function() {
gulp.src(paths.dest.html)
.pipe(rev())
.pipe(gulp.dest(paths.dest.base));
});
gulp.task('copy_libs', function () {
gulp.src(paths.source.libs)
.pipe(uglify({outSourceMaps: false}))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('canvas_js', function() {
gulp.src(paths.source.canvas_js)
.pipe(plumber())
.pipe(browserify())
.pipe(concat('canvas.js'))
.pipe(gulpif(production, uglify()))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('web_js', function() {
gulp.src(paths.source.web_js)
.pipe(plumber())
.pipe(browserify())
.pipe(concat('web.js'))
.pipe(gulpif(production, uglify()))
.pipe(gulp.dest(paths.dest.js));
});
gulp.task('canvas_css', function() {
gulp.src(paths.source.canvas_css)
.pipe(plumber())
.pipe(less({ compress: true }))
.pipe(gulp.dest(paths.dest.css));
});
gulp.task('web_css', function() {
gulp.src(paths.source.web_css)
.pipe(plumber())
.pipe(less({ compress: true }))
.pipe(gulp.dest(paths.dest.css));
});
gulp.task('lint', function() {
gulp.src(paths.source.js)
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
gulp.task('watch', function() {
gulp.watch(paths.source.baseJsDir, function() {
sequence('canvas_js', 'web_js', 'lint')
});
gulp.watch(paths.source.css, function() {
sequence('canvas_css', 'web_css')
})
});
gulp.task('zip', function () {
return gulp.src([
'public/' + game_name + '/**/*'
])
.pipe(zip(game_name +'_dist.zip'))
.pipe(gulp.dest('./dist'))
});
gulp.task('build', [
'canvas_js',
'web_js',
'canvas_css',
'web_css',
'rev'
]);
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
var path = require('path');
// Basic Gulp task syntax
gulp.task('hello', function() {
console.log('Hello Martin!');
});
// Development Tasks
// -----------------
// Start browserSync server
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: 'app'
}
})
});
gulp.task('sass', function() {
return gulp.src('app/css/*.+(scss|sass)') // Gets all files ending with .scss in app/scss and children dirs
.pipe(sass()) // Passes it through a gulp-sass
.pipe(gulp.dest('app/css')) // Outputs it in the css folder
.pipe(browserSync.reload({ // Reloading with Browser Sync
stream: true
}));
});
// Watchers
gulp.task('watch', function() {
gulp.watch('app/css/*.+(scss|sass)', ['sass']);
gulp.watch('app/*.html', browserSync.reload);
gulp.watch('app/js/**/*.js', browserSync.reload);
});
// Optimization Tasks
// ------------------
// Optimizing CSS and JavaScript
gulp.task('useref', function() {
return gulp.src('app/*.html')
.pipe(useref())
.pipe(gulpIf('app/js/*.js', uglify()))
.pipe(gulpIf('app/css/*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
// Optimizing Images
gulp.task('images', function() {
return gulp.src('app/img/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true,
})))
.pipe(gulp.dest('dist/images'))
});
// Copying fonts
gulp.task('fonts', function() {
return gulp.src('app/fonts/**/*').pipe(gulp.dest('dist/fonts'))
});
// Cleaning
gulp.task('clean', function() {
return del.sync('dist').then(function(cb) {return cache.clearAll(cb);});
});
gulp.task('clean:dist', function() {
return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});
// Build Sequences
// ---------------
gulp.task('default', function(callback) {
runSequence(['sass', 'browserSync'], 'watch', callback)
});
gulp.task('build', function(callback) {
runSequence('clean:dist', 'sass', ['useref', 'images', 'fonts'], callback)
});
|
(function () {
var Demo = {
init: function () {
this.syntaxHighlight();
this.sticky();
},
syntaxHighlight: function () {
hljs.initHighlighting();
},
sticky: function () {
var $sticky = $('[data-sticky]');
$sticky.sticky({
topSpacing: 10
});
}
};
Demo.init();
})();
|
var Tile = function (type, x, y) {
this.type = type;
this.tint = 0;
this.hover = false;
this.isAllowed = undefined;
this.isAllowedForBeat = undefined;
this.x = x;
this.y = y;
this.graphic = new fabric.Rect({
left: Tile.size * x,
top: Tile.size * y,
fill: type === Tile.TileType.NONPLAYABLE ? Tile.ColorNonplayable : Tile.ColorPlayable,
width: Tile.size,
height: Tile.size,
selectable: false,
obj: this
});
canvas.add(this.graphic);
};
Tile.size = undefined;
Tile.ColorPlayable = "#717070";
Tile.ColorNonplayable = "#d9d9d9";
Tile.ColorAllowed = "#38b321";
Tile.ColorMovingToNow = "#b8c153";
Tile.ColorAllowedForBeat = "#cf3a3a";
Tile.TileType = {
PLAYABLE: 0,
NONPLAYABLE: 1
};
Tile.prototype.setMan = function(man) {
this.man = man;
};
Tile.prototype.clearMan = function() {
this.man = undefined; //TODO null? +RETHINK
};
Tile.prototype.setAsAllowed = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowed, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowed = true;
};
Tile.prototype.setAsAllowedForBeat = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorAllowedForBeat, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowedForBeat = true;
};
Tile.prototype.clearHighlights = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorPlayable, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
this.isAllowed = false;
this.isAllowedForBeat = false;
};
Tile.prototype.setAsMovingToNow = function() {
var graphic = this.graphic;
fabric.util.animateColor(this.graphic.fill, Tile.ColorMovingToNow, colorAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
};
Tile.prototype.isAllowedForMove = function() {
return this.isAllowed || this.isAllowedForBeat;
};
Tile.prototype.onMouseOver = function() {
if (this.isAllowedForMove()) {
var graphic = this.graphic;
fabric.util.animateColor(graphic.fill, //TODO: colorAllowed/this.fill +REFACTOR
Color(graphic.fill).lightenByRatio(0.2).toString(), hoverAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
}
};
Tile.prototype.onMouseOut = function() {
if (this.isAllowedForMove()) {
var graphic = this.graphic;
fabric.util.animateColor(graphic.fill, Color(graphic.fill).darkenByRatio(0.1666).toString(),
hoverAnimationTime, {
onChange: function(val) {
graphic.setFill(val);
canvas.renderAll();
}
});
}
};
Tile.prototype.onMouseDown = function() {
if (this.isAllowedForMove()) {
//move men to selected (this) tile
board.sendMove(board.selectedMan.tile, this);
board.moveSelectedManTo(this);
} else {
//or unselect man, if clicked on empty tile
board.unselect();
}
};
|
define( 'type.Integer', {
// class configuration
alias : 'int integer',
extend : __lib__.type.Number,
// public properties
precision : 0,
// public methods
valid : function( v ) {
return this.parent( v, true ) && Math.floor( v ) === v;
},
// internal methods
init : function() {
var max = this.max, min = this.min;
this.precision = 0;
this.parent( arguments );
// since we want our Types to be instantiated with as much correctness as possible,
// we don't want to cast our max/min as Integers
if ( max !== Number.POSITIVE_INFINITY )
this.max = max;
if ( min !== Number.NEGATIVE_INFINITY )
this.min = min;
},
value : function( v ) {
return Math.round( this.parent( arguments ) );
}
} );
|
var fs = require('fs'),
es = require('event-stream'),
asyncJoin = require('gwm-util').asyncJoin;
module.exports = function(options) {
var type = options.buildType,
configFileName = './config/' + type + '.json',
fileData = {},
successCallback,
errorText,
blocker = asyncJoin(function() {
successCallback && successCallback();
successCallback = true;
});
function fileCallback(key) {
return function(err, data) {
if (err) {
errorText = err;
}
fileData[key] = data;
}
};
function loadFile(filePath, key) {
if (fs.existsSync(filePath)) {
fs.readFile(filePath, {encoding: 'utf-8'}, blocker.newCallback(fileCallback(key)));
}
}
loadFile(configFileName, 'config');
loadFile(__dirname + '/section-header.hbm', 'header');
loadFile(__dirname + '/section-footer.hbm', 'footer');
blocker.complete();
return es.map(function (file, cb) {
function onLoadedFiles() {
if (errorText) {
cb('could not load file: ' + errorText, file);
} else {
options.config = fileData.config;
var handlebars = require('handlebars'),
header = handlebars.compile(fileData.header),
footer = handlebars.compile(fileData.footer)
headerContent = header(options),
footerContent = footer(options);
file.contents = Buffer.concat([new Buffer(headerContent), file.contents, new Buffer(footerContent)]);
cb(null, file);
}
}
// there will only be a single file in this stream so we're using successCallback as a flag if we've fully loaded
if (successCallback) {
onLoadedFiles();
} else {
successCallback = onLoadedFiles;
}
});
};
|
var postData = querystring.stringify({
'value' : '55',
'room_id' : '1'
});
var options = {
hostname: 'localhost',
port: 80,
path: '/temperatures',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
|
'use strict';
/**
* Created by x on 11/23/15.
*/
var path = require('path');
var webpack = require('webpack');
var os = require('os');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config.dev');
var pathToBuild = path.resolve(__dirname, 'www');
var IPv4
for(var i=0;i<os.networkInterfaces().en0.length;i++){
if(os.networkInterfaces().en0[i].family=='IPv4'){
IPv4=os.networkInterfaces().en0[i].address;
}
}
console.log(IPv4)
//import config from './webpack.dev.config';
var open = require('open');
const opts_config = {
port: 8676
}
var compiler = webpack(config);
/***
* publicPath 启动服务的资源路径
*/
var server = new WebpackDevServer(compiler, {
contentBase: path.resolve(__dirname,'www'),
compress: true,
hot: true,
public:IPv4,
publicPath: config.output.publicPath,
open: true,
inline: true,
/* proxy: {
"/": {
target: "http://192.168.1.102:8000",
secure: false
}
}*/
})
server.listen(9090, '0.0.0.0', function (err, result) {
if (err) {
console.log(err);
}
console.log(`Listening at ${IPv4}:9090/index.html`);
open(`http://${IPv4}:9090/index.html`);
}); |
import React from 'react';
import PostImage from '../components/story/PostImage';
import TwoPostImages from '../components/story/TwoPostImages';
import StoryPage from '../components/story/StoryPage';
import StoryTextBlock from '../components/story/StoryTextBlock';
import StoryImages from '../components/story/StoryImages';
import StoryIntro from '../components/story/StoryIntro';
const imgDirPath = "/images/stories/2016-11-20-irina-and-lucian-maternity-photo-session/";
const imgDirPath1 = "stories/2016-11-20-irina-and-lucian-maternity-photo-session";
class IrinaAndLucianMaternityPhotoSessionStory extends React.Component {
constructor() {
super();
}
render() {
return (
<StoryPage logoDirPath={imgDirPath1}
logoPrefix="teaser"
logoNumber="08-2048"
title="Irina & Lucian Maternity Photos"
author="Dan"
location="Charlottenburg Palace, Berlin"
tags="maternity, baby, pregnancy">
<StoryIntro>
Our friends, Lucian and Irina are having a baby. This is such a wonderful moment!
We decided to go together at the Charlottenburg Palace to do a maternity photo session.
We were really lucky we got a wonderful sunny weekend, the last sunny one this autumn,
before all of the leaves have already fallen.
</StoryIntro>
<StoryTextBlock title="The Charlottenburg Palace">
The impressive palace is a great place to take photos and this time is
covered with scaffolding, which somehow gives a symbolic hint to our photo shoot:
"work in progress!" We start our photo session here,
taking advantage of the bright sun. I'm using a polarizer filter here,
to make the colors pop!
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="01" />
<TwoPostImages dirPath={imgDirPath}
number1="02"
number2="03" />
<TwoPostImages dirPath={imgDirPath}
number1="05"
number2="06" />
<PostImage dirPath={imgDirPath} number="07" />
<PostImage dirPath={imgDirPath} number="10" />
<PostImage dirPath={imgDirPath} number="27" />
</StoryImages>
<StoryTextBlock title="The Forest">
The sun coming through the colorful leaves of the autumn gave the perfect light for the next photos.
Using a long lens allowed me to isolate my subjects and bring that great shallow depth of field!
I'll let you observe the authentic joy on Lucian and Irina's faces, brought by this great moment in their lives,
having a baby.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="16" />
<TwoPostImages dirPath={imgDirPath}
number1="13"
number2="15" />
<PostImage dirPath={imgDirPath} number="19" />
<TwoPostImages dirPath={imgDirPath}
number1="20"
number2="21" />
<PostImage dirPath={imgDirPath} number="22" />
<TwoPostImages dirPath={imgDirPath}
number1="23"
number2="24" />
<PostImage dirPath={imgDirPath} number="35" />
</StoryImages>
<StoryTextBlock title="The Lake">
Moving away from "the forest", we chose the nearby lake is our third location.
<br/>
In the next photo, the contrast between the blue lake and Irina's orange
pullover is just amazing.
<br/>
You might already know that the bridge in the Charlottenburg Garden is
one of our <a href="/streets-of-berlin/charlottenburg-bridge-in-autumn.html">favorite
places</a>. Like always, it gave me a really nice opportunity to play
with reflections.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="28" />
<PostImage dirPath={imgDirPath} number="30" />
<PostImage dirPath={imgDirPath} number="31" />
<PostImage dirPath={imgDirPath} number="37" />
<PostImage dirPath={imgDirPath} number="39" />
<PostImage dirPath={imgDirPath} number="42" />
</StoryImages>
<StoryTextBlock title="The Autumn">
The colors of the autumn are just amazing! My favorite photo from this
series is the next one. I call it "The Tree of Life", as there are four
colors spreading from each of the corners, one for each of the seasons.
We have spring and summer to the left, and autumn and winter to the right.
And of course, pregnant Irina in the middle getting support from her dear
husband, Lucian.
</StoryTextBlock>
<StoryImages>
<PostImage dirPath={imgDirPath} number="44" />
<PostImage dirPath={imgDirPath} number="46" />
<PostImage dirPath={imgDirPath} number="48" />
<PostImage dirPath={imgDirPath} number="51" />
<TwoPostImages dirPath={imgDirPath}
number1="52"
number2="53" />
<PostImage dirPath={imgDirPath} number="54" />
<TwoPostImages dirPath={imgDirPath}
number1="55"
number2="56" />
<PostImage dirPath={imgDirPath} number="59" />
<TwoPostImages dirPath={imgDirPath}
number1="60"
number2="61" />
<TwoPostImages dirPath={imgDirPath}
number1="62"
number2="63" />
<PostImage dirPath={imgDirPath} number="64" />
</StoryImages>
</StoryPage>);
}
}
export default IrinaAndLucianMaternityPhotoSessionStory;
|
import{B as t,K as e}from"./index-82df5684.js";export default class extends t{connected(){const{host:t,params:s}=this,{name:o}=s,i=`--nu${o?"-"+o:""}-offset-x`,n=`--nu${o?"-"+o:""}-offset-y`,r=e=>{this._active=!0;const s=t.getBoundingClientRect(),o=e.clientX-s.left,r=e.clientY-s.top,h=o/s.width*2-1,c=r/s.height*2-1;t.style.setProperty(i,String(h)),t.style.setProperty(n,String(c))};this.on("mousemove",r),this.on("mouseover",s=>{r(s),e(t,()=>{this._active&&this.setMod("offset",!0)})}),this.on("mouseout",()=>{this._active=!1,this.setMod("offset",!1),setTimeout(()=>{this._active||(t.style.setProperty(i,"0"),t.style.setProperty(n,"0"))})})}}
|
search_result['3225']=["topic_00000000000007B9.html","ApplicantDetailRequestDto.Notes Property",""]; |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Portal = undefined;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /* Created by meyve on 10.10.17*/
var Portal = exports.Portal = function (_React$Component) {
_inherits(Portal, _React$Component);
function Portal(props) {
_classCallCheck(this, Portal);
var _this = _possibleConstructorReturn(this, (Portal.__proto__ || Object.getPrototypeOf(Portal)).call(this, props));
_this.wrapper = function () {
return _react2.default.createElement(
'div',
{ className: 'react_portal-wrapper',
ref: function ref(wrapper) {
return _this.wrapperElement = wrapper;
} },
_this.props.children
);
};
_this.portalContainer = null;
_this.state = {
isOpened: Boolean(props.isOpened)
};
_this.openPortal = _this.openPortal.bind(_this);
_this.closePortal = _this.closePortal.bind(_this);
_this.handleEscKeyPress = _this.handleEscKeyPress.bind(_this);
_this.handleOutsideClick = _this.handleOutsideClick.bind(_this);
_this.getDefaultDomNode = _this.getDefaultDomNode.bind(_this);
_this.createPortal = _this.createPortal.bind(_this);
return _this;
}
_createClass(Portal, [{
key: 'componentDidMount',
value: function componentDidMount() {
if (this.props.closeOnEsc) {
document.addEventListener('keydown', this.handleEscKeyPress);
}
if (this.props.closeOnOutsideClick) {
document.addEventListener('mouseup', this.handleOutsideClick);
document.addEventListener('touchstart', this.handleOutsideClick);
}
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
if (this.props.hasOwnProperty('isOpened')) {
if (this.props.isOpened !== nextProps.isOpened) {
return nextProps.isOpened ? this.openPortal() : this.closePortal();
}
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.props.closeOnEsc) {
document.removeEventListener('keydown', this.handleEscKeyPress);
}
if (this.props.closeOnOutsideClick) {
document.removeEventListener('mouseup', this.handleOutsideClick);
document.removeEventListener('touchstart', this.handleOutsideClick);
}
}
}, {
key: 'getDefaultDomNode',
value: function getDefaultDomNode() {
var reactContainerId = 'react_portal-container';
this.portalContainer = document.getElementById(reactContainerId);
if (!this.portalContainer) {
this.portalContainer = document.createElement('div');
this.portalContainer.id = reactContainerId;
document.body.appendChild(this.portalContainer);
}
return document.getElementById(reactContainerId);
}
}, {
key: 'openPortal',
value: function openPortal() {
if (this.props.beforeOpen) this.props.beforeOpen();
return this.setState({ isOpened: true }, this.props.onOpen);
}
}, {
key: 'closePortal',
value: function closePortal() {
if (this.props.beforeClose) this.props.beforeClose();
return this.setState({ isOpened: false }, this.props.onClose);
}
}, {
key: 'handleOutsideClick',
value: function handleOutsideClick(event) {
if (!this.state.isOpened) return;
if (!this.wrapperElement || this.wrapperElement.contains(event.target)) {
return;
}
this.closePortal();
}
}, {
key: 'handleEscKeyPress',
value: function handleEscKeyPress(event) {
if (event.keyCode === 27 && this.state.isOpened) {
this.closePortal();
}
}
}, {
key: 'createPortal',
value: function createPortal() {
return _reactDom2.default.createPortal(this.wrapper(), this.portalContainer);
}
}, {
key: 'render',
value: function render() {
var _this2 = this;
if (!this.props.node && !this.portalContainer) this.getDefaultDomNode();
return _react2.default.createElement(
'div',
{ className: 'react_portal-root', ref: function ref(root) {
return _this2.root = root;
} },
this.props.openPortalByClickOnElement && _react2.default.cloneElement(this.props.openPortalByClickOnElement, { onClick: this.openPortal }),
this.state.isOpened && this.createPortal()
);
}
}]);
return Portal;
}(_react2.default.Component);
Portal.propTypes = {
isOpened: _propTypes2.default.bool,
closeOnEsc: _propTypes2.default.bool,
closeOnOutsideClick: _propTypes2.default.bool,
openPortalByClickOnElement: _propTypes2.default.any,
onOpen: _propTypes2.default.func,
beforeOpen: _propTypes2.default.func,
onClose: _propTypes2.default.func,
beforeClose: _propTypes2.default.func
}; |
/* global HTMLImageElement */
/* global HTMLCanvasElement */
/* global SVGElement */
import getOptionsFromElement from "./getOptionsFromElement.js";
import renderers from "../renderers";
import {InvalidElementException} from "../exceptions/exceptions.js";
// Takes an element and returns an object with information about how
// it should be rendered
// This could also return an array with these objects
// {
// element: The element that the renderer should draw on
// renderer: The name of the renderer
// afterRender (optional): If something has to done after the renderer
// completed, calls afterRender (function)
// options (optional): Options that can be defined in the element
// }
function getRenderProperties(element){
// If the element is a string, query select call again
if(typeof element === "string"){
return querySelectedRenderProperties(element);
}
// If element is array. Recursivly call with every object in the array
else if(Array.isArray(element)){
var returnArray = [];
for(let i = 0; i < element.length; i++){
returnArray.push(getRenderProperties(element[i]));
}
return returnArray;
}
// If element, render on canvas and set the uri as src
else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLImageElement){
return newCanvasRenderProperties(element);
}
// If SVG
else if(
(element && element.nodeName && element.nodeName.toLowerCase() === 'svg') ||
(typeof SVGElement !== 'undefined' && element instanceof SVGElement)
){
return {
element: element,
options: getOptionsFromElement(element),
renderer: renderers.SVGRenderer
};
}
// If canvas (in browser)
else if(typeof HTMLCanvasElement !== 'undefined' && element instanceof HTMLCanvasElement){
return {
element: element,
options: getOptionsFromElement(element),
renderer: renderers.CanvasRenderer
};
}
// If canvas (in node)
else if(element && element.getContext){
return {
element: element,
renderer: renderers.CanvasRenderer
};
}
else if(element && typeof element === 'object' && !element.nodeName) {
return {
element: element,
renderer: renderers.ObjectRenderer
};
}
else{
throw new InvalidElementException();
}
}
function querySelectedRenderProperties(string){
var selector = document.querySelectorAll(string);
if(selector.length === 0){
return undefined;
}
else{
let returnArray = [];
for(let i = 0; i < selector.length; i++){
returnArray.push(getRenderProperties(selector[i]));
}
return returnArray;
}
}
function newCanvasRenderProperties(imgElement){
var canvas = document.createElement('canvas');
return {
element: canvas,
options: getOptionsFromElement(imgElement),
renderer: renderers.CanvasRenderer,
afterRender: function(){
imgElement.setAttribute("src", canvas.toDataURL());
}
};
}
export default getRenderProperties;
|
import EVENTS from '../events.js';
import external from '../externalModules.js';
import mouseButtonTool from './mouseButtonTool.js';
import touchTool from './touchTool.js';
import pointInsideBoundingBox from '../util/pointInsideBoundingBox.js';
import toolColors from '../stateManagement/toolColors.js';
import isMouseButtonEnabled from '../util/isMouseButtonEnabled.js';
import drawTextBox from '../util/drawTextBox.js';
import { removeToolState, getToolState } from '../stateManagement/toolState.js';
import { getToolOptions } from '../toolOptions.js';
const toolType = 'textMarker';
// /////// BEGIN ACTIVE TOOL ///////
function createNewMeasurement (mouseEventData) {
const config = textMarker.getConfiguration();
if (!config.current) {
return;
}
// Create the measurement data for this tool with the end handle activated
const measurementData = {
visible: true,
active: true,
text: config.current,
handles: {
end: {
x: mouseEventData.currentPoints.image.x,
y: mouseEventData.currentPoints.image.y,
highlight: true,
active: true,
hasBoundingBox: true
}
}
};
// Create a rectangle representing the image
const imageRect = {
left: 0,
top: 0,
width: mouseEventData.image.width,
height: mouseEventData.image.height
};
// Check if the current handle is outside the image,
// If it is, prevent the handle creation
if (!external.cornerstoneMath.point.insideRect(measurementData.handles.end, imageRect)) {
return;
}
// Update the current marker for the next marker
let currentIndex = config.markers.indexOf(config.current);
if (config.ascending) {
currentIndex += 1;
if (currentIndex >= config.markers.length) {
if (config.loop) {
currentIndex -= config.markers.length;
} else {
currentIndex = -1;
}
}
} else {
currentIndex -= 1;
if (currentIndex < 0) {
if (config.loop) {
currentIndex += config.markers.length;
} else {
currentIndex = -1;
}
}
}
config.current = config.markers[currentIndex];
return measurementData;
}
// /////// END ACTIVE TOOL ///////
// /////// BEGIN IMAGE RENDERING ///////
function pointNearTool (element, data, coords) {
if (!data.handles.end.boundingBox) {
return;
}
const distanceToPoint = external.cornerstoneMath.rect.distanceToPoint(data.handles.end.boundingBox, coords);
const insideBoundingBox = pointInsideBoundingBox(data.handles.end, coords);
return (distanceToPoint < 10) || insideBoundingBox;
}
function onImageRendered (e) {
const eventData = e.detail;
// If we have no toolData for this element, return immediately as there is nothing to do
const toolData = getToolState(eventData.element, toolType);
if (!toolData) {
return;
}
// We have tool data for this element - iterate over each one and draw it
const context = eventData.canvasContext.canvas.getContext('2d');
context.setTransform(1, 0, 0, 1, 0, 0);
const config = textMarker.getConfiguration();
for (let i = 0; i < toolData.data.length; i++) {
const data = toolData.data[i];
let color = toolColors.getToolColor();
if (data.active) {
color = toolColors.getActiveColor();
}
context.save();
if (config && config.shadow) {
context.shadowColor = config.shadowColor || '#000000';
context.shadowOffsetX = config.shadowOffsetX || 1;
context.shadowOffsetY = config.shadowOffsetY || 1;
}
// Draw text
context.fillStyle = color;
const measureText = context.measureText(data.text);
data.textWidth = measureText.width + 10;
const textCoords = external.cornerstone.pixelToCanvas(eventData.element, data.handles.end);
const options = {
centering: {
x: true,
y: true
}
};
data.handles.end.boundingBox = drawTextBox(context, data.text, textCoords.x, textCoords.y - 10, color, options);
context.restore();
}
}
function doubleClickCallback (e) {
const eventData = e.detail;
const cornerstone = external.cornerstone;
const element = eventData.element;
let data;
const options = getToolOptions(toolType, element);
if (!isMouseButtonEnabled(eventData.which, options.mouseButtonMask)) {
return;
}
function doneChangingTextCallback (data, updatedText, deleteTool) {
if (deleteTool === true) {
removeToolState(element, toolType, data);
} else {
data.text = updatedText;
}
data.active = false;
cornerstone.updateImage(element);
element.addEventListener(EVENTS.MOUSE_MOVE, textMarker.mouseMoveCallback);
element.addEventListener(EVENTS.MOUSE_DOWN, textMarker.mouseDownCallback);
element.addEventListener(EVENTS.MOUSE_DOWN_ACTIVATE, textMarker.mouseDownActivateCallback);
element.addEventListener(EVENTS.MOUSE_DOUBLE_CLICK, textMarker.mouseDoubleClickCallback);
}
const config = textMarker.getConfiguration();
const coords = eventData.currentPoints.canvas;
const toolData = getToolState(element, toolType);
// Now check to see if there is a handle we can move
if (!toolData) {
return;
}
for (let i = 0; i < toolData.data.length; i++) {
data = toolData.data[i];
if (pointNearTool(element, data, coords)) {
data.active = true;
cornerstone.updateImage(element);
element.removeEventListener(EVENTS.MOUSE_MOVE, textMarker.mouseMoveCallback);
element.removeEventListener(EVENTS.MOUSE_DOWN, textMarker.mouseDownCallback);
element.removeEventListener(EVENTS.MOUSE_DOWN_ACTIVATE, textMarker.mouseDownActivateCallback);
element.removeEventListener(EVENTS.MOUSE_DOUBLE_CLICK, textMarker.mouseDoubleClickCallback);
// Allow relabelling via a callback
config.changeTextCallback(data, eventData, doneChangingTextCallback);
e.stopImmediatePropagation();
e.preventDefault();
e.stopPropagation();
return;
}
}
e.preventDefault();
e.stopPropagation();
}
function touchPressCallback (e) {
const eventData = e.detail;
const cornerstone = external.cornerstone;
const element = eventData.element;
let data;
function doneChangingTextCallback (data, updatedText, deleteTool) {
if (deleteTool === true) {
removeToolState(element, toolType, data);
} else {
data.text = updatedText;
}
data.active = false;
cornerstone.updateImage(element);
element.addEventListener(EVENTS.TOUCH_DRAG, textMarkerTouch.touchMoveCallback);
element.addEventListener(EVENTS.TOUCH_START_ACTIVE, textMarkerTouch.touchDownActivateCallback);
element.addEventListener(EVENTS.TOUCH_START, textMarkerTouch.touchStartCallback);
element.addEventListener(EVENTS.TAP, textMarkerTouch.tapCallback);
element.addEventListener(EVENTS.TOUCH_PRESS, textMarkerTouch.pressCallback);
}
const config = textMarker.getConfiguration();
const coords = eventData.currentPoints.canvas;
const toolData = getToolState(element, toolType);
// Now check to see if there is a handle we can move
if (!toolData) {
return false;
}
if (eventData.handlePressed) {
eventData.handlePressed.active = true;
cornerstone.updateImage(element);
element.removeEventListener(EVENTS.TOUCH_DRAG, textMarkerTouch.touchMoveCallback);
element.removeEventListener(EVENTS.TOUCH_START_ACTIVE, textMarkerTouch.touchDownActivateCallback);
element.removeEventListener(EVENTS.TOUCH_START, textMarkerTouch.touchStartCallback);
element.removeEventListener(EVENTS.TAP, textMarkerTouch.tapCallback);
element.removeEventListener(EVENTS.TOUCH_PRESS, textMarkerTouch.pressCallback);
// Allow relabelling via a callback
config.changeTextCallback(eventData.handlePressed, eventData, doneChangingTextCallback);
e.stopImmediatePropagation();
e.preventDefault();
e.stopPropagation();
return;
}
for (let i = 0; i < toolData.data.length; i++) {
data = toolData.data[i];
if (pointNearTool(element, data, coords)) {
data.active = true;
cornerstone.updateImage(element);
element.removeEventListener(EVENTS.TOUCH_DRAG, textMarkerTouch.touchMoveCallback);
element.removeEventListener(EVENTS.TOUCH_START_ACTIVE, textMarkerTouch.touchDownActivateCallback);
element.removeEventListener(EVENTS.TOUCH_START, textMarkerTouch.touchStartCallback);
element.removeEventListener(EVENTS.TAP, textMarkerTouch.tapCallback);
element.removeEventListener(EVENTS.TOUCH_PRESS, textMarkerTouch.pressCallback);
// Allow relabelling via a callback
config.changeTextCallback(data, eventData, doneChangingTextCallback);
e.stopImmediatePropagation();
e.preventDefault();
e.stopPropagation();
return;
}
}
e.preventDefault();
e.stopPropagation();
}
const textMarker = mouseButtonTool({
createNewMeasurement,
onImageRendered,
pointNearTool,
toolType,
mouseDoubleClickCallback: doubleClickCallback
});
const textMarkerTouch = touchTool({
createNewMeasurement,
onImageRendered,
pointNearTool,
toolType,
pressCallback: touchPressCallback
});
export {
textMarker,
textMarkerTouch
};
|
import assert from 'assert';
import sinon from 'sinon';
import fs from 'fs';
import stream from 'stream';
import { InsertStream } from '../';
/**
* Transform class to turn our string JSON data into objects.
*/
class TransformToObject extends stream.Transform {
constructor() {
super({objectMode:true});
}
_transform(data, encoding, cb) {
data.split('\n')
.filter(line => line.length)
.forEach(line => this.push(JSON.parse(line)));
cb();
}
}
function getSpies() {
const insertSpy = sinon.spy();
const insertManySpy = sinon.spy();
const collection = {
insert(data, cb) {
insertSpy(data);
cb();
},
insertMany(data, cb) {
insertManySpy(data);
cb();
}
};
return [insertSpy, insertManySpy, collection];
}
function getOption(opts) {
return {
highWaterMark: opts.highWaterMark,
collectionName: 'test-collection',
db: {
collection: function(name, cb) {
cb(opts.err, opts.collection);
}
}
};
}
function createTestStream(highWaterMark, err, cb) {
const [insertSpy, insertManySpy, collection] = getSpies();
const option = getOption({highWaterMark, collection, err});
const stream = fs.createReadStream(`${__dirname}/data.json`, {encoding: 'utf8'})
.pipe(new TransformToObject())
.pipe(new InsertStream(option));
cb(stream, {insertSpy, insertManySpy});
}
export function testSingleWrite(done) {
createTestStream(1, null, (stream, spies) => {
stream.on('finish', () => {
assert.ok(spies.insertSpy.calledThrice);
assert.ok(spies.insertManySpy.notCalled);
done();
});
});
}
export function testBatchWrite(done) {
createTestStream(2, null, (stream, spies) => {
stream.on('finish', () => {
assert.ok(spies.insertSpy.calledOnce);
assert.ok(spies.insertManySpy.calledOnce);
assert.equal(spies.insertManySpy.getCall(0).args[0].length, 2);
done();
});
});
}
export function testError(done) {
createTestStream(1, {}, stream => {
stream.on('error', () => {
assert.ok(true);
done();
});
});
}
|
/*
[Discuz!] (C)2001-2099 Comsenz Inc.
This is NOT a freeware, use is subject to license terms
$Id: forum.js 33082 2013-04-18 11:13:53Z zhengqingpeng $
*/
function saveData(ignoreempty) {
var ignoreempty = isUndefined(ignoreempty) ? 0 : ignoreempty;
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : ($('fastpostform') ? $('fastpostform') : $('postform'));
if(!obj) return;
if(typeof isfirstpost != 'undefined') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
var messageisnull = trim(html2bbcode(editdoc.body.innerHTML)) === '';
} else {
var messageisnull = $('postform').message.value === '';
}
if(isfirstpost && (messageisnull && $('postform').subject.value === '')) {
return;
}
if(!isfirstpost && messageisnull) {
return;
}
}
var data = subject = message = '';
for(var i = 0; i < obj.elements.length; i++) {
var el = obj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden' || el.type == 'select')) && el.name.substr(0, 6) != 'attach') {
var elvalue = el.value;
if(el.name == 'subject') {
subject = trim(elvalue);
} else if(el.name == 'message') {
if(typeof wysiwyg != 'undefined' && wysiwyg == 1) {
elvalue = html2bbcode(editdoc.body.innerHTML);
}
message = trim(elvalue);
}
if((el.type == 'checkbox' || el.type == 'radio') && !el.checked) {
continue;
} else if(el.tagName == 'SELECT') {
elvalue = el.value;
} else if(el.type == 'hidden') {
if(el.id) {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
elvalue = elvalue;
if($(el.id + '_url')) {
elvalue += String.fromCharCode(1) + $(el.id + '_url').value;
}
} else {
continue;
}
} else {
continue;
}
}
if(trim(elvalue)) {
data += el.name + String.fromCharCode(9) + el.tagName + String.fromCharCode(9) + el.type + String.fromCharCode(9) + elvalue + String.fromCharCode(9, 9);
}
}
}
if(!subject && !message && !ignoreempty) {
return;
}
saveUserdata('forum_'+discuz_uid, data);
}
function fastUload() {
appendscript(JSPATH + 'forum_post.js?' + VERHASH);
safescript('forum_post_js', function () { uploadWindow(function (aid, url) {updatefastpostattach(aid, url)}, 'file') }, 100, 50);
}
function switchAdvanceMode(url) {
var obj = $('postform') && (($('fwin_newthread') && $('fwin_newthread').style.display == '') || ($('fwin_reply') && $('fwin_reply').style.display == '')) ? $('postform') : $('fastpostform');
if(obj && obj.message.value != '') {
saveData();
url += (url.indexOf('?') != -1 ? '&' : '?') + 'cedit=yes';
}
location.href = url;
return false;
}
function sidebar_collapse(lang) {
if(lang[0]) {
toggle_collapse('sidebar', null, null, lang);
$('wrap').className = $('wrap').className == 'wrap with_side s_clear' ? 'wrap s_clear' : 'wrap with_side s_clear';
} else {
var collapsed = getcookie('collapse');
collapsed = updatestring(collapsed, 'sidebar', 1);
setcookie('collapse', collapsed, (collapsed ? 2592000 : -2592000));
location.reload();
}
}
function keyPageScroll(e, prev, next, url, page) {
if(loadUserdata('is_blindman')) {
return true;
}
e = e ? e : window.event;
var tagname = BROWSER.ie ? e.srcElement.tagName : e.target.tagName;
if(tagname == 'INPUT' || tagname == 'TEXTAREA') return;
actualCode = e.keyCode ? e.keyCode : e.charCode;
if(next && actualCode == 39) {
window.location = url + '&page=' + (page + 1);
}
if(prev && actualCode == 37) {
window.location = url + '&page=' + (page - 1);
}
}
function announcement() {
var ann = new Object();
ann.anndelay = 3000;ann.annst = 0;ann.annstop = 0;ann.annrowcount = 0;ann.anncount = 0;ann.annlis = $('anc').getElementsByTagName("li");ann.annrows = new Array();
ann.announcementScroll = function () {
if(this.annstop) {this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);return;}
if(!this.annst) {
var lasttop = -1;
for(i = 0;i < this.annlis.length;i++) {
if(lasttop != this.annlis[i].offsetTop) {
if(lasttop == -1) lasttop = 0;
this.annrows[this.annrowcount] = this.annlis[i].offsetTop - lasttop;this.annrowcount++;
}
lasttop = this.annlis[i].offsetTop;
}
if(this.annrows.length == 1) {
$('an').onmouseover = $('an').onmouseout = null;
} else {
this.annrows[this.annrowcount] = this.annrows[1];
$('ancl').innerHTML += $('ancl').innerHTML;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
$('an').onmouseover = function () {ann.annstop = 1;};
$('an').onmouseout = function () {ann.annstop = 0;};
}
this.annrowcount = 1;
return;
}
if(this.annrowcount >= this.annrows.length) {
$('anc').scrollTop = 0;
this.annrowcount = 1;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
} else {
this.anncount = 0;
this.announcementScrollnext(this.annrows[this.annrowcount]);
}
};
ann.announcementScrollnext = function (time) {
$('anc').scrollTop++;
this.anncount++;
if(this.anncount != time) {
this.annst = setTimeout(function () {ann.announcementScrollnext(time);}, 10);
} else {
this.annrowcount++;
this.annst = setTimeout(function () {ann.announcementScroll();}, this.anndelay);
}
};
ann.announcementScroll();
}
function removeindexheats() {
return confirm('You to confirm that this topic should remove it from the hot topic?');
}
function showTypes(id, mod) {
var o = $(id);
if(!o) return false;
var s = o.className;
mod = isUndefined(mod) ? 1 : mod;
var baseh = o.getElementsByTagName('li')[0].offsetHeight * 2;
var tmph = o.offsetHeight;
var lang = ['Expansion', 'Collapse'];
var cls = ['unfold', 'fold'];
if(tmph > baseh) {
var octrl = document.createElement('li');
octrl.className = cls[mod];
octrl.innerHTML = lang[mod];
o.insertBefore(octrl, o.firstChild);
o.className = s + ' cttp';
mod && (o.style.height = 'auto');
octrl.onclick = function () {
if(this.className == cls[0]) {
o.style.height = 'auto';
this.className = cls[1];
this.innerHTML = lang[1];
} else {
o.style.height = '';
this.className = cls[0];
this.innerHTML = lang[0];
}
}
}
}
var postpt = 0;
function fastpostvalidate(theform, noajaxpost) {
if(postpt) {
return false;
}
postpt = 1;
setTimeout(function() {postpt = 0}, 2000);
noajaxpost = !noajaxpost ? 0 : noajaxpost;
s = '';
if(typeof fastpostvalidateextra == 'function') {
var v = fastpostvalidateextra();
if(!v) {
return false;
}
}
if(theform.message.value == '' || theform.subject.value == '') {
s = 'Sorry, you can not enter a title or content';
theform.message.focus();
} else if(mb_strlen(theform.subject.value) > 80) {
s = 'Your title is longer than 80 characters limit';
theform.subject.focus();
}
if(!disablepostctrl && ((postminchars != 0 && mb_strlen(theform.message.value) < postminchars) || (postmaxchars != 0 && mb_strlen(theform.message.value) > postmaxchars))) {
s = 'Not meet the requirements of the length of your posts.\n\nCurrent length: ' + mb_strlen(theform.message.value) + ' ' + 'Byte\nSystem limits: ' + postminchars + ' to ' + postmaxchars + ' Byte';
}
if(s) {
showError(s);
doane();
$('fastpostsubmit').disabled = false;
return false;
}
$('fastpostsubmit').disabled = true;
theform.message.value = theform.message.value.replace(/([^>=\]"'\/]|^)((((https?|ftp):\/\/)|www\.)([\w\-]+\.)*[\w\-\u4e00-\u9fa5]+\.([\.a-zA-Z0-9]+|\u4E2D\u56FD|\u7F51\u7EDC|\u516C\u53F8)((\?|\/|:)+[\w\.\/=\?%\-&~`@':+!]*)+\.(jpg|gif|png|bmp))/ig, '$1[img]$2[/img]');
theform.message.value = parseurl(theform.message.value);
if(!noajaxpost) {
ajaxpost('fastpostform', 'fastpostreturn', 'fastpostreturn', 'onerror', $('fastpostsubmit'));
return false;
} else {
return true;
}
}
function updatefastpostattach(aid, url) {
ajaxget('forum.php?mod=ajax&action=attachlist&posttime=' + $('posttime').value + (!fid ? '' : '&fid=' + fid), 'attachlist');
$('attach_tblheader').style.display = '';
}
function succeedhandle_fastnewpost(locationhref, message, param) {
location.href = locationhref;
}
function errorhandle_fastnewpost() {
$('fastpostsubmit').disabled = false;
}
function atarget(obj) {
obj.target = getcookie('atarget') > 0 ? '_blank' : '';
}
function setatarget(v) {
$('atarget').className = 'y atarget_' + v;
$('atarget').onclick = function() {setatarget(v == 1 ? -1 : 1);};
setcookie('atarget', v, 2592000);
}
function loadData(quiet, formobj) {
var evalevent = function (obj) {
var script = obj.parentNode.innerHTML;
var re = /onclick="(.+?)["|>]/ig;
var matches = re.exec(script);
if(matches != null) {
matches[1] = matches[1].replace(/this\./ig, 'obj.');
eval(matches[1]);
}
};
var data = '';
data = loadUserdata('forum_'+discuz_uid);
var formobj = !formobj ? $('postform') : formobj;
if(in_array((data = trim(data)), ['', 'null', 'false', null, false])) {
if(!quiet) {
showDialog('No data can be restored!', 'info');
}
return;
}
if(!quiet && !confirm('This action will overwrite the current content of the post, You sure you want to recover data?')) {
return;
}
var data = data.split(/\x09\x09/);
for(var i = 0; i < formobj.elements.length; i++) {
var el = formobj.elements[i];
if(el.name != '' && (el.tagName == 'SELECT' || el.tagName == 'TEXTAREA' || el.tagName == 'INPUT' && (el.type == 'text' || el.type == 'checkbox' || el.type == 'radio' || el.type == 'hidden'))) {
for(var j = 0; j < data.length; j++) {
var ele = data[j].split(/\x09/);
if(ele[0] == el.name) {
elvalue = !isUndefined(ele[3]) ? ele[3] : '';
if(ele[1] == 'INPUT') {
if(ele[2] == 'text') {
el.value = elvalue;
} else if((ele[2] == 'checkbox' || ele[2] == 'radio') && ele[3] == el.value) {
el.checked = true;
evalevent(el);
} else if(ele[2] == 'hidden') {
eval('var check = typeof ' + el.id + '_upload == \'function\'');
if(check) {
var v = elvalue.split(/\x01/);
el.value = v[0];
if(el.value) {
if($(el.id + '_url') && v[1]) {
$(el.id + '_url').value = v[1];
}
eval(el.id + '_upload(\'' + v[0] + '\', \'' + v[1] + '\')');
if($('unused' + v[0])) {
var attachtype = $('unused' + v[0]).parentNode.parentNode.parentNode.parentNode.id.substr(11);
$('unused' + v[0]).parentNode.parentNode.outerHTML = '';
$('unusednum_' + attachtype).innerHTML = parseInt($('unusednum_' + attachtype).innerHTML) - 1;
if($('unusednum_' + attachtype).innerHTML == 0 && $('attachnotice_' + attachtype)) {
$('attachnotice_' + attachtype).style.display = 'none';
}
}
}
}
}
} else if(ele[1] == 'TEXTAREA') {
if(ele[0] == 'message') {
if(!wysiwyg) {
textobj.value = elvalue;
} else {
editdoc.body.innerHTML = bbcode2html(elvalue);
}
} else {
el.value = elvalue;
}
} else if(ele[1] == 'SELECT') {
if($(el.id + '_ctrl_menu')) {
var lis = $(el.id + '_ctrl_menu').getElementsByTagName('li');
for(var k = 0; k < lis.length; k++) {
if(ele[3] == lis[k].k_value) {
lis[k].onclick();
break;
}
}
} else {
for(var k = 0; k < el.options.length; k++) {
if(ele[3] == el.options[k].value) {
el.options[k].selected = true;
break;
}
}
}
}
break;
}
}
}
}
if($('rstnotice')) {
$('rstnotice').style.display = 'none';
}
extraCheckall();
}
var checkForumcount = 0, checkForumtimeout = 30000, checkForumnew_handle;
function checkForumnew(fid, lasttime) {
var timeout = checkForumtimeout;
var x = new Ajax();
x.get('forum.php?mod=ajax&action=forumchecknew&fid=' + fid + '&time=' + lasttime + '&inajax=yes', function(s){
if(s > 0) {
var table = $('separatorline').parentNode;
if(!isUndefined(checkForumnew_handle)) {
clearTimeout(checkForumnew_handle);
}
removetbodyrow(table, 'forumnewshow');
var colspan = table.getElementsByTagName('tbody')[0].rows[0].children.length;
var checknew = {'tid':'', 'thread':{'common':{'className':'', 'val':'<a href="javascript:void(0);" onclick="ajaxget(\'forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=1&inajax=yes\', \'forumnew\');">New topic Reply, Click to view', 'colspan': colspan }}};
addtbodyrow(table, ['tbody'], ['forumnewshow'], 'separatorline', checknew);
} else {
if(checkForumcount < 50) {
if(checkForumcount > 0) {
var multiple = Math.ceil(50 / checkForumcount);
if(multiple < 5) {
timeout = checkForumtimeout * (5 - multiple + 1);
}
}
checkForumnew_handle = setTimeout(function () {checkForumnew(fid, lasttime);}, timeout);
}
}
checkForumcount++;
});
}
function checkForumnew_btn(fid) {
if(isUndefined(fid)) return;
ajaxget('forum.php?mod=ajax&action=forumchecknew&fid=' + fid+ '&time='+lasttime+'&uncheck=2&inajax=yes', 'forumnew', 'ajaxwaitid');
lasttime = parseInt(Date.parse(new Date()) / 1000);
}
function addtbodyrow (table, insertID, changename, separatorid, jsonval) {
if(isUndefined(table) || isUndefined(insertID[0])) {
return;
}
var insertobj = document.createElement(insertID[0]);
var thread = jsonval.thread;
var tid = !isUndefined(jsonval.tid) ? jsonval.tid : '' ;
if(!isUndefined(changename[1])) {
removetbodyrow(table, changename[1] + tid);
}
insertobj.id = changename[0] + tid;
if(!isUndefined(insertID[1])) {
insertobj.className = insertID[1];
}
if($(separatorid)) {
table.insertBefore(insertobj, $(separatorid).nextSibling);
} else {
table.insertBefore(insertobj, table.firstChild);
}
var newTH = insertobj.insertRow(-1);
for(var value in thread) {
if(value != 0) {
var cell = newTH.insertCell(-1);
if(isUndefined(thread[value]['val'])) {
cell.innerHTML = thread[value];
} else {
cell.innerHTML = thread[value]['val'];
}
if(!isUndefined(thread[value]['className'])) {
cell.className = thread[value]['className'];
}
if(!isUndefined(thread[value]['colspan'])) {
cell.colSpan = thread[value]['colspan'];
}
}
}
if(!isUndefined(insertID[2])) {
_attachEvent(insertobj, insertID[2], function() {insertobj.className = '';});
}
}
function removetbodyrow(from, objid) {
if(!isUndefined(from) && $(objid)) {
from.removeChild($(objid));
}
}
function leftside(id) {
$(id).className = $(id).className == 'a' ? '' : 'a';
if(id == 'lf_fav') {
setcookie('leftsidefav', $(id).className == 'a' ? 0 : 1, 2592000);
}
}
var DTimers = new Array();
var DItemIDs = new Array();
var DTimers_exists = false;
function settimer(timer, itemid) {
if(timer && itemid) {
DTimers.push(timer);
DItemIDs.push(itemid);
}
if(!DTimers_exists) {
setTimeout("showtime()", 1000);
DTimers_exists = true;
}
}
function showtime() {
for(i=0; i<=DTimers.length; i++) {
if(DItemIDs[i]) {
if(DTimers[i] == 0) {
$(DItemIDs[i]).innerHTML = 'Has ended';
DItemIDs[i] = '';
continue;
}
var timestr = '';
var timer_day = Math.floor(DTimers[i] / 86400);
var timer_hour = Math.floor((DTimers[i] % 86400) / 3600);
var timer_minute = Math.floor(((DTimers[i] % 86400) % 3600) / 60);
var timer_second = (((DTimers[i] % 86400) % 3600) % 60);
if(timer_day > 0) {
timestr += timer_day + 'Day';
}
if(timer_hour > 0) {
timestr += timer_hour + 'Hour'
}
if(timer_minute > 0) {
timestr += timer_minute + 'Min.'
}
if(timer_second > 0) {
timestr += timer_second + 'Sec.'
}
DTimers[i] = DTimers[i] - 1;
$(DItemIDs[i]).innerHTML = timestr;
}
}
setTimeout("showtime()", 1000);
}
function fixed_top_nv(eleid, disbind) {
this.nv = eleid && $(eleid) || $('nv');
this.openflag = this.nv && BROWSER.ie != 6;
this.nvdata = {};
this.init = function (disattachevent) {
if(this.openflag) {
if(!disattachevent) {
var obj = this;
_attachEvent(window, 'resize', function(){obj.reset();obj.init(1);obj.run();});
var switchwidth = $('switchwidth');
if(switchwidth) {
_attachEvent(switchwidth, 'click', function(){obj.reset();obj.openflag=false;});
}
}
var next = this.nv;
try {
while((next = next.nextSibling).nodeType != 1 || next.style.display === 'none') {}
this.nvdata.next = next;
this.nvdata.height = parseInt(this.nv.offsetHeight, 10);
this.nvdata.width = parseInt(this.nv.offsetWidth, 10);
this.nvdata.left = this.nv.getBoundingClientRect().left - document.documentElement.clientLeft;
this.nvdata.position = this.nv.style.position;
this.nvdata.opacity = this.nv.style.opacity;
} catch (e) {
this.nvdata.next = null;
}
}
};
this.run = function () {
var fixedheight = 0;
if(this.openflag && this.nvdata.next){
var nvnexttop = document.body.scrollTop || document.documentElement.scrollTop;
var dofixed = nvnexttop !== 0 && document.documentElement.clientHeight >= 15 && this.nvdata.next.getBoundingClientRect().top - this.nvdata.height < 0;
if(dofixed) {
if(this.nv.style.position != 'fixed') {
this.nv.style.borderLeftWidth = '0';
this.nv.style.borderRightWidth = '0';
this.nv.style.height = this.nvdata.height + 'px';
this.nv.style.width = this.nvdata.width + 'px';
this.nv.style.top = '0';
this.nv.style.left = this.nvdata.left + 'px';
this.nv.style.position = 'fixed';
this.nv.style.zIndex = '199';
this.nv.style.opacity = 0.85;
}
} else {
if(this.nv.style.position != this.nvdata.position) {
this.reset();
}
}
if(this.nv.style.position == 'fixed') {
fixedheight = this.nvdata.height;
}
}
return fixedheight;
};
this.reset = function () {
if(this.nv) {
this.nv.style.position = this.nvdata.position;
this.nv.style.borderLeftWidth = '';
this.nv.style.borderRightWidth = '';
this.nv.style.height = '';
this.nv.style.width = '';
this.nv.style.opacity = this.nvdata.opacity;
}
};
if(!disbind && this.openflag) {
this.init();
_attachEvent(window, 'scroll', this.run);
}
}
var previewTbody = null, previewTid = null, previewDiv = null;
function previewThread(tid, tbody) {
if(!$('threadPreviewTR_'+tid)) {
appendscript(JSPATH + 'forum_viewthread.js?' + VERHASH);
newTr = document.createElement('tr');
newTr.id = 'threadPreviewTR_'+tid;
newTr.className = 'threadpre';
$(tbody).appendChild(newTr);
newTd = document.createElement('td');
newTd.colSpan = listcolspan;
newTd.className = 'threadpretd';
newTr.appendChild(newTd);
newTr.style.display = 'none';
previewTbody = tbody;
previewTid = tid;
if(BROWSER.ie) {
previewDiv = document.createElement('div');
previewDiv.id = 'threadPreview_'+tid;
previewDiv.style.id = 'none';
var x = Ajax();
x.get('forum.php?mod=viewthread&tid='+tid+'&inajax=1&from=preview', function(ret) {
var evaled = false;
if(ret.indexOf('ajaxerror') != -1) {
evalscript(ret);
evaled = true;
}
previewDiv.innerHTML = ret;
newTd.appendChild(previewDiv);
if(!evaled) evalscript(ret);
newTr.style.display = '';
});
} else {
newTd.innerHTML += '<div id="threadPreview_'+tid+'"></div>';
ajaxget('forum.php?mod=viewthread&tid='+tid+'&from=preview', 'threadPreview_'+tid, null, null, null, function() {newTr.style.display = '';});
}
} else {
$(tbody).removeChild($('threadPreviewTR_'+tid));
previewTbody = previewTid = null;
}
}
function hideStickThread(tid) {
var pre = 'stickthread_';
var tids = (new Function("return ("+(loadUserdata('sticktids') || '[]')+")"))();
var format = function (data) {
var str = '{';
for (var i in data) {
if(data[i] instanceof Array) {
str += i + ':' + '[';
for (var j = data[i].length - 1; j >= 0; j--) {
str += data[i][j] + ',';
};
str = str.substr(0, str.length -1);
str += '],';
}
}
str = str.substr(0, str.length -1);
str += '}';
return str;
};
if(!tid) {
if(tids.length > 0) {
for (var i = tids.length - 1; i >= 0; i--) {
var ele = $(pre+tids[i]);
if(ele) {
ele.parentNode.removeChild(ele);
}
};
}
} else {
var eletbody = $(pre+tid);
if(eletbody) {
eletbody.parentNode.removeChild(eletbody);
tids.push(tid);
saveUserdata('sticktids', '['+tids.join(',')+']');
}
}
var clearstickthread = $('clearstickthread');
if(clearstickthread) {
if(tids.length > 0) {
$('clearstickthread').style.display = '';
} else {
$('clearstickthread').style.display = 'none';
}
}
var separatorline = $('separatorline');
if(separatorline) {
try {
if(typeof separatorline.previousElementSibling === 'undefined') {
var findele = separatorline.previousSibling;
while(findele && findele.nodeType != 1){
findele = findele.previousSibling;
}
if(findele === null) {
separatorline.parentNode.removeChild(separatorline);
}
} else {
if(separatorline.previousElementSibling === null) {
separatorline.parentNode.removeChild(separatorline);
}
}
} catch(e) {
}
}
}
function viewhot() {
var obj = $('hottime');
window.location.href = "forum.php?mod=forumdisplay&filter=hot&fid="+obj.getAttribute('fid')+"&time="+obj.value;
}
function clearStickThread () {
saveUserdata('sticktids', '[]');
location.reload();
} |
/*jslint node: true */
'use strict';
var npm = require('npm');
module.exports = Npm;
function Npm (callback) {
var conf = {
jobs: 1
};
npm.load(conf, callback);
}
Npm.prototype.search = function (searchTerms, callback) {
npm.commands.search(searchTerms, true, callback);
};
Npm.prototype.view = function (name, callback) {
npm.commands.view([name], callback);
};
|
import { EmailTemplate } from 'email-templates'
import Promise from 'bluebird'
const sendgrid = require('sendgrid')(process.env.SENDGRID_MAILER_KEY)
const sendEmail = Promise.promisify(sendgrid.send, { context: sendgrid })
const DEVELOPMENT = process.env.NODE_ENV === 'development'
const sanitize = DEVELOPMENT ? require('sanitize-filename') : null
import path from 'path'
import fs from 'fs'
export function getTemplate(templateName) {
const templatePath = path.join(__dirname, '../', 'templates', templateName)
return new EmailTemplate(templatePath, {
juiceOptions: {
preserveMediaQueries: true,
preserveImportant: true,
removeStyleTags: true
}
})
}
export async function send({ template, sendgridGroupId, data, emailSettings, to, subject, replyto }) { // eslint-disable-line max-len
try {
const result = await template.render(data)
if (DEVELOPMENT) {
fs.writeFileSync(
`${__dirname}/.temp/${sanitize(`test-${subject}-${to}.html`)}`, result.html)
}
const params = {
from: emailSettings.from,
fromname: emailSettings.fromName,
replyto: replyto || emailSettings.from,
to: [to],
subject: `${subject}`,
html: result.html
}
const sendgridEmail = new sendgrid.Email(params)
sendgridEmail.setASMGroupID(sendgridGroupId)
const email = await sendEmail(sendgridEmail)
return { email }
} catch (err) {
console.log('send error: ', err)
return { err }
}
}
|
/* globals __dirname */
'use strict';
var autoprefixer = require('autoprefixer-core');
var Webpack = require('webpack');
var HtmlWebpack = require('html-webpack-plugin');
var path = require('path');
var npmPath = path.resolve(__dirname, 'node_modules');
var config = {
sassOptions : (
'?outputStyle=nested&includePaths[]=' + npmPath
)
};
module.exports = {
entry: [
'./demo/bootstrap.js',
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:9001'
],
module: {
loaders: [
{
test : /\.(jsx|js)$/,
loaders : ['babel', 'react-hot'],
exclude : /node_modules/
},
{
test : /\.scss$/,
loader : 'style!css!postcss!sass' + config.sassOptions,
include : /scss/
},
{
test : /\.css$/,
loader : 'style-loader!css-loader'
}
]
},
output: {
filename : 'demo.js',
path : path.resolve(__dirname, 'demo-build'),
publicPath : '/'
},
resolve : {
extensions : ['', '.js', '.jsx', '.css', '.scss']
},
plugins: [
new HtmlWebpack({
template : './demo/index.html'
}),
new Webpack.HotModuleReplacementPlugin(),
new Webpack.optimize.OccurenceOrderPlugin()
],
postcss : function() {
return [autoprefixer];
}
};
|
MD.Keyboard = function(){
const keys = {
"v": { name: "Select tool", cb: ()=> state.set("canvasMode", "select") },
"q": { name: "Freehand tool", cb: ()=> state.set("canvasMode", "fhpath") },
"l": { name: "Line tool", cb: ()=> state.set("canvasMode", "fhplineath")},
"r": { name: "Rectangle tool", cb: ()=> state.set("canvasMode", "rect")},
"o": { name: "Ellipse tool", cb: ()=> state.set("canvasMode", "ellipse")},
"s": { name: "Shape tool", cb: ()=> state.set("canvasMode", "shapelib")},
"p": { name: "Path tool", cb: ()=> state.set("canvasMode", "path")},
"t": { name: "Text tool", cb: ()=> state.set("canvasMode", "text")},
"z": { name: "Zoom tool", cb: ()=> state.set("canvasMode", "zoom")},
"e": { name: "Eyedropper tool", cb: ()=> state.set("canvasMode", "eyedropper")},
"x": { name: "Focus fill/stroke", cb: ()=> editor.focusPaint()},
"shift_x": { name: "Switch fill/stroke", cb: ()=> editor.switchPaint()},
"alt": { name: false, cb: ()=> $("#workarea").toggleClass("out", state.get("canvasMode") === "zoom" )},
"cmd_s": { name: "Save SVG File", cb: ()=> editor.save()},
"cmd_z": { name: "Undo", cb: ()=> editor.undo()},
"cmd_y": { name: "Redo", cb: ()=> editor.redo()},
"cmd_shift_z": { name: "Redo", cb: ()=> editor.redo()},
"cmd_c": { name: "Copy", cb: ()=> editor.copySelected()},
"cmd_x": { name: "Cut", cb: ()=> editor.cutSelected()},
"cmd_v": { name: "Paste", cb: ()=> editor.pasteSelected()},
"cmd_d": { name: "Duplicate", cb: ()=> editor.duplicateSelected()},
"cmd_u": { name: "View source", cb: ()=> editor.source()},
"cmd_a": { name: "Select All", cb: ()=> svgCanvas.selectAllInCurrentLayer()},
"cmd_b": { name: "Set bold text", cb: ()=> editor.text.setBold()},
"cmd_i": { name: "Set italic text", cb: ()=> editor.text.setItalic()},
"cmd_g": { name: "Group selected", cb: ()=> editor.groupSelected()},
"cmd_shift_g": { name: "Ungroup", cb: ()=> editor.ungroupSelected()},
"cmd_o": { name: "Open SVG File", cb: ()=> editor.import.open()},
"cmd_k": { name: "Place image", cb: ()=> editor.import.place()},
"backspace": { name: "Delete", cb: ()=> editor.deleteSelected()},
"delete": { name: "Delete", cb: ()=> editor.deleteSelected()},
"ctrl_arrowleft": { name: "Rotate -1deg", cb: ()=> editor.rotateSelected(0,1)},
"ctrl_arrowright": { name: "Rotate +1deg", cb: ()=> editor.rotateSelected(1,1)},
"ctrl_shift_arrowleft": { name: "Rotate -5deg", cb: ()=> editor.rotateSelected(0,5)},
"ctrl_shift_arrowright": { name: "Rotate +5deg ", cb: ()=> editor.rotateSelected(1,5)},
"shift_o": { name: "Next item", cb: ()=> svgCanvas.cycleElement(0)},
"shift_p": { name: "Prev item", cb: ()=> svgCanvas.cycleElement(1)},
"shift_r": { name: "Show/hide rulers", cb: ()=> editor.rulers.toggleRulers()},
"cmd_+": { name: "Zoom in", cb: ()=> editor.zoom.multiply(1.5)},
"cmd_-": { name: "Zoom out", cb: ()=> editor.zoom.multiply(0.75)},
"cmd_=": { name: "Actual size", cb: ()=> editor.zoom.reset()},
"arrowleft": { name: "Nudge left", cb: ()=> editor.moveSelected(-1,0)},
"arrowright": { name: "Nudge right", cb: ()=> editor.moveSelected(1,0)},
"arrowup": { name: "Nudge up", cb: ()=> editor.moveSelected(0,-1)},
"arrowdown": { name: "Nudge down", cb: ()=> editor.moveSelected(0,1)},
"shift_arrowleft": {name: "Jump left", cb: () => editor.moveSelected(state.get("canvasSnapStep") * -1, 0)},
"shift_arrowright": {name: "Jump right", cb: () => editor.moveSelected(state.get("canvasSnapStep") * 1, 0)},
"shift_arrowup": {name: "Jump up", cb: () => editor.moveSelected(0, state.get("canvasSnapStep") * -1)},
"shift_arrowdown": {name: "Jump down", cb: () => editor.moveSelected(0, state.get("canvasSnapStep") * 1)},
"cmd_arrowup":{ name: "Bring forward", cb: () => editor.moveUpSelected()},
"cmd_arrowdown":{ name: "Send backward", cb: () => editor.moveDownSelected()},
"cmd_shift_arrowup":{ name: "Bring to front", cb: () => editor.moveToTopSelected()},
"cmd_shift_arrowdown":{ name: "Send to back", cb: () => editor.moveToBottomSelected()},
"escape": { name: false, cb: ()=> editor.escapeMode()},
"enter": { name: false, cb: ()=> editor.escapeMode()},
" ": { name: "Pan canvas", cb: (e)=> editor.pan.startPan(e)},
};
document.addEventListener("keydown", function(e){
const exceptions = $(":focus").length || $("#color_picker").is(":visible");
if (exceptions) return false;
const modKey = !svgedit.browser.isMac() ? "ctrlKey" : "metaKey";
const cmd = e[modKey] ? "cmd_" : "";
const shift = e.shiftKey ? "shift_" : "";
const key = cmd + shift + e.key.toLowerCase();
const canvasMode = state.get("canvasMode");
const modalIsOpen = Object.values(editor.modal).filter((modal) => {
const isHidden = modal.el.classList.contains("hidden");
if (!isHidden && key === "cmd_enter") modal.confirm();
if (!isHidden && key === "escape") modal.close();
return !isHidden;
}).length;
// keyboard shortcut exists for app
if (!modalIsOpen && keys[key]) {
e.preventDefault();
keys[key].cb();
}
});
document.addEventListener("keyup", function(e){
if ($("#color_picker").is(":visible")) return e;
const canvasMode = state.get("canvasMode");
const key = e.key.toLowerCase();
const keys = {
"alt": ()=> $("#workarea").removeClass("out"),
" ": ()=> editor.pan.stopPan(),
}
if (keys[key]) {
e.preventDefault();
keys[key]();
}
})
// modal shortcuts
const shortcutEl = document.getElementById("shortcuts");
const docFrag = document.createDocumentFragment();
for (const key in keys) {
const name = keys[key].name;
if (!name) continue;
const shortcut = document.createElement("div");
shortcut.classList.add("shortcut")
const chords = key.split("_");
const shortcutKeys = document.createElement("div");
shortcutKeys.classList.add("shortcut-keys")
chords.forEach(key => {
const shortcutKey = document.createElement("div");
shortcutKey.classList.add("shortcut-key");
if (key === "arrowright") key = "→";
if (key === "arrowleft") key = "←";
if (key === "arrowup") key = "↑";
if (key === "arrowdown") key = "↓";
if (key === " ") key = "SPACEBAR";
if (key === "shift") key = "⇧";
if (key === "cmd") key = svgedit.browser.isMac() ? "⌘" : "Ctrl";
shortcutKey.textContent = key;
shortcutKeys.appendChild(shortcutKey);
shortcut.appendChild(shortcutKeys);
});
const shortcutName = document.createElement("div");
shortcutName.classList.add("shortcut-name");
shortcutName.textContent = name;
shortcutKeys.appendChild(shortcutName);
docFrag.appendChild(shortcutKeys);
}
shortcutEl.appendChild(docFrag);
} |
const path = require('path')
const sassTrue = require('sass-true')
const sassFile = path.join(__dirname, 'flex-columns.test.scss')
sassTrue.runSass({ file: sassFile }, describe, test)
|
// React app
import React from 'react'
import {render} from 'react-dom'
import App from './components/base_layout/App.jsx'
// Redux state manager
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import reducers from './state_manager/reducers'
// Electron IPC communication events
import ipcRendererEvents from './ipc_layer/ipcRendererEvents'
//////////////////////////
/// React Application ////
//////////////////////////
export let store = createStore(reducers)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
)
//////////////////////////////
/// IPC with main process ////
//////////////////////////////
ipcRendererEvents(store)
///////////////////
/// Workarounds ///
///////////////////
/* The chunk below will be executed after the react app is rendered */
import {resizer} from './components/base_layout/layout.css'
let nav = document.querySelector('nav')
let node = document.querySelector('.'+resizer)
let startX, startWidth
const initDrag = e => {
startX = e.clientX
startWidth = parseInt(window.getComputedStyle(nav).width)
window.addEventListener('mousemove', doDrag, false)
window.addEventListener('mouseup', stopDrag, false)
}
const doDrag = e => {
const newWidth = (startWidth + e.clientX - startX)
nav.style.width = (newWidth < 200 ? 200 : (newWidth > 400 ? 400: newWidth) ) + 'px'
}
const stopDrag = e => {
window.removeEventListener('mousemove', doDrag, false)
window.removeEventListener('mouseup', stopDrag, false)
}
node.addEventListener('mousedown', initDrag, false)
|
var mongoose = require('mongoose'),
bcrypt = require('bcrypt'),
userSchema = mongoose.Schema({
fullName: { type: String },
email: { type: String, required: true, unique: true, lowercase: true },
password: { type: String, required: true },
user_avatar: { type: String, default: 'http://s3.amazonaws.com/37assets/svn/765-default-avatar.png' },
registered_on: { type: Date, default: Date.now }
});
userSchema.pre('save', function(next) {
var user = this;
if (!user.isModified('password')) {
return next();
}
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(user.password, salt, function(err, hash) {
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(password, done) {
bcrypt.compare(password, this.password, function(err, isMatch) {
done(err, isMatch);
});
};
module.exports = mongoose.model('User', userSchema, 'users');
|
Ext.define('sisprod.view.MobileUnit.UpdateMobileUnit', {
extend: 'sisprod.view.base.BaseDataWindow',
alias: 'widget.updateMobileUnit',
messages: {
basicDataTitle: 'Basic Data',
componentsTitle: 'Allocation of Components',
featuresTitle: 'Additional Features',
equipmentNameLabel: 'Equipment Name',
equipmentModelLabel: 'Model',
equipmentCodeLabel: 'Code',
serialNumberLabel: 'Serial Number',
equipmentTypeLabel: 'Equipment Type',
markLabel: 'Mark',
equipmentConditionLabel: 'Condition',
locationLabel: 'Location',
locationEmptyText: 'Type a Location',
equipmentEmptyText: 'Type a Equipment',
addButtonText: 'Add',
removeButtonText: 'Remove',
supplierLabel: 'Owner',
isOwn: 'Is Own',
firstSelectALot: 'Select a Lot First',
lot: 'Lot'
},
title: 'Update Mobile Unit',
modal: true,
width: 550,
initComponent: function() {
var me = this;
me.formOptions = {
bodyPadding: 2,
items: [
{
xtype: 'hiddenfield',
name: 'idMobileUnit',
id: 'idMobileUnit'
},
{
xtype: 'hiddenfield',
name: 'idEquipment',
id: 'idEquipment'
},
{
xtype: 'tabpanel',
height: 350,
items: [
{
id: 'basicData',
xtype: 'panel',
layout: 'anchor',
title: me.messages.basicDataTitle,
autoScroll: true,
margin: '5 5 0 5',
items: [
{
xtype: 'textfield',
grow: true,
name: 'equipmentName',
fieldLabel: me.messages.equipmentNameLabel,
fieldStyle: {
textTransform: 'uppercase'
},
labelWidth: 120,
anchor: '100%',
allowBlank: false,
maxLength: 200
},
{
xtype: 'textfield',
grow: true,
name: 'equipmentModel',
fieldLabel: me.messages.equipmentModelLabel,
fieldStyle: {
textTransform: 'uppercase'
},
labelWidth: 120,
anchor: '100%',
maxLength: 100
},
{
xtype: 'textfield',
grow: true,
name: 'equipmentCode',
fieldLabel: me.messages.equipmentCodeLabel,
fieldStyle: {
textTransform: 'uppercase'
},
labelWidth: 120,
anchor: '100%',
maxLength: 200
},
{
xtype: 'textfield',
grow: true,
name: 'serialNumber',
fieldLabel: me.messages.serialNumberLabel,
fieldStyle: {
textTransform: 'uppercase'
},
labelWidth: 120,
anchor: '100%',
maxLength: 50
},
{
xtype: 'combobox',
fieldLabel: me.messages.supplierLabel,
store: Ext.create('sisprod.store.SupplierAll').load(),
displayField: 'entityName',
valueField: 'idSupplier',
name: 'cboSupplier',
id: 'cboSupplier',
labelWidth: 120,
forceSelection: true,
allowBlank: true,
editable: false,
anchor: '100%'
},
{
xtype: 'combofieldcontainer',
showButtons: false,
comboBoxOptions: {
xtype: 'combobox',
anchor: '100%',
fieldLabel: me.messages.equipmentTypeLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.EquipmentTypeAll').load(),
displayField: 'equipmentTypeName',
valueField: 'idEquipmentType',
name: 'idEquipmentType',
id: 'idEquipmentType',
allowBlank: false,
forceSelection: true,
editable: false,
width: 455,
readOnly: true
}
},
{
xtype: 'combofieldcontainer',
comboBoxOptions: {
xtype: 'combobox',
width: 455,
fieldLabel: me.messages.markLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.MarkAll').load(),
displayField: 'markName',
valueField: 'idMark',
name: 'idMark',
id: 'idMark',
forceSelection: true,
editable: false
}
},
{
xtype: 'combobox',
grow: true,
name: 'idLot',
id: 'idLot',
labelWidth: 120,
store: Ext.create('sisprod.store.LotAll'),
fieldLabel: me.messages.lot,
displayField: 'lotName',
valueField: 'idLot',
allowBlank: false,
margins: '0 5 0 0',
forceSelection: true,
editable: false,
flex: 1
},
{
xtype: 'sensitivecombocontainer',
anchor: '100%',
sensitiveComboBoxOptions: {
labelWidth: 120,
width: 455,
name: 'idLocation',
id: 'idLocation',
fieldLabel: me.messages.locationLabel,
store: Ext.create('sisprod.store.LocationTemplate'),
emptyText: me.messages.locationEmptyText,
forceSelection: true,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{locationName}', '</tpl>'),
valueField: 'idLocation',
listConfig: {
getInnerTpl: function() {
return "{locationName}";
}
}
}
},
{
xtype: 'combofieldcontainer',
comboBoxOptions: {
xtype: 'combobox',
anchor: '100%',
fieldLabel: me.messages.equipmentConditionLabel,
labelWidth: 120,
store: Ext.create('sisprod.store.EquipmentConditionAll').load(),
displayField: 'equipmentConditionName',
valueField: 'idEquipmentCondition',
name: 'idEquipmentCondition',
id: 'idEquipmentCondition',
forceSelection: true,
editable: false,
width: 455
}
},
{
xtype: 'checkbox',
grow: true,
name: 'own',
id: 'own',
fieldLabel: me.messages.isOwn,
labelWidth: 120,
anchor: '100%'
}
]
},
{
xtype: 'panel',
layout: 'anchor',
autoScroll: true,
title: me.messages.componentsTitle,
items: [
{
xtype: 'gridpanel',
id: 'componentsGrid',
store: Ext.StoreManager.lookup('componentStoreGrid'),
collapsible: true,
columns: [
{
text: 'Id',
dataIndex: 'idEquipment',
flex: 1,
hidden: true
},
{
text: me.messages.equipmentNameLabel,
dataIndex: 'equipmentName',
flex: 10
}
],
dockedItems: [{
xtype: 'toolbar',
dock: 'top',
items: ['->',
{
xtype: 'sensitivecombo',
width: 350,
name: 'cboComponent',
fieldLabel: '',
store: Ext.create('sisprod.store.EquipmentNotAsignedTemplate'),
emptyText: me.messages.equipmentEmptyText,
id: 'cboComponent',
forceSelection: true,
displayTpl: Ext.create('Ext.XTemplate',
'<tpl for=".">', '{equipmentName}', '</tpl>'),
valueField: 'idEquipment',
listConfig: {
getInnerTpl: function() {
return "{equipmentName} - {equipmentTypeName}";
}
}
},
{
iconCls: 'add',
id: 'savecomponent',
action: 'savecomponent',
text: me.messages.addButtonText
},
{
iconCls: 'remove',
id: 'removecomponent',
text: me.messages.removeButtonText
}
]
}]
}
]
},
{
xtype: 'panel',
id: 'featuresPanel',
layout: 'anchor',
autoScroll: true,
title: me.messages.featuresTitle,
width: '100%',
height: 250,
border: true,
bodyPadding: 5,
fieldDefaults: {
labelWidth: 250
},
items: [
]
}
]
}
]
};
me.callParent(arguments);
}
}); |
// 对字符串头尾进行空格字符的去除、包括全角半角空格、Tab等,返回一个字符串
function trim(str) {
var regex1 = /^\s*/;
var regex2 = /\s*$/;
return (str.replace(regex1, "")).replace(regex2, "");
}
// 给一个element绑定一个针对event事件的响应,响应函数为listener
function addEvent(element, event, listener, isCorrect) {
if (element.addEventListener) {
element.addEventListener(event, listener, isCorrect);
}
else if (element.attachEvent) {
element.attachEvent("on" + event, listener);
}
else {
element["on" + event] = listener;
}
}
var validate = {
//将name中的所有中文字符替换(1中文字符长度=2英文字符长度)
nameVali: function (str) {
var chineseRegex = /[\u4E00-\uFA29]|[\uE7C7-\uE7F3]/g;
var lenRegex = /^.{4,16}$/;
if (str.length == 0) {
return false;
}
else if (!lenRegex.test(str)) {
return false
}
else {
return true;
}
},
//密码验证
passwordVali: function (str) {
return (str.length >= 8 && str.length<= 20);
},
//再次输入的密码验证
repasswordVali: function (str, id) {
var password = document.querySelector("#" + id).value;
return (str === password);
},
// 判断是否为邮箱地址
// 第一部分:由字母、数字、下划线、短线“-”、点号“.”组成,
// 第二部分:为一个域名,域名由字母、数字、短线“-”、域名后缀组成,
// 而域名后缀一般为.xxx或.xxx.xx,一区的域名后缀一般为2-4位,如cn,com,net,现在域名有的也会大于4位
emailVali: function (str) {
var regex = /^([\w-*\.*]+)@([\w-]+)((\.[\w-]{2,4}){1,2})$/;
return regex.test(str);
},
// 判断是否为手机号
telephoneVali: function (str) {
var regex = /^1[0-9]{10}$/;
return regex.test(str);
},
allVali: function () {
var inputArray = document.querySelectorAll("input");
var count = 0;
for (var cur = 0; cur < inputArray.length; cur++) {
if (inputArray[cur].className == "correctInput") {
count++;
}
}
return (count === inputArray.length);
}
}
function formFactory(data) {
var whole = {
settings: {
label: data.label,
name: data.name,
type: data.type,
validator: data.validator,
rules: data.rules,
success: data.success,
empty: data.empty,
fail: data.fail
},
generateInput: function(type) {
var that = this;
var container = document.getElementById("father");
var span = document.createElement("span");
span.innerText = that.settings.label;
var p = document.createElement("p");
p.className = "status";
var label = document.createElement("label");
var input = document.createElement("input");
input.name = that.settings.name;
input.type = that.settings.type;
input.id = that.settings.name;
addEvent(input, "focus", function() {
input.className = "inputFocus";
p.innerText = that.settings.rules;
}, true);
addEvent(input, "blur", function() {
var verify = "";
if (type == "single") {
verify = that.settings.validator(this.value);
}
else if (type == "verify") {
verify = that.settings.validator(this.value) && (this.value.length != 0);
}
if (verify) {
input.className = "correctInput";
p.className = "status correctSta";
p.innerText = that.settings.success;
}
else {
input.className = "wrongInput";
p.className = "status wrongSta";
if (this.value.length == 0) {
p.innerText = that.settings.empty;
}
else p.innerText = that.settings.fail;
}
}, true);
container.appendChild(label);
label.appendChild(span);
label.appendChild(input);
container.appendChild(p);
},
generateButton: function() {
var that = this;
var container = document.getElementById("father");
var button = document.createElement("button");
button.innerHTML = that.settings.label;
addEvent(button, "click", function() {
if (that.settings.validator()) {
alert("提交成功!");
}
else alert("提交失败!");
}, false);
container.appendChild(button);
},
init: function() {
var that = this;
//判断类型
switch (that.settings.name) {
case 'name':
that.generateInput('single');
break;
case 'password':
that.generateInput('single');
break;
case 'repassword':
that.generateInput('verify');
break;
case 'email':
that.generateInput('single');
break;
case 'telephone':
that.generateInput('single');
break;
case 'submit':
that.generateButton();
break;
}
}
}
return whole.init();
}
window.onload = function() {
for (var i = 0; i < data.length; i++) {
formFactory(data[i]);
}
} |
import * as React from 'react';
import {px2rem} from '@bizfe/biz-mobile-ui/build/util/util';
import {
Button,
LinearProgress,
CircleProgress
} from '@bizfe/biz-mobile-ui';
const styles = {
progress: {
width: '90%',
margin: '20px auto 0',
},
}
export default class Progress extends React.Component {
constructor(...args) {
super(...args);
this.state = {progress: 10}
}
changeProgress(value) {
if (value < 0) {
value = 0;
} else if (value > 100) {
value = 100;
}
this.setState({progress: value});
}
render() {
return (
<div>
<CircleProgress value={25}/>
<CircleProgress value={90} color="red"/>
<CircleProgress value={this.state.progress} size={px2rem(100)} linecap="round"/>
<LinearProgress style={styles.progress}/>
<LinearProgress style={Object.assign({},styles.progress,{height: px2rem(15)})}
color="#8E24AA"
fillColor="#FFF"/>
<LinearProgress style={styles.progress} mode="determinate" value={this.state.progress}/>
<Button style={Object.assign({},styles.progress, {display: 'block'})}
onTouchTap={()=>this.changeProgress(this.state.progress + 20)}
size="small">+ 20</Button>
<Button style={Object.assign({},styles.progress, {display: 'block'})}
onTouchTap={()=>this.changeProgress(this.state.progress - 10)}
size="small">- 10</Button>
</div>
);
}
}
|
/* Copyright (C) 2012 Kory Nunn
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
NOTE:
This code is formatted for run-speed and to assist compilers.
This might make it harder to read at times, but the code's intention should be transparent. */
// IIFE our function
((exporter) => {
// Define our function and its properties
// These strings are used multiple times, so this makes things smaller once compiled
const func = 'function',
isNodeString = 'isNode',
d = document,
// Helper functions used throughout the script
isType = (object, type) => typeof object === type,
// Recursively appends children to given element. As a text node if not already an element
appendChild = (element, child) => {
if (child !== null) {
if (Array.isArray(child)) { // Support (deeply) nested child elements
child.map(subChild => appendChild(element, subChild));
} else {
if (!crel[isNodeString](child)) {
child = d.createTextNode(child);
}
element.appendChild(child);
}
}
};
//
function crel (element, settings) {
// Define all used variables / shortcuts here, to make things smaller once compiled
let args = arguments, // Note: assigned to a variable to assist compilers.
index = 1,
key,
attribute;
// If first argument is an element, use it as is, otherwise treat it as a tagname
element = crel.isElement(element) ? element : d.createElement(element);
// Check if second argument is a settings object
if (isType(settings, 'object') && !crel[isNodeString](settings) && !Array.isArray(settings)) {
// Don't treat settings as a child
index++;
// Go through settings / attributes object, if it exists
for (key in settings) {
// Store the attribute into a variable, before we potentially modify the key
attribute = settings[key];
// Get mapped key / function, if one exists
key = crel.attrMap[key] || key;
// Note: We want to prioritise mapping over properties
if (isType(key, func)) {
key(element, attribute);
} else if (isType(attribute, func)) { // ex. onClick property
element[key] = attribute;
} else {
// Set the element attribute
element.setAttribute(key, attribute);
}
}
}
// Loop through all arguments, if any, and append them to our element if they're not `null`
for (; index < args.length; index++) {
appendChild(element, args[index]);
}
return element;
}
// Used for mapping attribute keys to supported versions in bad browsers, or to custom functionality
crel.attrMap = {};
crel.isElement = object => object instanceof Element;
crel[isNodeString] = node => node instanceof Node;
// Expose proxy interface
crel.proxy = new Proxy(crel, {
get: (target, key) => {
!(key in crel) && (crel[key] = crel.bind(null, key));
return crel[key];
}
});
// Export crel
exporter(crel, func);
})((product, func) => {
if (typeof exports === 'object') {
// Export for Browserify / CommonJS format
module.exports = product;
} else if (typeof define === func && define.amd) {
// Export for RequireJS / AMD format
define(() => product);
} else {
// Export as a 'global' function
this.crel = product;
}
});
|
const fs = require('fs');
const dns = require('dns');
const argv = require('yargs').argv;
const Seismometer = require('./seismometer');
const Communicator = require('./communicator');
function assertOnline() {
return new Promise((fulfill, reject) => {
dns.resolve('www.google.com', err => {
if (err) {
reject(new Error('Not online. Cannot resolve www.google.com'));
} else {
fulfill();
}
});
});
}
function main() {
if (argv.help) {
console.log('usage: npm run [--port /dev/port]');
process.exit(0);
}
if (argv.port) {
if (!fs.existsSync(argv.port)) {
console.error(`Port "${argv.port}" does not exist.`);
process.exit(1);
}
}
const communicator = new Communicator();
const seismometer = new Seismometer();
seismometer.watch();
assertOnline()
.then(() => communicator.connect(argv.port))
.then(() => {
console.log('Connected to', communicator.port.path);
seismometer.on('quake', info => {
console.log(`Quake! At ${info.date} with a magnitude of ${info.magnitude}`);
communicator.send(info);
});
console.log('Watching for quakes...');
})
.catch(err => {
console.error(err);
process.exit(1);
});
}
main();
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import IncredibleOffersContainer from './IncredibleOffers/IncredibleOfferContainer';
export default (
<Route path="/" component={App}>
<IndexRoute component={IncredibleOffersContainer} />
<Route path="/special-offers" component={IncredibleOffersContainer} />
<Route path="/special-offers/:filter" component={IncredibleOffersContainer} />
</Route>
);
|
console.style('<css="color: rgba(0, 0, 0, 0.6);font-size: 30px;background-color: rgb(110, 110, 110);text-shadow: rgba(255, 255, 255, 0.2) 3px 2px 3px; padding-left:10px;">Welcome to Ivy Theme</css>'); |
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
var port = normalizePort(process.env.PORT || '3000');
module.exports = {
port: port,
db: 'mongodb://'+process.env.IP+'/nexus'
}; |
(function() {
'use strict';
angular
.module('lcRegistration')
.config(["$routeProvider", function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "/client/app/regForm/regForm.html",
controller: "registrationController"
}).when("/hello", {
templateUrl: "/client/app/hello/hello.html",
controller: "helloController"
}).otherwise({
redirectTo: "/"
});
} ]);
})(); |
export{C as CreateGameReducer,G as Game}from"./reducer-b8b81041.js";import"immer";export{I as InitializeGame}from"./initialize-2ee3d05a.js";export{A as Async}from"./base-c99f5be2.js"; |
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
// Simple REST server.
var users = [];
app.post('/user', function(req, res) {
users[req.body.name] = req.body;
res.send({ error: false });
});
app.get('/user/:name', function(req, res) {
var user = users[req.params.name];
if (user) {
res.send({ error: false, data: user });
} else {
res.send({ error: true });
}
});
app.put('/user/:name', function(req, res) {
var user = users[req.params.name];
if (user) {
res.send({ error: false });
user.weight = req.body.weight;
} else {
res.send({ error: true });
}
});
app.del('/user/:name', function(req, res) {
var user = users[req.params.name];
if (user) {
delete users[req.params.name];
res.send({ error: false });
} else {
res.send({ error: true });
}
});
// XMLJSON file
app.get('/xhr-json.js', function(req, res) {
res.sendfile('xhr-json.js', { root: __dirname + '/..' });
});
// Mocha/Chai files
var mochaDir = path.dirname(require.resolve('mocha'));
var chaiDir = path.dirname(require.resolve('chai'));
app.get('/mocha.css', function(req, res) {
res.sendfile('mocha.css', { root: mochaDir });
});
app.get('/mocha.js', function(req, res) {
res.sendfile('mocha.js', { root: mochaDir });
});
app.get('/chai.js', function(req, res) {
res.sendfile('chai.js', { root: chaiDir });
});
http.createServer(app).listen(4444, function() {
console.log('Express server listening.');
}); |
'use strict';
function getBetterUpgradeMessage(foundVersion) {
let version = (foundVersion && foundVersion[1]) ? `(${foundVersion[1]}) ` : '';
return `A new version of Ghost Core ${version}is available! Hot Damn. \
<a href="http://support.ghost.org/how-to-upgrade/" target="_blank">Click here</a> \
to learn more on upgrading Ghost Core.`;
}
/**
* Simple timeout + attempt based function that checks to see if Ghost Core has an update available,
* and replaces the notification text with something a little more specific.';
*/
function upgradeNotification(attempts = 100) {
const elements = document.querySelectorAll('aside.gh-alerts .gh-alert-content');
elements.forEach((element) => {
let foundVersion = /Ghost (\d\.\d\.\d) is available/g.exec(element.innerText);
element.innerHTML = getBetterUpgradeMessage(foundVersion);
});
if (elements.length === 0 && attempts > 0) {
setTimeout(() => upgradeNotification(attempts - 1), 50);
}
}
/**
* Init
*/
document.addEventListener('DOMContentLoaded', () => setTimeout(upgradeNotification, 50)); |
'use strict'
var PassThrough = require('stream').PassThrough
var statistics = require('vfile-statistics')
var fileSetPipeline = require('./file-set-pipeline')
module.exports = run
// Run the file set pipeline once.
// `callback` is invoked with a fatal error, or with a status code (`0` on
// success, `1` on failure).
function run(options, callback) {
var settings = {}
var stdin = new PassThrough()
var tree
var detectConfig
var hasConfig
var detectIgnore
var hasIgnore
try {
stdin = process.stdin
} catch (_) {
// Obscure bug in Node (seen on Windows).
// See: <https://github.com/nodejs/node/blob/f856234/lib/internal/process/stdio.js#L82>,
// <https://github.com/AtomLinter/linter-markdown/pull/85>.
}
if (!callback) {
throw new Error('Missing `callback`')
}
if (!options || !options.processor) {
return next(new Error('Missing `processor`'))
}
// Processor.
settings.processor = options.processor
// Path to run as.
settings.cwd = options.cwd || process.cwd()
// Input.
settings.files = options.files || []
settings.extensions = (options.extensions || []).map(extension)
settings.filePath = options.filePath || null
settings.streamIn = options.streamIn || stdin
// Output.
settings.streamOut = options.streamOut || process.stdout
settings.streamError = options.streamError || process.stderr
settings.alwaysStringify = options.alwaysStringify
settings.output = options.output
settings.out = options.out
// Null overwrites config settings, `undefined` does not.
if (settings.output === null || settings.output === undefined) {
settings.output = undefined
}
if (settings.output && settings.out) {
return next(new Error('Cannot accept both `output` and `out`'))
}
// Process phase management.
tree = options.tree || false
settings.treeIn = options.treeIn
settings.treeOut = options.treeOut
settings.inspect = options.inspect
if (settings.treeIn === null || settings.treeIn === undefined) {
settings.treeIn = tree
}
if (settings.treeOut === null || settings.treeOut === undefined) {
settings.treeOut = tree
}
// Configuration.
detectConfig = options.detectConfig
hasConfig = Boolean(options.rcName || options.packageField)
if (detectConfig && !hasConfig) {
return next(
new Error('Missing `rcName` or `packageField` with `detectConfig`')
)
}
settings.detectConfig =
detectConfig === null || detectConfig === undefined
? hasConfig
: detectConfig
settings.rcName = options.rcName || null
settings.rcPath = options.rcPath || null
settings.packageField = options.packageField || null
settings.settings = options.settings || {}
settings.configTransform = options.configTransform
settings.defaultConfig = options.defaultConfig
// Ignore.
detectIgnore = options.detectIgnore
hasIgnore = Boolean(options.ignoreName)
settings.detectIgnore =
detectIgnore === null || detectIgnore === undefined
? hasIgnore
: detectIgnore
settings.ignoreName = options.ignoreName || null
settings.ignorePath = options.ignorePath || null
settings.ignorePatterns = options.ignorePatterns || []
settings.silentlyIgnore = Boolean(options.silentlyIgnore)
if (detectIgnore && !hasIgnore) {
return next(new Error('Missing `ignoreName` with `detectIgnore`'))
}
// Plugins.
settings.pluginPrefix = options.pluginPrefix || null
settings.plugins = options.plugins || {}
// Reporting.
settings.reporter = options.reporter || null
settings.reporterOptions = options.reporterOptions || null
settings.color = options.color || false
settings.silent = options.silent || false
settings.quiet = options.quiet || false
settings.frail = options.frail || false
// Process.
fileSetPipeline.run({files: options.files || []}, settings, next)
function next(error, context) {
var stats = statistics((context || {}).files)
var failed = Boolean(
settings.frail ? stats.fatal || stats.warn : stats.fatal
)
if (error) {
callback(error)
} else {
callback(null, failed ? 1 : 0, context)
}
}
}
function extension(ext) {
return ext.charAt(0) === '.' ? ext : '.' + ext
}
|
'use strict';
import {should as should_} from 'chai';
const should = should_();
import {spy, stub} from 'sinon';
import {setCanvas, canvas, context} from '../src/canvas';
import draw from '../src/draw';
// import {Sprite} from '../../../script/src/sprite';
describe('draw.js', () => {
let ctx;
before(() => {
setCanvas('game');
// Reset settings
draw.setFont({reset: true});
draw.setLine({reset: true});
draw.setShadow({reset: true});
ctx = {
fillRect: stub(context, 'fillRect'),
strokeRect: stub(context, 'strokeRect'),
clearRect: stub(context, 'clearRect'),
fillText: stub(context, 'fillText'),
strokeText: stub(context, 'strokeText'),
measureText: spy(context, 'measureText'),
beginPath: spy(context, 'beginPath'),
moveTo: spy(context, 'moveTo'),
lineTo: spy(context, 'lineTo'),
arc: spy(context, 'arc'),
arcTo: spy(context, 'arcTo'),
rect: spy(context, 'rect'),
quadraticCurveTo: spy(context, 'quadraticCurveTo'),
bezierCurveTo: spy(context, 'bezierCurveTo'),
closePath: spy(context, 'closePath'),
fill: stub(context, 'fill'),
stroke: stub(context, 'stroke'),
clip: stub(context, 'clip'),
drawImage: stub(context, 'drawImage'),
getImageData: spy(context, 'getImageData'),
putImageData: stub(context, 'putImageData'),
createImageData: spy(context, 'createImageData'),
save: stub(context, 'save'),
scale: stub(context, 'scale'),
rotate: stub(context, 'rotate'),
translate: stub(context, 'translate'),
transform: stub(context, 'transform'),
restore: stub(context, 'restore'),
};
});
afterEach(() => {
for(let i in ctx) {
ctx[i].reset();
}
});
after(() => {
for(let i in ctx) {
ctx[i].restore();
}
});
describe('rect(x, y, w, h, stroke = false)', () => {
it('should fill a rectangle with a falsey 5th parameter', () => {
draw.rect(0, 0, 100, 100);
ctx.fillRect.should.have.been.calledWith(0, 0, 100, 100);
ctx.strokeRect.should.have.not.been.called;
});
it('should stroke a rectangle with a truthy 5th parameter', () => {
draw.rect(0, 0, 100, 100, true);
ctx.fillRect.should.have.not.been.called;
ctx.strokeRect.should.have.been.calledWith(0, 0, 100, 100);
});
});
describe('point(x, y)', () => {
it('should fill a 1x1 px rectangle', () => {
draw.point(0, 0);
ctx.fillRect.should.have.been.calledWith(0, 0, 1, 1);
});
});
describe('circle(x, y, r, stroke = false)', () => {
it('should fill a circle with a falsey 5th parameter', () => {
draw.circle(0, 0, 5);
ctx.beginPath.should.have.been.calledOnce;
ctx.arc.should.have.been.calledWith(0, 0, 5);
ctx.fill.should.have.been.calledOnce;
ctx.stroke.should.have.not.been.called;
});
it('should stroke a circle with a truthy 5th parameter', () => {
draw.circle(0, 0, 5, true);
ctx.beginPath.should.have.been.calledOnce;
ctx.arc.should.have.been.calledWith(0, 0, 5);
ctx.fill.should.have.not.been.called;
ctx.stroke.should.have.been.calledOnce;
});
});
describe('text(str, x, y, stroke = false)', () => {
it('should fill the text with a falsey 5th parameter', () => {
draw.text('Hello World', 0, 0);
ctx.fillText.should.have.been.calledWith('Hello World', 0, 0);
ctx.strokeText.should.have.not.been.called;
});
it('should stroke the text with a truthy 5th parameter', () => {
draw.text('Hello World', 0, 0, true);
ctx.fillText.should.have.not.been.called;
ctx.strokeText.should.have.been.calledWith('Hello World', 0, 0);
});
});
describe('textWidth(text)', () => {
it('should not draw any text', () => {
draw.textWidth('Hello World');
ctx.measureText.should.have.been.calledWith('Hello World');
ctx.fillText.should.have.not.been.called;
ctx.strokeText.should.have.not.been.called;
});
it('return a number (the width of the text)', () => {
draw.text('Hello World');
draw.textWidth('Hello World').should.be.a('number');
});
});
describe('image(img[, sx, sy, swidth, sheight], x, y[, w, h])', () => {
it('should draw the image', () => {
const img = new Image(40, 50);
draw.image({img: img, swidth: 32, sheight: 32, x: 0, y: 0, width: 32, height: 32});
draw.image({img: img, sx: 10, sy: 10, x: 0, y: 0, width: 32, height: 32});
draw.image(img, 20, 20);
ctx.drawImage.should.have.been.calledThrice;
ctx.drawImage.should.have.been.calledWith(img, 0, 0, 32, 32, 0, 0, 32, 32);
ctx.drawImage.should.have.been.calledWith(img, 10, 10, 32, 32, 0, 0, 32, 32);
ctx.drawImage.should.have.been.calledWith(img, 20, 20);
});
});
describe('pixelData(pd, x, y)', () => {
it('should be an alias for pd.draw(x, y)', () => {
const pd = new draw.PixelData(32, 32);
const fn = stub(pd, 'draw');
draw.pixelData(pd, 32, 32);
fn.should.have.been.calledWith(32, 32);
fn.restore();
});
});
describe('clear()', () => {
it('should clear the entire canvas', () => {
draw.clear();
ctx.clearRect.should.have.been.calledWith(0, 0, canvas.width(), canvas.height());
});
});
describe('setColor(color)', () => {
it('should set both stroke and fill colors', () => {
draw.setColor('#ff0000');
context.fillStyle.should.equal('#ff0000');
context.strokeStyle.should.equal('#ff0000');
draw.setColor('#0000ff');
context.fillStyle.should.equal('#0000ff');
context.strokeStyle.should.equal('#0000ff');
});
it('should accept numbers and convert them to strings', () => {
draw.setColor(0xff0000);
context.fillStyle.should.equal('#ff0000');
context.strokeStyle.should.equal('#ff0000');
draw.setColor(0x0000ff);
context.fillStyle.should.equal('#0000ff');
context.strokeStyle.should.equal('#0000ff');
});
});
describe('setAlpha(alpha)', () => {
it('should set the global alpha', () => {
draw.setAlpha(0.5);
context.globalAlpha.should.equal(0.5);
draw.setAlpha(1);
context.globalAlpha.should.equal(1);
});
it('should constrain alpha to range [0, 1]', () => {
draw.setAlpha(-2);
context.globalAlpha.should.equal(0);
draw.setAlpha(3);
context.globalAlpha.should.equal(1);
});
});
describe('setComposite(composite)', () => {
it('should set the global composite operation', () => {
draw.setComposite('source-atop');
context.globalCompositeOperation.should.equal('source-atop');
draw.setComposite('source-over');
context.globalCompositeOperation.should.equal('source-over');
});
});
describe('setLine({cap, join, width, miter, reset = false})', () => {
it('should set the appropriate line properties', () => {
draw.setLine({cap: 'round'});
context.lineCap.should.equal('round');
draw.setLine({width: 15});
context.lineCap.should.equal('round');
context.lineWidth.should.equal(15);
draw.setLine({join: 'bevel'});
context.lineCap.should.equal('round');
context.lineWidth.should.equal(15);
context.lineJoin.should.equal('bevel');
draw.setLine({miter: 15});
context.lineCap.should.equal('round');
context.lineWidth.should.equal(15);
context.lineJoin.should.equal('bevel');
context.miterLimit.should.equal(15);
draw.setLine({cap: 'butt', width: 1, join: 'miter', miter: 10});
context.lineCap.should.equal('butt');
context.lineWidth.should.equal(1);
context.lineJoin.should.equal('miter');
context.miterLimit.should.equal(10);
});
it('should ignore other values if reset is true', () => {
draw.setLine({reset: true, cap: 'round', width: 10});
context.lineCap.should.equal('butt');
context.lineWidth.should.equal(1);
context.lineJoin.should.equal('miter');
context.miterLimit.should.equal(10);
});
});
describe('setShadow({x, y, blur, color, reset = false})', () => {
it('should set the appropriate shadow properties', () => {
draw.setShadow({x: 5});
context.shadowOffsetX.should.equal(5);
draw.setShadow({y: 10});
context.shadowOffsetX.should.equal(5);
context.shadowOffsetY.should.equal(10);
draw.setShadow({blur: 15});
context.shadowOffsetX.should.equal(5);
context.shadowOffsetY.should.equal(10);
context.shadowBlur.should.equal(15);
draw.setShadow({color: 0xff0000});
context.shadowOffsetX.should.equal(5);
context.shadowOffsetY.should.equal(10);
context.shadowBlur.should.equal(15);
context.shadowColor.should.equal('#ff0000');
draw.setShadow({color: '#0000ff'});
context.shadowOffsetX.should.equal(5);
context.shadowOffsetY.should.equal(10);
context.shadowBlur.should.equal(15);
context.shadowColor.should.equal('#0000ff');
draw.setShadow({x: 0, y: 0, blur: 0, color: '#000000'});
context.shadowOffsetX.should.equal(0);
context.shadowOffsetY.should.equal(0);
context.shadowBlur.should.equal(0);
context.shadowColor.should.equal('#000000');
});
it('should ignore other values if reset is passed', () => {
draw.setShadow({x: 5, y: 5, blur: 3, color: '#00FF00', reset: true});
context.shadowOffsetX.should.equal(0);
context.shadowOffsetY.should.equal(0);
context.shadowBlur.should.equal(0);
context.shadowColor.should.equal('#000000');
});
});
describe('setFont({family, size, align, baseline, reset = false})', () => {
it('should set the appropriate font properties', () => {
draw.setFont({size: 15});
context.font.should.equal('15px sans-serif');
draw.setFont({family: 'serif'});
context.font.should.equal('15px serif');
draw.setFont({align: 'center'});
context.font.should.equal('15px serif');
context.textAlign.should.equal('center');
draw.setFont({baseline: 'top'});
context.font.should.equal('15px serif');
context.textAlign.should.equal('center');
context.textBaseline.should.equal('top');
draw.setFont({family: 'sans-serif', size: 10, align: 'start', baseline: 'alphabetic'});
context.font.should.equal('10px sans-serif');
context.textAlign.should.equal('start');
context.textBaseline.should.equal('alphabetic');
});
it('should ignore other values if reset is passed', () => {
draw.setFont({family: 'serif', size: 15, align: 'top', baseline: 'middle', reset: true});
context.font.should.equal('10px sans-serif');
context.textAlign.should.equal('start');
context.textBaseline.should.equal('alphabetic');
});
});
describe('transformed({scale: {x: 1, y: 1}, rotate, translate: {x: 0, y: 0}, transform: [1, 0, 0, 1, 0, 0]}, ...todo)', () => {
it('should context.save() at the beginning, context.restore() at the end, and other functions inbetween', () => {
const cb = spy();
draw.transformed({scale: {x: 2, y: 2}, rotate: 50, translate: {x: 15, y: 30}, transform: [1, 0, 0, 1, 0, 0]}, cb);
ctx.save.should.have.been.calledBefore(ctx.scale);
ctx.scale.should.have.been.calledBefore(ctx.rotate);
ctx.rotate.should.have.been.calledBefore(ctx.translate);
ctx.translate.should.have.been.calledBefore(ctx.transform);
ctx.transform.should.have.been.calledBefore(cb);
cb.should.have.been.calledOnce;
ctx.restore.should.have.been.calledAfter(cb);
});
it('should call all functions passed in order', () => {
const cbs = [spy(), spy(), spy()];
draw.transformed({}, ...cbs);
cbs[0].should.have.been.calledOnce;
cbs[0].should.have.been.calledBefore(cbs[1]);
cbs[1].should.have.been.calledOnce;
cbs[1].should.have.been.calledBefore(cbs[2]);
cbs[2].should.have.been.calledOnce;
});
});
describe('Path', () => {
it('should be constructed with new Path()', () => {
new draw.Path().should.be.an.instanceof(draw.Path);
(() => draw.Path()).should.throw(TypeError);
ctx.beginPath.should.not.have.been.called;
});
describe('#length', () => {
it('should return the number of actions in the stack', () => {
new draw.Path().move().line().length.should.equal(2);
});
it('should not include the initial beginPath call', () => {
new draw.Path().length.should.equal(0);
});
});
describe('#move(x, y)', () => {
it('should add context.moveTo(x, y) to the stack', () => {
const p = new draw.Path().move(32, 32);
p.length.should.equal(1);
p.stroke();
ctx.moveTo.should.have.been.calledWith(32, 32);
});
it('should not call context.moveTo(x, y)', () => {
new draw.Path().move(32, 32);
ctx.moveTo.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().move(32, 32).move(16, 16)).should.not.throw();
});
});
describe('#line(x, y)', () => {
it('should add context.lineTo(x, y) to the stack', () => {
const p = new draw.Path().line(32, 32);
p.length.should.equal(1);
p.stroke();
ctx.lineTo.should.have.been.calledWith(32, 32);
});
it('should not call context.lineTo(x, y)', () => {
new draw.Path().line(32, 32);
ctx.lineTo.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().line(32, 32).line(16, 16)).should.not.throw();
});
});
describe('#rect(x, y, w, h)', () => {
it('should add context.rect(x, y, w, h) to the stack', () => {
const p = new draw.Path().rect(16, 16, 32, 32);
p.length.should.equal(1);
p.stroke();
ctx.rect.should.have.been.calledWith(16, 16, 32, 32);
});
it('should not call context.rect(x, y)', () => {
new draw.Path().rect(32, 32, 16, 16);
ctx.rect.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().rect(16, 16, 32, 32).rect(32, 32, 16, 16)).should.not.throw();
});
});
describe('#arc(x, y, r, start, end[, ccw])', () => {
it('should add context.arc(x, y, r, start, end[, ccw]) to the stack', () => {
const p = new draw.Path().arc(32, 32, 32, 0, Math.PI, false);
p.length.should.equal(1);
p.stroke();
ctx.arc.should.have.been.calledWith(32, 32, 32, 0, Math.PI, false);
});
it('should not call context.arc(x, y, r, start, end[, ccw])', () => {
new draw.Path().arc(32, 32, 32, 0, Math.PI, false);
ctx.arc.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().arc(32, 32, 32, 0, Math.PI, false).arc(32, 32, 32, 0, Math.PI, false)).should.not.throw();
});
});
describe('#curve(x1, y1, x2, y2, r)', () => {
it('should add context.arcTo(x1, y1, x2, y2, r) to the stack', () => {
const p = new draw.Path().curve(32, 32, 32, 64, 32);
p.length.should.equal(1);
p.stroke();
ctx.arcTo.should.have.been.calledWith(32, 32, 32, 64, 32);
});
it('should not call context.arcTo(x1, y1, x2, y2, r)', () => {
new draw.Path().curve(32, 32, 32, 64, 32);
ctx.arcTo.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().curve(32, 32, 32, 64, 32).curve(32, 96, 64, 96, 32)).should.not.throw();
});
});
describe('#bezier(x1, y1, x2, y2[, x3, y3])', () => {
it('should add context.quadraticCurveTo(x1, y1, x2, y2) to the stack when called with 4 arguments', () => {
const p = new draw.Path().bezier(32, 32, 32, 64);
p.length.should.equal(1);
p.stroke();
ctx.quadraticCurveTo.should.have.been.calledWith(32, 32, 32, 64);
});
it('should add context.bezierCurveTo(x1, y1, x2, y2, x3, y3) to the stack when called with 6 arguments', () => {
const p = new draw.Path().bezier(32, 32, 32, 64, 64, 64);
p.length.should.equal(1);
p.stroke();
ctx.bezierCurveTo.should.have.been.calledWith(32, 32, 32, 64, 64, 64);
});
it('should not call context.quadraticCurveTo(x1, y1, x2, y2) or context.bezierCurveTo(x1, y1, x2, y2, x3, y3)', () => {
new draw.Path().bezier(32, 32, 32, 64).bezier(32, 32, 32, 64, 64, 64);
ctx.quadraticCurveTo.should.not.have.been.called;
ctx.bezierCurveTo.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().bezier(32, 32, 32, 64).bezier(32, 32, 32, 64, 64, 64).move(32, 32)).should.not.throw();
});
});
describe('#close()', () => {
it('should add context.closePath() to the stack', () => {
const p = new draw.Path().close();
p.length.should.equal(1);
p.stroke();
ctx.closePath.should.have.been.calledOnce;
});
it('should not call context.close', () => {
new draw.Path().close();
ctx.closePath.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().close().close()).should.not.throw();
});
});
describe('#do(fn)', () => {
it('should add a given fn to the stack', () => {
const cb = spy();
const p = new draw.Path().do(cb);
p.length.should.equal(1);
p.stroke();
cb.should.have.been.calledOnce;
});
it('should not call fn', () => {
const cb = spy();
const p = new draw.Path().do(cb);
cb.should.not.have.been.called;
});
it('should be chainable', () => {
(() => new draw.Path().do(() => {}).do(() => {})).should.not.throw();
});
});
describe('#fill({color, shadow, transform})', () => {
it('should call context.save() at the beginning, context.restore() at the end, and context.fill() in the middle', () => {
new draw.Path().move(32, 32).line(64, 64).fill();
ctx.save.should.have.been.calledBefore(ctx.fill);
ctx.fill.should.have.been.calledBefore(ctx.restore);
ctx.restore.should.have.been.called;
});
it('should set the color, shadow, and transform if they are specified', () => {
new draw.Path().move(32, 32).do(() => {
context.fillStyle.should.equal('#ff0000');
context.shadowBlur.should.equal(5);
ctx.translate.should.have.been.calledWith(5, 0);
}).line(64, 64).fill({
color: 0xff0000,
shadow: {
blur: 5
},
transform: {
translate: {
x: 5
}
}
});
});
it('should call the entire stack in order', () => {
new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).fill();
ctx.beginPath.should.have.been.calledBefore(ctx.moveTo);
ctx.moveTo.should.have.been.calledBefore(ctx.lineTo);
ctx.lineTo.should.have.been.calledBefore(ctx.arc);
ctx.arc.should.have.been.calledBefore(ctx.rect);
ctx.rect.should.have.been.calledBefore(ctx.fill);
});
it('should be chainable', () => {
(() => new draw.Path().fill().fill({transform: {}, shadow: {}, color: 0x000000})).should.not.throw();
});
});
describe('#stroke({color, line, transform})', () => {
it('should call context.save() at the beginning, context.restore() at the end, and context.stroke() in the middle', () => {
new draw.Path().move(32, 32).line(64, 64).stroke();
ctx.save.should.have.been.calledBefore(ctx.stroke);
ctx.stroke.should.have.been.calledBefore(ctx.restore);
ctx.restore.should.have.been.called;
});
it('should set the color, line, and transform if they are specified', () => {
new draw.Path().move(32, 32).do(() => {
context.strokeStyle.should.equal('#ff0000');
context.lineWidth.should.equal(5);
ctx.translate.should.have.been.calledWith(5, 0);
}).line(64, 64).stroke({
color: 0xff0000,
line: {
width: 5
},
transform: {
translate: {
x: 5
}
}
});
});
it('should call the entire stack in order', () => {
new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).stroke();
ctx.beginPath.should.have.been.calledBefore(ctx.moveTo);
ctx.moveTo.should.have.been.calledBefore(ctx.lineTo);
ctx.lineTo.should.have.been.calledBefore(ctx.arc);
ctx.arc.should.have.been.calledBefore(ctx.rect);
ctx.rect.should.have.been.calledBefore(ctx.stroke);
});
it('should be chainable', () => {
(() => new draw.Path().stroke().stroke({transform: {}, line: '', color: 0x000000}).stroke()).should.not.throw();
});
});
describe('#doInside([{transform},] ...todo)', () => {
it('should call context.save() at the beginning, context.restore() at the end, and context.clip() in the middle', () => {
new draw.Path().rect(32, 32, 64, 64).doInside(() => {});
ctx.save.should.have.been.calledBefore(ctx.clip);
ctx.clip.should.have.been.calledBefore(ctx.restore);
ctx.restore.should.have.been.called;
});
it('should set the transform if given', () => {
new draw.Path().rect(32, 32, 64, 64).doInside({
translate: {
x: 5
}
}, () => {
ctx.translate.should.have.been.called;
});
});
it('should call the entire stack in order', () => {
new draw.Path().move(32, 32).line(64, 64).arc(32, 32, 0, 0, 3).rect(32, 32, 32, 32).doInside();
ctx.beginPath.should.have.been.calledBefore(ctx.moveTo);
ctx.moveTo.should.have.been.calledBefore(ctx.lineTo);
ctx.lineTo.should.have.been.calledBefore(ctx.arc);
ctx.arc.should.have.been.calledBefore(ctx.rect);
ctx.rect.should.have.been.calledBefore(ctx.clip);
});
it('should call all items in todo in order, after clipping', () => {
const cbs = [spy(), spy(), spy()];
new draw.Path().rect(32, 32, 64, 64).doInside(...cbs);
ctx.clip.should.have.been.calledBefore(cbs[0]);
cbs[0].should.have.been.calledOnce;
cbs[0].should.have.been.calledBefore(cbs[1]);
cbs[1].should.have.been.calledOnce;
cbs[1].should.have.been.calledBefore(cbs[2]);
cbs[2].should.have.been.calledOnce;
});
it('should be chainable', () => {
(() => new draw.Path().doInside({}, () => {}).doInside(() => {}).doInside()).should.not.throw();
});
});
describe('#copy()', () => {
it('should make an identical Path', () => {
const p = new draw.Path().move(32, 32).line(64, 64);
const c = p.copy();
c.should.be.an.instanceof(draw.Path);
c.length.should.deep.equal(p.length);
});
it('should not modify the original when the copy is changed used', () => {
const p = new draw.Path().move(32, 32).line(64, 64);
const c = p.copy().arc(64, 64, 32, 0, Math.PI * 2);
p.length.should.not.equal(c.length);
});
});
describe('#contains([offx, offy,] x, y)', () => {
it('should be true if the point is within the path', () => {
new draw.Path().move(0, 32).line(32, 32).contains(16, 32).should.be.true;
new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(30, 34).should.be.true;
});
it('should be true if the point is not within the path', () => {
new draw.Path().move(0, 32).line(32, 32).contains(48, 32).should.be.false;
new draw.Path().move(0, 32).line(32, 32).contains(16, 16).should.be.false;
});
it('should allow offsets to be specified', () => {
new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(130, 134).should.be.false;
new draw.Path().move(0, 32).line(32, 32).line(32, 64).contains(100, 100, 130, 134).should.be.true;
});
});
});
describe('PixelData', () => {
const [width, height] = [32, 32];
let pd;
before(() => pd = new draw.PixelData(width, height));
it('should be constructed with new PixelData([x, y,] w, h)', () => {
new draw.PixelData(32, 32).should.be.an.instanceof(draw.PixelData);
new draw.PixelData(16, 16, 16, 16).should.be.an.instanceof(draw.PixelData);
ctx.createImageData.should.have.been.calledWith(32, 32);
ctx.getImageData.should.have.been.calledWith(16, 16, 16, 16);
(() => draw.PixelData(32, 32)).should.throw(TypeError);
});
describe('#width', () => {
it('should return the width of the PixelData', () => {
pd.width.should.equal(32);
});
it('should be read only', () => {
(() => pd.width = 16).should.throw(TypeError);
});
});
describe('#height', () => {
it('should return the height of the PixelData', () => {
pd.height.should.equal(32);
});
it('should be read only', () => {
(() => pd.height = 16).should.throw(TypeError);
});
});
describe('#data[x][y]', () => {
it('should return a pixel from the ImageData', () => {
pd.data[16][16].should.deep.equal([0, 0, 0, 0]);
});
});
describe('#data[x][y]=', () => {
it('should be settable to change the ImageData', () => {
pd.data[16][16] = [255, 0, 0, 255];
pd.data[16][16].should.deep.equal([255, 0, 0, 255]);
pd.data[16][16] = [0, 0, 0, 0];
pd.data[16][16].should.deep.equal([0, 0, 0, 0]);
});
it('should not work with only one index', () => {
(() => pd.data[16] = [255, 0, 0, 255]).should.throw(TypeError);
});
});
describe('#draw(x, y)', () => {
it('should draw the PixelData', () => {
pd.draw(32, 32);
ctx.putImageData.should.have.been.calledOnce;
});
});
});
});
|
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['1277',"Tlece.Recruitment.Helpers Namespace","topic_00000000000004A2.html"],['1364',"StaffAuthorizeRequirement Class","topic_00000000000004FA.html"],['1365',"Properties","topic_00000000000004FA_props--.html"],['1366',"StaffRoles Property","topic_00000000000004FB.html"]]; |
"use strict";
var Piece = require('../lib/Piece'),
map = require('../lib/map');
describe('Piece.js', function() {
var piece;
beforeEach(function() {
piece = new Piece(1, 'black', 0, 0);
});
describe('Piece Constructor', function() {
// めんどくせいらね
});
describe('Piece.prototype.getPiece()', function() {
it('this.pieceを返す', function() {
expect(piece.getPiece()).toEqual(1);
});
});
describe('Piece.prototype.getFile()', function() {
it('this.fileを返す', function() {
expect(piece.getFile()).toEqual(0);
});
});
describe('Piece.prototype.getRank()', function() {
it('this.rankを返す', function() {
expect(piece.getRank()).toEqual(0);
});
});
describe('Piece.prototype.getPlayer()', function() {
it('this.playerを返す', function() {
expect(piece.getPlayer()).toEqual('black');
});
});
describe('Piece.prototype.update(args)', function() {
it('Pieceのフィールドの内容を引数で指定された値に変更する', function() {
piece.update({
'piece': 5,
'file': 6,
'rank': 5,
'player': 'white'
});
expect(piece.getPiece()).toEqual(5);
expect(piece.getFile()).toEqual(6);
expect(piece.getRank()).toEqual(5);
expect(piece.getPlayer()).toEqual('white');
});
});
describe('Piece.prototype.promote()', function() {
it('this.pieceの値を歩→と', function() {
piece.update({'piece': map.piece('歩')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('と'));
});
it('this.pieceの値を香→成香', function() {
piece.update({'piece': map.piece('香')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('成香'));
});
it('this.pieceの値を桂→成桂', function() {
piece.update({'piece': map.piece('桂')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('成桂'));
});
it('this.pieceの値を銀→成銀', function() {
piece.update({'piece': map.piece('銀')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('成銀'));
});
it('this.pieceの値を角→馬', function() {
piece.update({'piece': map.piece('角')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('馬'));
});
it('this.pieceの値を飛→龍', function() {
piece.update({'piece': map.piece('飛')});
piece.promote();
expect(piece.getPiece()).toEqual(map.piece('龍'));
});
});
describe('Piece.prototype.demote()', function() {
it('this.pieceの値をと→歩', function() {
piece.update({'piece': map.piece('と')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('歩'));
});
it('this.pieceの値を成香→香', function() {
piece.update({'piece': map.piece('成香')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('香'));
});
it('this.pieceの値を成桂→桂', function() {
piece.update({'piece': map.piece('成桂')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('桂'));
});
it('this.pieceの値を成銀→銀', function() {
piece.update({'piece': map.piece('成銀')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('銀'));
});
it('this.pieceの値を馬→角', function() {
piece.update({'piece': map.piece('馬')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('角'));
});
it('this.pieceの値を龍→飛', function() {
piece.update({'piece': map.piece('龍')});
piece.captured();
expect(piece.getPiece()).toEqual(map.piece('飛'));
});
});
describe('Piece.prototype.captured()', function() {
beforeEach(function () {
spyOn(piece, 'demote');
});
it('fileとrankを0にして、playerを反転させ駒を降格させる', function() {
piece.update({'player': 'black'});
piece.captured();
expect(piece.getFile()).toEqual(0);
expect(piece.getRank()).toEqual(0);
expect(piece.getPlayer()).toEqual('white');
expect(piece.demote).toHaveBeenCalled();
});
});
describe('Piece.prototype.matchMovement(move)', function() {
beforeEach(function () {
// パッと見わかりにくいがspyを仕込んでいる
for(var i = 1, l = map.csaPiece('RY'); i <= l; i++) {
spyOn(piece, 'case' + map.pieceToCsaPieceMapKey(i));
}
});
it('駒に対応する関数を呼び出す', function() {
var move = {
'turn': 'black',
'to': [0, 0],
'piece': 1
};
for(var i = 1, l = map.csaPiece('RY'); i <= l; i++) {
move.piece = i;
piece.matchMovement(move);
expect(piece['case' + map.pieceToCsaPieceMapKey(i)]).toHaveBeenCalled();
}
});
});
describe('Piece.prototype.checkRelative(move, dfile)', function() {
/*
先手と後手両方判定しているのでそこは気にしなくていい
*/
var move, players;
beforeEach(function () {
move = {
'turn': 'black',
'to': [5, 5],
'piece': undefined,
'relative': undefined
};
players = ['black', 'white'];
});
it('引数move.relativeが"右"でfileの位置も右側であればtrueを返す', function() {
var dfile = 0,
pos = [[4, 6], [6,4]];
move.relative = '右';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeTruthy();
}
});
it('引数move.relativeが"右"でfileの位置が同じか左側であればfalseを返す', function() {
var dfile = 0,
pos = [[5, 6], [5, 4],
[6, 6], [4, 4]];
move.relative = '右';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
}
});
it('引数move.relativeが"左"でfileの位置も左側であればtrueを返す', function() {
var dfile = 0,
pos = [[6, 6], [4,4]];
move.relative = '左';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeTruthy();
}
});
it('引数move.relativeが"左"でfileの位置が同じか右側であればfalseを返す', function() {
var dfile = 0,
pos = [[5, 6], [5, 4],
[4, 6], [6, 4]];
move.relative = '左';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
}
});
/*
馬と龍のケース
*/
it('馬と龍で引数move.relativeが"右"でfileも右側か同じ位置であればtrueを返す', function() {
var dfile = 0,
pos = [[4, 6], [6, 4],
[5, 6], [5, 4]],
pieces = [map.csaPiece('UM'), map.csaPiece('RY')];
move.relative = '右';
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
for(var j = 0, jl = pieces.length; j < jl; j++) {
move.piece = pieces[j];
piece.update({'piece': pieces[j]});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeTruthy();
}
}
});
it('馬と龍で引数move.relativeが"右"でfileが左側の位置であればfalseを返す', function() {
var dfile = 0,
pos = [[6, 6], [4, 4]],
pieces = [map.csaPiece('UM'), map.csaPiece('RY')];
move.relative = '右';
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
for(var j = 0, jl = pieces.length; j < jl; j++) {
move.piece = pieces[j];
piece.update({'piece': pieces[j]});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
}
}
});
it('馬と龍で引数move.relativeが"左"でfileも左側か同じ位置であればtrueを返す', function() {
var dfile = 0,
pos = [[6, 6], [4, 6],
[5, 6], [5, 4]],
pieces = [map.csaPiece('UM'), map.csaPiece('RY')];
move.relative = '左';
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
for(var j = 0, jl = pieces.length; j < jl; j++) {
move.piece = pieces[j];
piece.update({'piece': pieces[j]});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeTruthy();
}
}
});
it('馬と龍で引数move.relativeが"左"でfileが右側の位置であればfalseを返す', function() {
var dfile = 0,
pos = [[4, 6], [6, 4]],
pieces = [map.csaPiece('UM'), map.csaPiece('RY')];
move.relative = '左';
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
for(var j = 0, jl = pieces.length; j < jl; j++) {
move.piece = pieces[j];
piece.update({'piece': pieces[j]});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
}
}
});
it('引数move.relativeが"直"でfileの位置が同じであればtrueを返す', function() {
var dfile = 0;
move.relative = '直';
piece.update({
'piece': map.csaPiece('GI'),
'player': 'black',
'file': 5,
'rank': 6
});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeTruthy();
});
it('引数move.relativeが"直"でfileの位置が同じでなければfalseを返す', function() {
var dfile = 0;
move.relative = '直';
piece.update({
'piece': map.csaPiece('GI'),
'player': 'black',
'file': 5,
'rank': 6
});
// fileが右側になるのであればfalse
piece.update({'file': 4});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
// fileが左側になるのであればfalse
piece.update({'file': 6});
dfile = piece.getFile() - move.to[0];
expect(piece.checkRelative(move, dfile)).toBeFalsy();
});
});
describe('Piece.prototype.checkMotion(move)', function() {
/*
先手と後手両方判定しているのでそれは気にしなくていい
*/
var move, players;
beforeEach(function () {
move = {
'turn': 'black',
'to': [5, 5],
'piece': undefined,
'motion': undefined
};
players = ['black', 'white'];
});
it('引数move.motionが"上"でrankの位置がpieceより下側の位置であればtrueを返す', function() {
var drank = 0,
pos = [[4, 6], [6, 4]];
move.motion = '上';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeTruthy();
}
});
it('引数move.motionが"上"でrankの位置がpieceと同じであればfalseを返す', function() {
var drank = 0,
pos = [[4, 5], [5, 6]];
move.motion = '上';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeFalsy();
}
});
it('引数move.motionが"引"でrankの位置がpieceより上側の位置であればtrueを返す', function() {
var drank = 0,
pos = [[4, 4], [4, 6]];
move.motion = '引';
piece.update({'piece': map.csaPiece('GI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeTruthy();
}
});
it('引数move.motionが"引"でrankの位置がpieceと同じであればfalseを返す', function() {
var drank = 0,
pos = [[4, 5], [6, 5]];
move.motion = '引';
piece.update({'piece': map.csaPiece('KI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeFalsy();
}
});
it('引数move.motionが"寄"でrankの位置がpieceと同じであればtrueを返す', function() {
var drank = 0,
pos = [[4, 5], [6, 5]];
move.motion = '寄';
piece.update({'piece': map.csaPiece('KI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeTruthy();
}
});
it('引数move.motionが"寄"でrankの位置がpieceと同じでなければfalseを返す', function() {
var drank = 0,
pos = [[4, 6], [6, 4]];
move.motion = '寄';
piece.update({'piece': map.csaPiece('KI')});
for(var i = 0, l = players.length; i < l; i++) {
piece.update({
'player': players[i],
'file': pos[i][0],
'rank': pos[i][1]
});
drank = piece.getRank() - move.to[0];
expect(piece.checkMotion(move, drank)).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestForward(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [5, 4]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestForward(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [5, 6]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestForward(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestForward(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 4], [4, 6], [4, 5], [4, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestForward(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestBackward(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [5, 6]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [5, 4]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 4], [4, 6], [4, 5], [4, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBackward(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestUpperLeft(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [6, 4]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [4, 6]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestUpperLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestLeft(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [6, 5]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [4, 5]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestBottomLeft(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [6, 6]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [4, 4]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 6], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBottomLeft(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestUpperRight(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [4, 4]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [6, 6]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 5], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestUpperRight(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestRight(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [4, 5]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [6, 5]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 6], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestRight(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 4], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestRight(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestBottomrRight(file, rank)', function() {
it('(先手)trueを返す', function() {
var move = {
'turn': 'black',
'to': [4, 6]
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(後手)trueを返す', function() {
var move = {
'turn': 'white',
'to': [6, 4]
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeTruthy();
});
it('(先手)falseを返す', function() {
var to = [[6, 4], [6, 5], [6, 6], [5, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[6, 5], [6, 6], [5, 6], [4, 6], [4, 5], [4, 4], [5, 4], [5, 5]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestBottomRight(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestDirectly(file, rank)', function() {
it('(先手)trueを返す', function() {
var to = [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 1,
'rank': 9
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeTruthy();
}
});
it('(後手)trueを返す', function() {
var to = [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 1,
'rank': 1
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeTruthy();
}
});
it('(先手)falseを返す', function() {
var to = [[1, 9], [2, 1]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 1,
'rank': 9
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeFalsy();
}
});
it('(後手)falseを返す', function() {
var to = [[1, 1], [2, 9]],
move = {
'turn': 'white',
'to': []
};
piece.update({
'player': 'white',
'file': 1,
'rank': 1
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDirectly(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestDiagonal(file, rank)', function() {
it('(先後同じ)trueを返す', function() {
var to = [
[6, 4], [7, 3], [8, 2], [9, 1],
[6, 6], [7, 7], [8, 8], [9, 9],
[4, 4], [3, 3], [2, 2], [1, 1],
[4, 6], [3, 7], [2, 8], [1, 9]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDiagonal(move.to[0], move.to[1])).toBeTruthy();
}
});
it('falseを返す', function() {
var to = [
[5, 5],
[5, 6], [6, 5], [5, 4], [4, 5],
[10, 0], [5, 0], [0, 0], [0, 10]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestDiagonal(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.checkDestOrthogonal(file, rank)', function() {
it('(先後同じ)trueを返す', function() {
var to = [
[6, 5], [7, 5], [8, 5], [9, 5],
[5, 4], [5, 3], [5, 2], [5, 1],
[4, 5], [3, 5], [2, 5], [1, 5],
[5, 6], [5, 7], [5, 8], [5, 9]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestOrthogonal(move.to[0], move.to[1])).toBeTruthy();
}
});
it('falseを返す', function() {
var to = [
[5, 5],
[6, 4], [6, 6], [4, 4], [4, 6],
[10, 5], [5, 0], [0, 5], [5, 10]],
move = {
'turn': 'black',
'to': []
};
piece.update({
'player': 'black',
'file': 5,
'rank': 5
});
for(var i = 0, l = to.length; i < l; i++) {
move.to = to[i];
expect(piece.checkDestOrthogonal(move.to[0], move.to[1])).toBeFalsy();
}
});
});
describe('Piece.prototype.caseFU(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('FU'),
'file': 5,
'rank': 5
});
});
it('(先手)移動前の歩に該当すればtrueを返す', function() {
var move = {
'turn': 'black',
'to': [5, 4],
'piece': map.csaPiece('FU')
};
piece.update({'player': 'black'});
expect(piece.caseFU(move)).toBeTruthy();
});
it('(後手)移動前の歩に該当すればtrueを返す', function() {
var move = {
'turn': 'white',
'to': [5, 6],
'piece': map.csaPiece('FU')
};
piece.update({'player': 'white'});
expect(piece.caseFU(move)).toBeTruthy();
});
it('移動前の歩に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [5, 6],
'piece': map.csaPiece('FU')
};
piece.update({'player': 'black'});
expect(piece.caseFU(move)).toBeFalsy();
});
});
describe('Piece.prototype.caseKY(move)', function() {
it('(先手)移動前の香に該当すればtrueを返す', function() {
var move = {
'turn': 'black',
'to': [1, 1],
'piece': map.csaPiece('KY')
};
piece.update({
'piece': map.csaPiece('KY'),
'player': 'black',
'file': 1,
'rank': 9
});
expect(piece.caseKY(move)).toBeTruthy();
});
it('(後手)移動前の香に該当すればtrueを返す', function() {
var move = {
'turn': 'white',
'to': [1, 9],
'piece': map.csaPiece('KY')
};
piece.update({
'piece': map.csaPiece('KY'),
'player': 'white',
'file': 1,
'rank': 1
});
expect(piece.caseKY(move)).toBeTruthy();
});
it('移動前の香に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [1, 5],
'piece': map.csaPiece('KY')
};
piece.update({
'piece': map.csaPiece('KY'),
'player': 'black',
'file': 1,
'rank': 2
});
expect(piece.caseKY(move)).toBeFalsy();
});
});
describe('Piece.prototype.caseKE(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('KE'),
'file': 5,
'rank': 5
});
});
it('(先手)移動前の桂に該当すればtrueを返す', function() {
var move = {
'turn': 'black',
'to': [6, 3],
'piece': map.csaPiece('KE')
};
piece.update({'player': 'black'});
expect(piece.caseKE(move)).toBeTruthy();
});
it('(後手)移動前の桂に該当すればtrueを返す', function() {
var move = {
'turn': 'white',
'to': [6, 7],
'piece': map.csaPiece('KE')
};
piece.update({'player': 'white'});
expect(piece.caseKE(move)).toBeTruthy();
});
it('移動前の桂に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [6, 2],
'piece': map.csaPiece('KE')
};
piece.update({'player': 'black'});
expect(piece.caseKE(move)).toBeFalsy();
});
});
describe('Piece.prototype.caseGI(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('GI'),
'file': 5,
'rank': 5
});
});
it('(先手)移動前の銀に該当すればtrueを返す', function() {
var pos = [[4, 6], [6, 6], [6, 4], [4, 4], [5, 4]],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('GI')
};
piece.update({'player': 'black'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseGI(move)).toBeTruthy();
}
});
it('(後手)移動前の銀に該当すればtrueを返す', function() {
var pos = [[4, 6], [6, 6], [6, 4], [4, 4], [5, 6]],
move = {
'turn': 'white',
'to': [],
'piece': map.csaPiece('GI')
};
piece.update({'player': 'white'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseGI(move)).toBeTruthy();
}
});
it('移動前の銀に該当しなければfalseを返す', function() {
var pos = [[4, 5], [6, 5], [5, 6], [5, 5]],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('GI')
};
piece.update({'player': 'black'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseGI(move)).toBeFalsy();
}
});
});
describe('Piece.prototype.caseKI(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('KI'),
'file': 5,
'rank': 5
});
});
it('(先手)移動前の金に該当すればtrueを返す', function() {
var pos = [[5, 4], [4, 4], [4, 5], [5, 6], [6, 5], [6, 4]],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('KI')
};
piece.update({'player': 'black'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseKI(move)).toBeTruthy();
}
});
it('(後手)移動前の金に該当すればtrueを返す', function() {
var pos = [[5, 6], [6, 6], [6, 5], [5, 4], [4, 5], [4, 6]],
move = {
'turn': 'white',
'to': [],
'piece': map.csaPiece('KI')
};
piece.update({'player': 'white'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseKI(move)).toBeTruthy();
}
});
it('移動前の金に該当しなければfalseを返す', function() {
var pos = [[6, 6], [4, 6], [5, 5]],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('KI')
};
piece.update({'player': 'black'});
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseKI(move)).toBeFalsy();
}
});
});
describe('Piece.prototype.caseKA(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('KA'),
'file': 5,
'rank': 5
});
});
it('(先後同じ)移動前の角に該当すればtrueを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('KA')
};
piece.update({'player': 'black'});
pos = [
[6, 4], [7, 3], [8, 2], [9, 1],
[6, 6], [7, 7], [8, 8], [9, 9],
[4, 4], [3, 3], [2, 2], [1, 1],
[4, 6], [3, 7], [2, 8], [1, 9]
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseKA(move)).toBeTruthy();
}
});
it('移動前の角に該当しなければfalseを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('KA')
};
piece.update({'player': 'black'});
pos = [
[5, 5],
[5, 6], [6, 5], [5, 4], [4, 5],
[10, 0], [5, 0], [0, 0], [0, 10],
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseKA(move)).toBeFalsy();
}
});
});
describe('Piece.prototype.caseHI(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('HI'),
'file': 5,
'rank': 5
});
});
it('(先後同じ)移動前の飛車に該当すればtrueを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('HI')
};
piece.update({'player': 'black'});
pos = [
[6, 5], [7, 5], [8, 5], [9, 5],
[5, 4], [5, 3], [5, 2], [5, 1],
[4, 5], [3, 5], [2, 5], [1, 5],
[5, 6], [5, 7], [5, 8], [5, 9]
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseHI(move)).toBeTruthy();
}
});
it('移動前の飛車に該当しなければfalseを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('HI')
};
piece.update({'player': 'black'});
pos = [
[5, 5],
[6, 4], [6, 6], [4, 4], [4, 6],
[10, 5], [5, 0], [0, 5], [5, 10]
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseHI(move)).toBeFalsy();
}
});
});
describe('Piece.prototype.caseOU(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('OU'),
'player': 'black',
'file': 5,
'rank': 5
});
});
it('(先後同じ)移動前の王に該当すればtrueを返す', function() {
var pos = [[5, 4], [4, 4], [4, 5], [4, 6], [5, 6], [6, 6], [6, 5], [6, 4]],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('OU')
};
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseOU(move)).toBeTruthy();
}
});
it('移動前の王に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [5, 5],
'piece': map.csaPiece('OU')
};
expect(piece.caseOU(move)).toBeFalsy();
});
});
describe('Piece.prototype.caseUM(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('UM'),
'player': 'black',
'file': 5,
'rank': 5
});
});
it('(先後同じ)移動前の馬に該当すればtrueを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('UM')
};
pos = [
[6, 4], [7, 3], [8, 2], [9, 1],
[6, 6], [7, 7], [8, 8], [9, 9],
[4, 4], [3, 3], [2, 2], [1, 1],
[4, 6], [3, 7], [2, 8], [1, 9],
[5, 4], [4, 5], [5, 6], [6, 5]
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseUM(move)).toBeTruthy();
}
});
it('移動前の馬に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [5, 5],
'piece': map.csaPiece('UM')
};
expect(piece.caseUM(move)).toBeFalsy();
});
});
describe('Piece.prototype.caseRY(move)', function() {
beforeEach(function() {
piece.update({
'piece': map.csaPiece('RY'),
'player': 'black',
'file': 5,
'rank': 5
});
});
it('(先後同じ)移動前の龍に該当すればtrueを返す', function() {
var pos = [],
move = {
'turn': 'black',
'to': [],
'piece': map.csaPiece('RY')
};
pos = [
[6, 5], [7, 5], [8, 5], [9, 5],
[5, 4], [5, 3], [5, 2], [5, 1],
[4, 5], [3, 5], [2, 5], [1, 5],
[5, 6], [5, 7], [5, 8], [5, 9],
[4, 4], [4, 6], [6, 6], [6, 4]
];
for(var i = 0, l = pos.length; i < l; i++) {
move.to = pos[i];
expect(piece.caseRY(move)).toBeTruthy();
}
});
it('移動前の龍に該当しなければfalseを返す', function() {
var move = {
'turn': 'black',
'to': [5, 5],
'piece': map.csaPiece('RY')
};
expect(piece.caseRY(move)).toBeFalsy();
});
});
});
|
process.env.NODE_ENV = 'development';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var historyApiFallback = require('connect-history-api-fallback');
var httpProxyMiddleware = require('http-proxy-middleware');
var detect = require('detect-port');
var clearConsole = require('react-dev-utils/clearConsole');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var formatWebpackMessages = require('react-dev-utils/formatWebpackMessages');
var openBrowser = require('react-dev-utils/openBrowser');
var prompt = require('react-dev-utils/prompt');
var config = require('../config/webpack.config.dev');
var paths = require('../config/paths');
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Tools like Cloud9 rely on this.
var DEFAULT_PORT = process.env.PORT || 3000;
var compiler;
var handleCompile;
function setupCompiler(host, port, protocol) {
// "Compiler" is a low-level interface to Webpack.
// It lets us listen to some events and provide our own custom messages.
compiler = webpack(config, handleCompile);
// "invalid" event fires when you have changed a file, and Webpack is
// recompiling a bundle. WebpackDevServer takes care to pause serving the
// bundle, so if you refresh, it'll wait instead of serving the old one.
// "invalid" is short for "bundle invalidated", it doesn't imply any errors.
compiler.plugin('invalid', function() {
clearConsole();
console.log('Compiling...');
});
// "done" event fires when Webpack has finished recompiling the bundle.
// Whether or not you have warnings or errors, you will get this event.
compiler.plugin('done', function(stats) {
clearConsole();
// We have switched off the default Webpack output in WebpackDevServer
// options so we are going to "massage" the warnings and errors and present
// them in a readable focused way.
var messages = formatWebpackMessages(stats.toJson({}, true));
if (!messages.errors.length && !messages.warnings.length) {
console.log(chalk.green('Compiled successfully!'));
console.log();
console.log('The app is running at:');
console.log();
console.log(' ' + chalk.cyan(protocol + '://' + host + ':' + port + '/'));
console.log();
console.log('Note that the development build is not optimized.');
console.log('To create a production build, use ' + chalk.cyan('npm run build') + '.');
console.log();
}
// If errors exist, only show errors.
if (messages.errors.length) {
console.log(chalk.red('Failed to compile.'));
console.log();
messages.errors.forEach(message => {
console.log(message);
console.log();
});
return;
}
// Show warnings if no errors were found.
if (messages.warnings.length) {
console.log(chalk.yellow('Compiled with warnings.'));
console.log();
messages.warnings.forEach(message => {
console.log(message);
console.log();
});
// Teach some ESLint tricks.
console.log('You may use special comments to disable some warnings.');
console.log('Use ' + chalk.yellow('// eslint-disable-next-line') + ' to ignore the next line.');
console.log('Use ' + chalk.yellow('/* eslint-disable */') + ' to ignore all warnings in a file.');
}
});
}
// We need to provide a custom onError function for httpProxyMiddleware.
// It allows us to log custom error messages on the console.
function onProxyError(proxy) {
return function(err, req, res){
var host = req.headers && req.headers.host;
console.log(
chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url) +
' from ' + chalk.cyan(host) + ' to ' + chalk.cyan(proxy) + '.'
);
console.log(
'See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (' +
chalk.cyan(err.code) + ').'
);
console.log();
// And immediately send the proper error response to the client.
// Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
if (res.writeHead && !res.headersSent) {
res.writeHead(500);
}
res.end('Proxy error: Could not proxy request ' + req.url + ' from ' +
host + ' to ' + proxy + ' (' + err.code + ').'
);
}
}
function addMiddleware(devServer) {
// `proxy` lets you to specify a fallback server during development.
// Every unrecognized request will be forwarded to it.
var proxy = require(paths.appPackageJson).proxy;
devServer.use(historyApiFallback({
// Paths with dots should still use the history fallback.
// See https://github.com/facebookincubator/create-react-app/issues/387.
disableDotRule: true,
// For single page apps, we generally want to fallback to /index.html.
// However we also want to respect `proxy` for API calls.
// So if `proxy` is specified, we need to decide which fallback to use.
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
// Modern browsers include text/html into `accept` header when navigating.
// However API calls like `fetch()` won’t generally accept text/html.
// If this heuristic doesn’t work well for you, don’t use `proxy`.
htmlAcceptHeaders: proxy ?
['text/html'] :
['text/html', '*/*']
}));
if (proxy) {
if (typeof proxy !== 'string') {
console.log(chalk.red('When specified, "proxy" in package.json must be a string.'));
console.log(chalk.red('Instead, the type of "proxy" was "' + typeof proxy + '".'));
console.log(chalk.red('Either remove "proxy" from package.json, or make it a string.'));
process.exit(1);
}
// Otherwise, if proxy is specified, we will let it handle any request.
// There are a few exceptions which we won't send to the proxy:
// - /index.html (served as HTML5 history API fallback)
// - /*.hot-update.json (WebpackDevServer uses this too for hot reloading)
// - /sockjs-node/* (WebpackDevServer uses this for hot reloading)
// Tip: use https://jex.im/regulex/ to visualize the regex
var mayProxy = /^(?!\/(index\.html$|.*\.hot-update\.json$|sockjs-node\/)).*$/;
devServer.use(mayProxy,
// Pass the scope regex both to Express and to the middleware for proxying
// of both HTTP and WebSockets to work without false positives.
httpProxyMiddleware(pathname => mayProxy.test(pathname), {
target: proxy,
logLevel: 'silent',
onError: onProxyError(proxy),
secure: false,
changeOrigin: true
})
);
}
// Finally, by now we have certainly resolved the URL.
// It may be /index.html, so let the dev server try serving it again.
devServer.use(devServer.middleware);
}
function runDevServer(host, port, protocol) {
var devServer = new WebpackDevServer(compiler, {
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
clientLogLevel: 'none',
// By default WebpackDevServer serves physical files from current directory
// in addition to all the virtual build products that it serves from memory.
// This is confusing because those files won’t automatically be available in
// production build folder unless we copy them. However, copying the whole
// project directory is dangerous because we may expose sensitive files.
// Instead, we establish a convention that only files in `public` directory
// get served. Our build script will copy `public` into the `build` folder.
// In `index.html`, you can get URL of `public` folder with %PUBLIC_PATH%:
// <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
// In JavaScript code, you can access it with `process.env.PUBLIC_URL`.
// Note that we only recommend to use `public` folder as an escape hatch
// for files like `favicon.ico`, `manifest.json`, and libraries that are
// for some reason broken when imported through Webpack. If you just want to
// use an image, put it in `src` and `import` it from JavaScript instead.
contentBase: paths.appPublic,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: config.output.publicPath,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.plugin` calls above.
quiet: true,
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebookincubator/create-react-app/issues/293
watchOptions: {
ignored: /node_modules/
},
// Enable HTTPS if the HTTPS environment variable is set to 'true'
https: protocol === "https",
host: host
});
// Our custom middleware proxies requests to /index.html or a remote API.
addMiddleware(devServer);
// Launch WebpackDevServer.
devServer.listen(port, (err, result) => {
if (err) {
return console.log(err);
}
clearConsole();
console.log(chalk.cyan('Starting the development server...'));
console.log();
openBrowser(protocol + '://' + host + ':' + port + '/');
});
}
function run(port) {
var protocol = process.env.HTTPS === 'true' ? "https" : "http";
var host = process.env.HOST || 'localhost';
setupCompiler(host, port, protocol);
runDevServer(host, port, protocol);
}
// We attempt to use the default port but if it is busy, we offer the user to
// run on a different port. `detect()` Promise resolves to the next free port.
detect(DEFAULT_PORT).then(port => {
if (port == DEFAULT_PORT) {
run(port);
return;
}
clearConsole();
var question =
chalk.yellow('Something is already running on port ' + DEFAULT_PORT + '.') +
'\n\nWould you like to run the app on another port instead?';
prompt(question, true).then(shouldChangePort => {
if (shouldChangePort) {
run(port);
}
});
});
|
define([], () => {
'use strict';
class FeedsError extends Error {
constructor(...args) {
console.error('FeedsError', args);
super(args);
}
}
class ServerError extends Error {
constructor(...args) {
super(args);
}
}
function queryToString(query) {
return Array.from(query.entries()).map(([k, v]) => {
return [
k, encodeURIComponent(v)
].join('=');
}).join('&');
}
class FeedsClient {
constructor(params) {
this.params = params;
}
put(path, body) {
const url = (this.baseURLPath().concat(path)).join('/');
return fetch(url, {
headers: {
Authorization: this.params.token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
method: 'PUT',
body: JSON.stringify(body)
})
.then((response) => {
if (response.status === 500) {
switch (response.headers.get('Content-Type')) {
case 'application/json':
return response.json()
.then((result) => {
throw new FeedsError(result);
});
case 'text/plain':
return response.text()
.then((errorText) => {
throw new ServerError(errorText);
});
default:
throw new Error('Unexpected content type: ' + response.headers.get('Content-Type'));
}
} else if (response.status !== 200) {
throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText);
} else {
return response.json()
.then((result) => {
return result;
});
}
});
}
post(path, body) {
const url = (this.baseURLPath().concat(path)).join('/');
return fetch(url, {
headers: {
Authorization: this.params.token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
method: 'POST',
body: body ? JSON.stringify(body) : ''
})
.then((response) => {
if (response.status === 500) {
switch (response.headers.get('Content-Type')) {
case 'application/json':
return response.json()
.then((result) => {
throw new FeedsError(result);
});
case 'text/plain':
return response.text()
.then((errorText) => {
throw new ServerError(errorText);
});
default:
throw new Error('Unexpected content type: ' + response.headers.get('Content-Type'));
}
} else if (response.status === 200) {
return response.json();
} else if (response.status === 204) {
return null;
} else {
throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText);
}
});
}
postWithResult(path, body) {
const url = (this.baseURLPath().concat(path)).join('/');
return fetch(url, {
headers: {
Authorization: this.params.token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
method: 'POST',
body: body ? JSON.stringify(body) : ''
})
.then((response) => {
if (response.status === 500) {
switch (response.headers.get('Content-Type')) {
case 'application/json':
return response.json()
.then((result) => {
throw new FeedsError(result);
});
case 'text/plain':
return response.text()
.then((errorText) => {
throw new ServerError(errorText);
});
default:
throw new Error('Unexpected content type: ' + response.headers.get('Content-Type'));
}
} else if (response.status === 200) {
return response.json();
} else {
throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText);
}
});
}
makeUrl(path, query) {
const baseUrl = (this.baseURLPath().concat(path)).join('/');
if (query) {
return baseUrl +
'?' +
queryToString(query);
}
return baseUrl;
}
get(path, query) {
const url = this.makeUrl(path, query);
return fetch(url, {
headers: {
Authorization: this.params.token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
method: 'GET'
})
.then((response) => {
if (response.status === 500) {
switch (response.headers.get('Content-Type')) {
case 'application/json':
return response.json()
.then((result) => {
throw new FeedsError(result);
});
case 'text/plain':
return response.text()
.then((errorText) => {
throw new ServerError(errorText);
});
default:
throw new Error('Unexpected content type: ' + response.headers.get('Content-Type'));
}
} else if (response.status === 200) {
return response.json();
} else {
throw new Error('Unexpected response: ' + response.status + ' : ' + response.statusText);
}
});
}
baseURLPath() {
return [this.params.url, 'api', 'V1'];
}
getNotifications({ count = 100 } = {}) {
const options = new Map();
options.set('n', String(count));
return this.get(['notifications'], options);
}
getUnseenNotificationCount() {
return this.get(['notifications', 'unseen_count']);
}
seeNotifications(param) {
return this.postWithResult(['notifications', 'see'], param);
}
}
return { FeedsClient, FeedsError, ServerError };
}); |
export default {
analytics: () => {
return {
logEvent: () => {},
setCurrentScreen: () => {}
};
}
};
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'preview', 'ca', {
preview: 'Visualització prèvia'
} );
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Discount = mongoose.model('Discount');
/**
* Globals
*/
var user, discount;
/**
* Unit tests
*/
describe('Discount Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: '[email protected]',
username: 'username',
password: 'password'
});
user.save(function() {
discount = new Discount({
name: 'Discount Name',
user: user
});
done();
});
});
describe('Method Save', function() {
it('should be able to save without problems', function(done) {
return discount.save(function(err) {
should.not.exist(err);
done();
});
});
it('should be able to show an error when try to save without name', function(done) {
discount.name = '';
return discount.save(function(err) {
should.exist(err);
done();
});
});
});
afterEach(function(done) {
Discount.remove().exec();
User.remove().exec();
done();
});
}); |
/**
* SIP Transactions module.
*/
(function(JsSIP) {
var
C = {
// Transaction states
STATUS_TRYING: 1,
STATUS_PROCEEDING: 2,
STATUS_CALLING: 3,
STATUS_ACCEPTED: 4,
STATUS_COMPLETED: 5,
STATUS_TERMINATED: 6,
STATUS_CONFIRMED: 7,
// Transaction types
NON_INVITE_CLIENT: 'nict',
NON_INVITE_SERVER: 'nist',
INVITE_CLIENT: 'ict',
INVITE_SERVER: 'ist'
};
var NonInviteClientTransaction = function(request_sender, request, transport) {
var via,
via_transport,
events = ['stateChanged'];
this.type = C.NON_INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
this.logger = request_sender.ua.getLogger('jssip.transaction.nict', this.id);
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
this.initEvents(events);
};
NonInviteClientTransaction.prototype = new JsSIP.EventEmitter();
NonInviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged', this);
};
NonInviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_TRYING);
this.F = window.setTimeout(function() {tr.timer_F();}, JsSIP.Timers.TIMER_F);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
NonInviteClientTransaction.prototype.onTransportError = function() {
this.logger.debug('transport error occurred, deleting non-INVITE client transaction ' + this.id);
window.clearTimeout(this.F);
window.clearTimeout(this.K);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onTransportError();
};
NonInviteClientTransaction.prototype.timer_F = function() {
this.logger.debug('Timer F expired for non-INVITE client transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
};
NonInviteClientTransaction.prototype.timer_K = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
NonInviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code < 200) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
}
} else {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
window.clearTimeout(this.F);
if(status_code === 408) {
this.request_sender.onRequestTimeout();
} else {
this.request_sender.receiveResponse(response);
}
this.K = window.setTimeout(function() {tr.timer_K();}, JsSIP.Timers.TIMER_K);
break;
case C.STATUS_COMPLETED:
break;
}
}
};
var InviteClientTransaction = function(request_sender, request, transport) {
var via,
tr = this,
via_transport,
events = ['stateChanged'];
this.type = C.INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
this.logger = request_sender.ua.getLogger('jssip.transaction.ict', this.id);
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
// TODO: Adding here the cancel() method is a hack that must be fixed.
// Add the cancel property to the request.
//Will be called from the request instance, not the transaction itself.
this.request.cancel = function(reason) {
tr.cancel_request(tr, reason);
};
this.initEvents(events);
};
InviteClientTransaction.prototype = new JsSIP.EventEmitter();
InviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged', this);
};
InviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_CALLING);
this.B = window.setTimeout(function() {
tr.timer_B();
}, JsSIP.Timers.TIMER_B);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
InviteClientTransaction.prototype.onTransportError = function() {
this.logger.debug('transport error occurred, deleting INVITE client transaction ' + this.id);
window.clearTimeout(this.B);
window.clearTimeout(this.D);
window.clearTimeout(this.M);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
if (this.state !== C.STATUS_ACCEPTED) {
this.request_sender.onTransportError();
}
};
// RFC 6026 7.2
InviteClientTransaction.prototype.timer_M = function() {
this.logger.debug('Timer M expired for INVITE client transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
window.clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
}
};
// RFC 3261 17.1.1
InviteClientTransaction.prototype.timer_B = function() {
this.logger.debug('Timer B expired for INVITE client transaction ' + this.id);
if(this.state === C.STATUS_CALLING) {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
}
};
InviteClientTransaction.prototype.timer_D = function() {
this.logger.debug('Timer D expired for INVITE client transaction ' + this.id);
window.clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
InviteClientTransaction.prototype.sendACK = function(response) {
var tr = this;
this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n';
this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n';
}
this.ack += 'To: ' + response.getHeader('to') + '\r\n';
this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n';
this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n';
this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0];
this.ack += ' ACK\r\n';
this.ack += 'Content-Length: 0\r\n\r\n';
this.D = window.setTimeout(function() {tr.timer_D();}, JsSIP.Timers.TIMER_D);
this.transport.send(this.ack);
};
InviteClientTransaction.prototype.cancel_request = function(tr, reason) {
var request = tr.request;
this.cancel = JsSIP.C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n';
this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n';
}
this.cancel += 'To: ' + request.headers.To.toString() + '\r\n';
this.cancel += 'From: ' + request.headers.From.toString() + '\r\n';
this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n';
this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] +
' CANCEL\r\n';
if(reason) {
this.cancel += 'Reason: ' + reason + '\r\n';
}
this.cancel += 'Content-Length: 0\r\n\r\n';
// Send only if a provisional response (>100) has been received.
if(this.state === C.STATUS_PROCEEDING) {
this.transport.send(this.cancel);
}
};
InviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_CALLING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_PROCEEDING:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.M = window.setTimeout(function() {
tr.timer_M();
}, JsSIP.Timers.TIMER_M);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_ACCEPTED:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.sendACK(response);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_COMPLETED:
this.sendACK(response);
break;
}
}
};
var AckClientTransaction = function(request_sender, request, transport) {
var via,
via_transport;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
this.logger = request_sender.ua.getLogger('jssip.transaction.nict', this.id);
if (request_sender.ua.configuration.hack_via_tcp) {
via_transport = 'TCP';
}
else if (request_sender.ua.configuration.hack_via_ws) {
via_transport = 'WS';
}
else {
via_transport = transport.server.scheme;
}
via = 'SIP/2.0/' + via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
};
AckClientTransaction.prototype = new JsSIP.EventEmitter();
AckClientTransaction.prototype.send = function() {
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
AckClientTransaction.prototype.onTransportError = function() {
this.logger.debug('transport error occurred, for an ACK client transaction ' + this.id);
this.request_sender.onTransportError();
};
var NonInviteServerTransaction = function(request, ua) {
var events = ['stateChanged'];
this.type = C.NON_INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.logger = ua.getLogger('jssip.transaction.nist', this.id);
this.state = C.STATUS_TRYING;
ua.newTransaction(this);
this.initEvents(events);
};
NonInviteServerTransaction.prototype = new JsSIP.EventEmitter();
NonInviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged', this);
};
NonInviteServerTransaction.prototype.timer_J = function() {
this.logger.debug('Timer J expired for non-INVITE server transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
NonInviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
this.logger.debug('transport error occurred, deleting non-INVITE server transaction ' + this.id);
window.clearTimeout(this.J);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code === 100) {
/* RFC 4320 4.1
* 'A SIP element MUST NOT
* send any provisional response with a
* Status-Code other than 100 to a non-INVITE request.'
*/
switch(this.state) {
case C.STATUS_TRYING:
this.stateChanged(C.STATUS_PROCEEDING);
if(!this.transport.send(response)) {
this.onTransportError();
}
break;
case C.STATUS_PROCEEDING:
this.last_response = response;
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 200 && status_code <= 699) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.last_response = response;
this.J = window.setTimeout(function() {
tr.timer_J();
}, JsSIP.Timers.TIMER_J);
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
case C.STATUS_COMPLETED:
break;
}
}
};
var InviteServerTransaction = function(request, ua) {
var events = ['stateChanged'];
this.type = C.INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.logger = ua.getLogger('jssip.transaction.ist', this.id);
this.state = C.STATUS_PROCEEDING;
ua.newTransaction(this);
this.resendProvisionalTimer = null;
request.reply(100);
this.initEvents(events);
};
InviteServerTransaction.prototype = new JsSIP.EventEmitter();
InviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged', this);
};
InviteServerTransaction.prototype.timer_H = function() {
this.logger.debug('Timer H expired for INVITE server transaction ' + this.id);
if(this.state === C.STATUS_COMPLETED) {
this.logger.log('transactions', 'ACK for INVITE server transaction was never received, call will be terminated');
}
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
InviteServerTransaction.prototype.timer_I = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
// RFC 6026 7.1
InviteServerTransaction.prototype.timer_L = function() {
this.logger.debug('Timer L expired for INVITE server transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
this.logger.debug('transport error occurred, deleting INVITE server transaction ' + this.id);
if (this.resendProvisionalTimer !== null) {
window.clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
window.clearTimeout(this.L);
window.clearTimeout(this.H);
window.clearTimeout(this.I);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.resend_provisional = function() {
if(!this.transport.send(this.last_response)) {
this.onTransportError();
}
};
// INVITE Server Transaction RFC 3261 17.2.1
InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if(!this.transport.send(response)) {
this.onTransportError();
}
this.last_response = response;
break;
}
}
if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) {
// Trigger the resendProvisionalTimer only for the first non 100 provisional response.
if(this.resendProvisionalTimer === null) {
this.resendProvisionalTimer = window.setInterval(function() {
tr.resend_provisional();}, JsSIP.Timers.PROVISIONAL_RESPONSE_INTERVAL);
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.last_response = response;
this.L = window.setTimeout(function() {
tr.timer_L();
}, JsSIP.Timers.TIMER_L);
if (this.resendProvisionalTimer !== null) {
window.clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
/* falls through */
case C.STATUS_ACCEPTED:
// Note that this point will be reached for proceeding tr.state also.
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if (this.resendProvisionalTimer !== null) {
window.clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else {
this.stateChanged(C.STATUS_COMPLETED);
this.H = window.setTimeout(function() {
tr.timer_H();
}, JsSIP.Timers.TIMER_H);
if (onSuccess) {
onSuccess();
}
}
break;
}
}
};
/**
* INVITE:
* _true_ if retransmission
* _false_ new request
*
* ACK:
* _true_ ACK to non2xx response
* _false_ ACK must be passed to TU (accepted state)
* ACK to 2xx response
*
* CANCEL:
* _true_ no matching invite transaction
* _false_ matching invite transaction and no final response sent
*
* OTHER:
* _true_ retransmission
* _false_ new request
*/
var checkTransaction = function(ua, request) {
var tr;
switch(request.method) {
case JsSIP.C.INVITE:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_PROCEEDING:
tr.transport.send(tr.last_response);
break;
// RFC 6026 7.1 Invite retransmission
//received while in C.STATUS_ACCEPTED state. Absorb it.
case C.STATUS_ACCEPTED:
break;
}
return true;
}
break;
case JsSIP.C.ACK:
tr = ua.transactions.ist[request.via_branch];
// RFC 6026 7.1
if(tr) {
if(tr.state === C.STATUS_ACCEPTED) {
return false;
} else if(tr.state === C.STATUS_COMPLETED) {
tr.state = C.STATUS_CONFIRMED;
tr.I = window.setTimeout(function() {tr.timer_I();}, JsSIP.Timers.TIMER_I);
return true;
}
}
// ACK to 2XX Response.
else {
return false;
}
break;
case JsSIP.C.CANCEL:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
request.reply_sl(200);
if(tr.state === C.STATUS_PROCEEDING) {
return false;
} else {
return true;
}
} else {
request.reply_sl(481);
return true;
}
break;
default:
// Non-INVITE Server Transaction RFC 3261 17.2.2
tr = ua.transactions.nist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_TRYING:
break;
case C.STATUS_PROCEEDING:
case C.STATUS_COMPLETED:
tr.transport.send(tr.last_response);
break;
}
return true;
}
break;
}
};
JsSIP.Transactions = {
C: C,
checkTransaction: checkTransaction,
NonInviteClientTransaction: NonInviteClientTransaction,
InviteClientTransaction: InviteClientTransaction,
AckClientTransaction: AckClientTransaction,
NonInviteServerTransaction: NonInviteServerTransaction,
InviteServerTransaction: InviteServerTransaction
};
}(JsSIP));
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.10.0 (2021-10-11)
*/
(function () {
'use strict';
var global$3 = tinymce.util.Tools.resolve('tinymce.PluginManager');
var eq = function (t) {
return function (a) {
return t === a;
};
};
var isNull = eq(null);
var noop = function () {
};
var constant = function (value) {
return function () {
return value;
};
};
var identity = function (x) {
return x;
};
var never = constant(false);
var always = constant(true);
var none = function () {
return NONE;
};
var NONE = function () {
var call = function (thunk) {
return thunk();
};
var id = identity;
var me = {
fold: function (n, _s) {
return n();
},
isSome: never,
isNone: always,
getOr: id,
getOrThunk: call,
getOrDie: function (msg) {
throw new Error(msg || 'error: getOrDie called on none.');
},
getOrNull: constant(null),
getOrUndefined: constant(undefined),
or: id,
orThunk: call,
map: none,
each: noop,
bind: none,
exists: never,
forall: always,
filter: function () {
return none();
},
toArray: function () {
return [];
},
toString: constant('none()')
};
return me;
}();
var some = function (a) {
var constant_a = constant(a);
var self = function () {
return me;
};
var bind = function (f) {
return f(a);
};
var me = {
fold: function (n, s) {
return s(a);
},
isSome: always,
isNone: never,
getOr: constant_a,
getOrThunk: constant_a,
getOrDie: constant_a,
getOrNull: constant_a,
getOrUndefined: constant_a,
or: self,
orThunk: self,
map: function (f) {
return some(f(a));
},
each: function (f) {
f(a);
},
bind: bind,
exists: bind,
forall: bind,
filter: function (f) {
return f(a) ? me : NONE;
},
toArray: function () {
return [a];
},
toString: function () {
return 'some(' + a + ')';
}
};
return me;
};
var from = function (value) {
return value === null || value === undefined ? NONE : some(value);
};
var Optional = {
some: some,
none: none,
from: from
};
var exists = function (xs, pred) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
if (pred(x, i)) {
return true;
}
}
return false;
};
var map$1 = function (xs, f) {
var len = xs.length;
var r = new Array(len);
for (var i = 0; i < len; i++) {
var x = xs[i];
r[i] = f(x, i);
}
return r;
};
var each$1 = function (xs, f) {
for (var i = 0, len = xs.length; i < len; i++) {
var x = xs[i];
f(x, i);
}
};
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
return {
get: get,
set: set
};
};
var last = function (fn, rate) {
var timer = null;
var cancel = function () {
if (!isNull(timer)) {
clearTimeout(timer);
timer = null;
}
};
var throttle = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
cancel();
timer = setTimeout(function () {
timer = null;
fn.apply(null, args);
}, rate);
};
return {
cancel: cancel,
throttle: throttle
};
};
var insertEmoticon = function (editor, ch) {
editor.insertContent(ch);
};
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 keys = Object.keys;
var hasOwnProperty = Object.hasOwnProperty;
var each = function (obj, f) {
var props = keys(obj);
for (var k = 0, len = props.length; k < len; k++) {
var i = props[k];
var x = obj[i];
f(x, i);
}
};
var map = function (obj, f) {
return tupleMap(obj, function (x, i) {
return {
k: i,
v: f(x, i)
};
});
};
var tupleMap = function (obj, f) {
var r = {};
each(obj, function (x, i) {
var tuple = f(x, i);
r[tuple.k] = tuple.v;
});
return r;
};
var has = function (obj, key) {
return hasOwnProperty.call(obj, key);
};
var shallow = function (old, nu) {
return nu;
};
var baseMerge = function (merger) {
return function () {
var objects = [];
for (var _i = 0; _i < arguments.length; _i++) {
objects[_i] = arguments[_i];
}
if (objects.length === 0) {
throw new Error('Can\'t merge zero objects');
}
var ret = {};
for (var j = 0; j < objects.length; j++) {
var curObject = objects[j];
for (var key in curObject) {
if (has(curObject, key)) {
ret[key] = merger(ret[key], curObject[key]);
}
}
}
return ret;
};
};
var merge = baseMerge(shallow);
var singleton = function (doRevoke) {
var subject = Cell(Optional.none());
var revoke = function () {
return subject.get().each(doRevoke);
};
var clear = function () {
revoke();
subject.set(Optional.none());
};
var isSet = function () {
return subject.get().isSome();
};
var get = function () {
return subject.get();
};
var set = function (s) {
revoke();
subject.set(Optional.some(s));
};
return {
clear: clear,
isSet: isSet,
get: get,
set: set
};
};
var value = function () {
var subject = singleton(noop);
var on = function (f) {
return subject.get().each(f);
};
return __assign(__assign({}, subject), { on: on });
};
var checkRange = function (str, substr, start) {
return substr === '' || str.length >= substr.length && str.substr(start, start + substr.length) === substr;
};
var contains = function (str, substr) {
return str.indexOf(substr) !== -1;
};
var startsWith = function (str, prefix) {
return checkRange(str, prefix, 0);
};
var global$2 = tinymce.util.Tools.resolve('tinymce.Resource');
var global$1 = tinymce.util.Tools.resolve('tinymce.util.Delay');
var global = tinymce.util.Tools.resolve('tinymce.util.Promise');
var DEFAULT_ID = 'tinymce.plugins.emoticons';
var getEmoticonDatabase = function (editor) {
return editor.getParam('emoticons_database', 'emojis', 'string');
};
var getEmoticonDatabaseUrl = function (editor, pluginUrl) {
var database = getEmoticonDatabase(editor);
return editor.getParam('emoticons_database_url', pluginUrl + '/js/' + database + editor.suffix + '.js', 'string');
};
var getEmoticonDatabaseId = function (editor) {
return editor.getParam('emoticons_database_id', DEFAULT_ID, 'string');
};
var getAppendedEmoticons = function (editor) {
return editor.getParam('emoticons_append', {}, 'object');
};
var getEmotionsImageUrl = function (editor) {
return editor.getParam('emoticons_images_url', 'https://twemoji.maxcdn.com/v/13.0.1/72x72/', 'string');
};
var ALL_CATEGORY = 'All';
var categoryNameMap = {
symbols: 'Symbols',
people: 'People',
animals_and_nature: 'Animals and Nature',
food_and_drink: 'Food and Drink',
activity: 'Activity',
travel_and_places: 'Travel and Places',
objects: 'Objects',
flags: 'Flags',
user: 'User Defined'
};
var translateCategory = function (categories, name) {
return has(categories, name) ? categories[name] : name;
};
var getUserDefinedEmoticons = function (editor) {
var userDefinedEmoticons = getAppendedEmoticons(editor);
return map(userDefinedEmoticons, function (value) {
return __assign({
keywords: [],
category: 'user'
}, value);
});
};
var initDatabase = function (editor, databaseUrl, databaseId) {
var categories = value();
var all = value();
var emojiImagesUrl = getEmotionsImageUrl(editor);
var getEmoji = function (lib) {
if (startsWith(lib.char, '<img')) {
return lib.char.replace(/src="([^"]+)"/, function (match, url) {
return 'src="' + emojiImagesUrl + url + '"';
});
} else {
return lib.char;
}
};
var processEmojis = function (emojis) {
var cats = {};
var everything = [];
each(emojis, function (lib, title) {
var entry = {
title: title,
keywords: lib.keywords,
char: getEmoji(lib),
category: translateCategory(categoryNameMap, lib.category)
};
var current = cats[entry.category] !== undefined ? cats[entry.category] : [];
cats[entry.category] = current.concat([entry]);
everything.push(entry);
});
categories.set(cats);
all.set(everything);
};
editor.on('init', function () {
global$2.load(databaseId, databaseUrl).then(function (emojis) {
var userEmojis = getUserDefinedEmoticons(editor);
processEmojis(merge(emojis, userEmojis));
}, function (err) {
console.log('Failed to load emoticons: ' + err);
categories.set({});
all.set([]);
});
});
var listCategory = function (category) {
if (category === ALL_CATEGORY) {
return listAll();
}
return categories.get().bind(function (cats) {
return Optional.from(cats[category]);
}).getOr([]);
};
var listAll = function () {
return all.get().getOr([]);
};
var listCategories = function () {
return [ALL_CATEGORY].concat(keys(categories.get().getOr({})));
};
var waitForLoad = function () {
if (hasLoaded()) {
return global.resolve(true);
} else {
return new global(function (resolve, reject) {
var numRetries = 15;
var interval = global$1.setInterval(function () {
if (hasLoaded()) {
global$1.clearInterval(interval);
resolve(true);
} else {
numRetries--;
if (numRetries < 0) {
console.log('Could not load emojis from url: ' + databaseUrl);
global$1.clearInterval(interval);
reject(false);
}
}
}, 100);
});
}
};
var hasLoaded = function () {
return categories.isSet() && all.isSet();
};
return {
listCategories: listCategories,
hasLoaded: hasLoaded,
waitForLoad: waitForLoad,
listAll: listAll,
listCategory: listCategory
};
};
var emojiMatches = function (emoji, lowerCasePattern) {
return contains(emoji.title.toLowerCase(), lowerCasePattern) || exists(emoji.keywords, function (k) {
return contains(k.toLowerCase(), lowerCasePattern);
});
};
var emojisFrom = function (list, pattern, maxResults) {
var matches = [];
var lowerCasePattern = pattern.toLowerCase();
var reachedLimit = maxResults.fold(function () {
return never;
}, function (max) {
return function (size) {
return size >= max;
};
});
for (var i = 0; i < list.length; i++) {
if (pattern.length === 0 || emojiMatches(list[i], lowerCasePattern)) {
matches.push({
value: list[i].char,
text: list[i].title,
icon: list[i].char
});
if (reachedLimit(matches.length)) {
break;
}
}
}
return matches;
};
var patternName = 'pattern';
var open = function (editor, database) {
var initialState = {
pattern: '',
results: emojisFrom(database.listAll(), '', Optional.some(300))
};
var currentTab = Cell(ALL_CATEGORY);
var scan = function (dialogApi) {
var dialogData = dialogApi.getData();
var category = currentTab.get();
var candidates = database.listCategory(category);
var results = emojisFrom(candidates, dialogData[patternName], category === ALL_CATEGORY ? Optional.some(300) : Optional.none());
dialogApi.setData({ results: results });
};
var updateFilter = last(function (dialogApi) {
scan(dialogApi);
}, 200);
var searchField = {
label: 'Search',
type: 'input',
name: patternName
};
var resultsField = {
type: 'collection',
name: 'results'
};
var getInitialState = function () {
var body = {
type: 'tabpanel',
tabs: map$1(database.listCategories(), function (cat) {
return {
title: cat,
name: cat,
items: [
searchField,
resultsField
]
};
})
};
return {
title: 'Emoticons',
size: 'normal',
body: body,
initialData: initialState,
onTabChange: function (dialogApi, details) {
currentTab.set(details.newTabName);
updateFilter.throttle(dialogApi);
},
onChange: updateFilter.throttle,
onAction: function (dialogApi, actionData) {
if (actionData.name === 'results') {
insertEmoticon(editor, actionData.value);
dialogApi.close();
}
},
buttons: [{
type: 'cancel',
text: 'Close',
primary: true
}]
};
};
var dialogApi = editor.windowManager.open(getInitialState());
dialogApi.focus(patternName);
if (!database.hasLoaded()) {
dialogApi.block('Loading emoticons...');
database.waitForLoad().then(function () {
dialogApi.redial(getInitialState());
updateFilter.throttle(dialogApi);
dialogApi.focus(patternName);
dialogApi.unblock();
}).catch(function (_err) {
dialogApi.redial({
title: 'Emoticons',
body: {
type: 'panel',
items: [{
type: 'alertbanner',
level: 'error',
icon: 'warning',
text: '<p>Could not load emoticons</p>'
}]
},
buttons: [{
type: 'cancel',
text: 'Close',
primary: true
}],
initialData: {
pattern: '',
results: []
}
});
dialogApi.focus(patternName);
dialogApi.unblock();
});
}
};
var register$1 = function (editor, database) {
editor.addCommand('mceEmoticons', function () {
return open(editor, database);
});
};
var setup = function (editor) {
editor.on('PreInit', function () {
editor.parser.addAttributeFilter('data-emoticon', function (nodes) {
each$1(nodes, function (node) {
node.attr('data-mce-resize', 'false');
node.attr('data-mce-placeholder', '1');
});
});
});
};
var init = function (editor, database) {
editor.ui.registry.addAutocompleter('emoticons', {
ch: ':',
columns: 'auto',
minChars: 2,
fetch: function (pattern, maxResults) {
return database.waitForLoad().then(function () {
var candidates = database.listAll();
return emojisFrom(candidates, pattern, Optional.some(maxResults));
});
},
onAction: function (autocompleteApi, rng, value) {
editor.selection.setRng(rng);
editor.insertContent(value);
autocompleteApi.hide();
}
});
};
var register = function (editor) {
var onAction = function () {
return editor.execCommand('mceEmoticons');
};
editor.ui.registry.addButton('emoticons', {
tooltip: 'Emoticons',
icon: 'emoji',
onAction: onAction
});
editor.ui.registry.addMenuItem('emoticons', {
text: 'Emoticons...',
icon: 'emoji',
onAction: onAction
});
};
function Plugin () {
global$3.add('emoticons', function (editor, pluginUrl) {
var databaseUrl = getEmoticonDatabaseUrl(editor, pluginUrl);
var databaseId = getEmoticonDatabaseId(editor);
var database = initDatabase(editor, databaseUrl, databaseId);
register$1(editor, database);
register(editor);
init(editor, database);
setup(editor);
});
}
Plugin();
}());
|
/*
* ajaxify.js
* Ajaxify - The Ajax Plugin
* https://4nf.org/
*
* Copyright Arvind Gupta; MIT Licensed
*/
/* INTERFACE: See also https://4nf.org/interface/
Simplest plugin call:
let ajaxify = new Ajaxify({options});
Ajaxifies the whole site, dynamically replacing the elements specified in "elements" across pages
*/
// The main plugin - Ajaxify
// Is passed the global options
// Checks for necessary pre-conditions - otherwise gracefully degrades
// Initialises sub-plugins
// Calls Pronto
class Ajaxify { constructor(options) {
String.prototype.iO = function(s) { return this.toString().indexOf(s) + 1; }; //Intuitively better understandable shorthand for String.indexOf() - String.iO()
let $ = this;
//Options default values
$.s = {
// basic config parameters
elements: "body", //selector for element IDs that are going to be swapped (e.g. "#el1, #el2, #el3")
selector : "a:not(.no-ajaxy)", //selector for links to trigger swapping - not elements to be swapped - i.e. a selection of links
forms : "form:not(.no-ajaxy)", // selector for ajaxifying forms - set to "false" to disable
canonical : false, // Fetch current URL from "canonical" link if given, updating the History API. In case of a re-direct...
refresh : false, // Refresh the page even if link clicked is current page
// visual effects settings
requestDelay : 0, //in msec - Delay of Pronto request
scrolltop : "s", // Smart scroll, true = always scroll to top of page, false = no scroll
bodyClasses : false, // Copy body classes from target page, set to "true" to enable
// script and style handling settings, prefetch
deltas : true, // true = deltas loaded, false = all scripts loaded
asyncdef : true, // default async value for dynamically inserted external scripts, false = synchronous / true = asynchronous
alwayshints : false, // strings, - separated by ", " - if matched in any external script URL - these are always loaded on every page load
inline : true, // true = all inline scripts loaded, false = only specific inline scripts are loaded
inlinesync : true, // synchronise inline scripts loading by adding a central tiny delay to all of them
inlinehints : false, // strings - separated by ", " - if matched in any inline scripts - only these are executed - set "inline" to false beforehand
inlineskip : "adsbygoogle", // strings - separated by ", " - if matched in any inline scripts - these are NOT are executed - set "inline" to true beforehand
inlineappend : true, // append scripts to the main content element, instead of "eval"-ing them
style : true, // true = all style tags in the head loaded, false = style tags on target page ignored
prefetchoff : false, // Plugin pre-fetches pages on hoverIntent - true = set off completely // strings - separated by ", " - hints to select out
// debugging & advanced settings
verbosity : 0, //Debugging level to console: default off. Can be set to 10 and higher (in case of logging enabled)
memoryoff : false, // strings - separated by ", " - if matched in any URLs - only these are NOT executed - set to "true" to disable memory completely
cb : 0, // callback handler on completion of each Ajax request - default 0
pluginon : true, // Plugin set "on" or "off" (==false) manually
passCount: false // Show number of pass for debugging
};
$.pass = 0; $.currentURL = "";
$.parse = (s, pl) => (pl = document.createElement('div'), pl.insertAdjacentHTML('afterbegin', s), pl.firstElementChild); // HTML parser
$.trigger = (t, e) => { let ev = document.createEvent('HTMLEvents'); ev.initEvent("pronto." + t, true, false); ev.data = e ? e : $.Rq("e"); window.dispatchEvent(ev); }
$.internal = (url) => { if (!url) return false; if (typeof(url) === "object") url = url.href; if (url==="") return true; return url.substring(0,rootUrl.length) === rootUrl || !url.iO(":"); }
//Module global variables
let rootUrl = location.origin, api = window.history && window.history.pushState && window.history.replaceState,
//Regexes for escaping fetched HTML of a whole page - best of Baluptons Ajaxify
//Makes it possible to pre-fetch an entire page
docType = /<\!DOCTYPE[^>]*>/i,
tagso = /<(html|head|link)([\s\>])/gi,
tagsod = /<(body)([\s\>])/gi,
tagsc = /<\/(html|head|body|link)\>/gi,
//Helper strings
div12 = '<div class="ajy-$1"$2',
divid12 = '<div id="ajy-$1"$2',
linki = '<link rel="stylesheet" type="text/css" href="*" />',
linkr = 'link[href*="!"]',
scrr = 'script[src*="!"]',
inlineclass = "ajy-inline";
//Global helpers
let doc=document, bdy,
qa=(s,o=doc)=>o.querySelectorAll(s),
qs=(s,o=doc)=>o.querySelector(s);
function _copyAttributes(el, $S, flush) { //copy all attributes of element generically
if (flush) [...el.attributes].forEach(e => el.removeAttribute(e.name)); //delete all old attributes
[...$S.attributes].forEach(e => el.setAttribute(e.nodeName, e.nodeValue)); //low-level insertion
}
function _on(eventName, elementSelector, handler, el = document) { //e.currentTarget is document when the handler is called
el.addEventListener(eventName, function(e) {
// loop parent nodes from the target to the delegation node
for (var target = e.target; target && target != this; target = target.parentNode) {
if (target.matches(elementSelector)) {
handler(target, e);
break;
}
}
}, !!eventName.iO('mo'));
}
function Hints(hints) {
if (!(this instanceof Hints)) return new Hints(hints); //automatically create an instance
this.myHints = (typeof hints === 'string' && hints.length > 0) ? hints.split(", ") : false; //hints are passed as a comma separated string
}
Hints.prototype.find = function (t) {return (!t || !this.myHints) ? false : this.myHints.some(h => t.iO(h))}; //iterate through hints within passed text (t)
function lg(m){ $.s.verbosity && console && console.log(m); }
// The stateful Cache class
// Usage - parameter "o" values:
// none - returns currently cached page
// <URL> - returns page with specified URL
// <object> - saves the page in cache
// f - flushes the cache
class Cache { constructor() {
let d = false;
this.a = function (o) {
if (!o) return d;
if (typeof o === "string") { //URL or "f" passed
if(o === "f") { //"f" passed -> flush
$.pages("f"); //delegate flush to $.pages
lg("Cache flushed");
} else d = $.pages($.memory(o)); //URL passed -> look up page in memory
return d; //return cached page
}
if (typeof o === "object") {
d = o;
return d;
}
};
}}
// The stateful Memory class
// Usage: $.memory(<URL>) - returns the same URL if not turned off internally
class Memory { constructor(options) {
this.a = function (h) {
if (!h || $.s.memoryoff === true) return false;
if ($.s.memoryoff === false) return h;
return Hints($.s.memoryoff).find(h) ? false : h;
};
}}
// The stateful Pages class
// Usage - parameter "h" values:
// <URL> - returns page with specified URL from internal array
// <object> - saves the passed page in internal array
// false - returns false
class Pages { constructor() {
let d = [], i = -1;
this.a = function (h) {
if (typeof h === "string") {
if(h === "f") d = [];
else if((i=_iPage(h)) !== -1) return d[i][1];
}
if (typeof h === "object") {
if((i=_iPage(h)) === -1) d.push(h);
else d[i] = h;
}
if (typeof h === "boolean") return false;
};
let _iPage = h => d.findIndex(e => e[0] == h)
}}
// The GetPage class
// First parameter (o) is a switch:
// empty - returns cache
// <URL> - loads HTML via Ajax, second parameter "p" must be callback
// + - pre-fetches page, second parameter "p" must be URL, third parameter "p2" must be callback
// - - loads page into DOM and handle scripts, second parameter "p" must hold selection to load
// x - returns response
// otherwise - returns selection of current page to client
class GetPage { constructor() {
let rsp = 0, cb = 0, plus = 0, rt = "", ct = 0, rc = 0, ac = 0;
this.a = function (o, p, p2) {
if (!o) return $.cache();
if (o.iO("/")) {
cb = p;
if(plus == o) return;
return _lPage(o);
}
if (o === "+") {
plus = p;
cb = p2;
return _lPage(p, true);
}
if (o === "a") { if (rc > 0) {_cl(); ac.abort();} return; }
if (o === "s") return ((rc) ? 1 : 0) + rt;
if (o === "-") return _lSel(p);
if (o === "x") return rsp;
if (!$.cache()) return;
if (o === "body") return qs("#ajy-" + o, $.cache());
if (o === "script") return qa(o, $.cache());
return qs((o === "title") ? o : ".ajy-" + o, $.cache());
};
let _lSel = $t => (
$.pass++,
_lEls($t),
qa("body > script").forEach(e => (e.classList.contains(inlineclass)) ? e.parentNode.removeChild(e) : false),
$.scripts(true),
$.scripts("s"),
$.scripts("c")
),
_lPage = (h, pre) => {
if (h.iO("#")) h = h.split("#")[0];
if ($.Rq("is") || !$.cache(h)) return _lAjax(h, pre);
plus = 0;
if (cb) return cb();
},
_ld = ($t, $h) => {
if(!$h) {
lg("Inserting placeholder for ID: " + $t.getAttribute("id"));
var tagN = $t.tagName.toLowerCase();
$t.parentNode.replaceChild($.parse("<" + tagN + " id='" + $t.getAttribute("id") + "'></" + tagN + ">"), $t);
return;
}
var $c = $h.cloneNode(true); // clone element node (true = deep clone)
qa("script", $c).forEach(e => e.parentNode.removeChild(e));
_copyAttributes($t, $c, true);
$t.innerHTML = $c.innerHTML;
},
_lEls = $t =>
$.cache() && !_isBody($t) && $t.forEach(function($el) {
_ld($el, qs("#" + $el.getAttribute("id"), $.cache()));
}),
_isBody = $t => $t[0].tagName.toLowerCase() == "body" && (_ld(bdy, qs("#ajy-body", $.cache())), 1),
_lAjax = (hin, pre) => {
var ispost = $.Rq("is");
if (pre) rt="p"; else rt="c";
ac = new AbortController(); // set abort controller
rc++; // set active request counter
fetch(hin, {
method: ((ispost) ? "POST" : "GET"),
cache: "default",
mode: "same-origin",
headers: {"X-Requested-With": "XMLHttpRequest"},
body: (ispost) ? $.Rq("d") : null,
signal: ac.signal
}).then(r => {
if (!r.ok || !_isHtml(r)) {
if (!pre) {location.href = hin; _cl(); $.pronto(0, $.currentURL);}
return;
}
rsp = r; // store response
return r.text();
}).then(r => {
_cl(1); // clear only plus variable
if (!r) return; // ensure data
rsp.responseText = r; // store response text
return _cache(hin, r);
}).catch(err => {
if(err.name === "AbortError") return;
try {
$.trigger("error", err);
lg("Response text : " + err.message);
return _cache(hin, err.message, err);
} catch (e) {}
}).finally(() => rc--); // reset active request counter
},
_cl = c => (plus = 0, (!c) ? cb = 0 : 0), // clear plus AND/OR callback
_cache = (href, h, err) => $.cache($.parse(_parseHTML(h))) && ($.pages([href, $.cache()]), 1) && cb && cb(err),
_isHtml = x => (ct = x.headers.get("content-type")) && (ct.iO("html") || ct.iO("form-")),
_parseHTML = h => document.createElement("html").innerHTML = _replD(h).trim(),
_replD = h => String(h).replace(docType, "").replace(tagso, div12).replace(tagsod, divid12).replace(tagsc, "</div>")
}}
// The stateful Scripts plugin
// First parameter "o" is switch:
// i - initailise options
// c - fetch canonical URL
// <object> - handle one inline script
// otherwise - delta loading
class Scripts { constructor() {
let $s = false, txt = 0;
this.a = function (o) {
if (o === "i") {
if(!$s) $s = {};
return true;
}
if (o === "s") return _allstyle($s.y);
if (o === "1") {
$.detScripts($s);
return _addScripts($s);
}
if (o === "c") return $.s.canonical && $s.can ? $s.can.getAttribute("href") : false;
if (o === "d") return $.detScripts($s);
if (o && typeof o == "object") return _onetxt(o);
if ($.scripts("d")) return;
_addScripts($s);
};
let _allstyle = $s =>
!$.s.style || !$s || (
qa("style", qs("head")).forEach(e => e.parentNode.removeChild(e)),
$s.forEach(el => _addstyle(el.textContent))
),
_onetxt = $s =>
(!(txt = $s.textContent).iO(").ajaxify(") && (!txt.iO("new Ajaxify(")) &&
(($.s.inline && !Hints($.s.inlineskip).find(txt)) || $s.classList.contains("ajaxy") ||
Hints($.s.inlinehints).find(txt))
) && _addtxt($s),
_addtxt = $s => {
if(!txt || !txt.length) return;
if($.s.inlineappend || ($s.getAttribute("type") && !$s.getAttribute("type").iO("text/javascript"))) try { return _apptxt($s); } catch (e) { }
try { eval(txt); } catch (e1) {
lg("Error in inline script : " + txt + "\nError code : " + e1);
}
},
_apptxt = $s => { let sc = document.createElement("script"); _copyAttributes(sc, $s); sc.classList.add(inlineclass);
try {sc.appendChild(document.createTextNode($s.textContent))} catch(e) {sc.text = $s.textContent};
return qs("body").appendChild(sc);
},
_addstyle = t => qs("head").appendChild($.parse('<style>' + t + '</style>')),
_addScripts = $s => ( $.addAll($s.c, "href"), $.s.inlinesync ? setTimeout(() => $.addAll($s.j, "src")) : $.addAll($s.j, "src"))
}}
// The DetScripts plugin - stands for "detach scripts"
// Works on "$s" <object> that is passed in and fills it
// Fetches all stylesheets in the head
// Fetches the canonical URL
// Fetches all external scripts on the page
// Fetches all inline scripts on the page
class DetScripts { constructor() {
let head = 0, lk = 0, j = 0;
this.a = function ($s) {
head = $.pass ? $.fn("head") : qs("head"); //If "pass" is 0 -> fetch head from DOM, otherwise from target page
if (!head) return true;
lk = qa($.pass ? ".ajy-link" : "link", head); //If "pass" is 0 -> fetch links from DOM, otherwise from target page
j = $.pass ? $.fn("script") : qa("script"); //If "pass" is 0 -> fetch JSs from DOM, otherwise from target page
$s.c = _rel(lk, "stylesheet"); //Extract stylesheets
$s.y = qa("style", head); //Extract style tags
$s.can = _rel(lk, "canonical"); //Extract canonical tag
$s.j = j; //Assign JSs to internal selection
};
let _rel = (lk, v) => Array.prototype.filter.call(lk, e => e.getAttribute("rel").iO(v));
}}
// The AddAll plugin
// Works on a new selection of scripts to apply delta-loading to it
// pk parameter:
// href - operate on stylesheets in the new selection
// src - operate on JS scripts
class AddAll { constructor() {
let $scriptsO = [], $sCssO = [], $sO = [], PK = 0, url = 0;
this.a = function ($this, pk) {
if(!$this.length) return; //ensure input
if($.s.deltas === "n") return true; //Delta-loading completely disabled
PK = pk; //Copy "primary key" into internal variable
if(!$.s.deltas) return _allScripts($this); //process all scripts
//deltas presumed to be "true" -> proceed with normal delta-loading
$scriptsO = PK == "href" ? $sCssO : $sO; //Copy old. Stylesheets or JS
if(!$.pass) _newArray($this); //Fill new array on initial load, nothing more
else $this.forEach(function(s) { //Iterate through selection
var $t = s;
url = $t.getAttribute(PK);
if(_classAlways($t)) { //Class always handling
_removeScript(); //remove from DOM
_iScript($t); //insert back single external script in the head
return;
}
if(url) { //URL?
if(!$scriptsO.some(e => e == url)) { // Test, whether new
$scriptsO.push(url); //If yes: Push to old array
_iScript($t);
}
//Otherwise nothing to do
return;
}
if(PK != "href" && !$t.classList.contains("no-ajaxy")) $.scripts($t); //Inline JS script? -> inject into DOM
});
};
let _allScripts = $t => $t.forEach(e => _iScript(e)),
_newArray = $t => $t.forEach(e => (url = e.getAttribute(PK)) ? $scriptsO.push(url) : 0),
_classAlways = $t => $t.getAttribute("data-class") == "always" || Hints($.s.alwayshints).find(url),
_iScript = $S => {
url = $S.getAttribute(PK);
if(PK == "href") return qs("head").appendChild($.parse(linki.replace("*", url)));
if(!url) return $.scripts($S);
var sc = document.createElement("script");
sc.async = $.s.asyncdef;
_copyAttributes(sc, $S);
qs("head").appendChild(sc);
},
_removeScript = () => qa((PK == "href" ? linkr : scrr).replace("!", url)).forEach(e => e.parentNode.removeChild(e))
}}
// The Rq plugin - stands for request
// Stores all kinds of and manages data concerning the pending request
// Simplifies the Pronto plugin by managing request data separately, instead of passing it around...
// Second parameter (p) : data
// First parameter (o) values:
// = - check whether internally stored "href" ("h") variable is the same as the global currentURL
// ! - update last request ("l") variable with passed href
// ? - Edin's intelligent plausibility check - can spawn an external fetch abort
// v - validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards
// i - initialise request defaults and return "c" (currentTarget)
// h - access internal href hard
// e - set / get internal "e" (event)
// p - set / get internal "p" (push flag)
// is - set / get internal "ispost" (flag whether request is a POST)
// d - set / get internal "d" (data for central $.ajax())
// C - set / get internal "can" ("href" of canonical URL)
// c - check whether simple canonical URL is given and return, otherwise return value passed in "p"
class RQ { constructor() {
let ispost = 0, data = 0, push = 0, can = 0, e = 0, c = 0, h = 0, l = false;
this.a = function (o, p, t) {
if(o === "=") {
if(p) return h === $.currentURL //check whether internally stored "href" ("h") variable is the same as the global currentURL
|| h === l; //or href of last request ("l")
return h === $.currentURL; //for click requests
}
if(o === "!") return l = h; //store href in "l" (last request)
if(o === "?") { //Edin previously called this "isOK" - powerful intelligent plausibility check
let xs=$.fn("s");
if (!xs.iO("0") && !p) $.fn("a"); //if fetch is not idle and new request is standard one, do ac.abort() to set it free
if (xs==="1c" && p) return false; //if fetch is processing standard request and new request is prefetch, cancel prefetch until fetch is finished
if (xs==="1p" && p) $.s.memoryoff ? $.fn("a") : 1; //if fetch is processing prefetch request and new request is prefetch do nothing (see [options] comment below)
//([semaphore options for requests] $.fn("a") -> abort previous, proceed with new | return false -> leave previous, stop new | return true -> proceed)
return true;
}
if(o === "v") { //validate value passed in "p", which is expected to be a click event value - also performs "i" afterwards
if(!p) return false; //ensure data
_setE(p, t); //Set event and href in one go
if(!$.internal(h)) return false; //if not internal -> report failure
o = "i"; //continue with "i"
}
if(o === "i") { //initialise request defaults and return "c" (currentTarget)
ispost = false; //GET assumed
data = null; //reset data
push = true; //assume we want to push URL to the History API
can = false; //reset can (canonical URL)
return h; //return "h" (href)
}
if(o === "h") { // Access href hard
if(p) {
if (typeof p === "string") e = 0; // Reset e -> default handler
h = (p.href) ? p.href : p; // Poke in href hard
}
return h; //href
}
if(o === "e") { //set / get internal "e" (event)
if(p) _setE(p, t); //Set event and href in one go
return e ? e : h; // Return "e" or if not given "h"
}
if(o === "p") { //set / get internal "p" (push flag)
if(p !== undefined) push = p;
return push;
}
if(o === "is") { //set / get internal "ispost" (flag whether request is a POST)
if(p !== undefined) ispost = p;
return ispost;
}
if(o === "d") { //set / get internal "d" (data for central $.ajax())
if(p) data = p;
return data;
}
if(o === "C") { //set internal "can" ("href" of canonical URL)
if(p !== undefined) can = p;
return can;
}
if(o === "c") return can && can !== p && !p.iO("#") && !p.iO("?") ? can : p; //get internal "can" ("href" of canonical URL)
};
let _setE = (p, t) => h = typeof (e = p) !== "string" ? (e.currentTarget && e.currentTarget.href) || (t && t.href) || e.currentTarget.action || e.originalEvent.state.url : e
}}
// The Frms plugin - stands for forms
// Ajaxify all forms in the specified divs
// Switch (o) values:
// d - set divs variable
// a - Ajaxify all forms in divs
class Frms { constructor() {
let fm = 0, divs = 0;
this.a = function (o, p) {
if (!$.s.forms || !o) return; //ensure data
if(o === "d") divs = p; //set divs variable
if(o === "a") divs.forEach(div => { //iterate through divs
Array.prototype.filter.call(qa($.s.forms, div), function(e) { //filter forms
let c = e.getAttribute("action");
return($.internal(c && c.length > 0 ? c : $.currentURL)); //ensure "action"
}).forEach(frm => { //iterate through forms
frm.addEventListener("submit", q => { //create event listener
fm = q.target; // fetch target
p = _k(); //Serialise data
var g = "get", //assume GET
m = fm.getAttribute("method"); //fetch method attribute
if (m.length > 0 && m.toLowerCase() == "post") g = "post"; //Override with "post"
var h, a = fm.getAttribute("action"); //fetch action attribute
if (a && a.length > 0) h = a; //found -> store
else h = $.currentURL; //not found -> select current URL
$.Rq("v", q); //validate request
if (g == "get") h = _b(h, p); //GET -> copy URL parameters
else {
$.Rq("is", true); //set is POST in request data
$.Rq("d", p); //save data in request data
}
$.trigger("submit", h); //raise pronto.submit event
$.pronto(0, { href: h }); //programmatically change page
q.preventDefault(); //prevent default form action
return(false); //success -> disable default behaviour
})
});
});
};
let _k = () => {
let o = new FormData(fm), n = qs("input[name][type=submit]", fm);
if (n) o.append(n.getAttribute("name"), n.value);
return o;
},
_b = (m, n) => {
let s = "";
if (m.iO("?")) m = m.substring(0, m.iO("?"));
for (var [k, v] of n.entries()) s += `${k}=${encodeURIComponent(v)}&`;
return `${m}?${s.slice(0,-1)}`;
}
}}
// The stateful Offsets plugin
// Usage:
// 1) $.offsets(<URL>) - returns offset of specified URL from internal array
// 2) $.offsets() - saves the current URL + offset in internal array
class Offsets { constructor() {
let d = [], i = -1;
this.a = function (h) {
if (typeof h === "string") { //Lookup page offset
h = h.iO("?") ? h.split("?")[0] : h; //Handle root URL only from dynamic pages
i = _iOffset(h); //Fetch offset
if(i === -1) return 0; // scrollTop if not found
return d[i][1]; //Return offset that was found
}
//Add page offset
var u = $.currentURL, us1 = u.iO("?") ? u.split("?")[0] : u, us = us1.iO("#") ? us1.split("#")[0] : us1, os = [us, (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop];
i = _iOffset(us); //get page index
if(i === -1) d.push(os); //doesn't exist -> push to array
else d[i] = os; //exists -> overwrite
};
let _iOffset = h => d.findIndex(e => e[0] == h)
}}
// The Scrolly plugin - manages scroll effects centrally
// scrolltop values: "s" - "smart" (default), true - always scroll to top, false - no scroll
// Switch (o) values:
// + - add current page to offsets
// ! - scroll to current page offset
class Scrolly { constructor() {
this.a = function (o) {
if(!o) return; //ensure operator
var op = o; //cache operator
if(o === "+" || o === "!") o = $.currentURL; //fetch currentURL for "+" and "-" operators
if(op !== "+" && o.iO("#") && (o.iO("#") < o.length - 1)) { //if hash in URL and not standalone hash
let $el = qs("#" + o.split("#")[1]); //fetch the element
if (!$el) return; //nothing found -> return quickly
let box = $el.getBoundingClientRect();
_scrll(box.top + window.pageYOffset - document.documentElement.clientTop); // ...animate to ID
return;
}
if($.s.scrolltop === "s") { //smart scroll enabled
if(op === "+") $.offsets(); //add page offset
if(op === "!") _scrll($.offsets(o)); //scroll to stored position of page
return;
}
if(op !== "+" && $.s.scrolltop) _scrll(0); //otherwise scroll to top of page
//default -> do nothing
};
let _scrll = o => window.scrollTo(0, o)
}}
// The hApi plugin - manages operatios on the History API centrally
// Second parameter (p) - set global currentURL
// Switch (o) values:
// = - perform a replaceState, using currentURL
// otherwise - perform a pushState, using currentURL
class HApi { constructor() {
this.a = function (o, p) {
if(!o) return; //ensure operator
if(p) $.currentURL = p; //if p given -> update current URL
if(o === "=") history.replaceState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform replaceState
else if ($.currentURL !== window.location.href) history.pushState({ url: $.currentURL }, "state-" + $.currentURL, $.currentURL); //perform pushState
};
}}
// The Pronto plugin - Pronto variant of Ben Plum's Pronto plugin - low level event handling in general
// Works on a selection, passed to Pronto by the selection, which specifies, which elements to Ajaxify
// Switch (h) values:
// i - initialise Pronto
// <object> - fetch href part and continue with _request()
// <URL> - set "h" variable of Rq hard and continue with _request()
class Pronto { constructor() {
let $gthis = 0, requestTimer = 0, pd = 150, ptim = 0;
this.a = function ($this, h) {
if(!h) return; //ensure data
if(h === "i") { //request to initialise
bdy = document.body;
if(!$this.length) $this = "body";
$gthis = qa($this); //copy selection to global selector
$.frms = new Frms().a; //initialise forms sub-plugin
if($.s.idleTime) $.slides = new classSlides($).a; //initialise optional slideshow sub-plugin
$.scrolly = new Scrolly().a; //initialise scroll effects sub-plugin
$.offsets = new Offsets().a;
$.hApi = new HApi().a;
_init_p(); //initialise Pronto sub-plugin
return $this; //return query selector for chaining
}
if(typeof(h) === "object") { //jump to internal page programmatically -> handler for forms sub-plugin
$.Rq("h", h);
_request();
return;
}
if(h.iO("/")) { //jump to internal page programmatically -> default handler
$.Rq("h", h);
_request(true);
}
};
let _init_p = () => {
$.hApi("=", window.location.href);
window.addEventListener("popstate", _onPop);
if ($.s.prefetchoff !== true) {
_on("mouseenter", $.s.selector, _preftime); // start prefetch timeout
_on("mouseleave", $.s.selector, _prefstop); // stop prefetch timeout
_on("touchstart", $.s.selector, _prefetch);
}
_on("click", $.s.selector, _click, bdy);
$.frms("d", qa("body"));
$.frms("a");
$.frms("d", $gthis);
if($.s.idleTime) $.slides("i");
},
_preftime = (t, e) => ptim = setTimeout(()=> _prefetch(t, e), pd), // call prefetch if timeout expires without being cleared by _prefstop
_prefstop = () => clearTimeout(ptim),
_prefetch = (t, e) => {
if($.s.prefetchoff === true) return;
if (!$.Rq("?", true)) return;
var href = $.Rq("v", e, t);
if ($.Rq("=", true) || !href || Hints($.s.prefetchoff).find(href)) return;
$.fn("+", href, () => false);
},
_stopBubbling = e => (
e.preventDefault(),
e.stopPropagation(),
e.stopImmediatePropagation()
),
_click = (t, e, notPush) => {
if(!$.Rq("?")) return;
var href = $.Rq("v", e, t);
if(!href || _exoticKey(t)) return;
if(href.substr(-1) ==="#") return true;
if(_hashChange()) {
$.hApi("=", href);
return true;
}
$.scrolly("+");
_stopBubbling(e);
if($.Rq("=")) $.hApi("=");
if($.s.refresh || !$.Rq("=")) _request(notPush);
},
_request = notPush => {
$.Rq("!");
if(notPush) $.Rq("p", false);
$.trigger("request");
$.fn($.Rq("h"), err => {
if (err) {
lg("Error in _request : " + err);
$.trigger("error", err);
}
_render();
});
},
_render = () => {
$.trigger("beforeload");
if($.s.requestDelay) {
if(requestTimer) clearTimeout(requestTimer);
requestTimer = setTimeout(_doRender, $.s.requestDelay);
} else _doRender();
},
_onPop = e => {
var url = window.location.href;
$.Rq("i");
$.Rq("h", url);
$.Rq("p", false);
$.scrolly("+");
if (!url || url === $.currentURL) return;
$.trigger("request");
$.fn(url, _render);
},
_doRender = () => {
$.trigger("load");
if($.s.bodyClasses) { var classes = $.fn("body").getAttribute("class"); bdy.setAttribute("class", classes ? classes : ""); }
var href = $.Rq("h"), title;
href = $.Rq("c", href);
$.hApi($.Rq("p") ? "+" : "=", href);
if(title = $.fn("title")) qs("title").innerHTML = title.innerHTML;
$.Rq("C", $.fn("-", $gthis));
$.frms("a");
$.scrolly("!");
_gaCaptureView(href);
$.trigger("render");
if($.s.passCount) qs("#" + $.s.passCount).innerHTML = "Pass: " + $.pass;
if($.s.cb) $.s.cb();
},
_gaCaptureView = href => {
href = "/" + href.replace(rootUrl,"");
if (typeof window.ga !== "undefined") window.ga("send", "pageview", href);
else if (typeof window._gaq !== "undefined") window._gaq.push(["_trackPageview", href]);
},
_exoticKey = (t) => {
var href = $.Rq("h"), e = $.Rq("e"), tgt = e.currentTarget.target || t.target;
return (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || tgt === "_blank"
|| href.iO("wp-login") || href.iO("wp-admin"));
},
_hashChange = () => {
var e = $.Rq("e");
return (e.hash && e.href.replace(e.hash, "") === window.location.href.replace(location.hash, "") || e.href === window.location.href + "#");
}
}}
$.init = () => {
let o = options;
if (!o || typeof(o) !== "string") {
if (document.readyState === "complete" || (document.readyState !== "loading" && !document.documentElement.doScroll))
run();
else document.addEventListener('DOMContentLoaded', run);
return $;
}
else return $.pronto(0, o);
};
let run = () => {
$.s = Object.assign($.s, options);
$.pages = new Pages().a;
$.pronto = new Pronto().a;
if (load()) {
$.pronto($.s.elements, "i");
if ($.s.deltas) $.scripts("1");
}
},
load = () => {
if (!api || !$.s.pluginon) {
lg("Gracefully exiting...");
return false;
}
lg("Ajaxify loaded..."); //verbosity option steers, whether this initialisation message is output
$.scripts = new Scripts().a;
$.scripts("i");
$.cache = new Cache().a;
$.memory = new Memory().a;
$.fn = $.getPage = new GetPage().a;
$.detScripts = new DetScripts().a;
$.addAll = new AddAll().a;
$.Rq = new RQ().a;
return true;
}
$.init(); // initialize Ajaxify on definition
}} |
/**
* @license Highstock JS v8.1.0 (2020-05-05)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Sebastian Bochan
*
* License: www.highcharts.com/license
*/
'use strict';
(function (factory) {
if (typeof module === 'object' && module.exports) {
factory['default'] = factory;
module.exports = factory;
} else if (typeof define === 'function' && define.amd) {
define('highcharts/indicators/trendline', ['highcharts', 'highcharts/modules/stock'], function (Highcharts) {
factory(Highcharts);
factory.Highcharts = Highcharts;
return factory;
});
} else {
factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
}
}(function (Highcharts) {
var _modules = Highcharts ? Highcharts._modules : {};
function _registerModule(obj, path, args, fn) {
if (!obj.hasOwnProperty(path)) {
obj[path] = fn.apply(null, args);
}
}
_registerModule(_modules, 'indicators/trendline.src.js', [_modules['parts/Utilities.js']], function (U) {
/* *
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isArray = U.isArray,
seriesType = U.seriesType;
/**
* The Trend line series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.trendline
*
* @augments Highcharts.Series
*/
seriesType('trendline', 'sma',
/**
* Trendline (linear regression) fits a straight line to the selected data
* using a method called the Sum Of Least Squares. This series requires the
* `linkedTo` option to be set.
*
* @sample stock/indicators/trendline
* Trendline indicator
*
* @extends plotOptions.sma
* @since 7.1.3
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/trendline
* @optionparent plotOptions.trendline
*/
{
/**
* @excluding period
*/
params: {
/**
* The point index which indicator calculations will base. For
* example using OHLC data, index=2 means the indicator will be
* calculated using Low values.
*
* @default 3
*/
index: 3
}
},
/**
* @lends Highcharts.Series#
*/
{
nameBase: 'Trendline',
nameComponents: false,
getValues: function (series, params) {
var xVal = series.xData,
yVal = series.yData,
LR = [],
xData = [],
yData = [],
sumX = 0,
sumY = 0,
sumXY = 0,
sumX2 = 0,
xValLength = xVal.length,
index = params.index,
alpha,
beta,
i,
x,
y;
// Get sums:
for (i = 0; i < xValLength; i++) {
x = xVal[i];
y = isArray(yVal[i]) ? yVal[i][index] : yVal[i];
sumX += x;
sumY += y;
sumXY += x * y;
sumX2 += x * x;
}
// Get slope and offset:
alpha = (xValLength * sumXY - sumX * sumY) /
(xValLength * sumX2 - sumX * sumX);
if (isNaN(alpha)) {
alpha = 0;
}
beta = (sumY - alpha * sumX) / xValLength;
// Calculate linear regression:
for (i = 0; i < xValLength; i++) {
x = xVal[i];
y = alpha * x + beta;
// Prepare arrays required for getValues() method
LR[i] = [x, y];
xData[i] = x;
yData[i] = y;
}
return {
xData: xData,
yData: yData,
values: LR
};
}
});
/**
* A `TrendLine` series. If the [type](#series.trendline.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.trendline
* @since 7.1.3
* @product highstock
* @excluding dataParser, dataURL
* @requires stock/indicators/indicators
* @requires stock/indicators/trendline
* @apioption series.trendline
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/trendline.src.js', [], function () {
});
})); |
/*!
* FilePond 4.26.0
* Licensed under MIT, https://opensource.org/licenses/MIT/
* Please visit https://pqina.nl/filepond/ for details.
*/
/* eslint-disable */
(function(global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
? factory(exports)
: typeof define === 'function' && define.amd
? define(['exports'], factory)
: ((global = global || self), factory((global.FilePond = {})));
})(this, function(exports) {
'use strict';
var isNode = function isNode(value) {
return value instanceof HTMLElement;
};
var createStore = function createStore(initialState) {
var queries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var actions = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
// internal state
var state = Object.assign({}, initialState);
// contains all actions for next frame, is clear when actions are requested
var actionQueue = [];
var dispatchQueue = [];
// returns a duplicate of the current state
var getState = function getState() {
return Object.assign({}, state);
};
// returns a duplicate of the actions array and clears the actions array
var processActionQueue = function processActionQueue() {
// create copy of actions queue
var queue = [].concat(actionQueue);
// clear actions queue (we don't want no double actions)
actionQueue.length = 0;
return queue;
};
// processes actions that might block the main UI thread
var processDispatchQueue = function processDispatchQueue() {
// create copy of actions queue
var queue = [].concat(dispatchQueue);
// clear actions queue (we don't want no double actions)
dispatchQueue.length = 0;
// now dispatch these actions
queue.forEach(function(_ref) {
var type = _ref.type,
data = _ref.data;
dispatch(type, data);
});
};
// adds a new action, calls its handler and
var dispatch = function dispatch(type, data, isBlocking) {
// is blocking action (should never block if document is hidden)
if (isBlocking && !document.hidden) {
dispatchQueue.push({ type: type, data: data });
return;
}
// if this action has a handler, handle the action
if (actionHandlers[type]) {
actionHandlers[type](data);
}
// now add action
actionQueue.push({
type: type,
data: data,
});
};
var query = function query(str) {
var _queryHandles;
for (
var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
return queryHandles[str]
? (_queryHandles = queryHandles)[str].apply(_queryHandles, args)
: null;
};
var api = {
getState: getState,
processActionQueue: processActionQueue,
processDispatchQueue: processDispatchQueue,
dispatch: dispatch,
query: query,
};
var queryHandles = {};
queries.forEach(function(query) {
queryHandles = Object.assign({}, query(state), {}, queryHandles);
});
var actionHandlers = {};
actions.forEach(function(action) {
actionHandlers = Object.assign({}, action(dispatch, query, state), {}, actionHandlers);
});
return api;
};
var defineProperty = function defineProperty(obj, property, definition) {
if (typeof definition === 'function') {
obj[property] = definition;
return;
}
Object.defineProperty(obj, property, Object.assign({}, definition));
};
var forin = function forin(obj, cb) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
cb(key, obj[key]);
}
};
var createObject = function createObject(definition) {
var obj = {};
forin(definition, function(property) {
defineProperty(obj, property, definition[property]);
});
return obj;
};
var attr = function attr(node, name) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
if (value === null) {
return node.getAttribute(name) || node.hasAttribute(name);
}
node.setAttribute(name, value);
};
var ns = 'http://www.w3.org/2000/svg';
var svgElements = ['svg', 'path']; // only svg elements used
var isSVGElement = function isSVGElement(tag) {
return svgElements.includes(tag);
};
var createElement = function createElement(tag, className) {
var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (typeof className === 'object') {
attributes = className;
className = null;
}
var element = isSVGElement(tag)
? document.createElementNS(ns, tag)
: document.createElement(tag);
if (className) {
if (isSVGElement(tag)) {
attr(element, 'class', className);
} else {
element.className = className;
}
}
forin(attributes, function(name, value) {
attr(element, name, value);
});
return element;
};
var appendChild = function appendChild(parent) {
return function(child, index) {
if (typeof index !== 'undefined' && parent.children[index]) {
parent.insertBefore(child, parent.children[index]);
} else {
parent.appendChild(child);
}
};
};
var appendChildView = function appendChildView(parent, childViews) {
return function(view, index) {
if (typeof index !== 'undefined') {
childViews.splice(index, 0, view);
} else {
childViews.push(view);
}
return view;
};
};
var removeChildView = function removeChildView(parent, childViews) {
return function(view) {
// remove from child views
childViews.splice(childViews.indexOf(view), 1);
// remove the element
if (view.element.parentNode) {
parent.removeChild(view.element);
}
return view;
};
};
var IS_BROWSER = (function() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
})();
var isBrowser = function isBrowser() {
return IS_BROWSER;
};
var testElement = isBrowser() ? createElement('svg') : {};
var getChildCount =
'children' in testElement
? function(el) {
return el.children.length;
}
: function(el) {
return el.childNodes.length;
};
var getViewRect = function getViewRect(elementRect, childViews, offset, scale) {
var left = offset[0] || elementRect.left;
var top = offset[1] || elementRect.top;
var right = left + elementRect.width;
var bottom = top + elementRect.height * (scale[1] || 1);
var rect = {
// the rectangle of the element itself
element: Object.assign({}, elementRect),
// the rectangle of the element expanded to contain its children, does not include any margins
inner: {
left: elementRect.left,
top: elementRect.top,
right: elementRect.right,
bottom: elementRect.bottom,
},
// the rectangle of the element expanded to contain its children including own margin and child margins
// margins will be added after we've recalculated the size
outer: {
left: left,
top: top,
right: right,
bottom: bottom,
},
};
// expand rect to fit all child rectangles
childViews
.filter(function(childView) {
return !childView.isRectIgnored();
})
.map(function(childView) {
return childView.rect;
})
.forEach(function(childViewRect) {
expandRect(rect.inner, Object.assign({}, childViewRect.inner));
expandRect(rect.outer, Object.assign({}, childViewRect.outer));
});
// calculate inner width and height
calculateRectSize(rect.inner);
// append additional margin (top and left margins are included in top and left automatically)
rect.outer.bottom += rect.element.marginBottom;
rect.outer.right += rect.element.marginRight;
// calculate outer width and height
calculateRectSize(rect.outer);
return rect;
};
var expandRect = function expandRect(parent, child) {
// adjust for parent offset
child.top += parent.top;
child.right += parent.left;
child.bottom += parent.top;
child.left += parent.left;
if (child.bottom > parent.bottom) {
parent.bottom = child.bottom;
}
if (child.right > parent.right) {
parent.right = child.right;
}
};
var calculateRectSize = function calculateRectSize(rect) {
rect.width = rect.right - rect.left;
rect.height = rect.bottom - rect.top;
};
var isNumber = function isNumber(value) {
return typeof value === 'number';
};
/**
* Determines if position is at destination
* @param position
* @param destination
* @param velocity
* @param errorMargin
* @returns {boolean}
*/
var thereYet = function thereYet(position, destination, velocity) {
var errorMargin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.001;
return Math.abs(position - destination) < errorMargin && Math.abs(velocity) < errorMargin;
};
/**
* Spring animation
*/
var spring =
// default options
function spring() // method definition
{
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$stiffness = _ref.stiffness,
stiffness = _ref$stiffness === void 0 ? 0.5 : _ref$stiffness,
_ref$damping = _ref.damping,
damping = _ref$damping === void 0 ? 0.75 : _ref$damping,
_ref$mass = _ref.mass,
mass = _ref$mass === void 0 ? 10 : _ref$mass;
var target = null;
var position = null;
var velocity = 0;
var resting = false;
// updates spring state
var interpolate = function interpolate(ts, skipToEndState) {
// in rest, don't animate
if (resting) return;
// need at least a target or position to do springy things
if (!(isNumber(target) && isNumber(position))) {
resting = true;
velocity = 0;
return;
}
// calculate spring force
var f = -(position - target) * stiffness;
// update velocity by adding force based on mass
velocity += f / mass;
// update position by adding velocity
position += velocity;
// slow down based on amount of damping
velocity *= damping;
// we've arrived if we're near target and our velocity is near zero
if (thereYet(position, target, velocity) || skipToEndState) {
position = target;
velocity = 0;
resting = true;
// we done
api.onupdate(position);
api.oncomplete(position);
} else {
// progress update
api.onupdate(position);
}
};
/**
* Set new target value
* @param value
*/
var setTarget = function setTarget(value) {
// if currently has no position, set target and position to this value
if (isNumber(value) && !isNumber(position)) {
position = value;
}
// next target value will not be animated to
if (target === null) {
target = value;
position = value;
}
// let start moving to target
target = value;
// already at target
if (position === target || typeof target === 'undefined') {
// now resting as target is current position, stop moving
resting = true;
velocity = 0;
// done!
api.onupdate(position);
api.oncomplete(position);
return;
}
resting = false;
};
// need 'api' to call onupdate callback
var api = createObject({
interpolate: interpolate,
target: {
set: setTarget,
get: function get() {
return target;
},
},
resting: {
get: function get() {
return resting;
},
},
onupdate: function onupdate(value) {},
oncomplete: function oncomplete(value) {},
});
return api;
};
var easeLinear = function easeLinear(t) {
return t;
};
var easeInOutQuad = function easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
};
var tween =
// default values
function tween() // method definition
{
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$duration = _ref.duration,
duration = _ref$duration === void 0 ? 500 : _ref$duration,
_ref$easing = _ref.easing,
easing = _ref$easing === void 0 ? easeInOutQuad : _ref$easing,
_ref$delay = _ref.delay,
delay = _ref$delay === void 0 ? 0 : _ref$delay;
var start = null;
var t;
var p;
var resting = true;
var reverse = false;
var target = null;
var interpolate = function interpolate(ts, skipToEndState) {
if (resting || target === null) return;
if (start === null) {
start = ts;
}
if (ts - start < delay) return;
t = ts - start - delay;
if (t >= duration || skipToEndState) {
t = 1;
p = reverse ? 0 : 1;
api.onupdate(p * target);
api.oncomplete(p * target);
resting = true;
} else {
p = t / duration;
api.onupdate((t >= 0 ? easing(reverse ? 1 - p : p) : 0) * target);
}
};
// need 'api' to call onupdate callback
var api = createObject({
interpolate: interpolate,
target: {
get: function get() {
return reverse ? 0 : target;
},
set: function set(value) {
// is initial value
if (target === null) {
target = value;
api.onupdate(value);
api.oncomplete(value);
return;
}
// want to tween to a smaller value and have a current value
if (value < target) {
target = 1;
reverse = true;
} else {
// not tweening to a smaller value
reverse = false;
target = value;
}
// let's go!
resting = false;
start = null;
},
},
resting: {
get: function get() {
return resting;
},
},
onupdate: function onupdate(value) {},
oncomplete: function oncomplete(value) {},
});
return api;
};
var animator = {
spring: spring,
tween: tween,
};
/*
{ type: 'spring', stiffness: .5, damping: .75, mass: 10 };
{ translation: { type: 'spring', ... }, ... }
{ translation: { x: { type: 'spring', ... } } }
*/
var createAnimator = function createAnimator(definition, category, property) {
// default is single definition
// we check if transform is set, if so, we check if property is set
var def =
definition[category] && typeof definition[category][property] === 'object'
? definition[category][property]
: definition[category] || definition;
var type = typeof def === 'string' ? def : def.type;
var props = typeof def === 'object' ? Object.assign({}, def) : {};
return animator[type] ? animator[type](props) : null;
};
var addGetSet = function addGetSet(keys, obj, props) {
var overwrite = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
obj = Array.isArray(obj) ? obj : [obj];
obj.forEach(function(o) {
keys.forEach(function(key) {
var name = key;
var getter = function getter() {
return props[key];
};
var setter = function setter(value) {
return (props[key] = value);
};
if (typeof key === 'object') {
name = key.key;
getter = key.getter || getter;
setter = key.setter || setter;
}
if (o[name] && !overwrite) {
return;
}
o[name] = {
get: getter,
set: setter,
};
});
});
};
// add to state,
// add getters and setters to internal and external api (if not set)
// setup animators
var animations = function animations(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI;
// initial properties
var initialProps = Object.assign({}, viewProps);
// list of all active animations
var animations = [];
// setup animators
forin(mixinConfig, function(property, animation) {
var animator = createAnimator(animation);
if (!animator) {
return;
}
// when the animator updates, update the view state value
animator.onupdate = function(value) {
viewProps[property] = value;
};
// set animator target
animator.target = initialProps[property];
// when value is set, set the animator target value
var prop = {
key: property,
setter: function setter(value) {
// if already at target, we done!
if (animator.target === value) {
return;
}
animator.target = value;
},
getter: function getter() {
return viewProps[property];
},
};
// add getters and setters
addGetSet([prop], [viewInternalAPI, viewExternalAPI], viewProps, true);
// add it to the list for easy updating from the _write method
animations.push(animator);
});
// expose internal write api
return {
write: function write(ts) {
var skipToEndState = document.hidden;
var resting = true;
animations.forEach(function(animation) {
if (!animation.resting) resting = false;
animation.interpolate(ts, skipToEndState);
});
return resting;
},
destroy: function destroy() {},
};
};
var addEvent = function addEvent(element) {
return function(type, fn) {
element.addEventListener(type, fn);
};
};
var removeEvent = function removeEvent(element) {
return function(type, fn) {
element.removeEventListener(type, fn);
};
};
// mixin
var listeners = function listeners(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI,
viewState = _ref.viewState,
view = _ref.view;
var events = [];
var add = addEvent(view.element);
var remove = removeEvent(view.element);
viewExternalAPI.on = function(type, fn) {
events.push({
type: type,
fn: fn,
});
add(type, fn);
};
viewExternalAPI.off = function(type, fn) {
events.splice(
events.findIndex(function(event) {
return event.type === type && event.fn === fn;
}),
1
);
remove(type, fn);
};
return {
write: function write() {
// not busy
return true;
},
destroy: function destroy() {
events.forEach(function(event) {
remove(event.type, event.fn);
});
},
};
};
// add to external api and link to props
var apis = function apis(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewExternalAPI = _ref.viewExternalAPI;
addGetSet(mixinConfig, viewExternalAPI, viewProps);
};
var isDefined = function isDefined(value) {
return value != null;
};
// add to state,
// add getters and setters to internal and external api (if not set)
// set initial state based on props in viewProps
// apply as transforms each frame
var defaults = {
opacity: 1,
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0,
rotateX: 0,
rotateY: 0,
rotateZ: 0,
originX: 0,
originY: 0,
};
var styles = function styles(_ref) {
var mixinConfig = _ref.mixinConfig,
viewProps = _ref.viewProps,
viewInternalAPI = _ref.viewInternalAPI,
viewExternalAPI = _ref.viewExternalAPI,
view = _ref.view;
// initial props
var initialProps = Object.assign({}, viewProps);
// current props
var currentProps = {};
// we will add those properties to the external API and link them to the viewState
addGetSet(mixinConfig, [viewInternalAPI, viewExternalAPI], viewProps);
// override rect on internal and external rect getter so it takes in account transforms
var getOffset = function getOffset() {
return [viewProps['translateX'] || 0, viewProps['translateY'] || 0];
};
var getScale = function getScale() {
return [viewProps['scaleX'] || 0, viewProps['scaleY'] || 0];
};
var getRect = function getRect() {
return view.rect
? getViewRect(view.rect, view.childViews, getOffset(), getScale())
: null;
};
viewInternalAPI.rect = { get: getRect };
viewExternalAPI.rect = { get: getRect };
// apply view props
mixinConfig.forEach(function(key) {
viewProps[key] =
typeof initialProps[key] === 'undefined' ? defaults[key] : initialProps[key];
});
// expose api
return {
write: function write() {
// see if props have changed
if (!propsHaveChanged(currentProps, viewProps)) {
return;
}
// moves element to correct position on screen
applyStyles(view.element, viewProps);
// store new transforms
Object.assign(currentProps, Object.assign({}, viewProps));
// no longer busy
return true;
},
destroy: function destroy() {},
};
};
var propsHaveChanged = function propsHaveChanged(currentProps, newProps) {
// different amount of keys
if (Object.keys(currentProps).length !== Object.keys(newProps).length) {
return true;
}
// lets analyze the individual props
for (var prop in newProps) {
if (newProps[prop] !== currentProps[prop]) {
return true;
}
}
return false;
};
var applyStyles = function applyStyles(element, _ref2) {
var opacity = _ref2.opacity,
perspective = _ref2.perspective,
translateX = _ref2.translateX,
translateY = _ref2.translateY,
scaleX = _ref2.scaleX,
scaleY = _ref2.scaleY,
rotateX = _ref2.rotateX,
rotateY = _ref2.rotateY,
rotateZ = _ref2.rotateZ,
originX = _ref2.originX,
originY = _ref2.originY,
width = _ref2.width,
height = _ref2.height;
var transforms = '';
var styles = '';
// handle transform origin
if (isDefined(originX) || isDefined(originY)) {
styles += 'transform-origin: ' + (originX || 0) + 'px ' + (originY || 0) + 'px;';
}
// transform order is relevant
// 0. perspective
if (isDefined(perspective)) {
transforms += 'perspective(' + perspective + 'px) ';
}
// 1. translate
if (isDefined(translateX) || isDefined(translateY)) {
transforms +=
'translate3d(' + (translateX || 0) + 'px, ' + (translateY || 0) + 'px, 0) ';
}
// 2. scale
if (isDefined(scaleX) || isDefined(scaleY)) {
transforms +=
'scale3d(' +
(isDefined(scaleX) ? scaleX : 1) +
', ' +
(isDefined(scaleY) ? scaleY : 1) +
', 1) ';
}
// 3. rotate
if (isDefined(rotateZ)) {
transforms += 'rotateZ(' + rotateZ + 'rad) ';
}
if (isDefined(rotateX)) {
transforms += 'rotateX(' + rotateX + 'rad) ';
}
if (isDefined(rotateY)) {
transforms += 'rotateY(' + rotateY + 'rad) ';
}
// add transforms
if (transforms.length) {
styles += 'transform:' + transforms + ';';
}
// add opacity
if (isDefined(opacity)) {
styles += 'opacity:' + opacity + ';';
// if we reach zero, we make the element inaccessible
if (opacity === 0) {
styles += 'visibility:hidden;';
}
// if we're below 100% opacity this element can't be clicked
if (opacity < 1) {
styles += 'pointer-events:none;';
}
}
// add height
if (isDefined(height)) {
styles += 'height:' + height + 'px;';
}
// add width
if (isDefined(width)) {
styles += 'width:' + width + 'px;';
}
// apply styles
var elementCurrentStyle = element.elementCurrentStyle || '';
// if new styles does not match current styles, lets update!
if (styles.length !== elementCurrentStyle.length || styles !== elementCurrentStyle) {
element.style.cssText = styles;
// store current styles so we can compare them to new styles later on
// _not_ getting the style value is faster
element.elementCurrentStyle = styles;
}
};
var Mixins = {
styles: styles,
listeners: listeners,
animations: animations,
apis: apis,
};
var updateRect = function updateRect() {
var rect = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var element = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var style = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!element.layoutCalculated) {
rect.paddingTop = parseInt(style.paddingTop, 10) || 0;
rect.marginTop = parseInt(style.marginTop, 10) || 0;
rect.marginRight = parseInt(style.marginRight, 10) || 0;
rect.marginBottom = parseInt(style.marginBottom, 10) || 0;
rect.marginLeft = parseInt(style.marginLeft, 10) || 0;
element.layoutCalculated = true;
}
rect.left = element.offsetLeft || 0;
rect.top = element.offsetTop || 0;
rect.width = element.offsetWidth || 0;
rect.height = element.offsetHeight || 0;
rect.right = rect.left + rect.width;
rect.bottom = rect.top + rect.height;
rect.scrollTop = element.scrollTop;
rect.hidden = element.offsetParent === null;
return rect;
};
var createView =
// default view definition
function createView() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
_ref$tag = _ref.tag,
tag = _ref$tag === void 0 ? 'div' : _ref$tag,
_ref$name = _ref.name,
name = _ref$name === void 0 ? null : _ref$name,
_ref$attributes = _ref.attributes,
attributes = _ref$attributes === void 0 ? {} : _ref$attributes,
_ref$read = _ref.read,
read = _ref$read === void 0 ? function() {} : _ref$read,
_ref$write = _ref.write,
write = _ref$write === void 0 ? function() {} : _ref$write,
_ref$create = _ref.create,
create = _ref$create === void 0 ? function() {} : _ref$create,
_ref$destroy = _ref.destroy,
destroy = _ref$destroy === void 0 ? function() {} : _ref$destroy,
_ref$filterFrameActio = _ref.filterFrameActionsForChild,
filterFrameActionsForChild =
_ref$filterFrameActio === void 0
? function(child, actions) {
return actions;
}
: _ref$filterFrameActio,
_ref$didCreateView = _ref.didCreateView,
didCreateView = _ref$didCreateView === void 0 ? function() {} : _ref$didCreateView,
_ref$didWriteView = _ref.didWriteView,
didWriteView = _ref$didWriteView === void 0 ? function() {} : _ref$didWriteView,
_ref$ignoreRect = _ref.ignoreRect,
ignoreRect = _ref$ignoreRect === void 0 ? false : _ref$ignoreRect,
_ref$ignoreRectUpdate = _ref.ignoreRectUpdate,
ignoreRectUpdate = _ref$ignoreRectUpdate === void 0 ? false : _ref$ignoreRectUpdate,
_ref$mixins = _ref.mixins,
mixins = _ref$mixins === void 0 ? [] : _ref$mixins;
return function(
// each view requires reference to store
store
) {
var props = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// root element should not be changed
var element = createElement(tag, 'filepond--' + name, attributes);
// style reference should also not be changed
var style = window.getComputedStyle(element, null);
// element rectangle
var rect = updateRect();
var frameRect = null;
// rest state
var isResting = false;
// pretty self explanatory
var childViews = [];
// loaded mixins
var activeMixins = [];
// references to created children
var ref = {};
// state used for each instance
var state = {};
// list of writers that will be called to update this view
var writers = [
write, // default writer
];
var readers = [
read, // default reader
];
var destroyers = [
destroy, // default destroy
];
// core view methods
var getElement = function getElement() {
return element;
};
var getChildViews = function getChildViews() {
return childViews.concat();
};
var getReference = function getReference() {
return ref;
};
var createChildView = function createChildView(store) {
return function(view, props) {
return view(store, props);
};
};
var getRect = function getRect() {
if (frameRect) {
return frameRect;
}
frameRect = getViewRect(rect, childViews, [0, 0], [1, 1]);
return frameRect;
};
var getStyle = function getStyle() {
return style;
};
/**
* Read data from DOM
* @private
*/
var _read = function _read() {
frameRect = null;
// read child views
childViews.forEach(function(child) {
return child._read();
});
var shouldUpdate = !(ignoreRectUpdate && rect.width && rect.height);
if (shouldUpdate) {
updateRect(rect, element, style);
}
// readers
var api = { root: internalAPI, props: props, rect: rect };
readers.forEach(function(reader) {
return reader(api);
});
};
/**
* Write data to DOM
* @private
*/
var _write = function _write(ts, frameActions, shouldOptimize) {
// if no actions, we assume that the view is resting
var resting = frameActions.length === 0;
// writers
writers.forEach(function(writer) {
var writerResting = writer({
props: props,
root: internalAPI,
actions: frameActions,
timestamp: ts,
shouldOptimize: shouldOptimize,
});
if (writerResting === false) {
resting = false;
}
});
// run mixins
activeMixins.forEach(function(mixin) {
// if one of the mixins is still busy after write operation, we are not resting
var mixinResting = mixin.write(ts);
if (mixinResting === false) {
resting = false;
}
});
// updates child views that are currently attached to the DOM
childViews
.filter(function(child) {
return !!child.element.parentNode;
})
.forEach(function(child) {
// if a child view is not resting, we are not resting
var childResting = child._write(
ts,
filterFrameActionsForChild(child, frameActions),
shouldOptimize
);
if (!childResting) {
resting = false;
}
});
// append new elements to DOM and update those
childViews
//.filter(child => !child.element.parentNode)
.forEach(function(child, index) {
// skip
if (child.element.parentNode) {
return;
}
// append to DOM
internalAPI.appendChild(child.element, index);
// call read (need to know the size of these elements)
child._read();
// re-call write
child._write(
ts,
filterFrameActionsForChild(child, frameActions),
shouldOptimize
);
// we just added somthing to the dom, no rest
resting = false;
});
// update resting state
isResting = resting;
didWriteView({
props: props,
root: internalAPI,
actions: frameActions,
timestamp: ts,
});
// let parent know if we are resting
return resting;
};
var _destroy = function _destroy() {
activeMixins.forEach(function(mixin) {
return mixin.destroy();
});
destroyers.forEach(function(destroyer) {
destroyer({ root: internalAPI, props: props });
});
childViews.forEach(function(child) {
return child._destroy();
});
};
// sharedAPI
var sharedAPIDefinition = {
element: {
get: getElement,
},
style: {
get: getStyle,
},
childViews: {
get: getChildViews,
},
};
// private API definition
var internalAPIDefinition = Object.assign({}, sharedAPIDefinition, {
rect: {
get: getRect,
},
// access to custom children references
ref: {
get: getReference,
},
// dom modifiers
is: function is(needle) {
return name === needle;
},
appendChild: appendChild(element),
createChildView: createChildView(store),
linkView: function linkView(view) {
childViews.push(view);
return view;
},
unlinkView: function unlinkView(view) {
childViews.splice(childViews.indexOf(view), 1);
},
appendChildView: appendChildView(element, childViews),
removeChildView: removeChildView(element, childViews),
registerWriter: function registerWriter(writer) {
return writers.push(writer);
},
registerReader: function registerReader(reader) {
return readers.push(reader);
},
registerDestroyer: function registerDestroyer(destroyer) {
return destroyers.push(destroyer);
},
invalidateLayout: function invalidateLayout() {
return (element.layoutCalculated = false);
},
// access to data store
dispatch: store.dispatch,
query: store.query,
});
// public view API methods
var externalAPIDefinition = {
element: {
get: getElement,
},
childViews: {
get: getChildViews,
},
rect: {
get: getRect,
},
resting: {
get: function get() {
return isResting;
},
},
isRectIgnored: function isRectIgnored() {
return ignoreRect;
},
_read: _read,
_write: _write,
_destroy: _destroy,
};
// mixin API methods
var mixinAPIDefinition = Object.assign({}, sharedAPIDefinition, {
rect: {
get: function get() {
return rect;
},
},
});
// add mixin functionality
Object.keys(mixins)
.sort(function(a, b) {
// move styles to the back of the mixin list (so adjustments of other mixins are applied to the props correctly)
if (a === 'styles') {
return 1;
} else if (b === 'styles') {
return -1;
}
return 0;
})
.forEach(function(key) {
var mixinAPI = Mixins[key]({
mixinConfig: mixins[key],
viewProps: props,
viewState: state,
viewInternalAPI: internalAPIDefinition,
viewExternalAPI: externalAPIDefinition,
view: createObject(mixinAPIDefinition),
});
if (mixinAPI) {
activeMixins.push(mixinAPI);
}
});
// construct private api
var internalAPI = createObject(internalAPIDefinition);
// create the view
create({
root: internalAPI,
props: props,
});
// append created child views to root node
var childCount = getChildCount(element); // need to know the current child count so appending happens in correct order
childViews.forEach(function(child, index) {
internalAPI.appendChild(child.element, childCount + index);
});
// call did create
didCreateView(internalAPI);
// expose public api
return createObject(externalAPIDefinition);
};
};
var createPainter = function createPainter(read, write) {
var fps = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 60;
var name = '__framePainter';
// set global painter
if (window[name]) {
window[name].readers.push(read);
window[name].writers.push(write);
return;
}
window[name] = {
readers: [read],
writers: [write],
};
var painter = window[name];
var interval = 1000 / fps;
var last = null;
var id = null;
var requestTick = null;
var cancelTick = null;
var setTimerType = function setTimerType() {
if (document.hidden) {
requestTick = function requestTick() {
return window.setTimeout(function() {
return tick(performance.now());
}, interval);
};
cancelTick = function cancelTick() {
return window.clearTimeout(id);
};
} else {
requestTick = function requestTick() {
return window.requestAnimationFrame(tick);
};
cancelTick = function cancelTick() {
return window.cancelAnimationFrame(id);
};
}
};
document.addEventListener('visibilitychange', function() {
if (cancelTick) cancelTick();
setTimerType();
tick(performance.now());
});
var tick = function tick(ts) {
// queue next tick
id = requestTick(tick);
// limit fps
if (!last) {
last = ts;
}
var delta = ts - last;
if (delta <= interval) {
// skip frame
return;
}
// align next frame
last = ts - (delta % interval);
// update view
painter.readers.forEach(function(read) {
return read();
});
painter.writers.forEach(function(write) {
return write(ts);
});
};
setTimerType();
tick(performance.now());
return {
pause: function pause() {
cancelTick(id);
},
};
};
var createRoute = function createRoute(routes, fn) {
return function(_ref) {
var root = _ref.root,
props = _ref.props,
_ref$actions = _ref.actions,
actions = _ref$actions === void 0 ? [] : _ref$actions,
timestamp = _ref.timestamp,
shouldOptimize = _ref.shouldOptimize;
actions
.filter(function(action) {
return routes[action.type];
})
.forEach(function(action) {
return routes[action.type]({
root: root,
props: props,
action: action.data,
timestamp: timestamp,
shouldOptimize: shouldOptimize,
});
});
if (fn) {
fn({
root: root,
props: props,
actions: actions,
timestamp: timestamp,
shouldOptimize: shouldOptimize,
});
}
};
};
var insertBefore = function insertBefore(newNode, referenceNode) {
return referenceNode.parentNode.insertBefore(newNode, referenceNode);
};
var insertAfter = function insertAfter(newNode, referenceNode) {
return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
};
var isArray = function isArray(value) {
return Array.isArray(value);
};
var isEmpty = function isEmpty(value) {
return value == null;
};
var trim = function trim(str) {
return str.trim();
};
var toString = function toString(value) {
return '' + value;
};
var toArray = function toArray(value) {
var splitter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
if (isEmpty(value)) {
return [];
}
if (isArray(value)) {
return value;
}
return toString(value)
.split(splitter)
.map(trim)
.filter(function(str) {
return str.length;
});
};
var isBoolean = function isBoolean(value) {
return typeof value === 'boolean';
};
var toBoolean = function toBoolean(value) {
return isBoolean(value) ? value : value === 'true';
};
var isString = function isString(value) {
return typeof value === 'string';
};
var toNumber = function toNumber(value) {
return isNumber(value)
? value
: isString(value)
? toString(value).replace(/[a-z]+/gi, '')
: 0;
};
var toInt = function toInt(value) {
return parseInt(toNumber(value), 10);
};
var toFloat = function toFloat(value) {
return parseFloat(toNumber(value));
};
var isInt = function isInt(value) {
return isNumber(value) && isFinite(value) && Math.floor(value) === value;
};
var toBytes = function toBytes(value) {
var base = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
// is in bytes
if (isInt(value)) {
return value;
}
// is natural file size
var naturalFileSize = toString(value).trim();
// if is value in megabytes
if (/MB$/i.test(naturalFileSize)) {
naturalFileSize = naturalFileSize.replace(/MB$i/, '').trim();
return toInt(naturalFileSize) * base * base;
}
// if is value in kilobytes
if (/KB/i.test(naturalFileSize)) {
naturalFileSize = naturalFileSize.replace(/KB$i/, '').trim();
return toInt(naturalFileSize) * base;
}
return toInt(naturalFileSize);
};
var isFunction = function isFunction(value) {
return typeof value === 'function';
};
var toFunctionReference = function toFunctionReference(string) {
var ref = self;
var levels = string.split('.');
var level = null;
while ((level = levels.shift())) {
ref = ref[level];
if (!ref) {
return null;
}
}
return ref;
};
var methods = {
process: 'POST',
patch: 'PATCH',
revert: 'DELETE',
fetch: 'GET',
restore: 'GET',
load: 'GET',
};
var createServerAPI = function createServerAPI(outline) {
var api = {};
api.url = isString(outline) ? outline : outline.url || '';
api.timeout = outline.timeout ? parseInt(outline.timeout, 10) : 0;
api.headers = outline.headers ? outline.headers : {};
forin(methods, function(key) {
api[key] = createAction(key, outline[key], methods[key], api.timeout, api.headers);
});
// special treatment for remove
api.remove = outline.remove || null;
// remove generic headers from api object
delete api.headers;
return api;
};
var createAction = function createAction(name, outline, method, timeout, headers) {
// is explicitely set to null so disable
if (outline === null) {
return null;
}
// if is custom function, done! Dev handles everything.
if (typeof outline === 'function') {
return outline;
}
// build action object
var action = {
url: method === 'GET' || method === 'PATCH' ? '?' + name + '=' : '',
method: method,
headers: headers,
withCredentials: false,
timeout: timeout,
onload: null,
ondata: null,
onerror: null,
};
// is a single url
if (isString(outline)) {
action.url = outline;
return action;
}
// overwrite
Object.assign(action, outline);
// see if should reformat headers;
if (isString(action.headers)) {
var parts = action.headers.split(/:(.+)/);
action.headers = {
header: parts[0],
value: parts[1],
};
}
// if is bool withCredentials
action.withCredentials = toBoolean(action.withCredentials);
return action;
};
var toServerAPI = function toServerAPI(value) {
return createServerAPI(value);
};
var isNull = function isNull(value) {
return value === null;
};
var isObject = function isObject(value) {
return typeof value === 'object' && value !== null;
};
var isAPI = function isAPI(value) {
return (
isObject(value) &&
isString(value.url) &&
isObject(value.process) &&
isObject(value.revert) &&
isObject(value.restore) &&
isObject(value.fetch)
);
};
var getType = function getType(value) {
if (isArray(value)) {
return 'array';
}
if (isNull(value)) {
return 'null';
}
if (isInt(value)) {
return 'int';
}
if (/^[0-9]+ ?(?:GB|MB|KB)$/gi.test(value)) {
return 'bytes';
}
if (isAPI(value)) {
return 'api';
}
return typeof value;
};
var replaceSingleQuotes = function replaceSingleQuotes(str) {
return str
.replace(/{\s*'/g, '{"')
.replace(/'\s*}/g, '"}')
.replace(/'\s*:/g, '":')
.replace(/:\s*'/g, ':"')
.replace(/,\s*'/g, ',"')
.replace(/'\s*,/g, '",');
};
var conversionTable = {
array: toArray,
boolean: toBoolean,
int: function int(value) {
return getType(value) === 'bytes' ? toBytes(value) : toInt(value);
},
number: toFloat,
float: toFloat,
bytes: toBytes,
string: function string(value) {
return isFunction(value) ? value : toString(value);
},
function: function _function(value) {
return toFunctionReference(value);
},
serverapi: toServerAPI,
object: function object(value) {
try {
return JSON.parse(replaceSingleQuotes(value));
} catch (e) {
return null;
}
},
};
var convertTo = function convertTo(value, type) {
return conversionTable[type](value);
};
var getValueByType = function getValueByType(newValue, defaultValue, valueType) {
// can always assign default value
if (newValue === defaultValue) {
return newValue;
}
// get the type of the new value
var newValueType = getType(newValue);
// is valid type?
if (newValueType !== valueType) {
// is string input, let's attempt to convert
var convertedValue = convertTo(newValue, valueType);
// what is the type now
newValueType = getType(convertedValue);
// no valid conversions found
if (convertedValue === null) {
throw 'Trying to assign value with incorrect type to "' +
option +
'", allowed type: "' +
valueType +
'"';
} else {
newValue = convertedValue;
}
}
// assign new value
return newValue;
};
var createOption = function createOption(defaultValue, valueType) {
var currentValue = defaultValue;
return {
enumerable: true,
get: function get() {
return currentValue;
},
set: function set(newValue) {
currentValue = getValueByType(newValue, defaultValue, valueType);
},
};
};
var createOptions = function createOptions(options) {
var obj = {};
forin(options, function(prop) {
var optionDefinition = options[prop];
obj[prop] = createOption(optionDefinition[0], optionDefinition[1]);
});
return createObject(obj);
};
var createInitialState = function createInitialState(options) {
return {
// model
items: [],
// timeout used for calling update items
listUpdateTimeout: null,
// timeout used for stacking metadata updates
itemUpdateTimeout: null,
// queue of items waiting to be processed
processingQueue: [],
// options
options: createOptions(options),
};
};
var fromCamels = function fromCamels(string) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';
return string
.split(/(?=[A-Z])/)
.map(function(part) {
return part.toLowerCase();
})
.join(separator);
};
var createOptionAPI = function createOptionAPI(store, options) {
var obj = {};
forin(options, function(key) {
obj[key] = {
get: function get() {
return store.getState().options[key];
},
set: function set(value) {
store.dispatch('SET_' + fromCamels(key, '_').toUpperCase(), {
value: value,
});
},
};
});
return obj;
};
var createOptionActions = function createOptionActions(options) {
return function(dispatch, query, state) {
var obj = {};
forin(options, function(key) {
var name = fromCamels(key, '_').toUpperCase();
obj['SET_' + name] = function(action) {
try {
state.options[key] = action.value;
} catch (e) {} // nope, failed
// we successfully set the value of this option
dispatch('DID_SET_' + name, { value: state.options[key] });
};
});
return obj;
};
};
var createOptionQueries = function createOptionQueries(options) {
return function(state) {
var obj = {};
forin(options, function(key) {
obj['GET_' + fromCamels(key, '_').toUpperCase()] = function(action) {
return state.options[key];
};
});
return obj;
};
};
var InteractionMethod = {
API: 1,
DROP: 2,
BROWSE: 3,
PASTE: 4,
NONE: 5,
};
var getUniqueId = function getUniqueId() {
return Math.random()
.toString(36)
.substr(2, 9);
};
function _typeof(obj) {
if (typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol') {
_typeof = function(obj) {
return typeof obj;
};
} else {
_typeof = function(obj) {
return obj &&
typeof Symbol === 'function' &&
obj.constructor === Symbol &&
obj !== Symbol.prototype
? 'symbol'
: typeof obj;
};
}
return _typeof(obj);
}
var REACT_ELEMENT_TYPE;
function _jsx(type, props, key, children) {
if (!REACT_ELEMENT_TYPE) {
REACT_ELEMENT_TYPE =
(typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element')) ||
0xeac7;
}
var defaultProps = type && type.defaultProps;
var childrenLength = arguments.length - 3;
if (!props && childrenLength !== 0) {
props = {
children: void 0,
};
}
if (props && defaultProps) {
for (var propName in defaultProps) {
if (props[propName] === void 0) {
props[propName] = defaultProps[propName];
}
}
} else if (!props) {
props = defaultProps || {};
}
if (childrenLength === 1) {
props.children = children;
} else if (childrenLength > 1) {
var childArray = new Array(childrenLength);
for (var i = 0; i < childrenLength; i++) {
childArray[i] = arguments[i + 3];
}
props.children = childArray;
}
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key === undefined ? null : '' + key,
ref: null,
props: props,
_owner: null,
};
}
function _asyncIterator(iterable) {
var method;
if (typeof Symbol !== 'undefined') {
if (Symbol.asyncIterator) {
method = iterable[Symbol.asyncIterator];
if (method != null) return method.call(iterable);
}
if (Symbol.iterator) {
method = iterable[Symbol.iterator];
if (method != null) return method.call(iterable);
}
}
throw new TypeError('Object is not async iterable');
}
function _AwaitValue(value) {
this.wrapped = value;
}
function _AsyncGenerator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function(resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null,
};
if (back) {
back = back.next = request;
} else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
var wrappedAwait = value instanceof _AwaitValue;
Promise.resolve(wrappedAwait ? value.wrapped : value).then(
function(arg) {
if (wrappedAwait) {
resume('next', arg);
return;
}
settle(result.done ? 'return' : 'normal', arg);
},
function(err) {
resume('throw', err);
}
);
} catch (err) {
settle('throw', err);
}
}
function settle(type, value) {
switch (type) {
case 'return':
front.resolve({
value: value,
done: true,
});
break;
case 'throw':
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false,
});
break;
}
front = front.next;
if (front) {
resume(front.key, front.arg);
} else {
back = null;
}
}
this._invoke = send;
if (typeof gen.return !== 'function') {
this.return = undefined;
}
}
if (typeof Symbol === 'function' && Symbol.asyncIterator) {
_AsyncGenerator.prototype[Symbol.asyncIterator] = function() {
return this;
};
}
_AsyncGenerator.prototype.next = function(arg) {
return this._invoke('next', arg);
};
_AsyncGenerator.prototype.throw = function(arg) {
return this._invoke('throw', arg);
};
_AsyncGenerator.prototype.return = function(arg) {
return this._invoke('return', arg);
};
function _wrapAsyncGenerator(fn) {
return function() {
return new _AsyncGenerator(fn.apply(this, arguments));
};
}
function _awaitAsyncGenerator(value) {
return new _AwaitValue(value);
}
function _asyncGeneratorDelegate(inner, awaitWrap) {
var iter = {},
waiting = false;
function pump(key, value) {
waiting = true;
value = new Promise(function(resolve) {
resolve(inner[key](value));
});
return {
done: false,
value: awaitWrap(value),
};
}
if (typeof Symbol === 'function' && Symbol.iterator) {
iter[Symbol.iterator] = function() {
return this;
};
}
iter.next = function(value) {
if (waiting) {
waiting = false;
return value;
}
return pump('next', value);
};
if (typeof inner.throw === 'function') {
iter.throw = function(value) {
if (waiting) {
waiting = false;
throw value;
}
return pump('throw', value);
};
}
if (typeof inner.return === 'function') {
iter.return = function(value) {
return pump('return', value);
};
}
return iter;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function() {
var self = this,
args = arguments;
return new Promise(function(resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'next', value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, 'throw', err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function');
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ('value' in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineEnumerableProperties(obj, descs) {
for (var key in descs) {
var desc = descs[key];
desc.configurable = desc.enumerable = true;
if ('value' in desc) desc.writable = true;
Object.defineProperty(obj, key, desc);
}
if (Object.getOwnPropertySymbols) {
var objectSymbols = Object.getOwnPropertySymbols(descs);
for (var i = 0; i < objectSymbols.length; i++) {
var sym = objectSymbols[i];
var desc = descs[sym];
desc.configurable = desc.enumerable = true;
if ('value' in desc) desc.writable = true;
Object.defineProperty(obj, sym, desc);
}
}
return obj;
}
function _defaults(obj, defaults) {
var keys = Object.getOwnPropertyNames(defaults);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = Object.getOwnPropertyDescriptor(defaults, key);
if (value && value.configurable && obj[key] === undefined) {
Object.defineProperty(obj, key, value);
}
}
return obj;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true,
});
} else {
obj[key] = value;
}
return obj;
}
function _extends() {
_extends =
Object.assign ||
function(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
function _objectSpread(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === 'function') {
ownKeys = ownKeys.concat(
Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
})
);
}
ownKeys.forEach(function(key) {
_defineProperty(target, key, source[key]);
});
}
return target;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly)
symbols = symbols.filter(function(sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(source, true).forEach(function(key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(source).forEach(function(key) {
Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(source, key)
);
});
}
}
return target;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== 'function' && superClass !== null) {
throw new TypeError('Super expression must either be null or a function');
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true,
},
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf
? Object.getPrototypeOf
: function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf =
Object.setPrototypeOf ||
function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function isNativeReflectConstruct() {
if (typeof Reflect === 'undefined' || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === 'function') return true;
try {
Date.prototype.toString.call(Reflect.construct(Date, [], function() {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (isNativeReflectConstruct()) {
_construct = Reflect.construct;
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf('[native code]') !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === 'function' ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== 'function') {
throw new TypeError('Super expression must either be null or a function');
}
if (typeof _cache !== 'undefined') {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true,
},
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _instanceof(left, right) {
if (right != null && typeof Symbol !== 'undefined' && right[Symbol.hasInstance]) {
return !!right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule
? obj
: {
default: obj,
};
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc =
Object.defineProperty && Object.getOwnPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: {};
if (desc.get || desc.set) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
}
newObj.default = obj;
return newObj;
}
}
function _newArrowCheck(innerThis, boundThis) {
if (innerThis !== boundThis) {
throw new TypeError('Cannot instantiate an arrow function');
}
}
function _objectDestructuringEmpty(obj) {
if (obj == null) throw new TypeError('Cannot destructure undefined');
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === 'object' || typeof call === 'function')) {
return call;
}
return _assertThisInitialized(self);
}
function _superPropBase(object, property) {
while (!Object.prototype.hasOwnProperty.call(object, property)) {
object = _getPrototypeOf(object);
if (object === null) break;
}
return object;
}
function _get(target, property, receiver) {
if (typeof Reflect !== 'undefined' && Reflect.get) {
_get = Reflect.get;
} else {
_get = function _get(target, property, receiver) {
var base = _superPropBase(target, property);
if (!base) return;
var desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.get) {
return desc.get.call(receiver);
}
return desc.value;
};
}
return _get(target, property, receiver || target);
}
function set(target, property, value, receiver) {
if (typeof Reflect !== 'undefined' && Reflect.set) {
set = Reflect.set;
} else {
set = function set(target, property, value, receiver) {
var base = _superPropBase(target, property);
var desc;
if (base) {
desc = Object.getOwnPropertyDescriptor(base, property);
if (desc.set) {
desc.set.call(receiver, value);
return true;
} else if (!desc.writable) {
return false;
}
}
desc = Object.getOwnPropertyDescriptor(receiver, property);
if (desc) {
if (!desc.writable) {
return false;
}
desc.value = value;
Object.defineProperty(receiver, property, desc);
} else {
_defineProperty(receiver, property, value);
}
return true;
};
}
return set(target, property, value, receiver);
}
function _set(target, property, value, receiver, isStrict) {
var s = set(target, property, value, receiver || target);
if (!s && isStrict) {
throw new Error('failed to set property');
}
return value;
}
function _taggedTemplateLiteral(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
return Object.freeze(
Object.defineProperties(strings, {
raw: {
value: Object.freeze(raw),
},
})
);
}
function _taggedTemplateLiteralLoose(strings, raw) {
if (!raw) {
raw = strings.slice(0);
}
strings.raw = raw;
return strings;
}
function _temporalRef(val, name) {
if (val === _temporalUndefined) {
throw new ReferenceError(name + ' is not defined - temporal dead zone');
} else {
return val;
}
}
function _readOnlyError(name) {
throw new Error('"' + name + '" is read-only');
}
function _classNameTDZError(name) {
throw new Error('Class "' + name + '" cannot be referenced in computed property keys.');
}
var _temporalUndefined = {};
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _slicedToArrayLoose(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimitLoose(arr, i) || _nonIterableRest();
}
function _toArray(arr) {
return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (
Symbol.iterator in Object(iter) ||
Object.prototype.toString.call(iter) === '[object Arguments]'
)
return Array.from(iter);
}
function _iterableToArrayLimit(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i['return'] != null) _i['return']();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _iterableToArrayLimitLoose(arr, i) {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done; ) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
}
function _nonIterableSpread() {
throw new TypeError('Invalid attempt to spread non-iterable instance');
}
function _nonIterableRest() {
throw new TypeError('Invalid attempt to destructure non-iterable instance');
}
function _skipFirstGeneratorNext(fn) {
return function() {
var it = fn.apply(this, arguments);
it.next();
return it;
};
}
function _toPrimitive(input, hint) {
if (typeof input !== 'object' || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || 'default');
if (typeof res !== 'object') return res;
throw new TypeError('@@toPrimitive must return a primitive value.');
}
return (hint === 'string' ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, 'string');
return typeof key === 'symbol' ? key : String(key);
}
function _initializerWarningHelper(descriptor, context) {
throw new Error(
'Decorating class property failed. Please ensure that ' +
'proposal-class-properties is enabled and set to use loose mode. ' +
'To use proposal-class-properties in spec mode with decorators, wait for ' +
'the next major version of decorators in stage 2.'
);
}
function _initializerDefineProperty(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0,
});
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object.keys(descriptor).forEach(function(key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators
.slice()
.reverse()
.reduce(function(desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object.defineProperty(target, property, desc);
desc = null;
}
return desc;
}
var id = 0;
function _classPrivateFieldLooseKey(name) {
return '__private_' + id++ + '_' + name;
}
function _classPrivateFieldLooseBase(receiver, privateKey) {
if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
throw new TypeError('attempted to use private field on non-instance');
}
return receiver;
}
function _classPrivateFieldGet(receiver, privateMap) {
var descriptor = privateMap.get(receiver);
if (!descriptor) {
throw new TypeError('attempted to get private field on non-instance');
}
if (descriptor.get) {
return descriptor.get.call(receiver);
}
return descriptor.value;
}
function _classPrivateFieldSet(receiver, privateMap, value) {
var descriptor = privateMap.get(receiver);
if (!descriptor) {
throw new TypeError('attempted to set private field on non-instance');
}
if (descriptor.set) {
descriptor.set.call(receiver, value);
} else {
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
descriptor.value = value;
}
return value;
}
function _classPrivateFieldDestructureSet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError('attempted to set private field on non-instance');
}
var descriptor = privateMap.get(receiver);
if (descriptor.set) {
if (!('__destrObj' in descriptor)) {
descriptor.__destrObj = {
set value(v) {
descriptor.set.call(receiver, v);
},
};
}
return descriptor.__destrObj;
} else {
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
return descriptor;
}
}
function _classStaticPrivateFieldSpecGet(receiver, classConstructor, descriptor) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
return descriptor.value;
}
function _classStaticPrivateFieldSpecSet(receiver, classConstructor, descriptor, value) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
if (!descriptor.writable) {
throw new TypeError('attempted to set read only private field');
}
descriptor.value = value;
return value;
}
function _classStaticPrivateMethodGet(receiver, classConstructor, method) {
if (receiver !== classConstructor) {
throw new TypeError('Private static access of wrong provenance');
}
return method;
}
function _classStaticPrivateMethodSet() {
throw new TypeError('attempted to set read only static private field');
}
function _decorate(decorators, factory, superClass, mixins) {
var api = _getDecoratorsApi();
if (mixins) {
for (var i = 0; i < mixins.length; i++) {
api = mixins[i](api);
}
}
var r = factory(function initialize(O) {
api.initializeInstanceElements(O, decorated.elements);
}, superClass);
var decorated = api.decorateClass(
_coalesceClassElements(r.d.map(_createElementDescriptor)),
decorators
);
api.initializeClassElements(r.F, decorated.elements);
return api.runClassFinishers(r.F, decorated.finishers);
}
function _getDecoratorsApi() {
_getDecoratorsApi = function() {
return api;
};
var api = {
elementsDefinitionOrder: [['method'], ['field']],
initializeInstanceElements: function(O, elements) {
['method', 'field'].forEach(function(kind) {
elements.forEach(function(element) {
if (element.kind === kind && element.placement === 'own') {
this.defineClassElement(O, element);
}
}, this);
}, this);
},
initializeClassElements: function(F, elements) {
var proto = F.prototype;
['method', 'field'].forEach(function(kind) {
elements.forEach(function(element) {
var placement = element.placement;
if (
element.kind === kind &&
(placement === 'static' || placement === 'prototype')
) {
var receiver = placement === 'static' ? F : proto;
this.defineClassElement(receiver, element);
}
}, this);
}, this);
},
defineClassElement: function(receiver, element) {
var descriptor = element.descriptor;
if (element.kind === 'field') {
var initializer = element.initializer;
descriptor = {
enumerable: descriptor.enumerable,
writable: descriptor.writable,
configurable: descriptor.configurable,
value: initializer === void 0 ? void 0 : initializer.call(receiver),
};
}
Object.defineProperty(receiver, element.key, descriptor);
},
decorateClass: function(elements, decorators) {
var newElements = [];
var finishers = [];
var placements = {
static: [],
prototype: [],
own: [],
};
elements.forEach(function(element) {
this.addElementPlacement(element, placements);
}, this);
elements.forEach(function(element) {
if (!_hasDecorators(element)) return newElements.push(element);
var elementFinishersExtras = this.decorateElement(element, placements);
newElements.push(elementFinishersExtras.element);
newElements.push.apply(newElements, elementFinishersExtras.extras);
finishers.push.apply(finishers, elementFinishersExtras.finishers);
}, this);
if (!decorators) {
return {
elements: newElements,
finishers: finishers,
};
}
var result = this.decorateConstructor(newElements, decorators);
finishers.push.apply(finishers, result.finishers);
result.finishers = finishers;
return result;
},
addElementPlacement: function(element, placements, silent) {
var keys = placements[element.placement];
if (!silent && keys.indexOf(element.key) !== -1) {
throw new TypeError('Duplicated element (' + element.key + ')');
}
keys.push(element.key);
},
decorateElement: function(element, placements) {
var extras = [];
var finishers = [];
for (var decorators = element.decorators, i = decorators.length - 1; i >= 0; i--) {
var keys = placements[element.placement];
keys.splice(keys.indexOf(element.key), 1);
var elementObject = this.fromElementDescriptor(element);
var elementFinisherExtras = this.toElementFinisherExtras(
(0, decorators[i])(elementObject) || elementObject
);
element = elementFinisherExtras.element;
this.addElementPlacement(element, placements);
if (elementFinisherExtras.finisher) {
finishers.push(elementFinisherExtras.finisher);
}
var newExtras = elementFinisherExtras.extras;
if (newExtras) {
for (var j = 0; j < newExtras.length; j++) {
this.addElementPlacement(newExtras[j], placements);
}
extras.push.apply(extras, newExtras);
}
}
return {
element: element,
finishers: finishers,
extras: extras,
};
},
decorateConstructor: function(elements, decorators) {
var finishers = [];
for (var i = decorators.length - 1; i >= 0; i--) {
var obj = this.fromClassDescriptor(elements);
var elementsAndFinisher = this.toClassDescriptor(
(0, decorators[i])(obj) || obj
);
if (elementsAndFinisher.finisher !== undefined) {
finishers.push(elementsAndFinisher.finisher);
}
if (elementsAndFinisher.elements !== undefined) {
elements = elementsAndFinisher.elements;
for (var j = 0; j < elements.length - 1; j++) {
for (var k = j + 1; k < elements.length; k++) {
if (
elements[j].key === elements[k].key &&
elements[j].placement === elements[k].placement
) {
throw new TypeError(
'Duplicated element (' + elements[j].key + ')'
);
}
}
}
}
}
return {
elements: elements,
finishers: finishers,
};
},
fromElementDescriptor: function(element) {
var obj = {
kind: element.kind,
key: element.key,
placement: element.placement,
descriptor: element.descriptor,
};
var desc = {
value: 'Descriptor',
configurable: true,
};
Object.defineProperty(obj, Symbol.toStringTag, desc);
if (element.kind === 'field') obj.initializer = element.initializer;
return obj;
},
toElementDescriptors: function(elementObjects) {
if (elementObjects === undefined) return;
return _toArray(elementObjects).map(function(elementObject) {
var element = this.toElementDescriptor(elementObject);
this.disallowProperty(elementObject, 'finisher', 'An element descriptor');
this.disallowProperty(elementObject, 'extras', 'An element descriptor');
return element;
}, this);
},
toElementDescriptor: function(elementObject) {
var kind = String(elementObject.kind);
if (kind !== 'method' && kind !== 'field') {
throw new TypeError(
'An element descriptor\'s .kind property must be either "method" or' +
' "field", but a decorator created an element descriptor with' +
' .kind "' +
kind +
'"'
);
}
var key = _toPropertyKey(elementObject.key);
var placement = String(elementObject.placement);
if (placement !== 'static' && placement !== 'prototype' && placement !== 'own') {
throw new TypeError(
'An element descriptor\'s .placement property must be one of "static",' +
' "prototype" or "own", but a decorator created an element descriptor' +
' with .placement "' +
placement +
'"'
);
}
var descriptor = elementObject.descriptor;
this.disallowProperty(elementObject, 'elements', 'An element descriptor');
var element = {
kind: kind,
key: key,
placement: placement,
descriptor: Object.assign({}, descriptor),
};
if (kind !== 'field') {
this.disallowProperty(elementObject, 'initializer', 'A method descriptor');
} else {
this.disallowProperty(
descriptor,
'get',
'The property descriptor of a field descriptor'
);
this.disallowProperty(
descriptor,
'set',
'The property descriptor of a field descriptor'
);
this.disallowProperty(
descriptor,
'value',
'The property descriptor of a field descriptor'
);
element.initializer = elementObject.initializer;
}
return element;
},
toElementFinisherExtras: function(elementObject) {
var element = this.toElementDescriptor(elementObject);
var finisher = _optionalCallableProperty(elementObject, 'finisher');
var extras = this.toElementDescriptors(elementObject.extras);
return {
element: element,
finisher: finisher,
extras: extras,
};
},
fromClassDescriptor: function(elements) {
var obj = {
kind: 'class',
elements: elements.map(this.fromElementDescriptor, this),
};
var desc = {
value: 'Descriptor',
configurable: true,
};
Object.defineProperty(obj, Symbol.toStringTag, desc);
return obj;
},
toClassDescriptor: function(obj) {
var kind = String(obj.kind);
if (kind !== 'class') {
throw new TypeError(
'A class descriptor\'s .kind property must be "class", but a decorator' +
' created a class descriptor with .kind "' +
kind +
'"'
);
}
this.disallowProperty(obj, 'key', 'A class descriptor');
this.disallowProperty(obj, 'placement', 'A class descriptor');
this.disallowProperty(obj, 'descriptor', 'A class descriptor');
this.disallowProperty(obj, 'initializer', 'A class descriptor');
this.disallowProperty(obj, 'extras', 'A class descriptor');
var finisher = _optionalCallableProperty(obj, 'finisher');
var elements = this.toElementDescriptors(obj.elements);
return {
elements: elements,
finisher: finisher,
};
},
runClassFinishers: function(constructor, finishers) {
for (var i = 0; i < finishers.length; i++) {
var newConstructor = (0, finishers[i])(constructor);
if (newConstructor !== undefined) {
if (typeof newConstructor !== 'function') {
throw new TypeError('Finishers must return a constructor.');
}
constructor = newConstructor;
}
}
return constructor;
},
disallowProperty: function(obj, name, objectType) {
if (obj[name] !== undefined) {
throw new TypeError(objectType + " can't have a ." + name + ' property.');
}
},
};
return api;
}
function _createElementDescriptor(def) {
var key = _toPropertyKey(def.key);
var descriptor;
if (def.kind === 'method') {
descriptor = {
value: def.value,
writable: true,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'get') {
descriptor = {
get: def.value,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'set') {
descriptor = {
set: def.value,
configurable: true,
enumerable: false,
};
} else if (def.kind === 'field') {
descriptor = {
configurable: true,
writable: true,
enumerable: true,
};
}
var element = {
kind: def.kind === 'field' ? 'field' : 'method',
key: key,
placement: def.static ? 'static' : def.kind === 'field' ? 'own' : 'prototype',
descriptor: descriptor,
};
if (def.decorators) element.decorators = def.decorators;
if (def.kind === 'field') element.initializer = def.value;
return element;
}
function _coalesceGetterSetter(element, other) {
if (element.descriptor.get !== undefined) {
other.descriptor.get = element.descriptor.get;
} else {
other.descriptor.set = element.descriptor.set;
}
}
function _coalesceClassElements(elements) {
var newElements = [];
var isSameElement = function(other) {
return (
other.kind === 'method' &&
other.key === element.key &&
other.placement === element.placement
);
};
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var other;
if (element.kind === 'method' && (other = newElements.find(isSameElement))) {
if (_isDataDescriptor(element.descriptor) || _isDataDescriptor(other.descriptor)) {
if (_hasDecorators(element) || _hasDecorators(other)) {
throw new ReferenceError(
'Duplicated methods (' + element.key + ") can't be decorated."
);
}
other.descriptor = element.descriptor;
} else {
if (_hasDecorators(element)) {
if (_hasDecorators(other)) {
throw new ReferenceError(
"Decorators can't be placed on different accessors with for " +
'the same property (' +
element.key +
').'
);
}
other.decorators = element.decorators;
}
_coalesceGetterSetter(element, other);
}
} else {
newElements.push(element);
}
}
return newElements;
}
function _hasDecorators(element) {
return element.decorators && element.decorators.length;
}
function _isDataDescriptor(desc) {
return desc !== undefined && !(desc.value === undefined && desc.writable === undefined);
}
function _optionalCallableProperty(obj, name) {
var value = obj[name];
if (value !== undefined && typeof value !== 'function') {
throw new TypeError("Expected '" + name + "' to be a function");
}
return value;
}
function _classPrivateMethodGet(receiver, privateSet, fn) {
if (!privateSet.has(receiver)) {
throw new TypeError('attempted to get private field on non-instance');
}
return fn;
}
function _classPrivateMethodSet() {
throw new TypeError('attempted to reassign private method');
}
function _wrapRegExp(re, groups) {
_wrapRegExp = function(re, groups) {
return new BabelRegExp(re, groups);
};
var _RegExp = _wrapNativeSuper(RegExp);
var _super = RegExp.prototype;
var _groups = new WeakMap();
function BabelRegExp(re, groups) {
var _this = _RegExp.call(this, re);
_groups.set(_this, groups);
return _this;
}
_inherits(BabelRegExp, _RegExp);
BabelRegExp.prototype.exec = function(str) {
var result = _super.exec.call(this, str);
if (result) result.groups = buildGroups(result, this);
return result;
};
BabelRegExp.prototype[Symbol.replace] = function(str, substitution) {
if (typeof substitution === 'string') {
var groups = _groups.get(this);
return _super[Symbol.replace].call(
this,
str,
substitution.replace(/\$<([^>]+)>/g, function(_, name) {
return '$' + groups[name];
})
);
} else if (typeof substitution === 'function') {
var _this = this;
return _super[Symbol.replace].call(this, str, function() {
var args = [];
args.push.apply(args, arguments);
if (typeof args[args.length - 1] !== 'object') {
args.push(buildGroups(args, _this));
}
return substitution.apply(this, args);
});
} else {
return _super[Symbol.replace].call(this, str, substitution);
}
};
function buildGroups(result, re) {
var g = _groups.get(re);
return Object.keys(g).reduce(function(groups, name) {
groups[name] = result[g[name]];
return groups;
}, Object.create(null));
}
return _wrapRegExp.apply(this, arguments);
}
var arrayRemove = function arrayRemove(arr, index) {
return arr.splice(index, 1);
};
var run = function run(cb, sync) {
if (sync) {
cb();
} else if (document.hidden) {
Promise.resolve(1).then(cb);
} else {
setTimeout(cb, 0);
}
};
var on = function on() {
var listeners = [];
var off = function off(event, cb) {
arrayRemove(
listeners,
listeners.findIndex(function(listener) {
return listener.event === event && (listener.cb === cb || !cb);
})
);
};
var _fire = function fire(event, args, sync) {
listeners
.filter(function(listener) {
return listener.event === event;
})
.map(function(listener) {
return listener.cb;
})
.forEach(function(cb) {
return run(function() {
return cb.apply(void 0, _toConsumableArray(args));
}, sync);
});
};
return {
fireSync: function fireSync(event) {
for (
var _len = arguments.length,
args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1;
_key < _len;
_key++
) {
args[_key - 1] = arguments[_key];
}
_fire(event, args, true);
},
fire: function fire(event) {
for (
var _len2 = arguments.length,
args = new Array(_len2 > 1 ? _len2 - 1 : 0),
_key2 = 1;
_key2 < _len2;
_key2++
) {
args[_key2 - 1] = arguments[_key2];
}
_fire(event, args, false);
},
on: function on(event, cb) {
listeners.push({ event: event, cb: cb });
},
onOnce: function onOnce(event, _cb) {
listeners.push({
event: event,
cb: function cb() {
off(event, _cb);
_cb.apply(void 0, arguments);
},
});
},
off: off,
};
};
var copyObjectPropertiesToObject = function copyObjectPropertiesToObject(
src,
target,
excluded
) {
Object.getOwnPropertyNames(src)
.filter(function(property) {
return !excluded.includes(property);
})
.forEach(function(key) {
return Object.defineProperty(
target,
key,
Object.getOwnPropertyDescriptor(src, key)
);
});
};
var PRIVATE = [
'fire',
'process',
'revert',
'load',
'on',
'off',
'onOnce',
'retryLoad',
'extend',
'archive',
'archived',
'release',
'released',
'requestProcessing',
'freeze',
];
var createItemAPI = function createItemAPI(item) {
var api = {};
copyObjectPropertiesToObject(item, api, PRIVATE);
return api;
};
var removeReleasedItems = function removeReleasedItems(items) {
items.forEach(function(item, index) {
if (item.released) {
arrayRemove(items, index);
}
});
};
var ItemStatus = {
INIT: 1,
IDLE: 2,
PROCESSING_QUEUED: 9,
PROCESSING: 3,
PROCESSING_COMPLETE: 5,
PROCESSING_ERROR: 6,
PROCESSING_REVERT_ERROR: 10,
LOADING: 7,
LOAD_ERROR: 8,
};
var FileOrigin = {
INPUT: 1,
LIMBO: 2,
LOCAL: 3,
};
var getNonNumeric = function getNonNumeric(str) {
return /[^0-9]+/.exec(str);
};
var getDecimalSeparator = function getDecimalSeparator() {
return getNonNumeric((1.1).toLocaleString())[0];
};
var getThousandsSeparator = function getThousandsSeparator() {
// Added for browsers that do not return the thousands separator (happend on native browser Android 4.4.4)
// We check against the normal toString output and if they're the same return a comma when decimal separator is a dot
var decimalSeparator = getDecimalSeparator();
var thousandsStringWithSeparator = (1000.0).toLocaleString();
var thousandsStringWithoutSeparator = (1000.0).toString();
if (thousandsStringWithSeparator !== thousandsStringWithoutSeparator) {
return getNonNumeric(thousandsStringWithSeparator)[0];
}
return decimalSeparator === '.' ? ',' : '.';
};
var Type = {
BOOLEAN: 'boolean',
INT: 'int',
NUMBER: 'number',
STRING: 'string',
ARRAY: 'array',
OBJECT: 'object',
FUNCTION: 'function',
ACTION: 'action',
SERVER_API: 'serverapi',
REGEX: 'regex',
};
// all registered filters
var filters = [];
// loops over matching filters and passes options to each filter, returning the mapped results
var applyFilterChain = function applyFilterChain(key, value, utils) {
return new Promise(function(resolve, reject) {
// find matching filters for this key
var matchingFilters = filters
.filter(function(f) {
return f.key === key;
})
.map(function(f) {
return f.cb;
});
// resolve now
if (matchingFilters.length === 0) {
resolve(value);
return;
}
// first filter to kick things of
var initialFilter = matchingFilters.shift();
// chain filters
matchingFilters
.reduce(
// loop over promises passing value to next promise
function(current, next) {
return current.then(function(value) {
return next(value, utils);
});
},
// call initial filter, will return a promise
initialFilter(value, utils)
// all executed
)
.then(function(value) {
return resolve(value);
})
.catch(function(error) {
return reject(error);
});
});
};
var applyFilters = function applyFilters(key, value, utils) {
return filters
.filter(function(f) {
return f.key === key;
})
.map(function(f) {
return f.cb(value, utils);
});
};
// adds a new filter to the list
var addFilter = function addFilter(key, cb) {
return filters.push({ key: key, cb: cb });
};
var extendDefaultOptions = function extendDefaultOptions(additionalOptions) {
return Object.assign(defaultOptions, additionalOptions);
};
var getOptions = function getOptions() {
return Object.assign({}, defaultOptions);
};
var setOptions = function setOptions(opts) {
forin(opts, function(key, value) {
// key does not exist, so this option cannot be set
if (!defaultOptions[key]) {
return;
}
defaultOptions[key][0] = getValueByType(
value,
defaultOptions[key][0],
defaultOptions[key][1]
);
});
};
// default options on app
var defaultOptions = {
// the id to add to the root element
id: [null, Type.STRING],
// input field name to use
name: ['filepond', Type.STRING],
// disable the field
disabled: [false, Type.BOOLEAN],
// classname to put on wrapper
className: [null, Type.STRING],
// is the field required
required: [false, Type.BOOLEAN],
// Allow media capture when value is set
captureMethod: [null, Type.STRING],
// - "camera", "microphone" or "camcorder",
// - Does not work with multiple on apple devices
// - If set, acceptedFileTypes must be made to match with media wildcard "image/*", "audio/*" or "video/*"
// sync `acceptedFileTypes` property with `accept` attribute
allowSyncAcceptAttribute: [true, Type.BOOLEAN],
// Feature toggles
allowDrop: [true, Type.BOOLEAN], // Allow dropping of files
allowBrowse: [true, Type.BOOLEAN], // Allow browsing the file system
allowPaste: [true, Type.BOOLEAN], // Allow pasting files
allowMultiple: [false, Type.BOOLEAN], // Allow multiple files (disabled by default, as multiple attribute is also required on input to allow multiple)
allowReplace: [true, Type.BOOLEAN], // Allow dropping a file on other file to replace it (only works when multiple is set to false)
allowRevert: [true, Type.BOOLEAN], // Allows user to revert file upload
allowRemove: [true, Type.BOOLEAN], // Allow user to remove a file
allowProcess: [true, Type.BOOLEAN], // Allows user to process a file, when set to false, this removes the file upload button
allowReorder: [false, Type.BOOLEAN], // Allow reordering of files
allowDirectoriesOnly: [false, Type.BOOLEAN], // Allow only selecting directories with browse (no support for filtering dnd at this point)
// Revert mode
forceRevert: [false, Type.BOOLEAN], // Set to 'force' to require the file to be reverted before removal
// Input requirements
maxFiles: [null, Type.INT], // Max number of files
checkValidity: [false, Type.BOOLEAN], // Enables custom validity messages
// Where to put file
itemInsertLocationFreedom: [true, Type.BOOLEAN], // Set to false to always add items to begin or end of list
itemInsertLocation: ['before', Type.STRING], // Default index in list to add items that have been dropped at the top of the list
itemInsertInterval: [75, Type.INT],
// Drag 'n Drop related
dropOnPage: [false, Type.BOOLEAN], // Allow dropping of files anywhere on page (prevents browser from opening file if dropped outside of Up)
dropOnElement: [true, Type.BOOLEAN], // Drop needs to happen on element (set to false to also load drops outside of Up)
dropValidation: [false, Type.BOOLEAN], // Enable or disable validating files on drop
ignoredFiles: [['.ds_store', 'thumbs.db', 'desktop.ini'], Type.ARRAY],
// Upload related
instantUpload: [true, Type.BOOLEAN], // Should upload files immediately on drop
maxParallelUploads: [2, Type.INT], // Maximum files to upload in parallel
// Chunks
chunkUploads: [false, Type.BOOLEAN], // Enable chunked uploads
chunkForce: [false, Type.BOOLEAN], // Force use of chunk uploads even for files smaller than chunk size
chunkSize: [5000000, Type.INT], // Size of chunks (5MB default)
chunkRetryDelays: [[500, 1000, 3000], Type.ARRAY], // Amount of times to retry upload of a chunk when it fails
// The server api end points to use for uploading (see docs)
server: [null, Type.SERVER_API],
// File size calculations, can set to 1024, this is only used for display, properties use file size base 1000
fileSizeBase: [1000, Type.INT],
// Labels and status messages
labelDecimalSeparator: [getDecimalSeparator(), Type.STRING], // Default is locale separator
labelThousandsSeparator: [getThousandsSeparator(), Type.STRING], // Default is locale separator
labelIdle: [
'Drag & Drop your files or <span class="filepond--label-action">Browse</span>',
Type.STRING,
],
labelInvalidField: ['Field contains invalid files', Type.STRING],
labelFileWaitingForSize: ['Waiting for size', Type.STRING],
labelFileSizeNotAvailable: ['Size not available', Type.STRING],
labelFileCountSingular: ['file in list', Type.STRING],
labelFileCountPlural: ['files in list', Type.STRING],
labelFileLoading: ['Loading', Type.STRING],
labelFileAdded: ['Added', Type.STRING], // assistive only
labelFileLoadError: ['Error during load', Type.STRING],
labelFileRemoved: ['Removed', Type.STRING], // assistive only
labelFileRemoveError: ['Error during remove', Type.STRING],
labelFileProcessing: ['Uploading', Type.STRING],
labelFileProcessingComplete: ['Upload complete', Type.STRING],
labelFileProcessingAborted: ['Upload cancelled', Type.STRING],
labelFileProcessingError: ['Error during upload', Type.STRING],
labelFileProcessingRevertError: ['Error during revert', Type.STRING],
labelTapToCancel: ['tap to cancel', Type.STRING],
labelTapToRetry: ['tap to retry', Type.STRING],
labelTapToUndo: ['tap to undo', Type.STRING],
labelButtonRemoveItem: ['Remove', Type.STRING],
labelButtonAbortItemLoad: ['Abort', Type.STRING],
labelButtonRetryItemLoad: ['Retry', Type.STRING],
labelButtonAbortItemProcessing: ['Cancel', Type.STRING],
labelButtonUndoItemProcessing: ['Undo', Type.STRING],
labelButtonRetryItemProcessing: ['Retry', Type.STRING],
labelButtonProcessItem: ['Upload', Type.STRING],
// make sure width and height plus viewpox are even numbers so icons are nicely centered
iconRemove: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M11.586 13l-2.293 2.293a1 1 0 0 0 1.414 1.414L13 14.414l2.293 2.293a1 1 0 0 0 1.414-1.414L14.414 13l2.293-2.293a1 1 0 0 0-1.414-1.414L13 11.586l-2.293-2.293a1 1 0 0 0-1.414 1.414L11.586 13z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconProcess: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M14 10.414v3.585a1 1 0 0 1-2 0v-3.585l-1.293 1.293a1 1 0 0 1-1.414-1.415l3-3a1 1 0 0 1 1.414 0l3 3a1 1 0 0 1-1.414 1.415L14 10.414zM9 18a1 1 0 0 1 0-2h8a1 1 0 0 1 0 2H9z" fill="currentColor" fill-rule="evenodd"/></svg>',
Type.STRING,
],
iconRetry: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M10.81 9.185l-.038.02A4.997 4.997 0 0 0 8 13.683a5 5 0 0 0 5 5 5 5 0 0 0 5-5 1 1 0 0 1 2 0A7 7 0 1 1 9.722 7.496l-.842-.21a.999.999 0 1 1 .484-1.94l3.23.806c.535.133.86.675.73 1.21l-.804 3.233a.997.997 0 0 1-1.21.73.997.997 0 0 1-.73-1.21l.23-.928v-.002z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconUndo: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M9.185 10.81l.02-.038A4.997 4.997 0 0 1 13.683 8a5 5 0 0 1 5 5 5 5 0 0 1-5 5 1 1 0 0 0 0 2A7 7 0 1 0 7.496 9.722l-.21-.842a.999.999 0 1 0-1.94.484l.806 3.23c.133.535.675.86 1.21.73l3.233-.803a.997.997 0 0 0 .73-1.21.997.997 0 0 0-1.21-.73l-.928.23-.002-.001z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
iconDone: [
'<svg width="26" height="26" viewBox="0 0 26 26" xmlns="http://www.w3.org/2000/svg"><path d="M18.293 9.293a1 1 0 0 1 1.414 1.414l-7.002 7a1 1 0 0 1-1.414 0l-3.998-4a1 1 0 1 1 1.414-1.414L12 15.586l6.294-6.293z" fill="currentColor" fill-rule="nonzero"/></svg>',
Type.STRING,
],
// event handlers
oninit: [null, Type.FUNCTION],
onwarning: [null, Type.FUNCTION],
onerror: [null, Type.FUNCTION],
onactivatefile: [null, Type.FUNCTION],
oninitfile: [null, Type.FUNCTION],
onaddfilestart: [null, Type.FUNCTION],
onaddfileprogress: [null, Type.FUNCTION],
onaddfile: [null, Type.FUNCTION],
onprocessfilestart: [null, Type.FUNCTION],
onprocessfileprogress: [null, Type.FUNCTION],
onprocessfileabort: [null, Type.FUNCTION],
onprocessfilerevert: [null, Type.FUNCTION],
onprocessfile: [null, Type.FUNCTION],
onprocessfiles: [null, Type.FUNCTION],
onremovefile: [null, Type.FUNCTION],
onpreparefile: [null, Type.FUNCTION],
onupdatefiles: [null, Type.FUNCTION],
onreorderfiles: [null, Type.FUNCTION],
// hooks
beforeDropFile: [null, Type.FUNCTION],
beforeAddFile: [null, Type.FUNCTION],
beforeRemoveFile: [null, Type.FUNCTION],
beforePrepareFile: [null, Type.FUNCTION],
// styles
stylePanelLayout: [null, Type.STRING], // null 'integrated', 'compact', 'circle'
stylePanelAspectRatio: [null, Type.STRING], // null or '3:2' or 1
styleItemPanelAspectRatio: [null, Type.STRING],
styleButtonRemoveItemPosition: ['left', Type.STRING],
styleButtonProcessItemPosition: ['right', Type.STRING],
styleLoadIndicatorPosition: ['right', Type.STRING],
styleProgressIndicatorPosition: ['right', Type.STRING],
styleButtonRemoveItemAlign: [false, Type.BOOLEAN],
// custom initial files array
files: [[], Type.ARRAY],
// show support by displaying credits
credits: [['https://pqina.nl/', 'Powered by PQINA'], Type.ARRAY],
};
var getItemByQuery = function getItemByQuery(items, query) {
// just return first index
if (isEmpty(query)) {
return items[0] || null;
}
// query is index
if (isInt(query)) {
return items[query] || null;
}
// if query is item, get the id
if (typeof query === 'object') {
query = query.id;
}
// assume query is a string and return item by id
return (
items.find(function(item) {
return item.id === query;
}) || null
);
};
var getNumericAspectRatioFromString = function getNumericAspectRatioFromString(aspectRatio) {
if (isEmpty(aspectRatio)) {
return aspectRatio;
}
if (/:/.test(aspectRatio)) {
var parts = aspectRatio.split(':');
return parts[1] / parts[0];
}
return parseFloat(aspectRatio);
};
var getActiveItems = function getActiveItems(items) {
return items.filter(function(item) {
return !item.archived;
});
};
var Status = {
EMPTY: 0,
IDLE: 1, // waiting
ERROR: 2, // a file is in error state
BUSY: 3, // busy processing or loading
READY: 4, // all files uploaded
};
var ITEM_ERROR = [
ItemStatus.LOAD_ERROR,
ItemStatus.PROCESSING_ERROR,
ItemStatus.PROCESSING_REVERT_ERROR,
];
var ITEM_BUSY = [
ItemStatus.LOADING,
ItemStatus.PROCESSING,
ItemStatus.PROCESSING_QUEUED,
ItemStatus.INIT,
];
var ITEM_READY = [ItemStatus.PROCESSING_COMPLETE];
var isItemInErrorState = function isItemInErrorState(item) {
return ITEM_ERROR.includes(item.status);
};
var isItemInBusyState = function isItemInBusyState(item) {
return ITEM_BUSY.includes(item.status);
};
var isItemInReadyState = function isItemInReadyState(item) {
return ITEM_READY.includes(item.status);
};
var queries = function queries(state) {
return {
GET_STATUS: function GET_STATUS() {
var items = getActiveItems(state.items);
var EMPTY = Status.EMPTY,
ERROR = Status.ERROR,
BUSY = Status.BUSY,
IDLE = Status.IDLE,
READY = Status.READY;
if (items.length === 0) return EMPTY;
if (items.some(isItemInErrorState)) return ERROR;
if (items.some(isItemInBusyState)) return BUSY;
if (items.some(isItemInReadyState)) return READY;
return IDLE;
},
GET_ITEM: function GET_ITEM(query) {
return getItemByQuery(state.items, query);
},
GET_ACTIVE_ITEM: function GET_ACTIVE_ITEM(query) {
return getItemByQuery(getActiveItems(state.items), query);
},
GET_ACTIVE_ITEMS: function GET_ACTIVE_ITEMS() {
return getActiveItems(state.items);
},
GET_ITEMS: function GET_ITEMS() {
return state.items;
},
GET_ITEM_NAME: function GET_ITEM_NAME(query) {
var item = getItemByQuery(state.items, query);
return item ? item.filename : null;
},
GET_ITEM_SIZE: function GET_ITEM_SIZE(query) {
var item = getItemByQuery(state.items, query);
return item ? item.fileSize : null;
},
GET_STYLES: function GET_STYLES() {
return Object.keys(state.options)
.filter(function(key) {
return /^style/.test(key);
})
.map(function(option) {
return {
name: option,
value: state.options[option],
};
});
},
GET_PANEL_ASPECT_RATIO: function GET_PANEL_ASPECT_RATIO() {
var isShapeCircle = /circle/.test(state.options.stylePanelLayout);
var aspectRatio = isShapeCircle
? 1
: getNumericAspectRatioFromString(state.options.stylePanelAspectRatio);
return aspectRatio;
},
GET_ITEM_PANEL_ASPECT_RATIO: function GET_ITEM_PANEL_ASPECT_RATIO() {
return state.options.styleItemPanelAspectRatio;
},
GET_ITEMS_BY_STATUS: function GET_ITEMS_BY_STATUS(status) {
return getActiveItems(state.items).filter(function(item) {
return item.status === status;
});
},
GET_TOTAL_ITEMS: function GET_TOTAL_ITEMS() {
return getActiveItems(state.items).length;
},
IS_ASYNC: function IS_ASYNC() {
return (
isObject(state.options.server) &&
(isObject(state.options.server.process) ||
isFunction(state.options.server.process))
);
},
};
};
var hasRoomForItem = function hasRoomForItem(state) {
var count = getActiveItems(state.items).length;
// if cannot have multiple items, to add one item it should currently not contain items
if (!state.options.allowMultiple) {
return count === 0;
}
// if allows multiple items, we check if a max item count has been set, if not, there's no limit
var maxFileCount = state.options.maxFiles;
if (maxFileCount === null) {
return true;
}
// we check if the current count is smaller than the max count, if so, another file can still be added
if (count < maxFileCount) {
return true;
}
// no more room for another file
return false;
};
var limit = function limit(value, min, max) {
return Math.max(Math.min(max, value), min);
};
var arrayInsert = function arrayInsert(arr, index, item) {
return arr.splice(index, 0, item);
};
var insertItem = function insertItem(items, item, index) {
if (isEmpty(item)) {
return null;
}
// if index is undefined, append
if (typeof index === 'undefined') {
items.push(item);
return item;
}
// limit the index to the size of the items array
index = limit(index, 0, items.length);
// add item to array
arrayInsert(items, index, item);
// expose
return item;
};
var isBase64DataURI = function isBase64DataURI(str) {
return /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*)\s*$/i.test(
str
);
};
var getFilenameFromURL = function getFilenameFromURL(url) {
return url
.split('/')
.pop()
.split('?')
.shift();
};
var getExtensionFromFilename = function getExtensionFromFilename(name) {
return name.split('.').pop();
};
var guesstimateExtension = function guesstimateExtension(type) {
// if no extension supplied, exit here
if (typeof type !== 'string') {
return '';
}
// get subtype
var subtype = type.split('/').pop();
// is svg subtype
if (/svg/.test(subtype)) {
return 'svg';
}
if (/zip|compressed/.test(subtype)) {
return 'zip';
}
if (/plain/.test(subtype)) {
return 'txt';
}
if (/msword/.test(subtype)) {
return 'doc';
}
// if is valid subtype
if (/[a-z]+/.test(subtype)) {
// always use jpg extension
if (subtype === 'jpeg') {
return 'jpg';
}
// return subtype
return subtype;
}
return '';
};
var leftPad = function leftPad(value) {
var padding = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
return (padding + value).slice(-padding.length);
};
var getDateString = function getDateString() {
var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
return (
date.getFullYear() +
'-' +
leftPad(date.getMonth() + 1, '00') +
'-' +
leftPad(date.getDate(), '00') +
'_' +
leftPad(date.getHours(), '00') +
'-' +
leftPad(date.getMinutes(), '00') +
'-' +
leftPad(date.getSeconds(), '00')
);
};
var getFileFromBlob = function getFileFromBlob(blob, filename) {
var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var extension = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
var file =
typeof type === 'string'
? blob.slice(0, blob.size, type)
: blob.slice(0, blob.size, blob.type);
file.lastModifiedDate = new Date();
// copy relative path
if (blob._relativePath) file._relativePath = blob._relativePath;
// if blob has name property, use as filename if no filename supplied
if (!isString(filename)) {
filename = getDateString();
}
// if filename supplied but no extension and filename has extension
if (filename && extension === null && getExtensionFromFilename(filename)) {
file.name = filename;
} else {
extension = extension || guesstimateExtension(file.type);
file.name = filename + (extension ? '.' + extension : '');
}
return file;
};
var getBlobBuilder = function getBlobBuilder() {
return (window.BlobBuilder =
window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder);
};
var createBlob = function createBlob(arrayBuffer, mimeType) {
var BB = getBlobBuilder();
if (BB) {
var bb = new BB();
bb.append(arrayBuffer);
return bb.getBlob(mimeType);
}
return new Blob([arrayBuffer], {
type: mimeType,
});
};
var getBlobFromByteStringWithMimeType = function getBlobFromByteStringWithMimeType(
byteString,
mimeType
) {
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return createBlob(ab, mimeType);
};
var getMimeTypeFromBase64DataURI = function getMimeTypeFromBase64DataURI(dataURI) {
return (/^data:(.+);/.exec(dataURI) || [])[1] || null;
};
var getBase64DataFromBase64DataURI = function getBase64DataFromBase64DataURI(dataURI) {
// get data part of string (remove data:image/jpeg...,)
var data = dataURI.split(',')[1];
// remove any whitespace as that causes InvalidCharacterError in IE
return data.replace(/\s/g, '');
};
var getByteStringFromBase64DataURI = function getByteStringFromBase64DataURI(dataURI) {
return atob(getBase64DataFromBase64DataURI(dataURI));
};
var getBlobFromBase64DataURI = function getBlobFromBase64DataURI(dataURI) {
var mimeType = getMimeTypeFromBase64DataURI(dataURI);
var byteString = getByteStringFromBase64DataURI(dataURI);
return getBlobFromByteStringWithMimeType(byteString, mimeType);
};
var getFileFromBase64DataURI = function getFileFromBase64DataURI(dataURI, filename, extension) {
return getFileFromBlob(getBlobFromBase64DataURI(dataURI), filename, null, extension);
};
var getFileNameFromHeader = function getFileNameFromHeader(header) {
// test if is content disposition header, if not exit
if (!/^content-disposition:/i.test(header)) return null;
// get filename parts
var matches = header
.split(/filename=|filename\*=.+''/)
.splice(1)
.map(function(name) {
return name.trim().replace(/^["']|[;"']{0,2}$/g, '');
})
.filter(function(name) {
return name.length;
});
return matches.length ? decodeURI(matches[matches.length - 1]) : null;
};
var getFileSizeFromHeader = function getFileSizeFromHeader(header) {
if (/content-length:/i.test(header)) {
var size = header.match(/[0-9]+/)[0];
return size ? parseInt(size, 10) : null;
}
return null;
};
var getTranfserIdFromHeader = function getTranfserIdFromHeader(header) {
if (/x-content-transfer-id:/i.test(header)) {
var id = (header.split(':')[1] || '').trim();
return id || null;
}
return null;
};
var getFileInfoFromHeaders = function getFileInfoFromHeaders(headers) {
var info = {
source: null,
name: null,
size: null,
};
var rows = headers.split('\n');
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (
var _iterator = rows[Symbol.iterator](), _step;
!(_iteratorNormalCompletion = (_step = _iterator.next()).done);
_iteratorNormalCompletion = true
) {
var header = _step.value;
var name = getFileNameFromHeader(header);
if (name) {
info.name = name;
continue;
}
var size = getFileSizeFromHeader(header);
if (size) {
info.size = size;
continue;
}
var source = getTranfserIdFromHeader(header);
if (source) {
info.source = source;
continue;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return info;
};
var createFileLoader = function createFileLoader(fetchFn) {
var state = {
source: null,
complete: false,
progress: 0,
size: null,
timestamp: null,
duration: 0,
request: null,
};
var getProgress = function getProgress() {
return state.progress;
};
var abort = function abort() {
if (state.request && state.request.abort) {
state.request.abort();
}
};
// load source
var load = function load() {
// get quick reference
var source = state.source;
api.fire('init', source);
// Load Files
if (source instanceof File) {
api.fire('load', source);
} else if (source instanceof Blob) {
// Load blobs, set default name to current date
api.fire('load', getFileFromBlob(source, source.name));
} else if (isBase64DataURI(source)) {
// Load base 64, set default name to current date
api.fire('load', getFileFromBase64DataURI(source));
} else {
// Deal as if is external URL, let's load it!
loadURL(source);
}
};
// loads a url
var loadURL = function loadURL(url) {
// is remote url and no fetch method supplied
if (!fetchFn) {
api.fire('error', {
type: 'error',
body: "Can't load URL",
code: 400,
});
return;
}
// set request start
state.timestamp = Date.now();
// load file
state.request = fetchFn(
url,
function(response) {
// update duration
state.duration = Date.now() - state.timestamp;
// done!
state.complete = true;
// turn blob response into a file
if (response instanceof Blob) {
response = getFileFromBlob(
response,
response.name || getFilenameFromURL(url)
);
}
api.fire(
'load',
// if has received blob, we go with blob, if no response, we return null
response instanceof Blob ? response : response ? response.body : null
);
},
function(error) {
api.fire(
'error',
typeof error === 'string'
? {
type: 'error',
code: 0,
body: error,
}
: error
);
},
function(computable, current, total) {
// collected some meta data already
if (total) {
state.size = total;
}
// update duration
state.duration = Date.now() - state.timestamp;
// if we can't compute progress, we're not going to fire progress events
if (!computable) {
state.progress = null;
return;
}
// update progress percentage
state.progress = current / total;
// expose
api.fire('progress', state.progress);
},
function() {
api.fire('abort');
},
function(response) {
var fileinfo = getFileInfoFromHeaders(
typeof response === 'string' ? response : response.headers
);
api.fire('meta', {
size: state.size || fileinfo.size,
filename: fileinfo.name,
source: fileinfo.source,
});
}
);
};
var api = Object.assign({}, on(), {
setSource: function setSource(source) {
return (state.source = source);
},
getProgress: getProgress, // file load progress
abort: abort, // abort file load
load: load, // start load
});
return api;
};
var isGet = function isGet(method) {
return /GET|HEAD/.test(method);
};
var sendRequest = function sendRequest(data, url, options) {
var api = {
onheaders: function onheaders() {},
onprogress: function onprogress() {},
onload: function onload() {},
ontimeout: function ontimeout() {},
onerror: function onerror() {},
onabort: function onabort() {},
abort: function abort() {
aborted = true;
xhr.abort();
},
};
// timeout identifier, only used when timeout is defined
var aborted = false;
var headersReceived = false;
// set default options
options = Object.assign(
{
method: 'POST',
headers: {},
withCredentials: false,
},
options
);
// encode url
url = encodeURI(url);
// if method is GET, add any received data to url
if (isGet(options.method) && data) {
url =
'' +
url +
encodeURIComponent(typeof data === 'string' ? data : JSON.stringify(data));
}
// create request
var xhr = new XMLHttpRequest();
// progress of load
var process = isGet(options.method) ? xhr : xhr.upload;
process.onprogress = function(e) {
// no progress event when aborted ( onprogress is called once after abort() )
if (aborted) {
return;
}
api.onprogress(e.lengthComputable, e.loaded, e.total);
};
// tries to get header info to the app as fast as possible
xhr.onreadystatechange = function() {
// not interesting in these states ('unsent' and 'openend' as they don't give us any additional info)
if (xhr.readyState < 2) {
return;
}
// no server response
if (xhr.readyState === 4 && xhr.status === 0) {
return;
}
if (headersReceived) {
return;
}
headersReceived = true;
// we've probably received some useful data in response headers
api.onheaders(xhr);
};
// load successful
xhr.onload = function() {
// is classified as valid response
if (xhr.status >= 200 && xhr.status < 300) {
api.onload(xhr);
} else {
api.onerror(xhr);
}
};
// error during load
xhr.onerror = function() {
return api.onerror(xhr);
};
// request aborted
xhr.onabort = function() {
aborted = true;
api.onabort();
};
// request timeout
xhr.ontimeout = function() {
return api.ontimeout(xhr);
};
// open up open up!
xhr.open(options.method, url, true);
// set timeout if defined (do it after open so IE11 plays ball)
if (isInt(options.timeout)) {
xhr.timeout = options.timeout;
}
// add headers
Object.keys(options.headers).forEach(function(key) {
var value = unescape(encodeURIComponent(options.headers[key]));
xhr.setRequestHeader(key, value);
});
// set type of response
if (options.responseType) {
xhr.responseType = options.responseType;
}
// set credentials
if (options.withCredentials) {
xhr.withCredentials = true;
}
// let's send our data
xhr.send(data);
return api;
};
var createResponse = function createResponse(type, code, body, headers) {
return {
type: type,
code: code,
body: body,
headers: headers,
};
};
var createTimeoutResponse = function createTimeoutResponse(cb) {
return function(xhr) {
cb(createResponse('error', 0, 'Timeout', xhr.getAllResponseHeaders()));
};
};
var hasQS = function hasQS(str) {
return /\?/.test(str);
};
var buildURL = function buildURL() {
var url = '';
for (var _len = arguments.length, parts = new Array(_len), _key = 0; _key < _len; _key++) {
parts[_key] = arguments[_key];
}
parts.forEach(function(part) {
url += hasQS(url) && hasQS(part) ? part.replace(/\?/, '&') : part;
});
return url;
};
var createFetchFunction = function createFetchFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
// custom handler (should also handle file, load, error, progress and abort)
if (typeof action === 'function') {
return action;
}
// no action supplied
if (!action || !isString(action.url)) {
return null;
}
// set onload hanlder
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// internal handler
return function(url, load, error, progress, abort, headers) {
// do local or remote request based on if the url is external
var request = sendRequest(
url,
buildURL(apiUrl, action.url),
Object.assign({}, action, {
responseType: 'blob',
})
);
request.onload = function(xhr) {
// get headers
var headers = xhr.getAllResponseHeaders();
// get filename
var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);
// create response
load(
createResponse(
'load',
xhr.status,
action.method === 'HEAD'
? null
: getFileFromBlob(onload(xhr.response), filename),
headers
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.onheaders = function(xhr) {
headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
};
var ChunkStatus = {
QUEUED: 0,
COMPLETE: 1,
PROCESSING: 2,
ERROR: 3,
WAITING: 4,
};
/*
function signature:
(file, metadata, load, error, progress, abort, transfer, options) => {
return {
abort:() => {}
}
}
*/
// apiUrl, action, name, file, metadata, load, error, progress, abort, transfer, options
var processFileChunked = function processFileChunked(
apiUrl,
action,
name,
file,
metadata,
load,
error,
progress,
abort,
transfer,
options
) {
// all chunks
var chunks = [];
var chunkTransferId = options.chunkTransferId,
chunkServer = options.chunkServer,
chunkSize = options.chunkSize,
chunkRetryDelays = options.chunkRetryDelays;
// default state
var state = {
serverId: chunkTransferId,
aborted: false,
};
// set onload handlers
var ondata =
action.ondata ||
function(fd) {
return fd;
};
var onload =
action.onload ||
function(xhr, method) {
return method === 'HEAD' ? xhr.getResponseHeader('Upload-Offset') : xhr.response;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// create server hook
var requestTransferId = function requestTransferId(cb) {
var formData = new FormData();
// add metadata under same name
if (isObject(metadata)) formData.append(name, JSON.stringify(metadata));
var headers =
typeof action.headers === 'function'
? action.headers(file, metadata)
: Object.assign({}, action.headers, {
'Upload-Length': file.size,
});
var requestParams = Object.assign({}, action, {
headers: headers,
});
// send request object
var request = sendRequest(
ondata(formData),
buildURL(apiUrl, action.url),
requestParams
);
request.onload = function(xhr) {
return cb(onload(xhr, requestParams.method));
};
request.onerror = function(xhr) {
return error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
};
var requestTransferOffset = function requestTransferOffset(cb) {
var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);
var headers =
typeof action.headers === 'function'
? action.headers(state.serverId)
: Object.assign({}, action.headers);
var requestParams = {
headers: headers,
method: 'HEAD',
};
var request = sendRequest(null, requestUrl, requestParams);
request.onload = function(xhr) {
return cb(onload(xhr, requestParams.method));
};
request.onerror = function(xhr) {
return error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
};
// create chunks
var lastChunkIndex = Math.floor(file.size / chunkSize);
for (var i = 0; i <= lastChunkIndex; i++) {
var offset = i * chunkSize;
var data = file.slice(offset, offset + chunkSize, 'application/offset+octet-stream');
chunks[i] = {
index: i,
size: data.size,
offset: offset,
data: data,
file: file,
progress: 0,
retries: _toConsumableArray(chunkRetryDelays),
status: ChunkStatus.QUEUED,
error: null,
request: null,
timeout: null,
};
}
var completeProcessingChunks = function completeProcessingChunks() {
return load(state.serverId);
};
var canProcessChunk = function canProcessChunk(chunk) {
return chunk.status === ChunkStatus.QUEUED || chunk.status === ChunkStatus.ERROR;
};
var processChunk = function processChunk(chunk) {
// processing is paused, wait here
if (state.aborted) return;
// get next chunk to process
chunk = chunk || chunks.find(canProcessChunk);
// no more chunks to process
if (!chunk) {
// all done?
if (
chunks.every(function(chunk) {
return chunk.status === ChunkStatus.COMPLETE;
})
) {
completeProcessingChunks();
}
// no chunk to handle
return;
}
// now processing this chunk
chunk.status = ChunkStatus.PROCESSING;
chunk.progress = null;
// allow parsing of formdata
var ondata =
chunkServer.ondata ||
function(fd) {
return fd;
};
var onerror =
chunkServer.onerror ||
function(res) {
return null;
};
// send request object
var requestUrl = buildURL(apiUrl, chunkServer.url, state.serverId);
var headers =
typeof chunkServer.headers === 'function'
? chunkServer.headers(chunk)
: Object.assign({}, chunkServer.headers, {
'Content-Type': 'application/offset+octet-stream',
'Upload-Offset': chunk.offset,
'Upload-Length': file.size,
'Upload-Name': file.name,
});
var request = (chunk.request = sendRequest(
ondata(chunk.data),
requestUrl,
Object.assign({}, chunkServer, {
headers: headers,
})
));
request.onload = function() {
// done!
chunk.status = ChunkStatus.COMPLETE;
// remove request reference
chunk.request = null;
// start processing more chunks
processChunks();
};
request.onprogress = function(lengthComputable, loaded, total) {
chunk.progress = lengthComputable ? loaded : null;
updateTotalProgress();
};
request.onerror = function(xhr) {
chunk.status = ChunkStatus.ERROR;
chunk.request = null;
chunk.error = onerror(xhr.response) || xhr.statusText;
if (!retryProcessChunk(chunk)) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
}
};
request.ontimeout = function(xhr) {
chunk.status = ChunkStatus.ERROR;
chunk.request = null;
if (!retryProcessChunk(chunk)) {
createTimeoutResponse(error)(xhr);
}
};
request.onabort = function() {
chunk.status = ChunkStatus.QUEUED;
chunk.request = null;
abort();
};
};
var retryProcessChunk = function retryProcessChunk(chunk) {
// no more retries left
if (chunk.retries.length === 0) return false;
// new retry
chunk.status = ChunkStatus.WAITING;
clearTimeout(chunk.timeout);
chunk.timeout = setTimeout(function() {
processChunk(chunk);
}, chunk.retries.shift());
// we're going to retry
return true;
};
var updateTotalProgress = function updateTotalProgress() {
// calculate total progress fraction
var totalBytesTransfered = chunks.reduce(function(p, chunk) {
if (p === null || chunk.progress === null) return null;
return p + chunk.progress;
}, 0);
// can't compute progress
if (totalBytesTransfered === null) return progress(false, 0, 0);
// calculate progress values
var totalSize = chunks.reduce(function(total, chunk) {
return total + chunk.size;
}, 0);
// can update progress indicator
progress(true, totalBytesTransfered, totalSize);
};
// process new chunks
var processChunks = function processChunks() {
var totalProcessing = chunks.filter(function(chunk) {
return chunk.status === ChunkStatus.PROCESSING;
}).length;
if (totalProcessing >= 1) return;
processChunk();
};
var abortChunks = function abortChunks() {
chunks.forEach(function(chunk) {
clearTimeout(chunk.timeout);
if (chunk.request) {
chunk.request.abort();
}
});
};
// let's go!
if (!state.serverId) {
requestTransferId(function(serverId) {
// stop here if aborted, might have happened in between request and callback
if (state.aborted) return;
// pass back to item so we can use it if something goes wrong
transfer(serverId);
// store internally
state.serverId = serverId;
processChunks();
});
} else {
requestTransferOffset(function(offset) {
// stop here if aborted, might have happened in between request and callback
if (state.aborted) return;
// mark chunks with lower offset as complete
chunks
.filter(function(chunk) {
return chunk.offset < offset;
})
.forEach(function(chunk) {
chunk.status = ChunkStatus.COMPLETE;
chunk.progress = chunk.size;
});
// continue processing
processChunks();
});
}
return {
abort: function abort() {
state.aborted = true;
abortChunks();
},
};
};
/*
function signature:
(file, metadata, load, error, progress, abort) => {
return {
abort:() => {}
}
}
*/
var createFileProcessorFunction = function createFileProcessorFunction(
apiUrl,
action,
name,
options
) {
return function(file, metadata, load, error, progress, abort, transfer) {
// no file received
if (!file) return;
// if was passed a file, and we can chunk it, exit here
var canChunkUpload = options.chunkUploads;
var shouldChunkUpload = canChunkUpload && file.size > options.chunkSize;
var willChunkUpload = canChunkUpload && (shouldChunkUpload || options.chunkForce);
if (file instanceof Blob && willChunkUpload)
return processFileChunked(
apiUrl,
action,
name,
file,
metadata,
load,
error,
progress,
abort,
transfer,
options
);
// set handlers
var ondata =
action.ondata ||
function(fd) {
return fd;
};
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
var headers =
typeof action.headers === 'function'
? action.headers(file, metadata) || {}
: Object.assign(
{},
action.headers
);
var requestParams = Object.assign({}, action, {
headers: headers,
});
// create formdata object
var formData = new FormData();
// add metadata under same name
if (isObject(metadata)) {
formData.append(name, JSON.stringify(metadata));
}
// Turn into an array of objects so no matter what the input, we can handle it the same way
(file instanceof Blob ? [{ name: null, file: file }] : file).forEach(function(item) {
formData.append(
name,
item.file,
item.name === null ? item.file.name : '' + item.name + item.file.name
);
});
// send request object
var request = sendRequest(
ondata(formData),
buildURL(apiUrl, action.url),
requestParams
);
request.onload = function(xhr) {
load(
createResponse(
'load',
xhr.status,
onload(xhr.response),
xhr.getAllResponseHeaders()
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
};
var createProcessorFunction = function createProcessorFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
var name = arguments.length > 2 ? arguments[2] : undefined;
var options = arguments.length > 3 ? arguments[3] : undefined;
// custom handler (should also handle file, load, error, progress and abort)
if (typeof action === 'function')
return function() {
for (
var _len = arguments.length, params = new Array(_len), _key = 0;
_key < _len;
_key++
) {
params[_key] = arguments[_key];
}
return action.apply(void 0, [name].concat(params, [options]));
};
// no action supplied
if (!action || !isString(action.url)) return null;
// internal handler
return createFileProcessorFunction(apiUrl, action, name, options);
};
/*
function signature:
(uniqueFileId, load, error) => { }
*/
var createRevertFunction = function createRevertFunction() {
var apiUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var action = arguments.length > 1 ? arguments[1] : undefined;
// is custom implementation
if (typeof action === 'function') {
return action;
}
// no action supplied, return stub function, interface will work, but file won't be removed
if (!action || !isString(action.url)) {
return function(uniqueFileId, load) {
return load();
};
}
// set onload hanlder
var onload =
action.onload ||
function(res) {
return res;
};
var onerror =
action.onerror ||
function(res) {
return null;
};
// internal implementation
return function(uniqueFileId, load, error) {
var request = sendRequest(
uniqueFileId,
apiUrl + action.url,
action // contains method, headers and withCredentials properties
);
request.onload = function(xhr) {
load(
createResponse(
'load',
xhr.status,
onload(xhr.response),
xhr.getAllResponseHeaders()
)
);
};
request.onerror = function(xhr) {
error(
createResponse(
'error',
xhr.status,
onerror(xhr.response) || xhr.statusText,
xhr.getAllResponseHeaders()
)
);
};
request.ontimeout = createTimeoutResponse(error);
return request;
};
};
var getRandomNumber = function getRandomNumber() {
var min = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
return min + Math.random() * (max - min);
};
var createPerceivedPerformanceUpdater = function createPerceivedPerformanceUpdater(cb) {
var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1000;
var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
var tickMin = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 25;
var tickMax = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 250;
var timeout = null;
var start = Date.now();
var tick = function tick() {
var runtime = Date.now() - start;
var delay = getRandomNumber(tickMin, tickMax);
if (runtime + delay > duration) {
delay = runtime + delay - duration;
}
var progress = runtime / duration;
if (progress >= 1 || document.hidden) {
cb(1);
return;
}
cb(progress);
timeout = setTimeout(tick, delay);
};
tick();
return {
clear: function clear() {
clearTimeout(timeout);
},
};
};
var createFileProcessor = function createFileProcessor(processFn) {
var state = {
complete: false,
perceivedProgress: 0,
perceivedPerformanceUpdater: null,
progress: null,
timestamp: null,
perceivedDuration: 0,
duration: 0,
request: null,
response: null,
};
var process = function process(file, metadata) {
var progressFn = function progressFn() {
// we've not yet started the real download, stop here
// the request might not go through, for instance, there might be some server trouble
// if state.progress is null, the server does not allow computing progress and we show the spinner instead
if (state.duration === 0 || state.progress === null) return;
// as we're now processing, fire the progress event
api.fire('progress', api.getProgress());
};
var completeFn = function completeFn() {
state.complete = true;
api.fire('load-perceived', state.response.body);
};
// let's start processing
api.fire('start');
// set request start
state.timestamp = Date.now();
// create perceived performance progress indicator
state.perceivedPerformanceUpdater = createPerceivedPerformanceUpdater(
function(progress) {
state.perceivedProgress = progress;
state.perceivedDuration = Date.now() - state.timestamp;
progressFn();
// if fake progress is done, and a response has been received,
// and we've not yet called the complete method
if (state.response && state.perceivedProgress === 1 && !state.complete) {
// we done!
completeFn();
}
},
// random delay as in a list of files you start noticing
// files uploading at the exact same speed
getRandomNumber(750, 1500)
);
// remember request so we can abort it later
state.request = processFn(
// the file to process
file,
// the metadata to send along
metadata,
// callbacks (load, error, progress, abort, transfer)
// load expects the body to be a server id if
// you want to make use of revert
function(response) {
// we put the response in state so we can access
// it outside of this method
state.response = isObject(response)
? response
: {
type: 'load',
code: 200,
body: '' + response,
headers: {},
};
// update duration
state.duration = Date.now() - state.timestamp;
// force progress to 1 as we're now done
state.progress = 1;
// actual load is done let's share results
api.fire('load', state.response.body);
// we are really done
// if perceived progress is 1 ( wait for perceived progress to complete )
// or if server does not support progress ( null )
if (state.perceivedProgress === 1) {
completeFn();
}
},
// error is expected to be an object with type, code, body
function(error) {
// cancel updater
state.perceivedPerformanceUpdater.clear();
// update others about this error
api.fire(
'error',
isObject(error)
? error
: {
type: 'error',
code: 0,
body: '' + error,
}
);
},
// actual processing progress
function(computable, current, total) {
// update actual duration
state.duration = Date.now() - state.timestamp;
// update actual progress
state.progress = computable ? current / total : null;
progressFn();
},
// abort does not expect a value
function() {
// stop updater
state.perceivedPerformanceUpdater.clear();
// fire the abort event so we can switch visuals
api.fire('abort', state.response ? state.response.body : null);
},
// register the id for this transfer
function(transferId) {
api.fire('transfer', transferId);
}
);
};
var abort = function abort() {
// no request running, can't abort
if (!state.request) return;
// stop updater
state.perceivedPerformanceUpdater.clear();
// abort actual request
if (state.request.abort) state.request.abort();
// if has response object, we've completed the request
state.complete = true;
};
var reset = function reset() {
abort();
state.complete = false;
state.perceivedProgress = 0;
state.progress = 0;
state.timestamp = null;
state.perceivedDuration = 0;
state.duration = 0;
state.request = null;
state.response = null;
};
var getProgress = function getProgress() {
return state.progress ? Math.min(state.progress, state.perceivedProgress) : null;
};
var getDuration = function getDuration() {
return Math.min(state.duration, state.perceivedDuration);
};
var api = Object.assign({}, on(), {
process: process, // start processing file
abort: abort, // abort active process request
getProgress: getProgress,
getDuration: getDuration,
reset: reset,
});
return api;
};
var getFilenameWithoutExtension = function getFilenameWithoutExtension(name) {
return name.substr(0, name.lastIndexOf('.')) || name;
};
var createFileStub = function createFileStub(source) {
var data = [source.name, source.size, source.type];
// is blob or base64, then we need to set the name
if (source instanceof Blob || isBase64DataURI(source)) {
data[0] = source.name || getDateString();
} else if (isBase64DataURI(source)) {
// if is base64 data uri we need to determine the average size and type
data[1] = source.length;
data[2] = getMimeTypeFromBase64DataURI(source);
} else if (isString(source)) {
// url
data[0] = getFilenameFromURL(source);
data[1] = 0;
data[2] = 'application/octet-stream';
}
return {
name: data[0],
size: data[1],
type: data[2],
};
};
var isFile = function isFile(value) {
return !!(value instanceof File || (value instanceof Blob && value.name));
};
var deepCloneObject = function deepCloneObject(src) {
if (!isObject(src)) return src;
var target = isArray(src) ? [] : {};
for (var key in src) {
if (!src.hasOwnProperty(key)) continue;
var v = src[key];
target[key] = v && isObject(v) ? deepCloneObject(v) : v;
}
return target;
};
var createItem = function createItem() {
var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var serverFileReference =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var file = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
// unique id for this item, is used to identify the item across views
var id = getUniqueId();
/**
* Internal item state
*/
var state = {
// is archived
archived: false,
// if is frozen, no longer fires events
frozen: false,
// removed from view
released: false,
// original source
source: null,
// file model reference
file: file,
// id of file on server
serverFileReference: serverFileReference,
// id of file transfer on server
transferId: null,
// is aborted
processingAborted: false,
// current item status
status: serverFileReference ? ItemStatus.PROCESSING_COMPLETE : ItemStatus.INIT,
// active processes
activeLoader: null,
activeProcessor: null,
};
// callback used when abort processing is called to link back to the resolve method
var abortProcessingRequestComplete = null;
/**
* Externally added item metadata
*/
var metadata = {};
// item data
var setStatus = function setStatus(status) {
return (state.status = status);
};
// fire event unless the item has been archived
var fire = function fire(event) {
if (state.released || state.frozen) return;
for (
var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
params[_key - 1] = arguments[_key];
}
api.fire.apply(api, [event].concat(params));
};
// file data
var getFileExtension = function getFileExtension() {
return getExtensionFromFilename(state.file.name);
};
var getFileType = function getFileType() {
return state.file.type;
};
var getFileSize = function getFileSize() {
return state.file.size;
};
var getFile = function getFile() {
return state.file;
};
//
// logic to load a file
//
var load = function load(source, loader, onload) {
// remember the original item source
state.source = source;
// source is known
api.fireSync('init');
// file stub is already there
if (state.file) {
api.fireSync('load-skip');
return;
}
// set a stub file object while loading the actual data
state.file = createFileStub(source);
// starts loading
loader.on('init', function() {
fire('load-init');
});
// we'eve received a size indication, let's update the stub
loader.on('meta', function(meta) {
// set size of file stub
state.file.size = meta.size;
// set name of file stub
state.file.filename = meta.filename;
// if has received source, we done
if (meta.source) {
origin = FileOrigin.LIMBO;
state.serverFileReference = meta.source;
state.status = ItemStatus.PROCESSING_COMPLETE;
}
// size has been updated
fire('load-meta');
});
// the file is now loading we need to update the progress indicators
loader.on('progress', function(progress) {
setStatus(ItemStatus.LOADING);
fire('load-progress', progress);
});
// an error was thrown while loading the file, we need to switch to error state
loader.on('error', function(error) {
setStatus(ItemStatus.LOAD_ERROR);
fire('load-request-error', error);
});
// user or another process aborted the file load (cannot retry)
loader.on('abort', function() {
setStatus(ItemStatus.INIT);
fire('load-abort');
});
// done loading
loader.on('load', function(file) {
// as we've now loaded the file the loader is no longer required
state.activeLoader = null;
// called when file has loaded succesfully
var success = function success(result) {
// set (possibly) transformed file
state.file = isFile(result) ? result : state.file;
// file received
if (origin === FileOrigin.LIMBO && state.serverFileReference) {
setStatus(ItemStatus.PROCESSING_COMPLETE);
} else {
setStatus(ItemStatus.IDLE);
}
fire('load');
};
var error = function error(result) {
// set original file
state.file = file;
fire('load-meta');
setStatus(ItemStatus.LOAD_ERROR);
fire('load-file-error', result);
};
// if we already have a server file reference, we don't need to call the onload method
if (state.serverFileReference) {
success(file);
return;
}
// no server id, let's give this file the full treatment
onload(file, success, error);
});
// set loader source data
loader.setSource(source);
// set as active loader
state.activeLoader = loader;
// load the source data
loader.load();
};
var retryLoad = function retryLoad() {
if (!state.activeLoader) {
return;
}
state.activeLoader.load();
};
var abortLoad = function abortLoad() {
if (state.activeLoader) {
state.activeLoader.abort();
return;
}
setStatus(ItemStatus.INIT);
fire('load-abort');
};
//
// logic to process a file
//
var process = function process(processor, onprocess) {
// processing was aborted
if (state.processingAborted) {
state.processingAborted = false;
return;
}
// now processing
setStatus(ItemStatus.PROCESSING);
// reset abort callback
abortProcessingRequestComplete = null;
// if no file loaded we'll wait for the load event
if (!(state.file instanceof Blob)) {
api.on('load', function() {
process(processor, onprocess);
});
return;
}
// setup processor
processor.on('load', function(serverFileReference) {
// need this id to be able to revert the upload
state.transferId = null;
state.serverFileReference = serverFileReference;
});
// register transfer id
processor.on('transfer', function(transferId) {
// need this id to be able to revert the upload
state.transferId = transferId;
});
processor.on('load-perceived', function(serverFileReference) {
// no longer required
state.activeProcessor = null;
// need this id to be able to rever the upload
state.transferId = null;
state.serverFileReference = serverFileReference;
setStatus(ItemStatus.PROCESSING_COMPLETE);
fire('process-complete', serverFileReference);
});
processor.on('start', function() {
fire('process-start');
});
processor.on('error', function(error) {
state.activeProcessor = null;
setStatus(ItemStatus.PROCESSING_ERROR);
fire('process-error', error);
});
processor.on('abort', function(serverFileReference) {
state.activeProcessor = null;
// if file was uploaded but processing was cancelled during perceived processor time store file reference
state.transferId = null;
state.serverFileReference = serverFileReference;
setStatus(ItemStatus.IDLE);
fire('process-abort');
// has timeout so doesn't interfere with remove action
if (abortProcessingRequestComplete) {
abortProcessingRequestComplete();
}
});
processor.on('progress', function(progress) {
fire('process-progress', progress);
});
// when successfully transformed
var success = function success(file) {
// if was archived in the mean time, don't process
if (state.archived) return;
// process file!
processor.process(file, Object.assign({}, metadata));
};
// something went wrong during transform phase
var error = console.error;
// start processing the file
onprocess(state.file, success, error);
// set as active processor
state.activeProcessor = processor;
};
var requestProcessing = function requestProcessing() {
state.processingAborted = false;
setStatus(ItemStatus.PROCESSING_QUEUED);
};
var abortProcessing = function abortProcessing() {
return new Promise(function(resolve) {
if (!state.activeProcessor) {
state.processingAborted = true;
setStatus(ItemStatus.IDLE);
fire('process-abort');
resolve();
return;
}
abortProcessingRequestComplete = function abortProcessingRequestComplete() {
resolve();
};
state.activeProcessor.abort();
});
};
//
// logic to revert a processed file
//
var revert = function revert(revertFileUpload, forceRevert) {
return new Promise(function(resolve, reject) {
// cannot revert without a server id for this process
if (state.serverFileReference === null) {
resolve();
return;
}
// revert the upload (fire and forget)
revertFileUpload(
state.serverFileReference,
function() {
// reset file server id as now it's no available on the server
state.serverFileReference = null;
resolve();
},
function(error) {
// don't set error state when reverting is optional, it will always resolve
if (!forceRevert) {
resolve();
return;
}
// oh no errors
setStatus(ItemStatus.PROCESSING_REVERT_ERROR);
fire('process-revert-error');
reject(error);
}
);
// fire event
setStatus(ItemStatus.IDLE);
fire('process-revert');
});
};
// exposed methods
var _setMetadata = function setMetadata(key, value, silent) {
var keys = key.split('.');
var root = keys[0];
var last = keys.pop();
var data = metadata;
keys.forEach(function(key) {
return (data = data[key]);
});
// compare old value against new value, if they're the same, we're not updating
if (JSON.stringify(data[last]) === JSON.stringify(value)) return;
// update value
data[last] = value;
// don't fire update
if (silent) return;
// fire update
fire('metadata-update', {
key: root,
value: metadata[root],
});
};
var getMetadata = function getMetadata(key) {
return deepCloneObject(key ? metadata[key] : metadata);
};
var api = Object.assign(
{
id: {
get: function get() {
return id;
},
},
origin: {
get: function get() {
return origin;
},
},
serverId: {
get: function get() {
return state.serverFileReference;
},
},
transferId: {
get: function get() {
return state.transferId;
},
},
status: {
get: function get() {
return state.status;
},
},
filename: {
get: function get() {
return state.file.name;
},
},
filenameWithoutExtension: {
get: function get() {
return getFilenameWithoutExtension(state.file.name);
},
},
fileExtension: { get: getFileExtension },
fileType: { get: getFileType },
fileSize: { get: getFileSize },
file: { get: getFile },
relativePath: {
get: function get() {
return state.file._relativePath;
},
},
source: {
get: function get() {
return state.source;
},
},
getMetadata: getMetadata,
setMetadata: function setMetadata(key, value, silent) {
if (isObject(key)) {
var data = key;
Object.keys(data).forEach(function(key) {
_setMetadata(key, data[key], value);
});
return key;
}
_setMetadata(key, value, silent);
return value;
},
extend: function extend(name, handler) {
return (itemAPI[name] = handler);
},
abortLoad: abortLoad,
retryLoad: retryLoad,
requestProcessing: requestProcessing,
abortProcessing: abortProcessing,
load: load,
process: process,
revert: revert,
},
on(),
{
freeze: function freeze() {
return (state.frozen = true);
},
release: function release() {
return (state.released = true);
},
released: {
get: function get() {
return state.released;
},
},
archive: function archive() {
return (state.archived = true);
},
archived: {
get: function get() {
return state.archived;
},
},
}
);
// create it here instead of returning it instantly so we can extend it later
var itemAPI = createObject(api);
return itemAPI;
};
var getItemIndexByQuery = function getItemIndexByQuery(items, query) {
// just return first index
if (isEmpty(query)) {
return 0;
}
// invalid queries
if (!isString(query)) {
return -1;
}
// return item by id (or -1 if not found)
return items.findIndex(function(item) {
return item.id === query;
});
};
var getItemById = function getItemById(items, itemId) {
var index = getItemIndexByQuery(items, itemId);
if (index < 0) {
return;
}
return items[index] || null;
};
var fetchBlob = function fetchBlob(url, load, error, progress, abort, headers) {
var request = sendRequest(null, url, {
method: 'GET',
responseType: 'blob',
});
request.onload = function(xhr) {
// get headers
var headers = xhr.getAllResponseHeaders();
// get filename
var filename = getFileInfoFromHeaders(headers).name || getFilenameFromURL(url);
// create response
load(
createResponse('load', xhr.status, getFileFromBlob(xhr.response, filename), headers)
);
};
request.onerror = function(xhr) {
error(createResponse('error', xhr.status, xhr.statusText, xhr.getAllResponseHeaders()));
};
request.onheaders = function(xhr) {
headers(createResponse('headers', xhr.status, null, xhr.getAllResponseHeaders()));
};
request.ontimeout = createTimeoutResponse(error);
request.onprogress = progress;
request.onabort = abort;
// should return request
return request;
};
var getDomainFromURL = function getDomainFromURL(url) {
if (url.indexOf('//') === 0) {
url = location.protocol + url;
}
return url
.toLowerCase()
.replace('blob:', '')
.replace(/([a-z])?:\/\//, '$1')
.split('/')[0];
};
var isExternalURL = function isExternalURL(url) {
return (
(url.indexOf(':') > -1 || url.indexOf('//') > -1) &&
getDomainFromURL(location.href) !== getDomainFromURL(url)
);
};
var dynamicLabel = function dynamicLabel(label) {
return function() {
return isFunction(label) ? label.apply(void 0, arguments) : label;
};
};
var isMockItem = function isMockItem(item) {
return !isFile(item.file);
};
var listUpdated = function listUpdated(dispatch, state) {
clearTimeout(state.listUpdateTimeout);
state.listUpdateTimeout = setTimeout(function() {
dispatch('DID_UPDATE_ITEMS', { items: getActiveItems(state.items) });
}, 0);
};
var optionalPromise = function optionalPromise(fn) {
for (
var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1;
_key < _len;
_key++
) {
params[_key - 1] = arguments[_key];
}
return new Promise(function(resolve) {
if (!fn) {
return resolve(true);
}
var result = fn.apply(void 0, params);
if (result == null) {
return resolve(true);
}
if (typeof result === 'boolean') {
return resolve(result);
}
if (typeof result.then === 'function') {
result.then(resolve);
}
});
};
var sortItems = function sortItems(state, compare) {
state.items.sort(function(a, b) {
return compare(createItemAPI(a), createItemAPI(b));
});
};
// returns item based on state
var getItemByQueryFromState = function getItemByQueryFromState(state, itemHandler) {
return function() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var query = _ref.query,
_ref$success = _ref.success,
success = _ref$success === void 0 ? function() {} : _ref$success,
_ref$failure = _ref.failure,
failure = _ref$failure === void 0 ? function() {} : _ref$failure,
options = _objectWithoutProperties(_ref, ['query', 'success', 'failure']);
var item = getItemByQuery(state.items, query);
if (!item) {
failure({
error: createResponse('error', 0, 'Item not found'),
file: null,
});
return;
}
itemHandler(item, success, failure, options || {});
};
};
var actions = function actions(dispatch, query, state) {
return {
/**
* Aborts all ongoing processes
*/
ABORT_ALL: function ABORT_ALL() {
getActiveItems(state.items).forEach(function(item) {
item.freeze();
item.abortLoad();
item.abortProcessing();
});
},
/**
* Sets initial files
*/
DID_SET_FILES: function DID_SET_FILES(_ref2) {
var _ref2$value = _ref2.value,
value = _ref2$value === void 0 ? [] : _ref2$value;
// map values to file objects
var files = value.map(function(file) {
return {
source: file.source ? file.source : file,
options: file.options,
};
});
// loop over files, if file is in list, leave it be, if not, remove
// test if items should be moved
var activeItems = getActiveItems(state.items);
activeItems.forEach(function(item) {
// if item not is in new value, remove
if (
!files.find(function(file) {
return file.source === item.source || file.source === item.file;
})
) {
dispatch('REMOVE_ITEM', { query: item, remove: false });
}
});
// add new files
activeItems = getActiveItems(state.items);
files.forEach(function(file, index) {
// if file is already in list
if (
activeItems.find(function(item) {
return item.source === file.source || item.file === file.source;
})
)
return;
// not in list, add
dispatch(
'ADD_ITEM',
Object.assign({}, file, {
interactionMethod: InteractionMethod.NONE,
index: index,
})
);
});
},
DID_UPDATE_ITEM_METADATA: function DID_UPDATE_ITEM_METADATA(_ref3) {
var id = _ref3.id,
action = _ref3.action;
// if is called multiple times in close succession we combined all calls together to save resources
clearTimeout(state.itemUpdateTimeout);
state.itemUpdateTimeout = setTimeout(function() {
var item = getItemById(state.items, id);
// only revert and attempt to upload when we're uploading to a server
if (!query('IS_ASYNC')) {
// should we update the output data
applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {
item: item,
query: query,
action: action,
}).then(function(shouldPrepareOutput) {
// plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook
var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');
if (beforePrepareFile)
shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);
if (!shouldPrepareOutput) return;
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });
},
},
true
);
});
return;
}
// for async scenarios
var upload = function upload() {
// we push this forward a bit so the interface is updated correctly
setTimeout(function() {
dispatch('REQUEST_ITEM_PROCESSING', { query: id });
}, 32);
};
var revert = function revert(doUpload) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
)
.then(doUpload ? upload : function() {})
.catch(function() {});
};
var abort = function abort(doUpload) {
item.abortProcessing().then(doUpload ? upload : function() {});
};
// if we should re-upload the file immediately
if (item.status === ItemStatus.PROCESSING_COMPLETE) {
return revert(state.options.instantUpload);
}
// if currently uploading, cancel upload
if (item.status === ItemStatus.PROCESSING) {
return abort(state.options.instantUpload);
}
if (state.options.instantUpload) {
upload();
}
}, 0);
},
MOVE_ITEM: function MOVE_ITEM(_ref4) {
var query = _ref4.query,
index = _ref4.index;
var item = getItemByQuery(state.items, query);
if (!item) return;
var currentIndex = state.items.indexOf(item);
index = limit(index, 0, state.items.length - 1);
if (currentIndex === index) return;
state.items.splice(index, 0, state.items.splice(currentIndex, 1)[0]);
},
SORT: function SORT(_ref5) {
var compare = _ref5.compare;
sortItems(state, compare);
dispatch('DID_SORT_ITEMS', {
items: query('GET_ACTIVE_ITEMS'),
});
},
ADD_ITEMS: function ADD_ITEMS(_ref6) {
var items = _ref6.items,
index = _ref6.index,
interactionMethod = _ref6.interactionMethod,
_ref6$success = _ref6.success,
success = _ref6$success === void 0 ? function() {} : _ref6$success,
_ref6$failure = _ref6.failure,
failure = _ref6$failure === void 0 ? function() {} : _ref6$failure;
var currentIndex = index;
if (index === -1 || typeof index === 'undefined') {
var insertLocation = query('GET_ITEM_INSERT_LOCATION');
var totalItems = query('GET_TOTAL_ITEMS');
currentIndex = insertLocation === 'before' ? 0 : totalItems;
}
var ignoredFiles = query('GET_IGNORED_FILES');
var isValidFile = function isValidFile(source) {
return isFile(source)
? !ignoredFiles.includes(source.name.toLowerCase())
: !isEmpty(source);
};
var validItems = items.filter(isValidFile);
var promises = validItems.map(function(source) {
return new Promise(function(resolve, reject) {
dispatch('ADD_ITEM', {
interactionMethod: interactionMethod,
source: source.source || source,
success: resolve,
failure: reject,
index: currentIndex++,
options: source.options || {},
});
});
});
Promise.all(promises)
.then(success)
.catch(failure);
},
/**
* @param source
* @param index
* @param interactionMethod
*/
ADD_ITEM: function ADD_ITEM(_ref7) {
var source = _ref7.source,
_ref7$index = _ref7.index,
index = _ref7$index === void 0 ? -1 : _ref7$index,
interactionMethod = _ref7.interactionMethod,
_ref7$success = _ref7.success,
success = _ref7$success === void 0 ? function() {} : _ref7$success,
_ref7$failure = _ref7.failure,
failure = _ref7$failure === void 0 ? function() {} : _ref7$failure,
_ref7$options = _ref7.options,
options = _ref7$options === void 0 ? {} : _ref7$options;
// if no source supplied
if (isEmpty(source)) {
failure({
error: createResponse('error', 0, 'No source'),
file: null,
});
return;
}
// filter out invalid file items, used to filter dropped directory contents
if (
isFile(source) &&
state.options.ignoredFiles.includes(source.name.toLowerCase())
) {
// fail silently
return;
}
// test if there's still room in the list of files
if (!hasRoomForItem(state)) {
// if multiple allowed, we can't replace
// or if only a single item is allowed but we're not allowed to replace it we exit
if (
state.options.allowMultiple ||
(!state.options.allowMultiple && !state.options.allowReplace)
) {
var error = createResponse('warning', 0, 'Max files');
dispatch('DID_THROW_MAX_FILES', {
source: source,
error: error,
});
failure({ error: error, file: null });
return;
}
// let's replace the item
// id of first item we're about to remove
var _item = getActiveItems(state.items)[0];
// if has been processed remove it from the server as well
if (
_item.status === ItemStatus.PROCESSING_COMPLETE ||
_item.status === ItemStatus.PROCESSING_REVERT_ERROR
) {
var forceRevert = query('GET_FORCE_REVERT');
_item
.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
forceRevert
)
.then(function() {
if (!forceRevert) return;
// try to add now
dispatch('ADD_ITEM', {
source: source,
index: index,
interactionMethod: interactionMethod,
success: success,
failure: failure,
options: options,
});
})
.catch(function() {}); // no need to handle this catch state for now
if (forceRevert) return;
}
// remove first item as it will be replaced by this item
dispatch('REMOVE_ITEM', { query: _item.id });
}
// where did the file originate
var origin =
options.type === 'local'
? FileOrigin.LOCAL
: options.type === 'limbo'
? FileOrigin.LIMBO
: FileOrigin.INPUT;
// create a new blank item
var item = createItem(
// where did this file come from
origin,
// an input file never has a server file reference
origin === FileOrigin.INPUT ? null : source,
// file mock data, if defined
options.file
);
// set initial meta data
Object.keys(options.metadata || {}).forEach(function(key) {
item.setMetadata(key, options.metadata[key]);
});
// created the item, let plugins add methods
applyFilters('DID_CREATE_ITEM', item, { query: query, dispatch: dispatch });
// where to insert new items
var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');
// adjust index if is not allowed to pick location
if (!state.options.itemInsertLocationFreedom) {
index = itemInsertLocation === 'before' ? -1 : state.items.length;
}
// add item to list
insertItem(state.items, item, index);
// sort items in list
if (isFunction(itemInsertLocation) && source) {
sortItems(state, itemInsertLocation);
}
// get a quick reference to the item id
var id = item.id;
// observe item events
item.on('init', function() {
dispatch('DID_INIT_ITEM', { id: id });
});
item.on('load-init', function() {
dispatch('DID_START_ITEM_LOAD', { id: id });
});
item.on('load-meta', function() {
dispatch('DID_UPDATE_ITEM_META', { id: id });
});
item.on('load-progress', function(progress) {
dispatch('DID_UPDATE_ITEM_LOAD_PROGRESS', { id: id, progress: progress });
});
item.on('load-request-error', function(error) {
var mainStatus = dynamicLabel(state.options.labelFileLoadError)(error);
// is client error, no way to recover
if (error.code >= 400 && error.code < 500) {
dispatch('DID_THROW_ITEM_INVALID', {
id: id,
error: error,
status: {
main: mainStatus,
sub: error.code + ' (' + error.body + ')',
},
});
// reject the file so can be dealt with through API
failure({ error: error, file: createItemAPI(item) });
return;
}
// is possible server error, so might be possible to retry
dispatch('DID_THROW_ITEM_LOAD_ERROR', {
id: id,
error: error,
status: {
main: mainStatus,
sub: state.options.labelTapToRetry,
},
});
});
item.on('load-file-error', function(error) {
dispatch('DID_THROW_ITEM_INVALID', {
id: id,
error: error.status,
status: error.status,
});
failure({ error: error.status, file: createItemAPI(item) });
});
item.on('load-abort', function() {
dispatch('REMOVE_ITEM', { query: id });
});
item.on('load-skip', function() {
dispatch('COMPLETE_LOAD_ITEM', {
query: id,
item: item,
data: {
source: source,
success: success,
},
});
});
item.on('load', function() {
var handleAdd = function handleAdd(shouldAdd) {
// no should not add this file
if (!shouldAdd) {
dispatch('REMOVE_ITEM', {
query: id,
});
return;
}
// now interested in metadata updates
item.on('metadata-update', function(change) {
dispatch('DID_UPDATE_ITEM_METADATA', { id: id, change: change });
});
// let plugins decide if the output data should be prepared at this point
// means we'll do this and wait for idle state
applyFilterChain('SHOULD_PREPARE_OUTPUT', false, {
item: item,
query: query,
}).then(function(shouldPrepareOutput) {
// plugins determined the output data should be prepared (or not), can be adjusted with beforePrepareOutput hook
var beforePrepareFile = query('GET_BEFORE_PREPARE_FILE');
if (beforePrepareFile)
shouldPrepareOutput = beforePrepareFile(item, shouldPrepareOutput);
var loadComplete = function loadComplete() {
dispatch('COMPLETE_LOAD_ITEM', {
query: id,
item: item,
data: {
source: source,
success: success,
},
});
listUpdated(dispatch, state);
};
// exit
if (shouldPrepareOutput) {
// wait for idle state and then run PREPARE_OUTPUT
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: id, file: file });
loadComplete();
},
},
true
);
return;
}
loadComplete();
});
};
// item loaded, allow plugins to
// - read data (quickly)
// - add metadata
applyFilterChain('DID_LOAD_ITEM', item, { query: query, dispatch: dispatch })
.then(function() {
optionalPromise(query('GET_BEFORE_ADD_FILE'), createItemAPI(item)).then(
handleAdd
);
})
.catch(function() {
handleAdd(false);
});
});
item.on('process-start', function() {
dispatch('DID_START_ITEM_PROCESSING', { id: id });
});
item.on('process-progress', function(progress) {
dispatch('DID_UPDATE_ITEM_PROCESS_PROGRESS', { id: id, progress: progress });
});
item.on('process-error', function(error) {
dispatch('DID_THROW_ITEM_PROCESSING_ERROR', {
id: id,
error: error,
status: {
main: dynamicLabel(state.options.labelFileProcessingError)(error),
sub: state.options.labelTapToRetry,
},
});
});
item.on('process-revert-error', function(error) {
dispatch('DID_THROW_ITEM_PROCESSING_REVERT_ERROR', {
id: id,
error: error,
status: {
main: dynamicLabel(state.options.labelFileProcessingRevertError)(error),
sub: state.options.labelTapToRetry,
},
});
});
item.on('process-complete', function(serverFileReference) {
dispatch('DID_COMPLETE_ITEM_PROCESSING', {
id: id,
error: null,
serverFileReference: serverFileReference,
});
dispatch('DID_DEFINE_VALUE', { id: id, value: serverFileReference });
});
item.on('process-abort', function() {
dispatch('DID_ABORT_ITEM_PROCESSING', { id: id });
});
item.on('process-revert', function() {
dispatch('DID_REVERT_ITEM_PROCESSING', { id: id });
dispatch('DID_DEFINE_VALUE', { id: id, value: null });
});
// let view know the item has been inserted
dispatch('DID_ADD_ITEM', {
id: id,
index: index,
interactionMethod: interactionMethod,
});
listUpdated(dispatch, state);
// start loading the source
var _ref8 = state.options.server || {},
url = _ref8.url,
load = _ref8.load,
restore = _ref8.restore,
fetch = _ref8.fetch;
item.load(
source,
// this creates a function that loads the file based on the type of file (string, base64, blob, file) and location of file (local, remote, limbo)
createFileLoader(
origin === FileOrigin.INPUT
? // input, if is remote, see if should use custom fetch, else use default fetchBlob
isString(source) && isExternalURL(source)
? fetch
? createFetchFunction(url, fetch)
: fetchBlob // remote url
: fetchBlob // try to fetch url
: // limbo or local
origin === FileOrigin.LIMBO
? createFetchFunction(url, restore) // limbo
: createFetchFunction(url, load) // local
),
// called when the file is loaded so it can be piped through the filters
function(file, success, error) {
// let's process the file
applyFilterChain('LOAD_FILE', file, { query: query })
.then(success)
.catch(error);
}
);
},
REQUEST_PREPARE_OUTPUT: function REQUEST_PREPARE_OUTPUT(_ref9) {
var item = _ref9.item,
success = _ref9.success,
_ref9$failure = _ref9.failure,
failure = _ref9$failure === void 0 ? function() {} : _ref9$failure;
// error response if item archived
var err = {
error: createResponse('error', 0, 'Item not found'),
file: null,
};
// don't handle archived items, an item could have been archived (load aborted) while waiting to be prepared
if (item.archived) return failure(err);
// allow plugins to alter the file data
applyFilterChain('PREPARE_OUTPUT', item.file, { query: query, item: item }).then(
function(result) {
applyFilterChain('COMPLETE_PREPARE_OUTPUT', result, {
query: query,
item: item,
}).then(function(result) {
// don't handle archived items, an item could have been archived (load aborted) while being prepared
if (item.archived) return failure(err);
// we done!
success(result);
});
}
);
},
COMPLETE_LOAD_ITEM: function COMPLETE_LOAD_ITEM(_ref10) {
var item = _ref10.item,
data = _ref10.data;
var success = data.success,
source = data.source;
// sort items in list
var itemInsertLocation = query('GET_ITEM_INSERT_LOCATION');
if (isFunction(itemInsertLocation) && source) {
sortItems(state, itemInsertLocation);
}
// let interface know the item has loaded
dispatch('DID_LOAD_ITEM', {
id: item.id,
error: null,
serverFileReference: item.origin === FileOrigin.INPUT ? null : source,
});
// item has been successfully loaded and added to the
// list of items so can now be safely returned for use
success(createItemAPI(item));
// if this is a local server file we need to show a different state
if (item.origin === FileOrigin.LOCAL) {
dispatch('DID_LOAD_LOCAL_ITEM', { id: item.id });
return;
}
// if is a temp server file we prevent async upload call here (as the file is already on the server)
if (item.origin === FileOrigin.LIMBO) {
dispatch('DID_COMPLETE_ITEM_PROCESSING', {
id: item.id,
error: null,
serverFileReference: source,
});
dispatch('DID_DEFINE_VALUE', {
id: item.id,
value: source,
});
return;
}
// id we are allowed to upload the file immediately, lets do it
if (query('IS_ASYNC') && state.options.instantUpload) {
dispatch('REQUEST_ITEM_PROCESSING', { query: item.id });
}
},
RETRY_ITEM_LOAD: getItemByQueryFromState(state, function(item) {
// try loading the source one more time
item.retryLoad();
}),
REQUEST_ITEM_PREPARE: getItemByQueryFromState(state, function(item, _success, failure) {
dispatch(
'REQUEST_PREPARE_OUTPUT',
{
query: item.id,
item: item,
success: function success(file) {
dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });
_success({
file: item,
output: file,
});
},
failure: failure,
},
true
);
}),
REQUEST_ITEM_PROCESSING: getItemByQueryFromState(state, function(
item,
success,
failure
) {
// cannot be queued (or is already queued)
var itemCanBeQueuedForProcessing =
// waiting for something
item.status === ItemStatus.IDLE ||
// processing went wrong earlier
item.status === ItemStatus.PROCESSING_ERROR;
// not ready to be processed
if (!itemCanBeQueuedForProcessing) {
var processNow = function processNow() {
return dispatch('REQUEST_ITEM_PROCESSING', {
query: item,
success: success,
failure: failure,
});
};
var process = function process() {
return document.hidden ? processNow() : setTimeout(processNow, 32);
};
// if already done processing or tried to revert but didn't work, try again
if (
item.status === ItemStatus.PROCESSING_COMPLETE ||
item.status === ItemStatus.PROCESSING_REVERT_ERROR
) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
)
.then(process)
.catch(function() {}); // don't continue with processing if something went wrong
} else if (item.status === ItemStatus.PROCESSING) {
item.abortProcessing().then(process);
}
return;
}
// already queued for processing
if (item.status === ItemStatus.PROCESSING_QUEUED) return;
item.requestProcessing();
dispatch('DID_REQUEST_ITEM_PROCESSING', { id: item.id });
dispatch('PROCESS_ITEM', { query: item, success: success, failure: failure }, true);
}),
PROCESS_ITEM: getItemByQueryFromState(state, function(item, success, failure) {
var maxParallelUploads = query('GET_MAX_PARALLEL_UPLOADS');
var totalCurrentUploads = query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING)
.length;
// queue and wait till queue is freed up
if (totalCurrentUploads === maxParallelUploads) {
// queue for later processing
state.processingQueue.push({
id: item.id,
success: success,
failure: failure,
});
// stop it!
return;
}
// if was not queued or is already processing exit here
if (item.status === ItemStatus.PROCESSING) return;
var processNext = function processNext() {
// process queueud items
var queueEntry = state.processingQueue.shift();
// no items left
if (!queueEntry) return;
// get item reference
var id = queueEntry.id,
success = queueEntry.success,
failure = queueEntry.failure;
var itemReference = getItemByQuery(state.items, id);
// if item was archived while in queue, jump to next
if (!itemReference || itemReference.archived) {
processNext();
return;
}
// process queued item
dispatch(
'PROCESS_ITEM',
{ query: id, success: success, failure: failure },
true
);
};
// we done function
item.onOnce('process-complete', function() {
success(createItemAPI(item));
processNext();
// All items processed? No errors?
var allItemsProcessed =
query('GET_ITEMS_BY_STATUS', ItemStatus.PROCESSING_COMPLETE).length ===
state.items.length;
if (allItemsProcessed) {
dispatch('DID_COMPLETE_ITEM_PROCESSING_ALL');
}
});
// we error function
item.onOnce('process-error', function(error) {
failure({ error: error, file: createItemAPI(item) });
processNext();
});
// start file processing
var options = state.options;
item.process(
createFileProcessor(
createProcessorFunction(
options.server.url,
options.server.process,
options.name,
{
chunkTransferId: item.transferId,
chunkServer: options.server.patch,
chunkUploads: options.chunkUploads,
chunkForce: options.chunkForce,
chunkSize: options.chunkSize,
chunkRetryDelays: options.chunkRetryDelays,
}
)
),
// called when the file is about to be processed so it can be piped through the transform filters
function(file, success, error) {
// allow plugins to alter the file data
applyFilterChain('PREPARE_OUTPUT', file, { query: query, item: item })
.then(function(file) {
dispatch('DID_PREPARE_OUTPUT', { id: item.id, file: file });
success(file);
})
.catch(error);
}
);
}),
RETRY_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
dispatch('REQUEST_ITEM_PROCESSING', { query: item });
}),
REQUEST_REMOVE_ITEM: getItemByQueryFromState(state, function(item) {
optionalPromise(query('GET_BEFORE_REMOVE_FILE'), createItemAPI(item)).then(function(
shouldRemove
) {
if (!shouldRemove) {
return;
}
dispatch('REMOVE_ITEM', { query: item });
});
}),
RELEASE_ITEM: getItemByQueryFromState(state, function(item) {
item.release();
}),
REMOVE_ITEM: getItemByQueryFromState(state, function(item, success, failure, options) {
var removeFromView = function removeFromView() {
// get id reference
var id = item.id;
// archive the item, this does not remove it from the list
getItemById(state.items, id).archive();
// tell the view the item has been removed
dispatch('DID_REMOVE_ITEM', { error: null, id: id, item: item });
// now the list has been modified
listUpdated(dispatch, state);
// correctly removed
success(createItemAPI(item));
};
// if this is a local file and the server.remove function has been configured, send source there so dev can remove file from server
var server = state.options.server;
if (
item.origin === FileOrigin.LOCAL &&
server &&
isFunction(server.remove) &&
options.remove !== false
) {
dispatch('DID_START_ITEM_REMOVE', { id: item.id });
server.remove(
item.source,
function() {
return removeFromView();
},
function(status) {
dispatch('DID_THROW_ITEM_REMOVE_ERROR', {
id: item.id,
error: createResponse('error', 0, status, null),
status: {
main: dynamicLabel(state.options.labelFileRemoveError)(status),
sub: state.options.labelTapToRetry,
},
});
}
);
} else {
// if is requesting revert and can revert need to call revert handler (not calling request_ because that would also trigger beforeRemoveHook)
if (
options.revert &&
item.origin !== FileOrigin.LOCAL &&
item.serverId !== null
) {
item.revert(
createRevertFunction(
state.options.server.url,
state.options.server.revert
),
query('GET_FORCE_REVERT')
);
}
// can now safely remove from view
removeFromView();
}
}),
ABORT_ITEM_LOAD: getItemByQueryFromState(state, function(item) {
item.abortLoad();
}),
ABORT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
// test if is already processed
if (item.serverId) {
dispatch('REVERT_ITEM_PROCESSING', { id: item.id });
return;
}
// abort
item.abortProcessing().then(function() {
var shouldRemove = state.options.instantUpload;
if (shouldRemove) {
dispatch('REMOVE_ITEM', { query: item.id });
}
});
}),
REQUEST_REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
// not instant uploading, revert immediately
if (!state.options.instantUpload) {
dispatch('REVERT_ITEM_PROCESSING', { query: item });
return;
}
// if we're instant uploading the file will also be removed if we revert,
// so if a before remove file hook is defined we need to run it now
var handleRevert = function handleRevert(shouldRevert) {
if (!shouldRevert) return;
dispatch('REVERT_ITEM_PROCESSING', { query: item });
};
var fn = query('GET_BEFORE_REMOVE_FILE');
if (!fn) {
return handleRevert(true);
}
var requestRemoveResult = fn(createItemAPI(item));
if (requestRemoveResult == null) {
// undefined or null
return handleRevert(true);
}
if (typeof requestRemoveResult === 'boolean') {
return handleRevert(requestRemoveResult);
}
if (typeof requestRemoveResult.then === 'function') {
requestRemoveResult.then(handleRevert);
}
}),
REVERT_ITEM_PROCESSING: getItemByQueryFromState(state, function(item) {
item.revert(
createRevertFunction(state.options.server.url, state.options.server.revert),
query('GET_FORCE_REVERT')
)
.then(function() {
var shouldRemove = state.options.instantUpload || isMockItem(item);
if (shouldRemove) {
dispatch('REMOVE_ITEM', { query: item.id });
}
})
.catch(function() {});
}),
SET_OPTIONS: function SET_OPTIONS(_ref11) {
var options = _ref11.options;
forin(options, function(key, value) {
dispatch('SET_' + fromCamels(key, '_').toUpperCase(), { value: value });
});
},
};
};
var formatFilename = function formatFilename(name) {
return name;
};
var createElement$1 = function createElement(tagName) {
return document.createElement(tagName);
};
var text = function text(node, value) {
var textNode = node.childNodes[0];
if (!textNode) {
textNode = document.createTextNode(value);
node.appendChild(textNode);
} else if (value !== textNode.nodeValue) {
textNode.nodeValue = value;
}
};
var polarToCartesian = function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (((angleInDegrees % 360) - 90) * Math.PI) / 180.0;
return {
x: centerX + radius * Math.cos(angleInRadians),
y: centerY + radius * Math.sin(angleInRadians),
};
};
var describeArc = function describeArc(x, y, radius, startAngle, endAngle, arcSweep) {
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
return ['M', start.x, start.y, 'A', radius, radius, 0, arcSweep, 0, end.x, end.y].join(' ');
};
var percentageArc = function percentageArc(x, y, radius, from, to) {
var arcSweep = 1;
if (to > from && to - from <= 0.5) {
arcSweep = 0;
}
if (from > to && from - to >= 0.5) {
arcSweep = 0;
}
return describeArc(
x,
y,
radius,
Math.min(0.9999, from) * 360,
Math.min(0.9999, to) * 360,
arcSweep
);
};
var create = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// start at 0
props.spin = false;
props.progress = 0;
props.opacity = 0;
// svg
var svg = createElement('svg');
root.ref.path = createElement('path', {
'stroke-width': 2,
'stroke-linecap': 'round',
});
svg.appendChild(root.ref.path);
root.ref.svg = svg;
root.appendChild(svg);
};
var write = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
if (props.opacity === 0) {
return;
}
if (props.align) {
root.element.dataset.align = props.align;
}
// get width of stroke
var ringStrokeWidth = parseInt(attr(root.ref.path, 'stroke-width'), 10);
// calculate size of ring
var size = root.rect.element.width * 0.5;
// ring state
var ringFrom = 0;
var ringTo = 0;
// now in busy mode
if (props.spin) {
ringFrom = 0;
ringTo = 0.5;
} else {
ringFrom = 0;
ringTo = props.progress;
}
// get arc path
var coordinates = percentageArc(size, size, size - ringStrokeWidth, ringFrom, ringTo);
// update progress bar
attr(root.ref.path, 'd', coordinates);
// hide while contains 0 value
attr(root.ref.path, 'stroke-opacity', props.spin || props.progress > 0 ? 1 : 0);
};
var progressIndicator = createView({
tag: 'div',
name: 'progress-indicator',
ignoreRectUpdate: true,
ignoreRect: true,
create: create,
write: write,
mixins: {
apis: ['progress', 'spin', 'align'],
styles: ['opacity'],
animations: {
opacity: { type: 'tween', duration: 500 },
progress: {
type: 'spring',
stiffness: 0.95,
damping: 0.65,
mass: 10,
},
},
},
});
var create$1 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.element.innerHTML = (props.icon || '') + ('<span>' + props.label + '</span>');
props.isDisabled = false;
};
var write$1 = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
var isDisabled = props.isDisabled;
var shouldDisable = root.query('GET_DISABLED') || props.opacity === 0;
if (shouldDisable && !isDisabled) {
props.isDisabled = true;
attr(root.element, 'disabled', 'disabled');
} else if (!shouldDisable && isDisabled) {
props.isDisabled = false;
root.element.removeAttribute('disabled');
}
};
var fileActionButton = createView({
tag: 'button',
attributes: {
type: 'button',
},
ignoreRect: true,
ignoreRectUpdate: true,
name: 'file-action-button',
mixins: {
apis: ['label'],
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
translateX: 'spring',
translateY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
listeners: true,
},
create: create$1,
write: write$1,
});
var toNaturalFileSize = function toNaturalFileSize(bytes) {
var decimalSeparator =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
var base = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;
// no negative byte sizes
bytes = Math.round(Math.abs(bytes));
var KB = base;
var MB = base * base;
var GB = base * base * base;
// just bytes
if (bytes < KB) {
return bytes + ' bytes';
}
// kilobytes
if (bytes < MB) {
return Math.floor(bytes / KB) + ' KB';
}
// megabytes
if (bytes < GB) {
return removeDecimalsWhenZero(bytes / MB, 1, decimalSeparator) + ' MB';
}
// gigabytes
return removeDecimalsWhenZero(bytes / GB, 2, decimalSeparator) + ' GB';
};
var removeDecimalsWhenZero = function removeDecimalsWhenZero(value, decimalCount, separator) {
return value
.toFixed(decimalCount)
.split('.')
.filter(function(part) {
return part !== '0';
})
.join(separator);
};
var create$2 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// filename
var fileName = createElement$1('span');
fileName.className = 'filepond--file-info-main';
// hide for screenreaders
// the file is contained in a fieldset with legend that contains the filename
// no need to read it twice
attr(fileName, 'aria-hidden', 'true');
root.appendChild(fileName);
root.ref.fileName = fileName;
// filesize
var fileSize = createElement$1('span');
fileSize.className = 'filepond--file-info-sub';
root.appendChild(fileSize);
root.ref.fileSize = fileSize;
// set initial values
text(fileSize, root.query('GET_LABEL_FILE_WAITING_FOR_SIZE'));
text(fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var updateFile = function updateFile(_ref2) {
var root = _ref2.root,
props = _ref2.props;
text(
root.ref.fileSize,
toNaturalFileSize(
root.query('GET_ITEM_SIZE', props.id),
'.',
root.query('GET_FILE_SIZE_BASE')
)
);
text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var updateFileSizeOnError = function updateFileSizeOnError(_ref3) {
var root = _ref3.root,
props = _ref3.props;
// if size is available don't fallback to unknown size message
if (isInt(root.query('GET_ITEM_SIZE', props.id))) {
return;
}
text(root.ref.fileSize, root.query('GET_LABEL_FILE_SIZE_NOT_AVAILABLE'));
};
var fileInfo = createView({
name: 'file-info',
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: updateFile,
DID_UPDATE_ITEM_META: updateFile,
DID_THROW_ITEM_LOAD_ERROR: updateFileSizeOnError,
DID_THROW_ITEM_INVALID: updateFileSizeOnError,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
create: create$2,
mixins: {
styles: ['translateX', 'translateY'],
animations: {
translateX: 'spring',
translateY: 'spring',
},
},
});
var toPercentage = function toPercentage(value) {
return Math.round(value * 100);
};
var create$3 = function create(_ref) {
var root = _ref.root;
// main status
var main = createElement$1('span');
main.className = 'filepond--file-status-main';
root.appendChild(main);
root.ref.main = main;
// sub status
var sub = createElement$1('span');
sub.className = 'filepond--file-status-sub';
root.appendChild(sub);
root.ref.sub = sub;
didSetItemLoadProgress({ root: root, action: { progress: null } });
};
var didSetItemLoadProgress = function didSetItemLoadProgress(_ref2) {
var root = _ref2.root,
action = _ref2.action;
var title =
action.progress === null
? root.query('GET_LABEL_FILE_LOADING')
: root.query('GET_LABEL_FILE_LOADING') + ' ' + toPercentage(action.progress) + '%';
text(root.ref.main, title);
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didSetItemProcessProgress = function didSetItemProcessProgress(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var title =
action.progress === null
? root.query('GET_LABEL_FILE_PROCESSING')
: root.query('GET_LABEL_FILE_PROCESSING') +
' ' +
toPercentage(action.progress) +
'%';
text(root.ref.main, title);
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didRequestItemProcessing = function didRequestItemProcessing(_ref4) {
var root = _ref4.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_CANCEL'));
};
var didAbortItemProcessing = function didAbortItemProcessing(_ref5) {
var root = _ref5.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_ABORTED'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_RETRY'));
};
var didCompleteItemProcessing = function didCompleteItemProcessing(_ref6) {
var root = _ref6.root;
text(root.ref.main, root.query('GET_LABEL_FILE_PROCESSING_COMPLETE'));
text(root.ref.sub, root.query('GET_LABEL_TAP_TO_UNDO'));
};
var clear = function clear(_ref7) {
var root = _ref7.root;
text(root.ref.main, '');
text(root.ref.sub, '');
};
var error = function error(_ref8) {
var root = _ref8.root,
action = _ref8.action;
text(root.ref.main, action.status.main);
text(root.ref.sub, action.status.sub);
};
var fileStatus = createView({
name: 'file-status',
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: clear,
DID_REVERT_ITEM_PROCESSING: clear,
DID_REQUEST_ITEM_PROCESSING: didRequestItemProcessing,
DID_ABORT_ITEM_PROCESSING: didAbortItemProcessing,
DID_COMPLETE_ITEM_PROCESSING: didCompleteItemProcessing,
DID_UPDATE_ITEM_PROCESS_PROGRESS: didSetItemProcessProgress,
DID_UPDATE_ITEM_LOAD_PROGRESS: didSetItemLoadProgress,
DID_THROW_ITEM_LOAD_ERROR: error,
DID_THROW_ITEM_INVALID: error,
DID_THROW_ITEM_PROCESSING_ERROR: error,
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: error,
DID_THROW_ITEM_REMOVE_ERROR: error,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
create: create$3,
mixins: {
styles: ['translateX', 'translateY', 'opacity'],
animations: {
opacity: { type: 'tween', duration: 250 },
translateX: 'spring',
translateY: 'spring',
},
},
});
/**
* Button definitions for the file view
*/
var Buttons = {
AbortItemLoad: {
label: 'GET_LABEL_BUTTON_ABORT_ITEM_LOAD',
action: 'ABORT_ITEM_LOAD',
className: 'filepond--action-abort-item-load',
align: 'LOAD_INDICATOR_POSITION', // right
},
RetryItemLoad: {
label: 'GET_LABEL_BUTTON_RETRY_ITEM_LOAD',
action: 'RETRY_ITEM_LOAD',
icon: 'GET_ICON_RETRY',
className: 'filepond--action-retry-item-load',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RemoveItem: {
label: 'GET_LABEL_BUTTON_REMOVE_ITEM',
action: 'REQUEST_REMOVE_ITEM',
icon: 'GET_ICON_REMOVE',
className: 'filepond--action-remove-item',
align: 'BUTTON_REMOVE_ITEM_POSITION', // left
},
ProcessItem: {
label: 'GET_LABEL_BUTTON_PROCESS_ITEM',
action: 'REQUEST_ITEM_PROCESSING',
icon: 'GET_ICON_PROCESS',
className: 'filepond--action-process-item',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
AbortItemProcessing: {
label: 'GET_LABEL_BUTTON_ABORT_ITEM_PROCESSING',
action: 'ABORT_ITEM_PROCESSING',
className: 'filepond--action-abort-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RetryItemProcessing: {
label: 'GET_LABEL_BUTTON_RETRY_ITEM_PROCESSING',
action: 'RETRY_ITEM_PROCESSING',
icon: 'GET_ICON_RETRY',
className: 'filepond--action-retry-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
RevertItemProcessing: {
label: 'GET_LABEL_BUTTON_UNDO_ITEM_PROCESSING',
action: 'REQUEST_REVERT_ITEM_PROCESSING',
icon: 'GET_ICON_UNDO',
className: 'filepond--action-revert-item-processing',
align: 'BUTTON_PROCESS_ITEM_POSITION', // right
},
};
// make a list of buttons, we can then remove buttons from this list if they're disabled
var ButtonKeys = [];
forin(Buttons, function(key) {
ButtonKeys.push(key);
});
var calculateFileInfoOffset = function calculateFileInfoOffset(root) {
if (getRemoveIndicatorAligment(root) === 'right') return 0;
var buttonRect = root.ref.buttonRemoveItem.rect.element;
return buttonRect.hidden ? null : buttonRect.width + buttonRect.left;
};
var calculateButtonWidth = function calculateButtonWidth(root) {
var buttonRect = root.ref.buttonAbortItemLoad.rect.element;
return buttonRect.width;
};
// Force on full pixels so text stays crips
var calculateFileVerticalCenterOffset = function calculateFileVerticalCenterOffset(root) {
return Math.floor(root.ref.buttonRemoveItem.rect.element.height / 4);
};
var calculateFileHorizontalCenterOffset = function calculateFileHorizontalCenterOffset(root) {
return Math.floor(root.ref.buttonRemoveItem.rect.element.left / 2);
};
var getLoadIndicatorAlignment = function getLoadIndicatorAlignment(root) {
return root.query('GET_STYLE_LOAD_INDICATOR_POSITION');
};
var getProcessIndicatorAlignment = function getProcessIndicatorAlignment(root) {
return root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION');
};
var getRemoveIndicatorAligment = function getRemoveIndicatorAligment(root) {
return root.query('GET_STYLE_BUTTON_REMOVE_ITEM_POSITION');
};
var DefaultStyle = {
buttonAbortItemLoad: { opacity: 0 },
buttonRetryItemLoad: { opacity: 0 },
buttonRemoveItem: { opacity: 0 },
buttonProcessItem: { opacity: 0 },
buttonAbortItemProcessing: { opacity: 0 },
buttonRetryItemProcessing: { opacity: 0 },
buttonRevertItemProcessing: { opacity: 0 },
loadProgressIndicator: { opacity: 0, align: getLoadIndicatorAlignment },
processProgressIndicator: { opacity: 0, align: getProcessIndicatorAlignment },
processingCompleteIndicator: { opacity: 0, scaleX: 0.75, scaleY: 0.75 },
info: { translateX: 0, translateY: 0, opacity: 0 },
status: { translateX: 0, translateY: 0, opacity: 0 },
};
var IdleStyle = {
buttonRemoveItem: { opacity: 1 },
buttonProcessItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset },
};
var ProcessingStyle = {
buttonAbortItemProcessing: { opacity: 1 },
processProgressIndicator: { opacity: 1 },
status: { opacity: 1 },
};
var StyleMap = {
DID_THROW_ITEM_INVALID: {
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset, opacity: 1 },
},
DID_START_ITEM_LOAD: {
buttonAbortItemLoad: { opacity: 1 },
loadProgressIndicator: { opacity: 1 },
status: { opacity: 1 },
},
DID_THROW_ITEM_LOAD_ERROR: {
buttonRetryItemLoad: { opacity: 1 },
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1 },
},
DID_START_ITEM_REMOVE: {
processProgressIndicator: { opacity: 1, align: getRemoveIndicatorAligment },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 0 },
},
DID_THROW_ITEM_REMOVE_ERROR: {
processProgressIndicator: { opacity: 0, align: getRemoveIndicatorAligment },
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1, translateX: calculateFileInfoOffset },
},
DID_LOAD_ITEM: IdleStyle,
DID_LOAD_LOCAL_ITEM: {
buttonRemoveItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { translateX: calculateFileInfoOffset },
},
DID_START_ITEM_PROCESSING: ProcessingStyle,
DID_REQUEST_ITEM_PROCESSING: ProcessingStyle,
DID_UPDATE_ITEM_PROCESS_PROGRESS: ProcessingStyle,
DID_COMPLETE_ITEM_PROCESSING: {
buttonRevertItemProcessing: { opacity: 1 },
info: { opacity: 1 },
status: { opacity: 1 },
},
DID_THROW_ITEM_PROCESSING_ERROR: {
buttonRemoveItem: { opacity: 1 },
buttonRetryItemProcessing: { opacity: 1 },
status: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
},
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: {
buttonRevertItemProcessing: { opacity: 1 },
status: { opacity: 1 },
info: { opacity: 1 },
},
DID_ABORT_ITEM_PROCESSING: {
buttonRemoveItem: { opacity: 1 },
buttonProcessItem: { opacity: 1 },
info: { translateX: calculateFileInfoOffset },
status: { opacity: 1 },
},
DID_REVERT_ITEM_PROCESSING: IdleStyle,
};
// complete indicator view
var processingCompleteIndicatorView = createView({
create: function create(_ref) {
var root = _ref.root;
root.element.innerHTML = root.query('GET_ICON_DONE');
},
name: 'processing-complete-indicator',
ignoreRect: true,
mixins: {
styles: ['scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
},
});
/**
* Creates the file view
*/
var create$4 = function create(_ref2) {
var root = _ref2.root,
props = _ref2.props;
var id = props.id;
// allow reverting upload
var allowRevert = root.query('GET_ALLOW_REVERT');
// allow remove file
var allowRemove = root.query('GET_ALLOW_REMOVE');
// allow processing upload
var allowProcess = root.query('GET_ALLOW_PROCESS');
// is instant uploading, need this to determine the icon of the undo button
var instantUpload = root.query('GET_INSTANT_UPLOAD');
// is async set up
var isAsync = root.query('IS_ASYNC');
// should align remove item buttons
var alignRemoveItemButton = root.query('GET_STYLE_BUTTON_REMOVE_ITEM_ALIGN');
// enabled buttons array
var buttonFilter;
if (isAsync) {
if (allowProcess && !allowRevert) {
// only remove revert button
buttonFilter = function buttonFilter(key) {
return !/RevertItemProcessing/.test(key);
};
} else if (!allowProcess && allowRevert) {
// only remove process button
buttonFilter = function buttonFilter(key) {
return !/ProcessItem|RetryItemProcessing|AbortItemProcessing/.test(key);
};
} else if (!allowProcess && !allowRevert) {
// remove all process buttons
buttonFilter = function buttonFilter(key) {
return !/Process/.test(key);
};
}
} else {
// no process controls available
buttonFilter = function buttonFilter(key) {
return !/Process/.test(key);
};
}
var enabledButtons = buttonFilter ? ButtonKeys.filter(buttonFilter) : ButtonKeys.concat();
// update icon and label for revert button when instant uploading
if (instantUpload && allowRevert) {
Buttons['RevertItemProcessing'].label = 'GET_LABEL_BUTTON_REMOVE_ITEM';
Buttons['RevertItemProcessing'].icon = 'GET_ICON_REMOVE';
}
// remove last button (revert) if not allowed
if (isAsync && !allowRevert) {
var map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];
map.info.translateX = calculateFileHorizontalCenterOffset;
map.info.translateY = calculateFileVerticalCenterOffset;
map.status.translateY = calculateFileVerticalCenterOffset;
map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };
}
// should align center
if (isAsync && !allowProcess) {
[
'DID_START_ITEM_PROCESSING',
'DID_REQUEST_ITEM_PROCESSING',
'DID_UPDATE_ITEM_PROCESS_PROGRESS',
'DID_THROW_ITEM_PROCESSING_ERROR',
].forEach(function(key) {
StyleMap[key].status.translateY = calculateFileVerticalCenterOffset;
});
StyleMap['DID_THROW_ITEM_PROCESSING_ERROR'].status.translateX = calculateButtonWidth;
}
// move remove button to right
if (alignRemoveItemButton && allowRevert) {
Buttons['RevertItemProcessing'].align = 'BUTTON_REMOVE_ITEM_POSITION';
var _map = StyleMap['DID_COMPLETE_ITEM_PROCESSING'];
_map.info.translateX = calculateFileInfoOffset;
_map.status.translateY = calculateFileVerticalCenterOffset;
_map.processingCompleteIndicator = { opacity: 1, scaleX: 1, scaleY: 1 };
}
if (!allowRemove) {
Buttons['RemoveItem'].disabled = true;
}
// create the button views
forin(Buttons, function(key, definition) {
// create button
var buttonView = root.createChildView(fileActionButton, {
label: root.query(definition.label),
icon: root.query(definition.icon),
opacity: 0,
});
// should be appended?
if (enabledButtons.includes(key)) {
root.appendChildView(buttonView);
}
// toggle
if (definition.disabled) {
buttonView.element.setAttribute('disabled', 'disabled');
buttonView.element.setAttribute('hidden', 'hidden');
}
// add position attribute
buttonView.element.dataset.align = root.query('GET_STYLE_' + definition.align);
// add class
buttonView.element.classList.add(definition.className);
// handle interactions
buttonView.on('click', function(e) {
e.stopPropagation();
if (definition.disabled) return;
root.dispatch(definition.action, { query: id });
});
// set reference
root.ref['button' + key] = buttonView;
});
// checkmark
root.ref.processingCompleteIndicator = root.appendChildView(
root.createChildView(processingCompleteIndicatorView)
);
root.ref.processingCompleteIndicator.element.dataset.align = root.query(
'GET_STYLE_BUTTON_PROCESS_ITEM_POSITION'
);
// create file info view
root.ref.info = root.appendChildView(root.createChildView(fileInfo, { id: id }));
// create file status view
root.ref.status = root.appendChildView(root.createChildView(fileStatus, { id: id }));
// add progress indicators
var loadIndicatorView = root.appendChildView(
root.createChildView(progressIndicator, {
opacity: 0,
align: root.query('GET_STYLE_LOAD_INDICATOR_POSITION'),
})
);
loadIndicatorView.element.classList.add('filepond--load-indicator');
root.ref.loadProgressIndicator = loadIndicatorView;
var progressIndicatorView = root.appendChildView(
root.createChildView(progressIndicator, {
opacity: 0,
align: root.query('GET_STYLE_PROGRESS_INDICATOR_POSITION'),
})
);
progressIndicatorView.element.classList.add('filepond--process-indicator');
root.ref.processProgressIndicator = progressIndicatorView;
// current active styles
root.ref.activeStyles = [];
};
var write$2 = function write(_ref3) {
var root = _ref3.root,
actions = _ref3.actions,
props = _ref3.props;
// route actions
route({ root: root, actions: actions, props: props });
// select last state change action
var action = actions
.concat()
.filter(function(action) {
return /^DID_/.test(action.type);
})
.reverse()
.find(function(action) {
return StyleMap[action.type];
});
// a new action happened, let's get the matching styles
if (action) {
// define new active styles
root.ref.activeStyles = [];
var stylesToApply = StyleMap[action.type];
forin(DefaultStyle, function(name, defaultStyles) {
// get reference to control
var control = root.ref[name];
// loop over all styles for this control
forin(defaultStyles, function(key, defaultValue) {
var value =
stylesToApply[name] && typeof stylesToApply[name][key] !== 'undefined'
? stylesToApply[name][key]
: defaultValue;
root.ref.activeStyles.push({ control: control, key: key, value: value });
});
});
}
// apply active styles to element
root.ref.activeStyles.forEach(function(_ref4) {
var control = _ref4.control,
key = _ref4.key,
value = _ref4.value;
control[key] = typeof value === 'function' ? value(root) : value;
});
};
var route = createRoute({
DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING: function DID_SET_LABEL_BUTTON_ABORT_ITEM_PROCESSING(
_ref5
) {
var root = _ref5.root,
action = _ref5.action;
root.ref.buttonAbortItemProcessing.label = action.value;
},
DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD: function DID_SET_LABEL_BUTTON_ABORT_ITEM_LOAD(_ref6) {
var root = _ref6.root,
action = _ref6.action;
root.ref.buttonAbortItemLoad.label = action.value;
},
DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL: function DID_SET_LABEL_BUTTON_ABORT_ITEM_REMOVAL(
_ref7
) {
var root = _ref7.root,
action = _ref7.action;
root.ref.buttonAbortItemRemoval.label = action.value;
},
DID_REQUEST_ITEM_PROCESSING: function DID_REQUEST_ITEM_PROCESSING(_ref8) {
var root = _ref8.root;
root.ref.processProgressIndicator.spin = true;
root.ref.processProgressIndicator.progress = 0;
},
DID_START_ITEM_LOAD: function DID_START_ITEM_LOAD(_ref9) {
var root = _ref9.root;
root.ref.loadProgressIndicator.spin = true;
root.ref.loadProgressIndicator.progress = 0;
},
DID_START_ITEM_REMOVE: function DID_START_ITEM_REMOVE(_ref10) {
var root = _ref10.root;
root.ref.processProgressIndicator.spin = true;
root.ref.processProgressIndicator.progress = 0;
},
DID_UPDATE_ITEM_LOAD_PROGRESS: function DID_UPDATE_ITEM_LOAD_PROGRESS(_ref11) {
var root = _ref11.root,
action = _ref11.action;
root.ref.loadProgressIndicator.spin = false;
root.ref.loadProgressIndicator.progress = action.progress;
},
DID_UPDATE_ITEM_PROCESS_PROGRESS: function DID_UPDATE_ITEM_PROCESS_PROGRESS(_ref12) {
var root = _ref12.root,
action = _ref12.action;
root.ref.processProgressIndicator.spin = false;
root.ref.processProgressIndicator.progress = action.progress;
},
});
var file = createView({
create: create$4,
write: write$2,
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
name: 'file',
});
/**
* Creates the file view
*/
var create$5 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// filename
root.ref.fileName = createElement$1('legend');
root.appendChild(root.ref.fileName);
// file appended
root.ref.file = root.appendChildView(root.createChildView(file, { id: props.id }));
// data has moved to data.js
root.ref.data = false;
};
/**
* Data storage
*/
var didLoadItem = function didLoadItem(_ref2) {
var root = _ref2.root,
props = _ref2.props;
// updates the legend of the fieldset so screenreaders can better group buttons
text(root.ref.fileName, formatFilename(root.query('GET_ITEM_NAME', props.id)));
};
var fileWrapper = createView({
create: create$5,
ignoreRect: true,
write: createRoute({
DID_LOAD_ITEM: didLoadItem,
}),
didCreateView: function didCreateView(root) {
applyFilters('CREATE_VIEW', Object.assign({}, root, { view: root }));
},
tag: 'fieldset',
name: 'file-wrapper',
});
var PANEL_SPRING_PROPS = { type: 'spring', damping: 0.6, mass: 7 };
var create$6 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
[
{
name: 'top',
},
{
name: 'center',
props: {
translateY: null,
scaleY: null,
},
mixins: {
animations: {
scaleY: PANEL_SPRING_PROPS,
},
styles: ['translateY', 'scaleY'],
},
},
{
name: 'bottom',
props: {
translateY: null,
},
mixins: {
animations: {
translateY: PANEL_SPRING_PROPS,
},
styles: ['translateY'],
},
},
].forEach(function(section) {
createSection(root, section, props.name);
});
root.element.classList.add('filepond--' + props.name);
root.ref.scalable = null;
};
var createSection = function createSection(root, section, className) {
var viewConstructor = createView({
name: 'panel-' + section.name + ' filepond--' + className,
mixins: section.mixins,
ignoreRectUpdate: true,
});
var view = root.createChildView(viewConstructor, section.props);
root.ref[section.name] = root.appendChildView(view);
};
var write$3 = function write(_ref2) {
var root = _ref2.root,
props = _ref2.props;
// update scalable state
if (root.ref.scalable === null || props.scalable !== root.ref.scalable) {
root.ref.scalable = isBoolean(props.scalable) ? props.scalable : true;
root.element.dataset.scalable = root.ref.scalable;
}
// no height, can't set
if (!props.height) return;
// get child rects
var topRect = root.ref.top.rect.element;
var bottomRect = root.ref.bottom.rect.element;
// make sure height never is smaller than bottom and top seciton heights combined (will probably never happen, but who knows)
var height = Math.max(topRect.height + bottomRect.height, props.height);
// offset center part
root.ref.center.translateY = topRect.height;
// scale center part
// use math ceil to prevent transparent lines because of rounding errors
root.ref.center.scaleY = (height - topRect.height - bottomRect.height) / 100;
// offset bottom part
root.ref.bottom.translateY = height - bottomRect.height;
};
var panel = createView({
name: 'panel',
read: function read(_ref3) {
var root = _ref3.root,
props = _ref3.props;
return (props.heightCurrent = root.ref.bottom.translateY);
},
write: write$3,
create: create$6,
ignoreRect: true,
mixins: {
apis: ['height', 'heightCurrent', 'scalable'],
},
});
var createDragHelper = function createDragHelper(items) {
var itemIds = items.map(function(item) {
return item.id;
});
var prevIndex = undefined;
return {
setIndex: function setIndex(index) {
prevIndex = index;
},
getIndex: function getIndex() {
return prevIndex;
},
getItemIndex: function getItemIndex(item) {
return itemIds.indexOf(item.id);
},
};
};
var ITEM_TRANSLATE_SPRING = {
type: 'spring',
stiffness: 0.75,
damping: 0.45,
mass: 10,
};
var ITEM_SCALE_SPRING = 'spring';
var StateMap = {
DID_START_ITEM_LOAD: 'busy',
DID_UPDATE_ITEM_LOAD_PROGRESS: 'loading',
DID_THROW_ITEM_INVALID: 'load-invalid',
DID_THROW_ITEM_LOAD_ERROR: 'load-error',
DID_LOAD_ITEM: 'idle',
DID_THROW_ITEM_REMOVE_ERROR: 'remove-error',
DID_START_ITEM_REMOVE: 'busy',
DID_START_ITEM_PROCESSING: 'busy processing',
DID_REQUEST_ITEM_PROCESSING: 'busy processing',
DID_UPDATE_ITEM_PROCESS_PROGRESS: 'processing',
DID_COMPLETE_ITEM_PROCESSING: 'processing-complete',
DID_THROW_ITEM_PROCESSING_ERROR: 'processing-error',
DID_THROW_ITEM_PROCESSING_REVERT_ERROR: 'processing-revert-error',
DID_ABORT_ITEM_PROCESSING: 'cancelled',
DID_REVERT_ITEM_PROCESSING: 'idle',
};
/**
* Creates the file view
*/
var create$7 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// select
root.ref.handleClick = function(e) {
return root.dispatch('DID_ACTIVATE_ITEM', { id: props.id });
};
// set id
root.element.id = 'filepond--item-' + props.id;
root.element.addEventListener('click', root.ref.handleClick);
// file view
root.ref.container = root.appendChildView(
root.createChildView(fileWrapper, { id: props.id })
);
// file panel
root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'item-panel' }));
// default start height
root.ref.panel.height = null;
// by default not marked for removal
props.markedForRemoval = false;
// if not allowed to reorder file items, exit here
if (!root.query('GET_ALLOW_REORDER')) return;
// set to idle so shows grab cursor
root.element.dataset.dragState = 'idle';
var grab = function grab(e) {
if (!e.isPrimary) return;
var removedActivateListener = false;
var origin = {
x: e.pageX,
y: e.pageY,
};
props.dragOrigin = {
x: root.translateX,
y: root.translateY,
};
props.dragCenter = {
x: e.offsetX,
y: e.offsetY,
};
var dragState = createDragHelper(root.query('GET_ACTIVE_ITEMS'));
root.dispatch('DID_GRAB_ITEM', { id: props.id, dragState: dragState });
var drag = function drag(e) {
if (!e.isPrimary) return;
e.stopPropagation();
e.preventDefault();
props.dragOffset = {
x: e.pageX - origin.x,
y: e.pageY - origin.y,
};
// if dragged stop listening to clicks, will re-add when done dragging
var dist =
props.dragOffset.x * props.dragOffset.x +
props.dragOffset.y * props.dragOffset.y;
if (dist > 16 && !removedActivateListener) {
removedActivateListener = true;
root.element.removeEventListener('click', root.ref.handleClick);
}
root.dispatch('DID_DRAG_ITEM', { id: props.id, dragState: dragState });
};
var drop = function drop(e) {
if (!e.isPrimary) return;
document.removeEventListener('pointermove', drag);
document.removeEventListener('pointerup', drop);
props.dragOffset = {
x: e.pageX - origin.x,
y: e.pageY - origin.y,
};
root.dispatch('DID_DROP_ITEM', { id: props.id, dragState: dragState });
// start listening to clicks again
if (removedActivateListener) {
setTimeout(function() {
return root.element.addEventListener('click', root.ref.handleClick);
}, 0);
}
};
document.addEventListener('pointermove', drag);
document.addEventListener('pointerup', drop);
};
root.element.addEventListener('pointerdown', grab);
};
var route$1 = createRoute({
DID_UPDATE_PANEL_HEIGHT: function DID_UPDATE_PANEL_HEIGHT(_ref2) {
var root = _ref2.root,
action = _ref2.action;
root.height = action.height;
},
});
var write$4 = createRoute(
{
DID_GRAB_ITEM: function DID_GRAB_ITEM(_ref3) {
var root = _ref3.root,
props = _ref3.props;
props.dragOrigin = {
x: root.translateX,
y: root.translateY,
};
},
DID_DRAG_ITEM: function DID_DRAG_ITEM(_ref4) {
var root = _ref4.root;
root.element.dataset.dragState = 'drag';
},
DID_DROP_ITEM: function DID_DROP_ITEM(_ref5) {
var root = _ref5.root,
props = _ref5.props;
props.dragOffset = null;
props.dragOrigin = null;
root.element.dataset.dragState = 'drop';
},
},
function(_ref6) {
var root = _ref6.root,
actions = _ref6.actions,
props = _ref6.props,
shouldOptimize = _ref6.shouldOptimize;
if (root.element.dataset.dragState === 'drop') {
if (root.scaleX <= 1) {
root.element.dataset.dragState = 'idle';
}
}
// select last state change action
var action = actions
.concat()
.filter(function(action) {
return /^DID_/.test(action.type);
})
.reverse()
.find(function(action) {
return StateMap[action.type];
});
// no need to set same state twice
if (action && action.type !== props.currentState) {
// set current state
props.currentState = action.type;
// set state
root.element.dataset.filepondItemState = StateMap[props.currentState] || '';
}
// route actions
var aspectRatio =
root.query('GET_ITEM_PANEL_ASPECT_RATIO') || root.query('GET_PANEL_ASPECT_RATIO');
if (!aspectRatio) {
route$1({ root: root, actions: actions, props: props });
if (!root.height && root.ref.container.rect.element.height > 0) {
root.height = root.ref.container.rect.element.height;
}
} else if (!shouldOptimize) {
root.height = root.rect.element.width * aspectRatio;
}
// sync panel height with item height
if (shouldOptimize) {
root.ref.panel.height = null;
}
root.ref.panel.height = root.height;
}
);
var item = createView({
create: create$7,
write: write$4,
destroy: function destroy(_ref7) {
var root = _ref7.root,
props = _ref7.props;
root.element.removeEventListener('click', root.ref.handleClick);
root.dispatch('RELEASE_ITEM', { query: props.id });
},
tag: 'li',
name: 'item',
mixins: {
apis: [
'id',
'interactionMethod',
'markedForRemoval',
'spawnDate',
'dragCenter',
'dragOrigin',
'dragOffset',
],
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity', 'height'],
animations: {
scaleX: ITEM_SCALE_SPRING,
scaleY: ITEM_SCALE_SPRING,
translateX: ITEM_TRANSLATE_SPRING,
translateY: ITEM_TRANSLATE_SPRING,
opacity: { type: 'tween', duration: 150 },
},
},
});
var getItemsPerRow = function(horizontalSpace, itemWidth) {
// add one pixel leeway, when using percentages for item width total items can be 1.99 per row
return Math.max(1, Math.floor((horizontalSpace + 1) / itemWidth));
};
var getItemIndexByPosition = function getItemIndexByPosition(view, children, positionInView) {
if (!positionInView) return;
var horizontalSpace = view.rect.element.width;
// const children = view.childViews;
var l = children.length;
var last = null;
// -1, don't move items to accomodate (either add to top or bottom)
if (l === 0 || positionInView.top < children[0].rect.element.top) return -1;
// let's get the item width
var item = children[0];
var itemRect = item.rect.element;
var itemHorizontalMargin = itemRect.marginLeft + itemRect.marginRight;
var itemWidth = itemRect.width + itemHorizontalMargin;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
for (var index = 0; index < l; index++) {
var child = children[index];
var childMid = child.rect.outer.top + child.rect.element.height * 0.5;
if (positionInView.top < childMid) {
return index;
}
}
return l;
}
// grid
var itemVerticalMargin = itemRect.marginTop + itemRect.marginBottom;
var itemHeight = itemRect.height + itemVerticalMargin;
for (var _index = 0; _index < l; _index++) {
var indexX = _index % itemsPerRow;
var indexY = Math.floor(_index / itemsPerRow);
var offsetX = indexX * itemWidth;
var offsetY = indexY * itemHeight;
var itemTop = offsetY - itemRect.marginTop;
var itemRight = offsetX + itemWidth;
var itemBottom = offsetY + itemHeight + itemRect.marginBottom;
if (positionInView.top < itemBottom && positionInView.top > itemTop) {
if (positionInView.left < itemRight) {
return _index;
} else if (_index !== l - 1) {
last = _index;
} else {
last = null;
}
}
}
if (last !== null) {
return last;
}
return l;
};
var dropAreaDimensions = {
height: 0,
width: 0,
get getHeight() {
return this.height;
},
set setHeight(val) {
if (this.height === 0 || val === 0) this.height = val;
},
get getWidth() {
return this.width;
},
set setWidth(val) {
if (this.width === 0 || val === 0) this.width = val;
},
setDimensions: function setDimensions(height, width) {
if (this.height === 0 || height === 0) this.height = height;
if (this.width === 0 || width === 0) this.width = width;
},
};
var create$8 = function create(_ref) {
var root = _ref.root;
// need to set role to list as otherwise it won't be read as a list by VoiceOver
attr(root.element, 'role', 'list');
root.ref.lastItemSpanwDate = Date.now();
};
/**
* Inserts a new item
* @param root
* @param action
*/
var addItemView = function addItemView(_ref2) {
var root = _ref2.root,
action = _ref2.action;
var id = action.id,
index = action.index,
interactionMethod = action.interactionMethod;
root.ref.addIndex = index;
var now = Date.now();
var spawnDate = now;
var opacity = 1;
if (interactionMethod !== InteractionMethod.NONE) {
opacity = 0;
var cooldown = root.query('GET_ITEM_INSERT_INTERVAL');
var dist = now - root.ref.lastItemSpanwDate;
spawnDate = dist < cooldown ? now + (cooldown - dist) : now;
}
root.ref.lastItemSpanwDate = spawnDate;
root.appendChildView(
root.createChildView(
// view type
item,
// props
{
spawnDate: spawnDate,
id: id,
opacity: opacity,
interactionMethod: interactionMethod,
}
),
index
);
};
var moveItem = function moveItem(item, x, y) {
var vx = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
var vy = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
// set to null to remove animation while dragging
if (item.dragOffset) {
item.translateX = null;
item.translateY = null;
item.translateX = item.dragOrigin.x + item.dragOffset.x;
item.translateY = item.dragOrigin.y + item.dragOffset.y;
item.scaleX = 1.025;
item.scaleY = 1.025;
} else {
item.translateX = x;
item.translateY = y;
if (Date.now() > item.spawnDate) {
// reveal element
if (item.opacity === 0) {
introItemView(item, x, y, vx, vy);
}
// make sure is default scale every frame
item.scaleX = 1;
item.scaleY = 1;
item.opacity = 1;
}
}
};
var introItemView = function introItemView(item, x, y, vx, vy) {
if (item.interactionMethod === InteractionMethod.NONE) {
item.translateX = null;
item.translateX = x;
item.translateY = null;
item.translateY = y;
} else if (item.interactionMethod === InteractionMethod.DROP) {
item.translateX = null;
item.translateX = x - vx * 20;
item.translateY = null;
item.translateY = y - vy * 10;
item.scaleX = 0.8;
item.scaleY = 0.8;
} else if (item.interactionMethod === InteractionMethod.BROWSE) {
item.translateY = null;
item.translateY = y - 30;
} else if (item.interactionMethod === InteractionMethod.API) {
item.translateX = null;
item.translateX = x - 30;
item.translateY = null;
}
};
/**
* Removes an existing item
* @param root
* @param action
*/
var removeItemView = function removeItemView(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var id = action.id;
// get the view matching the given id
var view = root.childViews.find(function(child) {
return child.id === id;
});
// if no view found, exit
if (!view) {
return;
}
// animate view out of view
view.scaleX = 0.9;
view.scaleY = 0.9;
view.opacity = 0;
// mark for removal
view.markedForRemoval = true;
};
var getItemHeight = function getItemHeight(child) {
return (
child.rect.element.height +
child.rect.element.marginBottom * 0.5 +
child.rect.element.marginTop * 0.5
);
};
var getItemWidth = function getItemWidth(child) {
return (
child.rect.element.width +
child.rect.element.marginLeft * 0.5 +
child.rect.element.marginRight * 0.5
);
};
var dragItem = function dragItem(_ref4) {
var root = _ref4.root,
action = _ref4.action;
var id = action.id,
dragState = action.dragState;
// reference to item
var item = root.query('GET_ITEM', { id: id });
// get the view matching the given id
var view = root.childViews.find(function(child) {
return child.id === id;
});
var numItems = root.childViews.length;
var oldIndex = dragState.getItemIndex(item);
// if no view found, exit
if (!view) return;
var dragPosition = {
x: view.dragOrigin.x + view.dragOffset.x + view.dragCenter.x,
y: view.dragOrigin.y + view.dragOffset.y + view.dragCenter.y,
};
// get drag area dimensions
var dragHeight = getItemHeight(view);
var dragWidth = getItemWidth(view);
// get rows and columns (There will always be at least one row and one column if a file is present)
var cols = Math.floor(root.rect.outer.width / dragWidth);
if (cols > numItems) cols = numItems;
// rows are used to find when we have left the preview area bounding box
var rows = Math.floor(numItems / cols + 1);
dropAreaDimensions.setHeight = dragHeight * rows;
dropAreaDimensions.setWidth = dragWidth * cols;
// get new index of dragged item
var location = {
y: Math.floor(dragPosition.y / dragHeight),
x: Math.floor(dragPosition.x / dragWidth),
getGridIndex: function getGridIndex() {
if (
dragPosition.y > dropAreaDimensions.getHeight ||
dragPosition.y < 0 ||
dragPosition.x > dropAreaDimensions.getWidth ||
dragPosition.x < 0
)
return oldIndex;
return this.y * cols + this.x;
},
getColIndex: function getColIndex() {
var items = root.query('GET_ACTIVE_ITEMS');
var visibleChildren = root.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = items.map(function(item) {
return visibleChildren.find(function(childView) {
return childView.id === item.id;
});
});
var currentIndex = children.findIndex(function(child) {
return child === view;
});
var dragHeight = getItemHeight(view);
var l = children.length;
var idx = l;
var childHeight = 0;
var childBottom = 0;
var childTop = 0;
for (var i = 0; i < l; i++) {
childHeight = getItemHeight(children[i]);
childTop = childBottom;
childBottom = childTop + childHeight;
if (dragPosition.y < childBottom) {
if (currentIndex > i) {
if (dragPosition.y < childTop + dragHeight) {
idx = i;
break;
}
continue;
}
idx = i;
break;
}
}
return idx;
},
};
// get new index
var index = cols > 1 ? location.getGridIndex() : location.getColIndex();
root.dispatch('MOVE_ITEM', { query: view, index: index });
// if the index of the item changed, dispatch reorder action
var currentIndex = dragState.getIndex();
if (currentIndex === undefined || currentIndex !== index) {
dragState.setIndex(index);
if (currentIndex === undefined) return;
root.dispatch('DID_REORDER_ITEMS', {
items: root.query('GET_ACTIVE_ITEMS'),
origin: oldIndex,
target: index,
});
}
};
/**
* Setup action routes
*/
var route$2 = createRoute({
DID_ADD_ITEM: addItemView,
DID_REMOVE_ITEM: removeItemView,
DID_DRAG_ITEM: dragItem,
});
/**
* Write to view
* @param root
* @param actions
* @param props
*/
var write$5 = function write(_ref5) {
var root = _ref5.root,
props = _ref5.props,
actions = _ref5.actions,
shouldOptimize = _ref5.shouldOptimize;
// route actions
route$2({ root: root, props: props, actions: actions });
var dragCoordinates = props.dragCoordinates;
// available space on horizontal axis
var horizontalSpace = root.rect.element.width;
// only draw children that have dimensions
var visibleChildren = root.childViews.filter(function(child) {
return child.rect.element.height;
});
// sort based on current active items
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
// get index
var dragIndex = dragCoordinates
? getItemIndexByPosition(root, children, dragCoordinates)
: null;
// add index is used to reserve the dropped/added item index till the actual item is rendered
var addIndex = root.ref.addIndex || null;
// add index no longer needed till possibly next draw
root.ref.addIndex = null;
var dragIndexOffset = 0;
var removeIndexOffset = 0;
var addIndexOffset = 0;
if (children.length === 0) return;
var childRect = children[0].rect.element;
var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;
var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;
var itemWidth = childRect.width + itemHorizontalMargin;
var itemHeight = childRect.height + itemVerticalMargin;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
var offsetY = 0;
var dragOffset = 0;
children.forEach(function(child, index) {
if (dragIndex) {
var dist = index - dragIndex;
if (dist === -2) {
dragOffset = -itemVerticalMargin * 0.25;
} else if (dist === -1) {
dragOffset = -itemVerticalMargin * 0.75;
} else if (dist === 0) {
dragOffset = itemVerticalMargin * 0.75;
} else if (dist === 1) {
dragOffset = itemVerticalMargin * 0.25;
} else {
dragOffset = 0;
}
}
if (shouldOptimize) {
child.translateX = null;
child.translateY = null;
}
if (!child.markedForRemoval) {
moveItem(child, 0, offsetY + dragOffset);
}
var itemHeight = child.rect.element.height + itemVerticalMargin;
var visualHeight = itemHeight * (child.markedForRemoval ? child.opacity : 1);
offsetY += visualHeight;
});
}
// grid
else {
var prevX = 0;
var prevY = 0;
children.forEach(function(child, index) {
if (index === dragIndex) {
dragIndexOffset = 1;
}
if (index === addIndex) {
addIndexOffset += 1;
}
if (child.markedForRemoval && child.opacity < 0.5) {
removeIndexOffset -= 1;
}
var visualIndex = index + addIndexOffset + dragIndexOffset + removeIndexOffset;
var indexX = visualIndex % itemsPerRow;
var indexY = Math.floor(visualIndex / itemsPerRow);
var offsetX = indexX * itemWidth;
var offsetY = indexY * itemHeight;
var vectorX = Math.sign(offsetX - prevX);
var vectorY = Math.sign(offsetY - prevY);
prevX = offsetX;
prevY = offsetY;
if (child.markedForRemoval) return;
if (shouldOptimize) {
child.translateX = null;
child.translateY = null;
}
moveItem(child, offsetX, offsetY, vectorX, vectorY);
});
}
};
/**
* Filters actions that are meant specifically for a certain child of the list
* @param child
* @param actions
*/
var filterSetItemActions = function filterSetItemActions(child, actions) {
return actions.filter(function(action) {
// if action has an id, filter out actions that don't have this child id
if (action.data && action.data.id) {
return child.id === action.data.id;
}
// allow all other actions
return true;
});
};
var list = createView({
create: create$8,
write: write$5,
tag: 'ul',
name: 'list',
didWriteView: function didWriteView(_ref6) {
var root = _ref6.root;
root.childViews
.filter(function(view) {
return view.markedForRemoval && view.opacity === 0 && view.resting;
})
.forEach(function(view) {
view._destroy();
root.removeChildView(view);
});
},
filterFrameActionsForChild: filterSetItemActions,
mixins: {
apis: ['dragCoordinates'],
},
});
var create$9 = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.ref.list = root.appendChildView(root.createChildView(list));
props.dragCoordinates = null;
props.overflowing = false;
};
var storeDragCoordinates = function storeDragCoordinates(_ref2) {
var root = _ref2.root,
props = _ref2.props,
action = _ref2.action;
if (!root.query('GET_ITEM_INSERT_LOCATION_FREEDOM')) return;
props.dragCoordinates = {
left: action.position.scopeLeft - root.ref.list.rect.element.left,
top:
action.position.scopeTop -
(root.rect.outer.top + root.rect.element.marginTop + root.rect.element.scrollTop),
};
};
var clearDragCoordinates = function clearDragCoordinates(_ref3) {
var props = _ref3.props;
props.dragCoordinates = null;
};
var route$3 = createRoute({
DID_DRAG: storeDragCoordinates,
DID_END_DRAG: clearDragCoordinates,
});
var write$6 = function write(_ref4) {
var root = _ref4.root,
props = _ref4.props,
actions = _ref4.actions;
// route actions
route$3({ root: root, props: props, actions: actions });
// current drag position
root.ref.list.dragCoordinates = props.dragCoordinates;
// if currently overflowing but no longer received overflow
if (props.overflowing && !props.overflow) {
props.overflowing = false;
// reset overflow state
root.element.dataset.state = '';
root.height = null;
}
// if is not overflowing currently but does receive overflow value
if (props.overflow) {
var newHeight = Math.round(props.overflow);
if (newHeight !== root.height) {
props.overflowing = true;
root.element.dataset.state = 'overflow';
root.height = newHeight;
}
}
};
var listScroller = createView({
create: create$9,
write: write$6,
name: 'list-scroller',
mixins: {
apis: ['overflow', 'dragCoordinates'],
styles: ['height', 'translateY'],
animations: {
translateY: 'spring',
},
},
});
var attrToggle = function attrToggle(element, name, state) {
var enabledValue = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
if (state) {
attr(element, name, enabledValue);
} else {
element.removeAttribute(name);
}
};
var resetFileInput = function resetFileInput(input) {
// no value, no need to reset
if (!input || input.value === '') {
return;
}
try {
// for modern browsers
input.value = '';
} catch (err) {}
// for IE10
if (input.value) {
// quickly append input to temp form and reset form
var form = createElement$1('form');
var parentNode = input.parentNode;
var ref = input.nextSibling;
form.appendChild(input);
form.reset();
// re-inject input where it originally was
if (ref) {
parentNode.insertBefore(input, ref);
} else {
parentNode.appendChild(input);
}
}
};
var create$a = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// set id so can be referenced from outside labels
root.element.id = 'filepond--browser-' + props.id;
// set name of element (is removed when a value is set)
attr(root.element, 'name', root.query('GET_NAME'));
// we have to link this element to the status element
attr(root.element, 'aria-controls', 'filepond--assistant-' + props.id);
// set label, we use labelled by as otherwise the screenreader does not read the "browse" text in the label (as it has tabindex: 0)
attr(root.element, 'aria-labelledby', 'filepond--drop-label-' + props.id);
// set configurable props
setAcceptedFileTypes({
root: root,
action: { value: root.query('GET_ACCEPTED_FILE_TYPES') },
});
toggleAllowMultiple({ root: root, action: { value: root.query('GET_ALLOW_MULTIPLE') } });
toggleDirectoryFilter({
root: root,
action: { value: root.query('GET_ALLOW_DIRECTORIES_ONLY') },
});
toggleDisabled({ root: root });
toggleRequired({ root: root, action: { value: root.query('GET_REQUIRED') } });
setCaptureMethod({ root: root, action: { value: root.query('GET_CAPTURE_METHOD') } });
// handle changes to the input field
root.ref.handleChange = function(e) {
if (!root.element.value) {
return;
}
// extract files and move value of webkitRelativePath path to _relativePath
var files = Array.from(root.element.files).map(function(file) {
file._relativePath = file.webkitRelativePath;
return file;
});
// we add a little delay so the OS file select window can move out of the way before we add our file
setTimeout(function() {
// load files
props.onload(files);
// reset input, it's just for exposing a method to drop files, should not retain any state
resetFileInput(root.element);
}, 250);
};
root.element.addEventListener('change', root.ref.handleChange);
};
var setAcceptedFileTypes = function setAcceptedFileTypes(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!root.query('GET_ALLOW_SYNC_ACCEPT_ATTRIBUTE')) return;
attrToggle(
root.element,
'accept',
!!action.value,
action.value ? action.value.join(',') : ''
);
};
var toggleAllowMultiple = function toggleAllowMultiple(_ref3) {
var root = _ref3.root,
action = _ref3.action;
attrToggle(root.element, 'multiple', action.value);
};
var toggleDirectoryFilter = function toggleDirectoryFilter(_ref4) {
var root = _ref4.root,
action = _ref4.action;
attrToggle(root.element, 'webkitdirectory', action.value);
};
var toggleDisabled = function toggleDisabled(_ref5) {
var root = _ref5.root;
var isDisabled = root.query('GET_DISABLED');
var doesAllowBrowse = root.query('GET_ALLOW_BROWSE');
var disableField = isDisabled || !doesAllowBrowse;
attrToggle(root.element, 'disabled', disableField);
};
var toggleRequired = function toggleRequired(_ref6) {
var root = _ref6.root,
action = _ref6.action;
// want to remove required, always possible
if (!action.value) {
attrToggle(root.element, 'required', false);
}
// if want to make required, only possible when zero items
else if (root.query('GET_TOTAL_ITEMS') === 0) {
attrToggle(root.element, 'required', true);
}
};
var setCaptureMethod = function setCaptureMethod(_ref7) {
var root = _ref7.root,
action = _ref7.action;
attrToggle(
root.element,
'capture',
!!action.value,
action.value === true ? '' : action.value
);
};
var updateRequiredStatus = function updateRequiredStatus(_ref8) {
var root = _ref8.root;
var element = root.element;
// always remove the required attribute when more than zero items
if (root.query('GET_TOTAL_ITEMS') > 0) {
attrToggle(element, 'required', false);
attrToggle(element, 'name', false);
} else {
// add name attribute
attrToggle(element, 'name', true, root.query('GET_NAME'));
// remove any validation messages
var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');
if (shouldCheckValidity) {
element.setCustomValidity('');
}
// we only add required if the field has been deemed required
if (root.query('GET_REQUIRED')) {
attrToggle(element, 'required', true);
}
}
};
var updateFieldValidityStatus = function updateFieldValidityStatus(_ref9) {
var root = _ref9.root;
var shouldCheckValidity = root.query('GET_CHECK_VALIDITY');
if (!shouldCheckValidity) return;
root.element.setCustomValidity(root.query('GET_LABEL_INVALID_FIELD'));
};
var browser = createView({
tag: 'input',
name: 'browser',
ignoreRect: true,
ignoreRectUpdate: true,
attributes: {
type: 'file',
},
create: create$a,
destroy: function destroy(_ref10) {
var root = _ref10.root;
root.element.removeEventListener('change', root.ref.handleChange);
},
write: createRoute({
DID_LOAD_ITEM: updateRequiredStatus,
DID_REMOVE_ITEM: updateRequiredStatus,
DID_THROW_ITEM_INVALID: updateFieldValidityStatus,
DID_SET_DISABLED: toggleDisabled,
DID_SET_ALLOW_BROWSE: toggleDisabled,
DID_SET_ALLOW_DIRECTORIES_ONLY: toggleDirectoryFilter,
DID_SET_ALLOW_MULTIPLE: toggleAllowMultiple,
DID_SET_ACCEPTED_FILE_TYPES: setAcceptedFileTypes,
DID_SET_CAPTURE_METHOD: setCaptureMethod,
DID_SET_REQUIRED: toggleRequired,
}),
});
var Key = {
ENTER: 13,
SPACE: 32,
};
var create$b = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// create the label and link it to the file browser
var label = createElement$1('label');
attr(label, 'for', 'filepond--browser-' + props.id);
// use for labeling file input (aria-labelledby on file input)
attr(label, 'id', 'filepond--drop-label-' + props.id);
// hide the label for screenreaders, the input element will read the contents of the label when it's focussed. If we don't set aria-hidden the screenreader will also navigate the contents of the label separately from the input.
attr(label, 'aria-hidden', 'true');
// handle keys
root.ref.handleKeyDown = function(e) {
var isActivationKey = e.keyCode === Key.ENTER || e.keyCode === Key.SPACE;
if (!isActivationKey) return;
// stops from triggering the element a second time
e.preventDefault();
// click link (will then in turn activate file input)
root.ref.label.click();
};
root.ref.handleClick = function(e) {
var isLabelClick = e.target === label || label.contains(e.target);
// don't want to click twice
if (isLabelClick) return;
// click link (will then in turn activate file input)
root.ref.label.click();
};
// attach events
label.addEventListener('keydown', root.ref.handleKeyDown);
root.element.addEventListener('click', root.ref.handleClick);
// update
updateLabelValue(label, props.caption);
// add!
root.appendChild(label);
root.ref.label = label;
};
var updateLabelValue = function updateLabelValue(label, value) {
label.innerHTML = value;
var clickable = label.querySelector('.filepond--label-action');
if (clickable) {
attr(clickable, 'tabindex', '0');
}
return value;
};
var dropLabel = createView({
name: 'drop-label',
ignoreRect: true,
create: create$b,
destroy: function destroy(_ref2) {
var root = _ref2.root;
root.ref.label.addEventListener('keydown', root.ref.handleKeyDown);
root.element.removeEventListener('click', root.ref.handleClick);
},
write: createRoute({
DID_SET_LABEL_IDLE: function DID_SET_LABEL_IDLE(_ref3) {
var root = _ref3.root,
action = _ref3.action;
updateLabelValue(root.ref.label, action.value);
},
}),
mixins: {
styles: ['opacity', 'translateX', 'translateY'],
animations: {
opacity: { type: 'tween', duration: 150 },
translateX: 'spring',
translateY: 'spring',
},
},
});
var blob = createView({
name: 'drip-blob',
ignoreRect: true,
mixins: {
styles: ['translateX', 'translateY', 'scaleX', 'scaleY', 'opacity'],
animations: {
scaleX: 'spring',
scaleY: 'spring',
translateX: 'spring',
translateY: 'spring',
opacity: { type: 'tween', duration: 250 },
},
},
});
var addBlob = function addBlob(_ref) {
var root = _ref.root;
var centerX = root.rect.element.width * 0.5;
var centerY = root.rect.element.height * 0.5;
root.ref.blob = root.appendChildView(
root.createChildView(blob, {
opacity: 0,
scaleX: 2.5,
scaleY: 2.5,
translateX: centerX,
translateY: centerY,
})
);
};
var moveBlob = function moveBlob(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!root.ref.blob) {
addBlob({ root: root });
return;
}
root.ref.blob.translateX = action.position.scopeLeft;
root.ref.blob.translateY = action.position.scopeTop;
root.ref.blob.scaleX = 1;
root.ref.blob.scaleY = 1;
root.ref.blob.opacity = 1;
};
var hideBlob = function hideBlob(_ref3) {
var root = _ref3.root;
if (!root.ref.blob) {
return;
}
root.ref.blob.opacity = 0;
};
var explodeBlob = function explodeBlob(_ref4) {
var root = _ref4.root;
if (!root.ref.blob) {
return;
}
root.ref.blob.scaleX = 2.5;
root.ref.blob.scaleY = 2.5;
root.ref.blob.opacity = 0;
};
var write$7 = function write(_ref5) {
var root = _ref5.root,
props = _ref5.props,
actions = _ref5.actions;
route$4({ root: root, props: props, actions: actions });
var blob = root.ref.blob;
if (actions.length === 0 && blob && blob.opacity === 0) {
root.removeChildView(blob);
root.ref.blob = null;
}
};
var route$4 = createRoute({
DID_DRAG: moveBlob,
DID_DROP: explodeBlob,
DID_END_DRAG: hideBlob,
});
var drip = createView({
ignoreRect: true,
ignoreRectUpdate: true,
name: 'drip',
write: write$7,
});
var create$c = function create(_ref) {
var root = _ref.root;
return (root.ref.fields = {});
};
var getField = function getField(root, id) {
return root.ref.fields[id];
};
var syncFieldPositionsWithItems = function syncFieldPositionsWithItems(root) {
root.query('GET_ACTIVE_ITEMS').forEach(function(item) {
if (!root.ref.fields[item.id]) return;
root.element.appendChild(root.ref.fields[item.id]);
});
};
var didReorderItems = function didReorderItems(_ref2) {
var root = _ref2.root;
return syncFieldPositionsWithItems(root);
};
var didAddItem = function didAddItem(_ref3) {
var root = _ref3.root,
action = _ref3.action;
var dataContainer = createElement$1('input');
dataContainer.type = 'hidden';
dataContainer.name = root.query('GET_NAME');
dataContainer.disabled = root.query('GET_DISABLED');
root.ref.fields[action.id] = dataContainer;
syncFieldPositionsWithItems(root);
};
var didLoadItem$1 = function didLoadItem(_ref4) {
var root = _ref4.root,
action = _ref4.action;
var field = getField(root, action.id);
if (!field || action.serverFileReference === null) return;
field.value = action.serverFileReference;
};
var didSetDisabled = function didSetDisabled(_ref5) {
var root = _ref5.root;
root.element.disabled = root.query('GET_DISABLED');
};
var didRemoveItem = function didRemoveItem(_ref6) {
var root = _ref6.root,
action = _ref6.action;
var field = getField(root, action.id);
if (!field) return;
if (field.parentNode) field.parentNode.removeChild(field);
delete root.ref.fields[action.id];
};
var didDefineValue = function didDefineValue(_ref7) {
var root = _ref7.root,
action = _ref7.action;
var field = getField(root, action.id);
if (!field) return;
if (action.value === null) {
field.removeAttribute('value');
} else {
field.value = action.value;
}
syncFieldPositionsWithItems(root);
};
var write$8 = createRoute({
DID_SET_DISABLED: didSetDisabled,
DID_ADD_ITEM: didAddItem,
DID_LOAD_ITEM: didLoadItem$1,
DID_REMOVE_ITEM: didRemoveItem,
DID_DEFINE_VALUE: didDefineValue,
DID_REORDER_ITEMS: didReorderItems,
DID_SORT_ITEMS: didReorderItems,
});
var data = createView({
tag: 'fieldset',
name: 'data',
create: create$c,
write: write$8,
ignoreRect: true,
});
var getRootNode = function getRootNode(element) {
return 'getRootNode' in element ? element.getRootNode() : document;
};
var images = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg', 'tiff'];
var text$1 = ['css', 'csv', 'html', 'txt'];
var map = {
zip: 'zip|compressed',
epub: 'application/epub+zip',
};
var guesstimateMimeType = function guesstimateMimeType() {
var extension = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
extension = extension.toLowerCase();
if (images.includes(extension)) {
return (
'image/' +
(extension === 'jpg' ? 'jpeg' : extension === 'svg' ? 'svg+xml' : extension)
);
}
if (text$1.includes(extension)) {
return 'text/' + extension;
}
return map[extension] || '';
};
var requestDataTransferItems = function requestDataTransferItems(dataTransfer) {
return new Promise(function(resolve, reject) {
// try to get links from transfer, if found we'll exit immediately (unless a file is in the dataTransfer as well, this is because Firefox could represent the file as a URL and a file object at the same time)
var links = getLinks(dataTransfer);
if (links.length && !hasFiles(dataTransfer)) {
return resolve(links);
}
// try to get files from the transfer
getFiles(dataTransfer).then(resolve);
});
};
/**
* Test if datatransfer has files
*/
var hasFiles = function hasFiles(dataTransfer) {
if (dataTransfer.files) return dataTransfer.files.length > 0;
return false;
};
/**
* Extracts files from a DataTransfer object
*/
var getFiles = function getFiles(dataTransfer) {
return new Promise(function(resolve, reject) {
// get the transfer items as promises
var promisedFiles = (dataTransfer.items ? Array.from(dataTransfer.items) : [])
// only keep file system items (files and directories)
.filter(function(item) {
return isFileSystemItem(item);
})
// map each item to promise
.map(function(item) {
return getFilesFromItem(item);
});
// if is empty, see if we can extract some info from the files property as a fallback
if (!promisedFiles.length) {
// TODO: test for directories (should not be allowed)
// Use FileReader, problem is that the files property gets lost in the process
resolve(dataTransfer.files ? Array.from(dataTransfer.files) : []);
return;
}
// done!
Promise.all(promisedFiles)
.then(function(returnedFileGroups) {
// flatten groups
var files = [];
returnedFileGroups.forEach(function(group) {
files.push.apply(files, group);
});
// done (filter out empty files)!
resolve(
files
.filter(function(file) {
return file;
})
.map(function(file) {
if (!file._relativePath)
file._relativePath = file.webkitRelativePath;
return file;
})
);
})
.catch(console.error);
});
};
var isFileSystemItem = function isFileSystemItem(item) {
if (isEntry(item)) {
var entry = getAsEntry(item);
if (entry) {
return entry.isFile || entry.isDirectory;
}
}
return item.kind === 'file';
};
var getFilesFromItem = function getFilesFromItem(item) {
return new Promise(function(resolve, reject) {
if (isDirectoryEntry(item)) {
getFilesInDirectory(getAsEntry(item))
.then(resolve)
.catch(reject);
return;
}
resolve([item.getAsFile()]);
});
};
var getFilesInDirectory = function getFilesInDirectory(entry) {
return new Promise(function(resolve, reject) {
var files = [];
// the total entries to read
var dirCounter = 0;
var fileCounter = 0;
var resolveIfDone = function resolveIfDone() {
if (fileCounter === 0 && dirCounter === 0) {
resolve(files);
}
};
// the recursive function
var readEntries = function readEntries(dirEntry) {
dirCounter++;
var directoryReader = dirEntry.createReader();
// directories are returned in batches, we need to process all batches before we're done
var readBatch = function readBatch() {
directoryReader.readEntries(function(entries) {
if (entries.length === 0) {
dirCounter--;
resolveIfDone();
return;
}
entries.forEach(function(entry) {
// recursively read more directories
if (entry.isDirectory) {
readEntries(entry);
} else {
// read as file
fileCounter++;
entry.file(function(file) {
var correctedFile = correctMissingFileType(file);
if (entry.fullPath)
correctedFile._relativePath = entry.fullPath;
files.push(correctedFile);
fileCounter--;
resolveIfDone();
});
}
});
// try to get next batch of files
readBatch();
}, reject);
};
// read first batch of files
readBatch();
};
// go!
readEntries(entry);
});
};
var correctMissingFileType = function correctMissingFileType(file) {
if (file.type.length) return file;
var date = file.lastModifiedDate;
var name = file.name;
var type = guesstimateMimeType(getExtensionFromFilename(file.name));
if (!type.length) return file;
file = file.slice(0, file.size, type);
file.name = name;
file.lastModifiedDate = date;
return file;
};
var isDirectoryEntry = function isDirectoryEntry(item) {
return isEntry(item) && (getAsEntry(item) || {}).isDirectory;
};
var isEntry = function isEntry(item) {
return 'webkitGetAsEntry' in item;
};
var getAsEntry = function getAsEntry(item) {
return item.webkitGetAsEntry();
};
/**
* Extracts links from a DataTransfer object
*/
var getLinks = function getLinks(dataTransfer) {
var links = [];
try {
// look in meta data property
links = getLinksFromTransferMetaData(dataTransfer);
if (links.length) {
return links;
}
links = getLinksFromTransferURLData(dataTransfer);
} catch (e) {
// nope nope nope (probably IE trouble)
}
return links;
};
var getLinksFromTransferURLData = function getLinksFromTransferURLData(dataTransfer) {
var data = dataTransfer.getData('url');
if (typeof data === 'string' && data.length) {
return [data];
}
return [];
};
var getLinksFromTransferMetaData = function getLinksFromTransferMetaData(dataTransfer) {
var data = dataTransfer.getData('text/html');
if (typeof data === 'string' && data.length) {
var matches = data.match(/src\s*=\s*"(.+?)"/);
if (matches) {
return [matches[1]];
}
}
return [];
};
var dragNDropObservers = [];
var eventPosition = function eventPosition(e) {
return {
pageLeft: e.pageX,
pageTop: e.pageY,
scopeLeft: e.offsetX || e.layerX,
scopeTop: e.offsetY || e.layerY,
};
};
var createDragNDropClient = function createDragNDropClient(
element,
scopeToObserve,
filterElement
) {
var observer = getDragNDropObserver(scopeToObserve);
var client = {
element: element,
filterElement: filterElement,
state: null,
ondrop: function ondrop() {},
onenter: function onenter() {},
ondrag: function ondrag() {},
onexit: function onexit() {},
onload: function onload() {},
allowdrop: function allowdrop() {},
};
client.destroy = observer.addListener(client);
return client;
};
var getDragNDropObserver = function getDragNDropObserver(element) {
// see if already exists, if so, return
var observer = dragNDropObservers.find(function(item) {
return item.element === element;
});
if (observer) {
return observer;
}
// create new observer, does not yet exist for this element
var newObserver = createDragNDropObserver(element);
dragNDropObservers.push(newObserver);
return newObserver;
};
var createDragNDropObserver = function createDragNDropObserver(element) {
var clients = [];
var routes = {
dragenter: dragenter,
dragover: dragover,
dragleave: dragleave,
drop: drop,
};
var handlers = {};
forin(routes, function(event, createHandler) {
handlers[event] = createHandler(element, clients);
element.addEventListener(event, handlers[event], false);
});
var observer = {
element: element,
addListener: function addListener(client) {
// add as client
clients.push(client);
// return removeListener function
return function() {
// remove client
clients.splice(clients.indexOf(client), 1);
// if no more clients, clean up observer
if (clients.length === 0) {
dragNDropObservers.splice(dragNDropObservers.indexOf(observer), 1);
forin(routes, function(event) {
element.removeEventListener(event, handlers[event], false);
});
}
};
},
};
return observer;
};
var elementFromPoint = function elementFromPoint(root, point) {
if (!('elementFromPoint' in root)) {
root = document;
}
return root.elementFromPoint(point.x, point.y);
};
var isEventTarget = function isEventTarget(e, target) {
// get root
var root = getRootNode(target);
// get element at position
// if root is not actual shadow DOM and does not have elementFromPoint method, use the one on document
var elementAtPosition = elementFromPoint(root, {
x: e.pageX - window.pageXOffset,
y: e.pageY - window.pageYOffset,
});
// test if target is the element or if one of its children is
return elementAtPosition === target || target.contains(elementAtPosition);
};
var initialTarget = null;
var setDropEffect = function setDropEffect(dataTransfer, effect) {
// is in try catch as IE11 will throw error if not
try {
dataTransfer.dropEffect = effect;
} catch (e) {}
};
var dragenter = function dragenter(root, clients) {
return function(e) {
e.preventDefault();
initialTarget = e.target;
clients.forEach(function(client) {
var element = client.element,
onenter = client.onenter;
if (isEventTarget(e, element)) {
client.state = 'enter';
// fire enter event
onenter(eventPosition(e));
}
});
};
};
var dragover = function dragover(root, clients) {
return function(e) {
e.preventDefault();
var dataTransfer = e.dataTransfer;
requestDataTransferItems(dataTransfer).then(function(items) {
var overDropTarget = false;
clients.some(function(client) {
var filterElement = client.filterElement,
element = client.element,
onenter = client.onenter,
onexit = client.onexit,
ondrag = client.ondrag,
allowdrop = client.allowdrop;
// by default we can drop
setDropEffect(dataTransfer, 'copy');
// allow transfer of these items
var allowsTransfer = allowdrop(items);
// only used when can be dropped on page
if (!allowsTransfer) {
setDropEffect(dataTransfer, 'none');
return;
}
// targetting this client
if (isEventTarget(e, element)) {
overDropTarget = true;
// had no previous state, means we are entering this client
if (client.state === null) {
client.state = 'enter';
onenter(eventPosition(e));
return;
}
// now over element (no matter if it allows the drop or not)
client.state = 'over';
// needs to allow transfer
if (filterElement && !allowsTransfer) {
setDropEffect(dataTransfer, 'none');
return;
}
// dragging
ondrag(eventPosition(e));
} else {
// should be over an element to drop
if (filterElement && !overDropTarget) {
setDropEffect(dataTransfer, 'none');
}
// might have just left this client?
if (client.state) {
client.state = null;
onexit(eventPosition(e));
}
}
});
});
};
};
var drop = function drop(root, clients) {
return function(e) {
e.preventDefault();
var dataTransfer = e.dataTransfer;
requestDataTransferItems(dataTransfer).then(function(items) {
clients.forEach(function(client) {
var filterElement = client.filterElement,
element = client.element,
ondrop = client.ondrop,
onexit = client.onexit,
allowdrop = client.allowdrop;
client.state = null;
// if we're filtering on element we need to be over the element to drop
if (filterElement && !isEventTarget(e, element)) return;
// no transfer for this client
if (!allowdrop(items)) return onexit(eventPosition(e));
// we can drop these items on this client
ondrop(eventPosition(e), items);
});
});
};
};
var dragleave = function dragleave(root, clients) {
return function(e) {
if (initialTarget !== e.target) {
return;
}
clients.forEach(function(client) {
var onexit = client.onexit;
client.state = null;
onexit(eventPosition(e));
});
};
};
var createHopper = function createHopper(scope, validateItems, options) {
// is now hopper scope
scope.classList.add('filepond--hopper');
// shortcuts
var catchesDropsOnPage = options.catchesDropsOnPage,
requiresDropOnElement = options.requiresDropOnElement,
_options$filterItems = options.filterItems,
filterItems =
_options$filterItems === void 0
? function(items) {
return items;
}
: _options$filterItems;
// create a dnd client
var client = createDragNDropClient(
scope,
catchesDropsOnPage ? document.documentElement : scope,
requiresDropOnElement
);
// current client state
var lastState = '';
var currentState = '';
// determines if a file may be dropped
client.allowdrop = function(items) {
// TODO: if we can, throw error to indicate the items cannot by dropped
return validateItems(filterItems(items));
};
client.ondrop = function(position, items) {
var filteredItems = filterItems(items);
if (!validateItems(filteredItems)) {
api.ondragend(position);
return;
}
currentState = 'drag-drop';
api.onload(filteredItems, position);
};
client.ondrag = function(position) {
api.ondrag(position);
};
client.onenter = function(position) {
currentState = 'drag-over';
api.ondragstart(position);
};
client.onexit = function(position) {
currentState = 'drag-exit';
api.ondragend(position);
};
var api = {
updateHopperState: function updateHopperState() {
if (lastState !== currentState) {
scope.dataset.hopperState = currentState;
lastState = currentState;
}
},
onload: function onload() {},
ondragstart: function ondragstart() {},
ondrag: function ondrag() {},
ondragend: function ondragend() {},
destroy: function destroy() {
// destroy client
client.destroy();
},
};
return api;
};
var listening = false;
var listeners$1 = [];
var handlePaste = function handlePaste(e) {
// if is pasting in input or textarea and the target is outside of a filepond scope, ignore
var activeEl = document.activeElement;
if (activeEl && /textarea|input/i.test(activeEl.nodeName)) {
// test textarea or input is contained in filepond root
var inScope = false;
var element = activeEl;
while (element !== document.body) {
if (element.classList.contains('filepond--root')) {
inScope = true;
break;
}
element = element.parentNode;
}
if (!inScope) return;
}
requestDataTransferItems(e.clipboardData).then(function(files) {
// no files received
if (!files.length) {
return;
}
// notify listeners of received files
listeners$1.forEach(function(listener) {
return listener(files);
});
});
};
var listen = function listen(cb) {
// can't add twice
if (listeners$1.includes(cb)) {
return;
}
// add initial listener
listeners$1.push(cb);
// setup paste listener for entire page
if (listening) {
return;
}
listening = true;
document.addEventListener('paste', handlePaste);
};
var unlisten = function unlisten(listener) {
arrayRemove(listeners$1, listeners$1.indexOf(listener));
// clean up
if (listeners$1.length === 0) {
document.removeEventListener('paste', handlePaste);
listening = false;
}
};
var createPaster = function createPaster() {
var cb = function cb(files) {
api.onload(files);
};
var api = {
destroy: function destroy() {
unlisten(cb);
},
onload: function onload() {},
};
listen(cb);
return api;
};
/**
* Creates the file view
*/
var create$d = function create(_ref) {
var root = _ref.root,
props = _ref.props;
root.element.id = 'filepond--assistant-' + props.id;
attr(root.element, 'role', 'status');
attr(root.element, 'aria-live', 'polite');
attr(root.element, 'aria-relevant', 'additions');
};
var addFilesNotificationTimeout = null;
var notificationClearTimeout = null;
var filenames = [];
var assist = function assist(root, message) {
root.element.textContent = message;
};
var clear$1 = function clear(root) {
root.element.textContent = '';
};
var listModified = function listModified(root, filename, label) {
var total = root.query('GET_TOTAL_ITEMS');
assist(
root,
label +
' ' +
filename +
', ' +
total +
' ' +
(total === 1
? root.query('GET_LABEL_FILE_COUNT_SINGULAR')
: root.query('GET_LABEL_FILE_COUNT_PLURAL'))
);
// clear group after set amount of time so the status is not read twice
clearTimeout(notificationClearTimeout);
notificationClearTimeout = setTimeout(function() {
clear$1(root);
}, 1500);
};
var isUsingFilePond = function isUsingFilePond(root) {
return root.element.parentNode.contains(document.activeElement);
};
var itemAdded = function itemAdded(_ref2) {
var root = _ref2.root,
action = _ref2.action;
if (!isUsingFilePond(root)) {
return;
}
root.element.textContent = '';
var item = root.query('GET_ITEM', action.id);
filenames.push(item.filename);
clearTimeout(addFilesNotificationTimeout);
addFilesNotificationTimeout = setTimeout(function() {
listModified(root, filenames.join(', '), root.query('GET_LABEL_FILE_ADDED'));
filenames.length = 0;
}, 750);
};
var itemRemoved = function itemRemoved(_ref3) {
var root = _ref3.root,
action = _ref3.action;
if (!isUsingFilePond(root)) {
return;
}
var item = action.item;
listModified(root, item.filename, root.query('GET_LABEL_FILE_REMOVED'));
};
var itemProcessed = function itemProcessed(_ref4) {
var root = _ref4.root,
action = _ref4.action;
// will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
var label = root.query('GET_LABEL_FILE_PROCESSING_COMPLETE');
assist(root, filename + ' ' + label);
};
var itemProcessedUndo = function itemProcessedUndo(_ref5) {
var root = _ref5.root,
action = _ref5.action;
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
var label = root.query('GET_LABEL_FILE_PROCESSING_ABORTED');
assist(root, filename + ' ' + label);
};
var itemError = function itemError(_ref6) {
var root = _ref6.root,
action = _ref6.action;
var item = root.query('GET_ITEM', action.id);
var filename = item.filename;
// will also notify the user when FilePond is not being used, as the user might be occupied with other activities while uploading a file
assist(root, action.status.main + ' ' + filename + ' ' + action.status.sub);
};
var assistant = createView({
create: create$d,
ignoreRect: true,
ignoreRectUpdate: true,
write: createRoute({
DID_LOAD_ITEM: itemAdded,
DID_REMOVE_ITEM: itemRemoved,
DID_COMPLETE_ITEM_PROCESSING: itemProcessed,
DID_ABORT_ITEM_PROCESSING: itemProcessedUndo,
DID_REVERT_ITEM_PROCESSING: itemProcessedUndo,
DID_THROW_ITEM_REMOVE_ERROR: itemError,
DID_THROW_ITEM_LOAD_ERROR: itemError,
DID_THROW_ITEM_INVALID: itemError,
DID_THROW_ITEM_PROCESSING_ERROR: itemError,
}),
tag: 'span',
name: 'assistant',
});
var toCamels = function toCamels(string) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '-';
return string.replace(new RegExp(separator + '.', 'g'), function(sub) {
return sub.charAt(1).toUpperCase();
});
};
var debounce = function debounce(func) {
var interval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 16;
var immidiateOnly =
arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var last = Date.now();
var timeout = null;
return function() {
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
clearTimeout(timeout);
var dist = Date.now() - last;
var fn = function fn() {
last = Date.now();
func.apply(void 0, args);
};
if (dist < interval) {
// we need to delay by the difference between interval and dist
// for example: if distance is 10 ms and interval is 16 ms,
// we need to wait an additional 6ms before calling the function)
if (!immidiateOnly) {
timeout = setTimeout(fn, interval - dist);
}
} else {
// go!
fn();
}
};
};
var MAX_FILES_LIMIT = 1000000;
var prevent = function prevent(e) {
return e.preventDefault();
};
var create$e = function create(_ref) {
var root = _ref.root,
props = _ref.props;
// Add id
var id = root.query('GET_ID');
if (id) {
root.element.id = id;
}
// Add className
var className = root.query('GET_CLASS_NAME');
if (className) {
className
.split(' ')
.filter(function(name) {
return name.length;
})
.forEach(function(name) {
root.element.classList.add(name);
});
}
// Field label
root.ref.label = root.appendChildView(
root.createChildView(
dropLabel,
Object.assign({}, props, {
translateY: null,
caption: root.query('GET_LABEL_IDLE'),
})
)
);
// List of items
root.ref.list = root.appendChildView(
root.createChildView(listScroller, { translateY: null })
);
// Background panel
root.ref.panel = root.appendChildView(root.createChildView(panel, { name: 'panel-root' }));
// Assistant notifies assistive tech when content changes
root.ref.assistant = root.appendChildView(
root.createChildView(assistant, Object.assign({}, props))
);
// Data
root.ref.data = root.appendChildView(root.createChildView(data, Object.assign({}, props)));
// Measure (tests if fixed height was set)
// DOCTYPE needs to be set for this to work
root.ref.measure = createElement$1('div');
root.ref.measure.style.height = '100%';
root.element.appendChild(root.ref.measure);
// information on the root height or fixed height status
root.ref.bounds = null;
// apply initial style properties
root.query('GET_STYLES')
.filter(function(style) {
return !isEmpty(style.value);
})
.map(function(_ref2) {
var name = _ref2.name,
value = _ref2.value;
root.element.dataset[name] = value;
});
// determine if width changed
root.ref.widthPrevious = null;
root.ref.widthUpdated = debounce(function() {
root.ref.updateHistory = [];
root.dispatch('DID_RESIZE_ROOT');
}, 250);
// history of updates
root.ref.previousAspectRatio = null;
root.ref.updateHistory = [];
// prevent scrolling and zooming on iOS (only if supports pointer events, for then we can enable reorder)
var canHover = window.matchMedia('(pointer: fine) and (hover: hover)').matches;
var hasPointerEvents = 'PointerEvent' in window;
if (root.query('GET_ALLOW_REORDER') && hasPointerEvents && !canHover) {
root.element.addEventListener('touchmove', prevent, { passive: false });
root.element.addEventListener('gesturestart', prevent);
}
// add credits
var credits = root.query('GET_CREDITS');
var hasCredits = credits.length === 2;
if (hasCredits) {
var frag = document.createElement('a');
frag.className = 'filepond--credits';
frag.setAttribute('aria-hidden', 'true');
frag.href = credits[0];
frag.tabindex = -1;
frag.target = '_blank';
frag.rel = 'noopener noreferrer';
frag.textContent = credits[1];
root.element.appendChild(frag);
root.ref.credits = frag;
}
};
var write$9 = function write(_ref3) {
var root = _ref3.root,
props = _ref3.props,
actions = _ref3.actions;
// route actions
route$5({ root: root, props: props, actions: actions });
// apply style properties
actions
.filter(function(action) {
return /^DID_SET_STYLE_/.test(action.type);
})
.filter(function(action) {
return !isEmpty(action.data.value);
})
.map(function(_ref4) {
var type = _ref4.type,
data = _ref4.data;
var name = toCamels(type.substr(8).toLowerCase(), '_');
root.element.dataset[name] = data.value;
root.invalidateLayout();
});
if (root.rect.element.hidden) return;
if (root.rect.element.width !== root.ref.widthPrevious) {
root.ref.widthPrevious = root.rect.element.width;
root.ref.widthUpdated();
}
// get box bounds, we do this only once
var bounds = root.ref.bounds;
if (!bounds) {
bounds = root.ref.bounds = calculateRootBoundingBoxHeight(root);
// destroy measure element
root.element.removeChild(root.ref.measure);
root.ref.measure = null;
}
// get quick references to various high level parts of the upload tool
var _root$ref = root.ref,
hopper = _root$ref.hopper,
label = _root$ref.label,
list = _root$ref.list,
panel = _root$ref.panel;
// sets correct state to hopper scope
if (hopper) {
hopper.updateHopperState();
}
// bool to indicate if we're full or not
var aspectRatio = root.query('GET_PANEL_ASPECT_RATIO');
var isMultiItem = root.query('GET_ALLOW_MULTIPLE');
var totalItems = root.query('GET_TOTAL_ITEMS');
var maxItems = isMultiItem ? root.query('GET_MAX_FILES') || MAX_FILES_LIMIT : 1;
var atMaxCapacity = totalItems === maxItems;
// action used to add item
var addAction = actions.find(function(action) {
return action.type === 'DID_ADD_ITEM';
});
// if reached max capacity and we've just reached it
if (atMaxCapacity && addAction) {
// get interaction type
var interactionMethod = addAction.data.interactionMethod;
// hide label
label.opacity = 0;
if (isMultiItem) {
label.translateY = -40;
} else {
if (interactionMethod === InteractionMethod.API) {
label.translateX = 40;
} else if (interactionMethod === InteractionMethod.BROWSE) {
label.translateY = 40;
} else {
label.translateY = 30;
}
}
} else if (!atMaxCapacity) {
label.opacity = 1;
label.translateX = 0;
label.translateY = 0;
}
var listItemMargin = calculateListItemMargin(root);
var listHeight = calculateListHeight(root);
var labelHeight = label.rect.element.height;
var currentLabelHeight = !isMultiItem || atMaxCapacity ? 0 : labelHeight;
var listMarginTop = atMaxCapacity ? list.rect.element.marginTop : 0;
var listMarginBottom = totalItems === 0 ? 0 : list.rect.element.marginBottom;
var visualHeight =
currentLabelHeight + listMarginTop + listHeight.visual + listMarginBottom;
var boundsHeight =
currentLabelHeight + listMarginTop + listHeight.bounds + listMarginBottom;
// link list to label bottom position
list.translateY =
Math.max(0, currentLabelHeight - list.rect.element.marginTop) - listItemMargin.top;
if (aspectRatio) {
// fixed aspect ratio
// calculate height based on width
var width = root.rect.element.width;
var height = width * aspectRatio;
// clear history if aspect ratio has changed
if (aspectRatio !== root.ref.previousAspectRatio) {
root.ref.previousAspectRatio = aspectRatio;
root.ref.updateHistory = [];
}
// remember this width
var history = root.ref.updateHistory;
history.push(width);
var MAX_BOUNCES = 2;
if (history.length > MAX_BOUNCES * 2) {
var l = history.length;
var bottom = l - 10;
var bounces = 0;
for (var i = l; i >= bottom; i--) {
if (history[i] === history[i - 2]) {
bounces++;
}
if (bounces >= MAX_BOUNCES) {
// dont adjust height
return;
}
}
}
// fix height of panel so it adheres to aspect ratio
panel.scalable = false;
panel.height = height;
// available height for list
var listAvailableHeight =
// the height of the panel minus the label height
height -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
if (listHeight.visual > listAvailableHeight) {
list.overflow = listAvailableHeight;
} else {
list.overflow = null;
}
// set container bounds (so pushes siblings downwards)
root.height = height;
} else if (bounds.fixedHeight) {
// fixed height
// fix height of panel
panel.scalable = false;
// available height for list
var _listAvailableHeight =
// the height of the panel minus the label height
bounds.fixedHeight -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
// set list height
if (listHeight.visual > _listAvailableHeight) {
list.overflow = _listAvailableHeight;
} else {
list.overflow = null;
}
// no need to set container bounds as these are handles by CSS fixed height
} else if (bounds.cappedHeight) {
// max-height
// not a fixed height panel
var isCappedHeight = visualHeight >= bounds.cappedHeight;
var panelHeight = Math.min(bounds.cappedHeight, visualHeight);
panel.scalable = true;
panel.height = isCappedHeight
? panelHeight
: panelHeight - listItemMargin.top - listItemMargin.bottom;
// available height for list
var _listAvailableHeight2 =
// the height of the panel minus the label height
panelHeight -
currentLabelHeight -
// the room we leave open between the end of the list and the panel bottom
(listMarginBottom - listItemMargin.bottom) -
// if we're full we need to leave some room between the top of the panel and the list
(atMaxCapacity ? listMarginTop : 0);
// set list height (if is overflowing)
if (visualHeight > bounds.cappedHeight && listHeight.visual > _listAvailableHeight2) {
list.overflow = _listAvailableHeight2;
} else {
list.overflow = null;
}
// set container bounds (so pushes siblings downwards)
root.height = Math.min(
bounds.cappedHeight,
boundsHeight - listItemMargin.top - listItemMargin.bottom
);
} else {
// flexible height
// not a fixed height panel
var itemMargin = totalItems > 0 ? listItemMargin.top + listItemMargin.bottom : 0;
panel.scalable = true;
panel.height = Math.max(labelHeight, visualHeight - itemMargin);
// set container bounds (so pushes siblings downwards)
root.height = Math.max(labelHeight, boundsHeight - itemMargin);
}
// move credits to bottom
if (root.ref.credits && panel.heightCurrent)
root.ref.credits.style.transform = 'translateY(' + panel.heightCurrent + 'px)';
};
var calculateListItemMargin = function calculateListItemMargin(root) {
var item = root.ref.list.childViews[0].childViews[0];
return item
? {
top: item.rect.element.marginTop,
bottom: item.rect.element.marginBottom,
}
: {
top: 0,
bottom: 0,
};
};
var calculateListHeight = function calculateListHeight(root) {
var visual = 0;
var bounds = 0;
// get file list reference
var scrollList = root.ref.list;
var itemList = scrollList.childViews[0];
var visibleChildren = itemList.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
// no children, done!
if (children.length === 0) return { visual: visual, bounds: bounds };
var horizontalSpace = itemList.rect.element.width;
var dragIndex = getItemIndexByPosition(itemList, children, scrollList.dragCoordinates);
var childRect = children[0].rect.element;
var itemVerticalMargin = childRect.marginTop + childRect.marginBottom;
var itemHorizontalMargin = childRect.marginLeft + childRect.marginRight;
var itemWidth = childRect.width + itemHorizontalMargin;
var itemHeight = childRect.height + itemVerticalMargin;
var newItem = typeof dragIndex !== 'undefined' && dragIndex >= 0 ? 1 : 0;
var removedItem = children.find(function(child) {
return child.markedForRemoval && child.opacity < 0.45;
})
? -1
: 0;
var verticalItemCount = children.length + newItem + removedItem;
var itemsPerRow = getItemsPerRow(horizontalSpace, itemWidth);
// stack
if (itemsPerRow === 1) {
children.forEach(function(item) {
var height = item.rect.element.height + itemVerticalMargin;
bounds += height;
visual += height * item.opacity;
});
}
// grid
else {
bounds = Math.ceil(verticalItemCount / itemsPerRow) * itemHeight;
visual = bounds;
}
return { visual: visual, bounds: bounds };
};
var calculateRootBoundingBoxHeight = function calculateRootBoundingBoxHeight(root) {
var height = root.ref.measureHeight || null;
var cappedHeight = parseInt(root.style.maxHeight, 10) || null;
var fixedHeight = height === 0 ? null : height;
return {
cappedHeight: cappedHeight,
fixedHeight: fixedHeight,
};
};
var exceedsMaxFiles = function exceedsMaxFiles(root, items) {
var allowReplace = root.query('GET_ALLOW_REPLACE');
var allowMultiple = root.query('GET_ALLOW_MULTIPLE');
var totalItems = root.query('GET_TOTAL_ITEMS');
var maxItems = root.query('GET_MAX_FILES');
// total amount of items being dragged
var totalBrowseItems = items.length;
// if does not allow multiple items and dragging more than one item
if (!allowMultiple && totalBrowseItems > 1) {
return true;
}
// limit max items to one if not allowed to drop multiple items
maxItems = allowMultiple ? maxItems : allowReplace ? maxItems : 1;
// no more room?
var hasMaxItems = isInt(maxItems);
if (hasMaxItems && totalItems + totalBrowseItems > maxItems) {
root.dispatch('DID_THROW_MAX_FILES', {
source: items,
error: createResponse('warning', 0, 'Max files'),
});
return true;
}
return false;
};
var getDragIndex = function getDragIndex(list, children, position) {
var itemList = list.childViews[0];
return getItemIndexByPosition(itemList, children, {
left: position.scopeLeft - itemList.rect.element.left,
top:
position.scopeTop -
(list.rect.outer.top + list.rect.element.marginTop + list.rect.element.scrollTop),
});
};
/**
* Enable or disable file drop functionality
*/
var toggleDrop = function toggleDrop(root) {
var isAllowed = root.query('GET_ALLOW_DROP');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.hopper) {
var hopper = createHopper(
root.element,
function(items) {
// allow quick validation of dropped items
var beforeDropFile =
root.query('GET_BEFORE_DROP_FILE') ||
function() {
return true;
};
// all items should be validated by all filters as valid
var dropValidation = root.query('GET_DROP_VALIDATION');
return dropValidation
? items.every(function(item) {
return (
applyFilters('ALLOW_HOPPER_ITEM', item, {
query: root.query,
}).every(function(result) {
return result === true;
}) && beforeDropFile(item)
);
})
: true;
},
{
filterItems: function filterItems(items) {
var ignoredFiles = root.query('GET_IGNORED_FILES');
return items.filter(function(item) {
if (isFile(item)) {
return !ignoredFiles.includes(item.name.toLowerCase());
}
return true;
});
},
catchesDropsOnPage: root.query('GET_DROP_ON_PAGE'),
requiresDropOnElement: root.query('GET_DROP_ON_ELEMENT'),
}
);
hopper.onload = function(items, position) {
// get item children elements and sort based on list sort
var list = root.ref.list.childViews[0];
var visibleChildren = list.childViews.filter(function(child) {
return child.rect.element.height;
});
var children = root
.query('GET_ACTIVE_ITEMS')
.map(function(item) {
return visibleChildren.find(function(child) {
return child.id === item.id;
});
})
.filter(function(item) {
return item;
});
applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(
queue
) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// go
root.dispatch('ADD_ITEMS', {
items: queue,
index: getDragIndex(root.ref.list, children, position),
interactionMethod: InteractionMethod.DROP,
});
});
root.dispatch('DID_DROP', { position: position });
root.dispatch('DID_END_DRAG', { position: position });
};
hopper.ondragstart = function(position) {
root.dispatch('DID_START_DRAG', { position: position });
};
hopper.ondrag = debounce(function(position) {
root.dispatch('DID_DRAG', { position: position });
});
hopper.ondragend = function(position) {
root.dispatch('DID_END_DRAG', { position: position });
};
root.ref.hopper = hopper;
root.ref.drip = root.appendChildView(root.createChildView(drip));
} else if (!enabled && root.ref.hopper) {
root.ref.hopper.destroy();
root.ref.hopper = null;
root.removeChildView(root.ref.drip);
}
};
/**
* Enable or disable browse functionality
*/
var toggleBrowse = function toggleBrowse(root, props) {
var isAllowed = root.query('GET_ALLOW_BROWSE');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.browser) {
root.ref.browser = root.appendChildView(
root.createChildView(
browser,
Object.assign({}, props, {
onload: function onload(items) {
applyFilterChain('ADD_ITEMS', items, {
dispatch: root.dispatch,
}).then(function(queue) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// add items!
root.dispatch('ADD_ITEMS', {
items: queue,
index: -1,
interactionMethod: InteractionMethod.BROWSE,
});
});
},
})
),
0
);
} else if (!enabled && root.ref.browser) {
root.removeChildView(root.ref.browser);
root.ref.browser = null;
}
};
/**
* Enable or disable paste functionality
*/
var togglePaste = function togglePaste(root) {
var isAllowed = root.query('GET_ALLOW_PASTE');
var isDisabled = root.query('GET_DISABLED');
var enabled = isAllowed && !isDisabled;
if (enabled && !root.ref.paster) {
root.ref.paster = createPaster();
root.ref.paster.onload = function(items) {
applyFilterChain('ADD_ITEMS', items, { dispatch: root.dispatch }).then(function(
queue
) {
// these files don't fit so stop here
if (exceedsMaxFiles(root, queue)) return false;
// add items!
root.dispatch('ADD_ITEMS', {
items: queue,
index: -1,
interactionMethod: InteractionMethod.PASTE,
});
});
};
} else if (!enabled && root.ref.paster) {
root.ref.paster.destroy();
root.ref.paster = null;
}
};
/**
* Route actions
*/
var route$5 = createRoute({
DID_SET_ALLOW_BROWSE: function DID_SET_ALLOW_BROWSE(_ref5) {
var root = _ref5.root,
props = _ref5.props;
toggleBrowse(root, props);
},
DID_SET_ALLOW_DROP: function DID_SET_ALLOW_DROP(_ref6) {
var root = _ref6.root;
toggleDrop(root);
},
DID_SET_ALLOW_PASTE: function DID_SET_ALLOW_PASTE(_ref7) {
var root = _ref7.root;
togglePaste(root);
},
DID_SET_DISABLED: function DID_SET_DISABLED(_ref8) {
var root = _ref8.root,
props = _ref8.props;
toggleDrop(root);
togglePaste(root);
toggleBrowse(root, props);
var isDisabled = root.query('GET_DISABLED');
if (isDisabled) {
root.element.dataset.disabled = 'disabled';
} else {
// delete root.element.dataset.disabled; <= this does not work on iOS 10
root.element.removeAttribute('data-disabled');
}
},
});
var root = createView({
name: 'root',
read: function read(_ref9) {
var root = _ref9.root;
if (root.ref.measure) {
root.ref.measureHeight = root.ref.measure.offsetHeight;
}
},
create: create$e,
write: write$9,
destroy: function destroy(_ref10) {
var root = _ref10.root;
if (root.ref.paster) {
root.ref.paster.destroy();
}
if (root.ref.hopper) {
root.ref.hopper.destroy();
}
root.element.removeEventListener('touchmove', prevent);
root.element.removeEventListener('gesturestart', prevent);
},
mixins: {
styles: ['height'],
},
});
// creates the app
var createApp = function createApp() {
var initialOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// let element
var originalElement = null;
// get default options
var defaultOptions = getOptions();
// create the data store, this will contain all our app info
var store = createStore(
// initial state (should be serializable)
createInitialState(defaultOptions),
// queries
[queries, createOptionQueries(defaultOptions)],
// action handlers
[actions, createOptionActions(defaultOptions)]
);
// set initial options
store.dispatch('SET_OPTIONS', { options: initialOptions });
// kick thread if visibility changes
var visibilityHandler = function visibilityHandler() {
if (document.hidden) return;
store.dispatch('KICK');
};
document.addEventListener('visibilitychange', visibilityHandler);
// re-render on window resize start and finish
var resizeDoneTimer = null;
var isResizing = false;
var isResizingHorizontally = false;
var initialWindowWidth = null;
var currentWindowWidth = null;
var resizeHandler = function resizeHandler() {
if (!isResizing) {
isResizing = true;
}
clearTimeout(resizeDoneTimer);
resizeDoneTimer = setTimeout(function() {
isResizing = false;
initialWindowWidth = null;
currentWindowWidth = null;
if (isResizingHorizontally) {
isResizingHorizontally = false;
store.dispatch('DID_STOP_RESIZE');
}
}, 500);
};
window.addEventListener('resize', resizeHandler);
// render initial view
var view = root(store, { id: getUniqueId() });
//
// PRIVATE API -------------------------------------------------------------------------------------
//
var isResting = false;
var isHidden = false;
var readWriteApi = {
// necessary for update loop
/**
* Reads from dom (never call manually)
* @private
*/
_read: function _read() {
// test if we're resizing horizontally
// TODO: see if we can optimize this by measuring root rect
if (isResizing) {
currentWindowWidth = window.innerWidth;
if (!initialWindowWidth) {
initialWindowWidth = currentWindowWidth;
}
if (!isResizingHorizontally && currentWindowWidth !== initialWindowWidth) {
store.dispatch('DID_START_RESIZE');
isResizingHorizontally = true;
}
}
if (isHidden && isResting) {
// test if is no longer hidden
isResting = view.element.offsetParent === null;
}
// if resting, no need to read as numbers will still all be correct
if (isResting) return;
// read view data
view._read();
// if is hidden we need to know so we exit rest mode when revealed
isHidden = view.rect.element.hidden;
},
/**
* Writes to dom (never call manually)
* @private
*/
_write: function _write(ts) {
// get all actions from store
var actions = store
.processActionQueue()
// filter out set actions (these will automatically trigger DID_SET)
.filter(function(action) {
return !/^SET_/.test(action.type);
});
// if was idling and no actions stop here
if (isResting && !actions.length) return;
// some actions might trigger events
routeActionsToEvents(actions);
// update the view
isResting = view._write(ts, actions, isResizingHorizontally);
// will clean up all archived items
removeReleasedItems(store.query('GET_ITEMS'));
// now idling
if (isResting) {
store.processDispatchQueue();
}
},
};
//
// EXPOSE EVENTS -------------------------------------------------------------------------------------
//
var createEvent = function createEvent(name) {
return function(data) {
// create default event
var event = {
type: name,
};
// no data to add
if (!data) {
return event;
}
// copy relevant props
if (data.hasOwnProperty('error')) {
event.error = data.error ? Object.assign({}, data.error) : null;
}
if (data.status) {
event.status = Object.assign({}, data.status);
}
if (data.file) {
event.output = data.file;
}
// only source is available, else add item if possible
if (data.source) {
event.file = data.source;
} else if (data.item || data.id) {
var item = data.item ? data.item : store.query('GET_ITEM', data.id);
event.file = item ? createItemAPI(item) : null;
}
// map all items in a possible items array
if (data.items) {
event.items = data.items.map(createItemAPI);
}
// if this is a progress event add the progress amount
if (/progress/.test(name)) {
event.progress = data.progress;
}
// copy relevant props
if (data.hasOwnProperty('origin') && data.hasOwnProperty('target')) {
event.origin = data.origin;
event.target = data.target;
}
return event;
};
};
var eventRoutes = {
DID_DESTROY: createEvent('destroy'),
DID_INIT: createEvent('init'),
DID_THROW_MAX_FILES: createEvent('warning'),
DID_INIT_ITEM: createEvent('initfile'),
DID_START_ITEM_LOAD: createEvent('addfilestart'),
DID_UPDATE_ITEM_LOAD_PROGRESS: createEvent('addfileprogress'),
DID_LOAD_ITEM: createEvent('addfile'),
DID_THROW_ITEM_INVALID: [createEvent('error'), createEvent('addfile')],
DID_THROW_ITEM_LOAD_ERROR: [createEvent('error'), createEvent('addfile')],
DID_THROW_ITEM_REMOVE_ERROR: [createEvent('error'), createEvent('removefile')],
DID_PREPARE_OUTPUT: createEvent('preparefile'),
DID_START_ITEM_PROCESSING: createEvent('processfilestart'),
DID_UPDATE_ITEM_PROCESS_PROGRESS: createEvent('processfileprogress'),
DID_ABORT_ITEM_PROCESSING: createEvent('processfileabort'),
DID_COMPLETE_ITEM_PROCESSING: createEvent('processfile'),
DID_COMPLETE_ITEM_PROCESSING_ALL: createEvent('processfiles'),
DID_REVERT_ITEM_PROCESSING: createEvent('processfilerevert'),
DID_THROW_ITEM_PROCESSING_ERROR: [createEvent('error'), createEvent('processfile')],
DID_REMOVE_ITEM: createEvent('removefile'),
DID_UPDATE_ITEMS: createEvent('updatefiles'),
DID_ACTIVATE_ITEM: createEvent('activatefile'),
DID_REORDER_ITEMS: createEvent('reorderfiles'),
};
var exposeEvent = function exposeEvent(event) {
// create event object to be dispatched
var detail = Object.assign({ pond: exports }, event);
delete detail.type;
view.element.dispatchEvent(
new CustomEvent('FilePond:' + event.type, {
// event info
detail: detail,
// event behaviour
bubbles: true,
cancelable: true,
composed: true, // triggers listeners outside of shadow root
})
);
// event object to params used for `on()` event handlers and callbacks `oninit()`
var params = [];
// if is possible error event, make it the first param
if (event.hasOwnProperty('error')) {
params.push(event.error);
}
// file is always section
if (event.hasOwnProperty('file')) {
params.push(event.file);
}
// append other props
var filtered = ['type', 'error', 'file'];
Object.keys(event)
.filter(function(key) {
return !filtered.includes(key);
})
.forEach(function(key) {
return params.push(event[key]);
});
// on(type, () => { })
exports.fire.apply(exports, [event.type].concat(params));
// oninit = () => {}
var handler = store.query('GET_ON' + event.type.toUpperCase());
if (handler) {
handler.apply(void 0, params);
}
};
var routeActionsToEvents = function routeActionsToEvents(actions) {
if (!actions.length) return;
actions
.filter(function(action) {
return eventRoutes[action.type];
})
.forEach(function(action) {
var routes = eventRoutes[action.type];
(Array.isArray(routes) ? routes : [routes]).forEach(function(route) {
// this isn't fantastic, but because of the stacking of settimeouts plugins can handle the did_load before the did_init
if (action.type === 'DID_INIT_ITEM') {
exposeEvent(route(action.data));
} else {
setTimeout(function() {
exposeEvent(route(action.data));
}, 0);
}
});
});
};
//
// PUBLIC API -------------------------------------------------------------------------------------
//
var setOptions = function setOptions(options) {
return store.dispatch('SET_OPTIONS', { options: options });
};
var getFile = function getFile(query) {
return store.query('GET_ACTIVE_ITEM', query);
};
var prepareFile = function prepareFile(query) {
return new Promise(function(resolve, reject) {
store.dispatch('REQUEST_ITEM_PREPARE', {
query: query,
success: function success(item) {
resolve(item);
},
failure: function failure(error) {
reject(error);
},
});
});
};
var addFile = function addFile(source) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new Promise(function(resolve, reject) {
addFiles([{ source: source, options: options }], { index: options.index })
.then(function(items) {
return resolve(items && items[0]);
})
.catch(reject);
});
};
var isFilePondFile = function isFilePondFile(obj) {
return obj.file && obj.id;
};
var removeFile = function removeFile(query, options) {
// if only passed options
if (typeof query === 'object' && !isFilePondFile(query) && !options) {
options = query;
query = undefined;
}
// request item removal
store.dispatch('REMOVE_ITEM', Object.assign({}, options, { query: query }));
// see if item has been removed
return store.query('GET_ACTIVE_ITEM', query) === null;
};
var addFiles = function addFiles() {
for (
var _len = arguments.length, args = new Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key];
}
return new Promise(function(resolve, reject) {
var sources = [];
var options = {};
// user passed a sources array
if (isArray(args[0])) {
sources.push.apply(sources, args[0]);
Object.assign(options, args[1] || {});
} else {
// user passed sources as arguments, last one might be options object
var lastArgument = args[args.length - 1];
if (typeof lastArgument === 'object' && !(lastArgument instanceof Blob)) {
Object.assign(options, args.pop());
}
// add rest to sources
sources.push.apply(sources, args);
}
store.dispatch('ADD_ITEMS', {
items: sources,
index: options.index,
interactionMethod: InteractionMethod.API,
success: resolve,
failure: reject,
});
});
};
var getFiles = function getFiles() {
return store.query('GET_ACTIVE_ITEMS');
};
var processFile = function processFile(query) {
return new Promise(function(resolve, reject) {
store.dispatch('REQUEST_ITEM_PROCESSING', {
query: query,
success: function success(item) {
resolve(item);
},
failure: function failure(error) {
reject(error);
},
});
});
};
var prepareFiles = function prepareFiles() {
for (
var _len2 = arguments.length, args = new Array(_len2), _key2 = 0;
_key2 < _len2;
_key2++
) {
args[_key2] = arguments[_key2];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
var items = queries.length ? queries : getFiles();
return Promise.all(items.map(prepareFile));
};
var processFiles = function processFiles() {
for (
var _len3 = arguments.length, args = new Array(_len3), _key3 = 0;
_key3 < _len3;
_key3++
) {
args[_key3] = arguments[_key3];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
if (!queries.length) {
var files = getFiles().filter(function(item) {
return (
!(item.status === ItemStatus.IDLE && item.origin === FileOrigin.LOCAL) &&
item.status !== ItemStatus.PROCESSING &&
item.status !== ItemStatus.PROCESSING_COMPLETE &&
item.status !== ItemStatus.PROCESSING_REVERT_ERROR
);
});
return Promise.all(files.map(processFile));
}
return Promise.all(queries.map(processFile));
};
var removeFiles = function removeFiles() {
for (
var _len4 = arguments.length, args = new Array(_len4), _key4 = 0;
_key4 < _len4;
_key4++
) {
args[_key4] = arguments[_key4];
}
var queries = Array.isArray(args[0]) ? args[0] : args;
var options;
if (typeof queries[queries.length - 1] === 'object') {
options = queries.pop();
} else if (Array.isArray(args[0])) {
options = args[1];
}
var files = getFiles();
if (!queries.length)
return Promise.all(
files.map(function(file) {
return removeFile(file, options);
})
);
// when removing by index the indexes shift after each file removal so we need to convert indexes to ids
var mappedQueries = queries
.map(function(query) {
return isNumber(query) ? (files[query] ? files[query].id : null) : query;
})
.filter(function(query) {
return query;
});
return mappedQueries.map(function(q) {
return removeFile(q, options);
});
};
var exports = Object.assign(
{},
on(),
{},
readWriteApi,
{},
createOptionAPI(store, defaultOptions),
{
/**
* Override options defined in options object
* @param options
*/
setOptions: setOptions,
/**
* Load the given file
* @param source - the source of the file (either a File, base64 data uri or url)
* @param options - object, { index: 0 }
*/
addFile: addFile,
/**
* Load the given files
* @param sources - the sources of the files to load
* @param options - object, { index: 0 }
*/
addFiles: addFiles,
/**
* Returns the file objects matching the given query
* @param query { string, number, null }
*/
getFile: getFile,
/**
* Upload file with given name
* @param query { string, number, null }
*/
processFile: processFile,
/**
* Request prepare output for file with given name
* @param query { string, number, null }
*/
prepareFile: prepareFile,
/**
* Removes a file by its name
* @param query { string, number, null }
*/
removeFile: removeFile,
/**
* Moves a file to a new location in the files list
*/
moveFile: function moveFile(query, index) {
return store.dispatch('MOVE_ITEM', { query: query, index: index });
},
/**
* Returns all files (wrapped in public api)
*/
getFiles: getFiles,
/**
* Starts uploading all files
*/
processFiles: processFiles,
/**
* Clears all files from the files list
*/
removeFiles: removeFiles,
/**
* Starts preparing output of all files
*/
prepareFiles: prepareFiles,
/**
* Sort list of files
*/
sort: function sort(compare) {
return store.dispatch('SORT', { compare: compare });
},
/**
* Browse the file system for a file
*/
browse: function browse() {
// needs to be trigger directly as user action needs to be traceable (is not traceable in requestAnimationFrame)
var input = view.element.querySelector('input[type=file]');
if (input) {
input.click();
}
},
/**
* Destroys the app
*/
destroy: function destroy() {
// request destruction
exports.fire('destroy', view.element);
// stop active processes (file uploads, fetches, stuff like that)
// loop over items and depending on states call abort for ongoing processes
store.dispatch('ABORT_ALL');
// destroy view
view._destroy();
// stop listening to resize
window.removeEventListener('resize', resizeHandler);
// stop listening to the visiblitychange event
document.removeEventListener('visibilitychange', visibilityHandler);
// dispatch destroy
store.dispatch('DID_DESTROY');
},
/**
* Inserts the plugin before the target element
*/
insertBefore: function insertBefore$1(element) {
return insertBefore(view.element, element);
},
/**
* Inserts the plugin after the target element
*/
insertAfter: function insertAfter$1(element) {
return insertAfter(view.element, element);
},
/**
* Appends the plugin to the target element
*/
appendTo: function appendTo(element) {
return element.appendChild(view.element);
},
/**
* Replaces an element with the app
*/
replaceElement: function replaceElement(element) {
// insert the app before the element
insertBefore(view.element, element);
// remove the original element
element.parentNode.removeChild(element);
// remember original element
originalElement = element;
},
/**
* Restores the original element
*/
restoreElement: function restoreElement() {
if (!originalElement) {
return; // no element to restore
}
// restore original element
insertAfter(originalElement, view.element);
// remove our element
view.element.parentNode.removeChild(view.element);
// remove reference
originalElement = null;
},
/**
* Returns true if the app root is attached to given element
* @param element
*/
isAttachedTo: function isAttachedTo(element) {
return view.element === element || originalElement === element;
},
/**
* Returns the root element
*/
element: {
get: function get() {
return view.element;
},
},
/**
* Returns the current pond status
*/
status: {
get: function get() {
return store.query('GET_STATUS');
},
},
}
);
// Done!
store.dispatch('DID_INIT');
// create actual api object
return createObject(exports);
};
var createAppObject = function createAppObject() {
var customOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
// default options
var defaultOptions = {};
forin(getOptions(), function(key, value) {
defaultOptions[key] = value[0];
});
// set app options
var app = createApp(
Object.assign(
{},
defaultOptions,
{},
customOptions
)
);
// return the plugin instance
return app;
};
var lowerCaseFirstLetter = function lowerCaseFirstLetter(string) {
return string.charAt(0).toLowerCase() + string.slice(1);
};
var attributeNameToPropertyName = function attributeNameToPropertyName(attributeName) {
return toCamels(attributeName.replace(/^data-/, ''));
};
var mapObject = function mapObject(object, propertyMap) {
// remove unwanted
forin(propertyMap, function(selector, mapping) {
forin(object, function(property, value) {
// create regexp shortcut
var selectorRegExp = new RegExp(selector);
// tests if
var matches = selectorRegExp.test(property);
// no match, skip
if (!matches) {
return;
}
// if there's a mapping, the original property is always removed
delete object[property];
// should only remove, we done!
if (mapping === false) {
return;
}
// move value to new property
if (isString(mapping)) {
object[mapping] = value;
return;
}
// move to group
var group = mapping.group;
if (isObject(mapping) && !object[group]) {
object[group] = {};
}
object[group][lowerCaseFirstLetter(property.replace(selectorRegExp, ''))] = value;
});
// do submapping
if (mapping.mapping) {
mapObject(object[mapping.group], mapping.mapping);
}
});
};
var getAttributesAsObject = function getAttributesAsObject(node) {
var attributeMapping =
arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// turn attributes into object
var attributes = [];
forin(node.attributes, function(index) {
attributes.push(node.attributes[index]);
});
var output = attributes
.filter(function(attribute) {
return attribute.name;
})
.reduce(function(obj, attribute) {
var value = attr(node, attribute.name);
obj[attributeNameToPropertyName(attribute.name)] =
value === attribute.name ? true : value;
return obj;
}, {});
// do mapping of object properties
mapObject(output, attributeMapping);
return output;
};
var createAppAtElement = function createAppAtElement(element) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
// how attributes of the input element are mapped to the options for the plugin
var attributeMapping = {
// translate to other name
'^class$': 'className',
'^multiple$': 'allowMultiple',
'^capture$': 'captureMethod',
'^webkitdirectory$': 'allowDirectoriesOnly',
// group under single property
'^server': {
group: 'server',
mapping: {
'^process': {
group: 'process',
},
'^revert': {
group: 'revert',
},
'^fetch': {
group: 'fetch',
},
'^restore': {
group: 'restore',
},
'^load': {
group: 'load',
},
},
},
// don't include in object
'^type$': false,
'^files$': false,
};
// add additional option translators
applyFilters('SET_ATTRIBUTE_TO_OPTION_MAP', attributeMapping);
// create final options object by setting options object and then overriding options supplied on element
var mergedOptions = Object.assign({}, options);
var attributeOptions = getAttributesAsObject(
element.nodeName === 'FIELDSET' ? element.querySelector('input[type=file]') : element,
attributeMapping
);
// merge with options object
Object.keys(attributeOptions).forEach(function(key) {
if (isObject(attributeOptions[key])) {
if (!isObject(mergedOptions[key])) {
mergedOptions[key] = {};
}
Object.assign(mergedOptions[key], attributeOptions[key]);
} else {
mergedOptions[key] = attributeOptions[key];
}
});
// if parent is a fieldset, get files from parent by selecting all input fields that are not file upload fields
// these will then be automatically set to the initial files
mergedOptions.files = (options.files || []).concat(
Array.from(element.querySelectorAll('input:not([type=file])')).map(function(input) {
return {
source: input.value,
options: {
type: input.dataset.type,
},
};
})
);
// build plugin
var app = createAppObject(mergedOptions);
// add already selected files
if (element.files) {
Array.from(element.files).forEach(function(file) {
app.addFile(file);
});
}
// replace the target element
app.replaceElement(element);
// expose
return app;
};
// if an element is passed, we create the instance at that element, if not, we just create an up object
var createApp$1 = function createApp() {
return isNode(arguments.length <= 0 ? undefined : arguments[0])
? createAppAtElement.apply(void 0, arguments)
: createAppObject.apply(void 0, arguments);
};
var PRIVATE_METHODS = ['fire', '_read', '_write'];
var createAppAPI = function createAppAPI(app) {
var api = {};
copyObjectPropertiesToObject(app, api, PRIVATE_METHODS);
return api;
};
/**
* Replaces placeholders in given string with replacements
* @param string - "Foo {bar}""
* @param replacements - { "bar": 10 }
*/
var replaceInString = function replaceInString(string, replacements) {
return string.replace(/(?:{([a-zA-Z]+)})/g, function(match, group) {
return replacements[group];
});
};
var createWorker = function createWorker(fn) {
var workerBlob = new Blob(['(', fn.toString(), ')()'], {
type: 'application/javascript',
});
var workerURL = URL.createObjectURL(workerBlob);
var worker = new Worker(workerURL);
return {
transfer: function transfer(message, cb) {},
post: function post(message, cb, transferList) {
var id = getUniqueId();
worker.onmessage = function(e) {
if (e.data.id === id) {
cb(e.data.message);
}
};
worker.postMessage(
{
id: id,
message: message,
},
transferList
);
},
terminate: function terminate() {
worker.terminate();
URL.revokeObjectURL(workerURL);
},
};
};
var loadImage = function loadImage(url) {
return new Promise(function(resolve, reject) {
var img = new Image();
img.onload = function() {
resolve(img);
};
img.onerror = function(e) {
reject(e);
};
img.src = url;
});
};
var renameFile = function renameFile(file, name) {
var renamedFile = file.slice(0, file.size, file.type);
renamedFile.lastModifiedDate = file.lastModifiedDate;
renamedFile.name = name;
return renamedFile;
};
var copyFile = function copyFile(file) {
return renameFile(file, file.name);
};
// already registered plugins (can't register twice)
var registeredPlugins = [];
// pass utils to plugin
var createAppPlugin = function createAppPlugin(plugin) {
// already registered
if (registeredPlugins.includes(plugin)) {
return;
}
// remember this plugin
registeredPlugins.push(plugin);
// setup!
var pluginOutline = plugin({
addFilter: addFilter,
utils: {
Type: Type,
forin: forin,
isString: isString,
isFile: isFile,
toNaturalFileSize: toNaturalFileSize,
replaceInString: replaceInString,
getExtensionFromFilename: getExtensionFromFilename,
getFilenameWithoutExtension: getFilenameWithoutExtension,
guesstimateMimeType: guesstimateMimeType,
getFileFromBlob: getFileFromBlob,
getFilenameFromURL: getFilenameFromURL,
createRoute: createRoute,
createWorker: createWorker,
createView: createView,
createItemAPI: createItemAPI,
loadImage: loadImage,
copyFile: copyFile,
renameFile: renameFile,
createBlob: createBlob,
applyFilterChain: applyFilterChain,
text: text,
getNumericAspectRatioFromString: getNumericAspectRatioFromString,
},
views: {
fileActionButton: fileActionButton,
},
});
// add plugin options to default options
extendDefaultOptions(pluginOutline.options);
};
// feature detection used by supported() method
var isOperaMini = function isOperaMini() {
return Object.prototype.toString.call(window.operamini) === '[object OperaMini]';
};
var hasPromises = function hasPromises() {
return 'Promise' in window;
};
var hasBlobSlice = function hasBlobSlice() {
return 'slice' in Blob.prototype;
};
var hasCreateObjectURL = function hasCreateObjectURL() {
return 'URL' in window && 'createObjectURL' in window.URL;
};
var hasVisibility = function hasVisibility() {
return 'visibilityState' in document;
};
var hasTiming = function hasTiming() {
return 'performance' in window;
}; // iOS 8.x
var hasCSSSupports = function hasCSSSupports() {
return 'supports' in (window.CSS || {});
}; // use to detect Safari 9+
var isIE11 = function isIE11() {
return /MSIE|Trident/.test(window.navigator.userAgent);
};
var supported = (function() {
// Runs immediately and then remembers result for subsequent calls
var isSupported =
// Has to be a browser
isBrowser() &&
// Can't run on Opera Mini due to lack of everything
!isOperaMini() &&
// Require these APIs to feature detect a modern browser
hasVisibility() &&
hasPromises() &&
hasBlobSlice() &&
hasCreateObjectURL() &&
hasTiming() &&
// doesn't need CSSSupports but is a good way to detect Safari 9+ (we do want to support IE11 though)
(hasCSSSupports() || isIE11());
return function() {
return isSupported;
};
})();
/**
* Plugin internal state (over all instances)
*/
var state = {
// active app instances, used to redraw the apps and to find the later
apps: [],
};
// plugin name
var name = 'filepond';
/**
* Public Plugin methods
*/
var fn = function fn() {};
exports.Status = {};
exports.FileStatus = {};
exports.FileOrigin = {};
exports.OptionTypes = {};
exports.create = fn;
exports.destroy = fn;
exports.parse = fn;
exports.find = fn;
exports.registerPlugin = fn;
exports.getOptions = fn;
exports.setOptions = fn;
// if not supported, no API
if (supported()) {
// start painter and fire load event
createPainter(
function() {
state.apps.forEach(function(app) {
return app._read();
});
},
function(ts) {
state.apps.forEach(function(app) {
return app._write(ts);
});
}
);
// fire loaded event so we know when FilePond is available
var dispatch = function dispatch() {
// let others know we have area ready
document.dispatchEvent(
new CustomEvent('FilePond:loaded', {
detail: {
supported: supported,
create: exports.create,
destroy: exports.destroy,
parse: exports.parse,
find: exports.find,
registerPlugin: exports.registerPlugin,
setOptions: exports.setOptions,
},
})
);
// clean up event
document.removeEventListener('DOMContentLoaded', dispatch);
};
if (document.readyState !== 'loading') {
// move to back of execution queue, FilePond should have been exported by then
setTimeout(function() {
return dispatch();
}, 0);
} else {
document.addEventListener('DOMContentLoaded', dispatch);
}
// updates the OptionTypes object based on the current options
var updateOptionTypes = function updateOptionTypes() {
return forin(getOptions(), function(key, value) {
exports.OptionTypes[key] = value[1];
});
};
exports.Status = Object.assign({}, Status);
exports.FileOrigin = Object.assign({}, FileOrigin);
exports.FileStatus = Object.assign({}, ItemStatus);
exports.OptionTypes = {};
updateOptionTypes();
// create method, creates apps and adds them to the app array
exports.create = function create() {
var app = createApp$1.apply(void 0, arguments);
app.on('destroy', exports.destroy);
state.apps.push(app);
return createAppAPI(app);
};
// destroys apps and removes them from the app array
exports.destroy = function destroy(hook) {
// returns true if the app was destroyed successfully
var indexToRemove = state.apps.findIndex(function(app) {
return app.isAttachedTo(hook);
});
if (indexToRemove >= 0) {
// remove from apps
var app = state.apps.splice(indexToRemove, 1)[0];
// restore original dom element
app.restoreElement();
return true;
}
return false;
};
// parses the given context for plugins (does not include the context element itself)
exports.parse = function parse(context) {
// get all possible hooks
var matchedHooks = Array.from(context.querySelectorAll('.' + name));
// filter out already active hooks
var newHooks = matchedHooks.filter(function(newHook) {
return !state.apps.find(function(app) {
return app.isAttachedTo(newHook);
});
});
// create new instance for each hook
return newHooks.map(function(hook) {
return exports.create(hook);
});
};
// returns an app based on the given element hook
exports.find = function find(hook) {
var app = state.apps.find(function(app) {
return app.isAttachedTo(hook);
});
if (!app) {
return null;
}
return createAppAPI(app);
};
// adds a plugin extension
exports.registerPlugin = function registerPlugin() {
for (
var _len = arguments.length, plugins = new Array(_len), _key = 0;
_key < _len;
_key++
) {
plugins[_key] = arguments[_key];
}
// register plugins
plugins.forEach(createAppPlugin);
// update OptionTypes, each plugin might have extended the default options
updateOptionTypes();
};
exports.getOptions = function getOptions$1() {
var opts = {};
forin(getOptions(), function(key, value) {
opts[key] = value[0];
});
return opts;
};
exports.setOptions = function setOptions$1(opts) {
if (isObject(opts)) {
// update existing plugins
state.apps.forEach(function(app) {
app.setOptions(opts);
});
// override defaults
setOptions(opts);
}
// return new options
return exports.getOptions();
};
}
exports.supported = supported;
Object.defineProperty(exports, '__esModule', { value: true });
});
|
import"./chunk-1fafdf15.js";import"./helpers.js";import"./chunk-953eb524.js";import"./chunk-36c7966f.js";import"./chunk-1f5e2a99.js";import{r as registerComponent,u as use}from"./chunk-cca88db8.js";import"./chunk-ed52317d.js";import"./chunk-ade7667b.js";import"./chunk-f1608931.js";import"./chunk-42f463e6.js";import"./chunk-0d253c8b.js";import"./chunk-63dd07b4.js";import"./chunk-c8fb60ff.js";import{T as Timepicker}from"./chunk-95ac44e5.js";export{T as BTimepicker}from"./chunk-95ac44e5.js";var Plugin={install:function(r){registerComponent(r,Timepicker)}};use(Plugin);export default Plugin; |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vega'), require('vega-lite')) :
typeof define === 'function' && define.amd ? define(['vega', 'vega-lite'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.vegaEmbed = factory(global.vega, global.vegaLite));
})(this, (function (vegaImport, vegaLiteImport) { 'use strict';
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var vegaImport__namespace = /*#__PURE__*/_interopNamespace(vegaImport);
var vegaLiteImport__namespace = /*#__PURE__*/_interopNamespace(vegaLiteImport);
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017 Joachim Wester
* MIT license
*/
var __extends = undefined && undefined.__extends || function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || {
__proto__: []
} instanceof Array && function (d, b) {
d.__proto__ = b;
} || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
}();
var _hasOwnProperty = Object.prototype.hasOwnProperty;
function hasOwnProperty(obj, key) {
return _hasOwnProperty.call(obj, key);
}
function _objectKeys(obj) {
if (Array.isArray(obj)) {
var keys = new Array(obj.length);
for (var k = 0; k < keys.length; k++) {
keys[k] = "" + k;
}
return keys;
}
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var i in obj) {
if (hasOwnProperty(obj, i)) {
keys.push(i);
}
}
return keys;
}
/**
* Deeply clone the object.
* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy)
* @param {any} obj value to clone
* @return {any} cloned obj
*/
function _deepClone(obj) {
switch (typeof obj) {
case "object":
return JSON.parse(JSON.stringify(obj));
//Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
case "undefined":
return null;
//this is how JSON.stringify behaves for array items
default:
return obj;
//no need to clone primitives
}
} //3x faster than cached /^\d+$/.test(str)
function isInteger(str) {
var i = 0;
var len = str.length;
var charCode;
while (i < len) {
charCode = str.charCodeAt(i);
if (charCode >= 48 && charCode <= 57) {
i++;
continue;
}
return false;
}
return true;
}
/**
* Escapes a json pointer path
* @param path The raw pointer
* @return the Escaped path
*/
function escapePathComponent(path) {
if (path.indexOf('/') === -1 && path.indexOf('~') === -1) return path;
return path.replace(/~/g, '~0').replace(/\//g, '~1');
}
/**
* Unescapes a json pointer path
* @param path The escaped pointer
* @return The unescaped path
*/
function unescapePathComponent(path) {
return path.replace(/~1/g, '/').replace(/~0/g, '~');
}
/**
* Recursively checks whether an object has any undefined values inside.
*/
function hasUndefined(obj) {
if (obj === undefined) {
return true;
}
if (obj) {
if (Array.isArray(obj)) {
for (var i = 0, len = obj.length; i < len; i++) {
if (hasUndefined(obj[i])) {
return true;
}
}
} else if (typeof obj === "object") {
var objKeys = _objectKeys(obj);
var objKeysLength = objKeys.length;
for (var i = 0; i < objKeysLength; i++) {
if (hasUndefined(obj[objKeys[i]])) {
return true;
}
}
}
}
return false;
}
function patchErrorMessageFormatter(message, args) {
var messageParts = [message];
for (var key in args) {
var value = typeof args[key] === 'object' ? JSON.stringify(args[key], null, 2) : args[key]; // pretty print
if (typeof value !== 'undefined') {
messageParts.push(key + ": " + value);
}
}
return messageParts.join('\n');
}
var PatchError = function (_super) {
__extends(PatchError, _super);
function PatchError(message, name, index, operation, tree) {
var _newTarget = this.constructor;
var _this = _super.call(this, patchErrorMessageFormatter(message, {
name: name,
index: index,
operation: operation,
tree: tree
})) || this;
_this.name = name;
_this.index = index;
_this.operation = operation;
_this.tree = tree;
Object.setPrototypeOf(_this, _newTarget.prototype); // restore prototype chain, see https://stackoverflow.com/a/48342359
_this.message = patchErrorMessageFormatter(message, {
name: name,
index: index,
operation: operation,
tree: tree
});
return _this;
}
return PatchError;
}(Error);
var JsonPatchError = PatchError;
var deepClone = _deepClone;
/* We use a Javascript hash to store each
function. Each hash entry (property) uses
the operation identifiers specified in rfc6902.
In this way, we can map each patch operation
to its dedicated function in efficient way.
*/
/* The operations applicable to an object */
var objOps = {
add: function (obj, key, document) {
obj[key] = this.value;
return {
newDocument: document
};
},
remove: function (obj, key, document) {
var removed = obj[key];
delete obj[key];
return {
newDocument: document,
removed: removed
};
},
replace: function (obj, key, document) {
var removed = obj[key];
obj[key] = this.value;
return {
newDocument: document,
removed: removed
};
},
move: function (obj, key, document) {
/* in case move target overwrites an existing value,
return the removed value, this can be taxing performance-wise,
and is potentially unneeded */
var removed = getValueByPointer(document, this.path);
if (removed) {
removed = _deepClone(removed);
}
var originalValue = applyOperation(document, {
op: "remove",
path: this.from
}).removed;
applyOperation(document, {
op: "add",
path: this.path,
value: originalValue
});
return {
newDocument: document,
removed: removed
};
},
copy: function (obj, key, document) {
var valueToCopy = getValueByPointer(document, this.from); // enforce copy by value so further operations don't affect source (see issue #177)
applyOperation(document, {
op: "add",
path: this.path,
value: _deepClone(valueToCopy)
});
return {
newDocument: document
};
},
test: function (obj, key, document) {
return {
newDocument: document,
test: _areEquals(obj[key], this.value)
};
},
_get: function (obj, key, document) {
this.value = obj[key];
return {
newDocument: document
};
}
};
/* The operations applicable to an array. Many are the same as for the object */
var arrOps = {
add: function (arr, i, document) {
if (isInteger(i)) {
arr.splice(i, 0, this.value);
} else {
// array props
arr[i] = this.value;
} // this may be needed when using '-' in an array
return {
newDocument: document,
index: i
};
},
remove: function (arr, i, document) {
var removedList = arr.splice(i, 1);
return {
newDocument: document,
removed: removedList[0]
};
},
replace: function (arr, i, document) {
var removed = arr[i];
arr[i] = this.value;
return {
newDocument: document,
removed: removed
};
},
move: objOps.move,
copy: objOps.copy,
test: objOps.test,
_get: objOps._get
};
/**
* Retrieves a value from a JSON document by a JSON pointer.
* Returns the value.
*
* @param document The document to get the value from
* @param pointer an escaped JSON pointer
* @return The retrieved value
*/
function getValueByPointer(document, pointer) {
if (pointer == '') {
return document;
}
var getOriginalDestination = {
op: "_get",
path: pointer
};
applyOperation(document, getOriginalDestination);
return getOriginalDestination.value;
}
/**
* Apply a single JSON Patch Operation on a JSON document.
* Returns the {newDocument, result} of the operation.
* It modifies the `document` and `operation` objects - it gets the values by reference.
* If you would like to avoid touching your values, clone them:
* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`.
*
* @param document The document to patch
* @param operation The operation to apply
* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
* @param mutateDocument Whether to mutate the original document or clone it before applying
* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
* @return `{newDocument, result}` after the operation
*/
function applyOperation(document, operation, validateOperation, mutateDocument, banPrototypeModifications, index) {
if (validateOperation === void 0) {
validateOperation = false;
}
if (mutateDocument === void 0) {
mutateDocument = true;
}
if (banPrototypeModifications === void 0) {
banPrototypeModifications = true;
}
if (index === void 0) {
index = 0;
}
if (validateOperation) {
if (typeof validateOperation == 'function') {
validateOperation(operation, 0, document, operation.path);
} else {
validator(operation, 0);
}
}
/* ROOT OPERATIONS */
if (operation.path === "") {
var returnValue = {
newDocument: document
};
if (operation.op === 'add') {
returnValue.newDocument = operation.value;
return returnValue;
} else if (operation.op === 'replace') {
returnValue.newDocument = operation.value;
returnValue.removed = document; //document we removed
return returnValue;
} else if (operation.op === 'move' || operation.op === 'copy') {
// it's a move or copy to root
returnValue.newDocument = getValueByPointer(document, operation.from); // get the value by json-pointer in `from` field
if (operation.op === 'move') {
// report removed item
returnValue.removed = document;
}
return returnValue;
} else if (operation.op === 'test') {
returnValue.test = _areEquals(document, operation.value);
if (returnValue.test === false) {
throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
}
returnValue.newDocument = document;
return returnValue;
} else if (operation.op === 'remove') {
// a remove on root
returnValue.removed = document;
returnValue.newDocument = null;
return returnValue;
} else if (operation.op === '_get') {
operation.value = document;
return returnValue;
} else {
/* bad operation */
if (validateOperation) {
throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
} else {
return returnValue;
}
}
}
/* END ROOT OPERATIONS */
else {
if (!mutateDocument) {
document = _deepClone(document);
}
var path = operation.path || "";
var keys = path.split('/');
var obj = document;
var t = 1; //skip empty element - http://jsperf.com/to-shift-or-not-to-shift
var len = keys.length;
var existingPathFragment = undefined;
var key = void 0;
var validateFunction = void 0;
if (typeof validateOperation == 'function') {
validateFunction = validateOperation;
} else {
validateFunction = validator;
}
while (true) {
key = keys[t];
if (key && key.indexOf('~') != -1) {
key = unescapePathComponent(key);
}
if (banPrototypeModifications && key == '__proto__') {
throw new TypeError('JSON-Patch: modifying `__proto__` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README');
}
if (validateOperation) {
if (existingPathFragment === undefined) {
if (obj[key] === undefined) {
existingPathFragment = keys.slice(0, t).join('/');
} else if (t == len - 1) {
existingPathFragment = operation.path;
}
if (existingPathFragment !== undefined) {
validateFunction(operation, 0, document, existingPathFragment);
}
}
}
t++;
if (Array.isArray(obj)) {
if (key === '-') {
key = obj.length;
} else {
if (validateOperation && !isInteger(key)) {
throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document);
} // only parse key when it's an integer for `arr.prop` to work
else if (isInteger(key)) {
key = ~~key;
}
}
if (t >= len) {
if (validateOperation && operation.op === "add" && key > obj.length) {
throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document);
}
var returnValue = arrOps[operation.op].call(operation, obj, key, document); // Apply patch
if (returnValue.test === false) {
throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
}
return returnValue;
}
} else {
if (t >= len) {
var returnValue = objOps[operation.op].call(operation, obj, key, document); // Apply patch
if (returnValue.test === false) {
throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
}
return returnValue;
}
}
obj = obj[key]; // If we have more keys in the path, but the next value isn't a non-null object,
// throw an OPERATION_PATH_UNRESOLVABLE error instead of iterating again.
if (validateOperation && t < len && (!obj || typeof obj !== "object")) {
throw new JsonPatchError('Cannot perform operation at the desired path', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
}
}
}
}
/**
* Apply a full JSON Patch array on a JSON document.
* Returns the {newDocument, result} of the patch.
* It modifies the `document` object and `patch` - it gets the values by reference.
* If you would like to avoid touching your values, clone them:
* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`.
*
* @param document The document to patch
* @param patch The patch to apply
* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation.
* @param mutateDocument Whether to mutate the original document or clone it before applying
* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`.
* @return An array of `{newDocument, result}` after the patch
*/
function applyPatch(document, patch, validateOperation, mutateDocument, banPrototypeModifications) {
if (mutateDocument === void 0) {
mutateDocument = true;
}
if (banPrototypeModifications === void 0) {
banPrototypeModifications = true;
}
if (validateOperation) {
if (!Array.isArray(patch)) {
throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
}
}
if (!mutateDocument) {
document = _deepClone(document);
}
var results = new Array(patch.length);
for (var i = 0, length_1 = patch.length; i < length_1; i++) {
// we don't need to pass mutateDocument argument because if it was true, we already deep cloned the object, we'll just pass `true`
results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i);
document = results[i].newDocument; // in case root was replaced
}
results.newDocument = document;
return results;
}
/**
* Apply a single JSON Patch Operation on a JSON document.
* Returns the updated document.
* Suitable as a reducer.
*
* @param document The document to patch
* @param operation The operation to apply
* @return The updated document
*/
function applyReducer(document, operation, index) {
var operationResult = applyOperation(document, operation);
if (operationResult.test === false) {
// failed test
throw new JsonPatchError("Test operation failed", 'TEST_OPERATION_FAILED', index, operation, document);
}
return operationResult.newDocument;
}
/**
* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error.
* @param {object} operation - operation object (patch)
* @param {number} index - index of operation in the sequence
* @param {object} [document] - object where the operation is supposed to be applied
* @param {string} [existingPathFragment] - comes along with `document`
*/
function validator(operation, index, document, existingPathFragment) {
if (typeof operation !== 'object' || operation === null || Array.isArray(operation)) {
throw new JsonPatchError('Operation is not an object', 'OPERATION_NOT_AN_OBJECT', index, operation, document);
} else if (!objOps[operation.op]) {
throw new JsonPatchError('Operation `op` property is not one of operations defined in RFC-6902', 'OPERATION_OP_INVALID', index, operation, document);
} else if (typeof operation.path !== 'string') {
throw new JsonPatchError('Operation `path` property is not a string', 'OPERATION_PATH_INVALID', index, operation, document);
} else if (operation.path.indexOf('/') !== 0 && operation.path.length > 0) {
// paths that aren't empty string should start with "/"
throw new JsonPatchError('Operation `path` property must start with "/"', 'OPERATION_PATH_INVALID', index, operation, document);
} else if ((operation.op === 'move' || operation.op === 'copy') && typeof operation.from !== 'string') {
throw new JsonPatchError('Operation `from` property is not present (applicable in `move` and `copy` operations)', 'OPERATION_FROM_REQUIRED', index, operation, document);
} else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && operation.value === undefined) {
throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_REQUIRED', index, operation, document);
} else if ((operation.op === 'add' || operation.op === 'replace' || operation.op === 'test') && hasUndefined(operation.value)) {
throw new JsonPatchError('Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)', 'OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED', index, operation, document);
} else if (document) {
if (operation.op == "add") {
var pathLen = operation.path.split("/").length;
var existingPathLen = existingPathFragment.split("/").length;
if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) {
throw new JsonPatchError('Cannot perform an `add` operation at the desired path', 'OPERATION_PATH_CANNOT_ADD', index, operation, document);
}
} else if (operation.op === 'replace' || operation.op === 'remove' || operation.op === '_get') {
if (operation.path !== existingPathFragment) {
throw new JsonPatchError('Cannot perform the operation at a path that does not exist', 'OPERATION_PATH_UNRESOLVABLE', index, operation, document);
}
} else if (operation.op === 'move' || operation.op === 'copy') {
var existingValue = {
op: "_get",
path: operation.from,
value: undefined
};
var error = validate([existingValue], document);
if (error && error.name === 'OPERATION_PATH_UNRESOLVABLE') {
throw new JsonPatchError('Cannot perform the operation from a path that does not exist', 'OPERATION_FROM_UNRESOLVABLE', index, operation, document);
}
}
}
}
/**
* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document.
* If error is encountered, returns a JsonPatchError object
* @param sequence
* @param document
* @returns {JsonPatchError|undefined}
*/
function validate(sequence, document, externalValidator) {
try {
if (!Array.isArray(sequence)) {
throw new JsonPatchError('Patch sequence must be an array', 'SEQUENCE_NOT_AN_ARRAY');
}
if (document) {
//clone document and sequence so that we can safely try applying operations
applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true);
} else {
externalValidator = externalValidator || validator;
for (var i = 0; i < sequence.length; i++) {
externalValidator(sequence[i], i, document, undefined);
}
}
} catch (e) {
if (e instanceof JsonPatchError) {
return e;
} else {
throw e;
}
}
} // based on https://github.com/epoberezkin/fast-deep-equal
// MIT License
// Copyright (c) 2017 Evgeny Poberezkin
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
function _areEquals(a, b) {
if (a === b) return true;
if (a && b && typeof a == 'object' && typeof b == 'object') {
var arrA = Array.isArray(a),
arrB = Array.isArray(b),
i,
length,
key;
if (arrA && arrB) {
length = a.length;
if (length != b.length) return false;
for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false;
return true;
}
if (arrA != arrB) return false;
var keys = Object.keys(a);
length = keys.length;
if (length !== Object.keys(b).length) return false;
for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false;
for (i = length; i-- !== 0;) {
key = keys[i];
if (!_areEquals(a[key], b[key])) return false;
}
return true;
}
return a !== a && b !== b;
}
var core = /*#__PURE__*/Object.freeze({
__proto__: null,
JsonPatchError: JsonPatchError,
deepClone: deepClone,
getValueByPointer: getValueByPointer,
applyOperation: applyOperation,
applyPatch: applyPatch,
applyReducer: applyReducer,
validator: validator,
validate: validate,
_areEquals: _areEquals
});
/*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017 Joachim Wester
* MIT license
*/
var beforeDict = new WeakMap();
var Mirror = function () {
function Mirror(obj) {
this.observers = new Map();
this.obj = obj;
}
return Mirror;
}();
var ObserverInfo = function () {
function ObserverInfo(callback, observer) {
this.callback = callback;
this.observer = observer;
}
return ObserverInfo;
}();
function getMirror(obj) {
return beforeDict.get(obj);
}
function getObserverFromMirror(mirror, callback) {
return mirror.observers.get(callback);
}
function removeObserverFromMirror(mirror, observer) {
mirror.observers.delete(observer.callback);
}
/**
* Detach an observer from an object
*/
function unobserve(root, observer) {
observer.unobserve();
}
/**
* Observes changes made to an object, which can then be retrieved using generate
*/
function observe(obj, callback) {
var patches = [];
var observer;
var mirror = getMirror(obj);
if (!mirror) {
mirror = new Mirror(obj);
beforeDict.set(obj, mirror);
} else {
var observerInfo = getObserverFromMirror(mirror, callback);
observer = observerInfo && observerInfo.observer;
}
if (observer) {
return observer;
}
observer = {};
mirror.value = _deepClone(obj);
if (callback) {
observer.callback = callback;
observer.next = null;
var dirtyCheck = function () {
generate(observer);
};
var fastCheck = function () {
clearTimeout(observer.next);
observer.next = setTimeout(dirtyCheck);
};
if (typeof window !== 'undefined') {
//not Node
window.addEventListener('mouseup', fastCheck);
window.addEventListener('keyup', fastCheck);
window.addEventListener('mousedown', fastCheck);
window.addEventListener('keydown', fastCheck);
window.addEventListener('change', fastCheck);
}
}
observer.patches = patches;
observer.object = obj;
observer.unobserve = function () {
generate(observer);
clearTimeout(observer.next);
removeObserverFromMirror(mirror, observer);
if (typeof window !== 'undefined') {
window.removeEventListener('mouseup', fastCheck);
window.removeEventListener('keyup', fastCheck);
window.removeEventListener('mousedown', fastCheck);
window.removeEventListener('keydown', fastCheck);
window.removeEventListener('change', fastCheck);
}
};
mirror.observers.set(callback, new ObserverInfo(callback, observer));
return observer;
}
/**
* Generate an array of patches from an observer
*/
function generate(observer, invertible) {
if (invertible === void 0) {
invertible = false;
}
var mirror = beforeDict.get(observer.object);
_generate(mirror.value, observer.object, observer.patches, "", invertible);
if (observer.patches.length) {
applyPatch(mirror.value, observer.patches);
}
var temp = observer.patches;
if (temp.length > 0) {
observer.patches = [];
if (observer.callback) {
observer.callback(temp);
}
}
return temp;
} // Dirty check if obj is different from mirror, generate patches and update mirror
function _generate(mirror, obj, patches, path, invertible) {
if (obj === mirror) {
return;
}
if (typeof obj.toJSON === "function") {
obj = obj.toJSON();
}
var newKeys = _objectKeys(obj);
var oldKeys = _objectKeys(mirror);
var deleted = false; //if ever "move" operation is implemented here, make sure this test runs OK: "should not generate the same patch twice (move)"
for (var t = oldKeys.length - 1; t >= 0; t--) {
var key = oldKeys[t];
var oldVal = mirror[key];
if (hasOwnProperty(obj, key) && !(obj[key] === undefined && oldVal !== undefined && Array.isArray(obj) === false)) {
var newVal = obj[key];
if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) {
_generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible);
} else {
if (oldVal !== newVal) {
if (invertible) {
patches.push({
op: "test",
path: path + "/" + escapePathComponent(key),
value: _deepClone(oldVal)
});
}
patches.push({
op: "replace",
path: path + "/" + escapePathComponent(key),
value: _deepClone(newVal)
});
}
}
} else if (Array.isArray(mirror) === Array.isArray(obj)) {
if (invertible) {
patches.push({
op: "test",
path: path + "/" + escapePathComponent(key),
value: _deepClone(oldVal)
});
}
patches.push({
op: "remove",
path: path + "/" + escapePathComponent(key)
});
deleted = true; // property has been deleted
} else {
if (invertible) {
patches.push({
op: "test",
path: path,
value: mirror
});
}
patches.push({
op: "replace",
path: path,
value: obj
});
}
}
if (!deleted && newKeys.length == oldKeys.length) {
return;
}
for (var t = 0; t < newKeys.length; t++) {
var key = newKeys[t];
if (!hasOwnProperty(mirror, key) && obj[key] !== undefined) {
patches.push({
op: "add",
path: path + "/" + escapePathComponent(key),
value: _deepClone(obj[key])
});
}
}
}
/**
* Create an array of patches from the differences in two objects
*/
function compare$b(tree1, tree2, invertible) {
if (invertible === void 0) {
invertible = false;
}
var patches = [];
_generate(tree1, tree2, patches, '', invertible);
return patches;
}
var duplex = /*#__PURE__*/Object.freeze({
__proto__: null,
unobserve: unobserve,
observe: observe,
generate: generate,
compare: compare$b
});
Object.assign({}, core, duplex, {
JsonPatchError: PatchError,
deepClone: _deepClone,
escapePathComponent,
unescapePathComponent
});
// working on the output of `JSON.stringify` we know that only valid strings
// are present (unless the user supplied a weird `options.indent` but in
// that case we don’t care since the output would be invalid anyway).
var stringOrChar = /("(?:[^\\"]|\\.)*")|[:,]/g;
var jsonStringifyPrettyCompact = function stringify(passedObj, options) {
var indent, maxLength, replacer;
options = options || {};
indent = JSON.stringify([1], undefined, options.indent === undefined ? 2 : options.indent).slice(2, -3);
maxLength = indent === "" ? Infinity : options.maxLength === undefined ? 80 : options.maxLength;
replacer = options.replacer;
return function _stringify(obj, currentIndent, reserved) {
// prettier-ignore
var end, index, items, key, keyPart, keys, length, nextIndent, prettified, start, string, value;
if (obj && typeof obj.toJSON === "function") {
obj = obj.toJSON();
}
string = JSON.stringify(obj, replacer);
if (string === undefined) {
return string;
}
length = maxLength - currentIndent.length - reserved;
if (string.length <= length) {
prettified = string.replace(stringOrChar, function (match, stringLiteral) {
return stringLiteral || match + " ";
});
if (prettified.length <= length) {
return prettified;
}
}
if (replacer != null) {
obj = JSON.parse(string);
replacer = undefined;
}
if (typeof obj === "object" && obj !== null) {
nextIndent = currentIndent + indent;
items = [];
index = 0;
if (Array.isArray(obj)) {
start = "[";
end = "]";
length = obj.length;
for (; index < length; index++) {
items.push(_stringify(obj[index], nextIndent, index === length - 1 ? 0 : 1) || "null");
}
} else {
start = "{";
end = "}";
keys = Object.keys(obj);
length = keys.length;
for (; index < length; index++) {
key = keys[index];
keyPart = JSON.stringify(key) + ": ";
value = _stringify(obj[key], nextIndent, keyPart.length + (index === length - 1 ? 0 : 1));
if (value !== undefined) {
items.push(keyPart + value);
}
}
}
if (items.length > 0) {
return [start, indent + items.join(",\n" + nextIndent), end].join("\n" + currentIndent);
}
}
return string;
}(passedObj, "", 0);
};
var re$5 = {exports: {}};
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0';
const MAX_LENGTH$2 = 256;
const MAX_SAFE_INTEGER$1 = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */
9007199254740991; // Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16;
var constants = {
SEMVER_SPEC_VERSION,
MAX_LENGTH: MAX_LENGTH$2,
MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1,
MAX_SAFE_COMPONENT_LENGTH
};
const debug$3 = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {};
var debug_1 = debug$3;
(function (module, exports) {
const {
MAX_SAFE_COMPONENT_LENGTH
} = constants;
const debug = debug_1;
exports = module.exports = {}; // The actual regexps go on exports.re
const re = exports.re = [];
const src = exports.src = [];
const t = exports.t = {};
let R = 0;
const createToken = (name, value, isGlobal) => {
const index = R++;
debug(index, value);
t[name] = index;
src[index] = value;
re[index] = new RegExp(value, isGlobal ? 'g' : undefined);
}; // The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*');
createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`);
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`);
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`);
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`);
createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`);
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`);
createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`);
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`);
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`);
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`);
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`);
createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)');
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true);
exports.tildeTrimReplace = '$1~';
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`);
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)');
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true);
exports.caretTrimReplace = '$1^';
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`);
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`);
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true);
exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`);
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$');
createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$');
})(re$5, re$5.exports);
// obj with keys in a consistent order.
const opts = ['includePrerelease', 'loose', 'rtl'];
const parseOptions$4 = options => !options ? {} : typeof options !== 'object' ? {
loose: true
} : opts.filter(k => options[k]).reduce((options, k) => {
options[k] = true;
return options;
}, {});
var parseOptions_1 = parseOptions$4;
const numeric = /^[0-9]+$/;
const compareIdentifiers$1 = (a, b) => {
const anum = numeric.test(a);
const bnum = numeric.test(b);
if (anum && bnum) {
a = +a;
b = +b;
}
return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1;
};
const rcompareIdentifiers = (a, b) => compareIdentifiers$1(b, a);
var identifiers = {
compareIdentifiers: compareIdentifiers$1,
rcompareIdentifiers
};
const debug$2 = debug_1;
const {
MAX_LENGTH: MAX_LENGTH$1,
MAX_SAFE_INTEGER
} = constants;
const {
re: re$4,
t: t$4
} = re$5.exports;
const parseOptions$3 = parseOptions_1;
const {
compareIdentifiers
} = identifiers;
class SemVer$e {
constructor(version, options) {
options = parseOptions$3(options);
if (version instanceof SemVer$e) {
if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) {
return version;
} else {
version = version.version;
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`);
}
if (version.length > MAX_LENGTH$1) {
throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`);
}
debug$2('SemVer', version, options);
this.options = options;
this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease;
const m = version.trim().match(options.loose ? re$4[t$4.LOOSE] : re$4[t$4.FULL]);
if (!m) {
throw new TypeError(`Invalid Version: ${version}`);
}
this.raw = version; // these are actually numbers
this.major = +m[1];
this.minor = +m[2];
this.patch = +m[3];
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version');
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version');
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version');
} // numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = [];
} else {
this.prerelease = m[4].split('.').map(id => {
if (/^[0-9]+$/.test(id)) {
const num = +id;
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num;
}
}
return id;
});
}
this.build = m[5] ? m[5].split('.') : [];
this.format();
}
format() {
this.version = `${this.major}.${this.minor}.${this.patch}`;
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`;
}
return this.version;
}
toString() {
return this.version;
}
compare(other) {
debug$2('SemVer.compare', this.version, this.options, other);
if (!(other instanceof SemVer$e)) {
if (typeof other === 'string' && other === this.version) {
return 0;
}
other = new SemVer$e(other, this.options);
}
if (other.version === this.version) {
return 0;
}
return this.compareMain(other) || this.comparePre(other);
}
compareMain(other) {
if (!(other instanceof SemVer$e)) {
other = new SemVer$e(other, this.options);
}
return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch);
}
comparePre(other) {
if (!(other instanceof SemVer$e)) {
other = new SemVer$e(other, this.options);
} // NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1;
} else if (!this.prerelease.length && other.prerelease.length) {
return 1;
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0;
}
let i = 0;
do {
const a = this.prerelease[i];
const b = other.prerelease[i];
debug$2('prerelease compare', i, a, b);
if (a === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a === undefined) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
}
compareBuild(other) {
if (!(other instanceof SemVer$e)) {
other = new SemVer$e(other, this.options);
}
let i = 0;
do {
const a = this.build[i];
const b = other.build[i];
debug$2('prerelease compare', i, a, b);
if (a === undefined && b === undefined) {
return 0;
} else if (b === undefined) {
return 1;
} else if (a === undefined) {
return -1;
} else if (a === b) {
continue;
} else {
return compareIdentifiers(a, b);
}
} while (++i);
} // preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc(release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0;
this.patch = 0;
this.minor = 0;
this.major++;
this.inc('pre', identifier);
break;
case 'preminor':
this.prerelease.length = 0;
this.patch = 0;
this.minor++;
this.inc('pre', identifier);
break;
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0;
this.inc('patch', identifier);
this.inc('pre', identifier);
break;
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier);
}
this.inc('pre', identifier);
break;
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) {
this.major++;
}
this.minor = 0;
this.patch = 0;
this.prerelease = [];
break;
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++;
}
this.patch = 0;
this.prerelease = [];
break;
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++;
}
this.prerelease = [];
break;
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0];
} else {
let i = this.prerelease.length;
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++;
i = -2;
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0);
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (this.prerelease[0] === identifier) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0];
}
} else {
this.prerelease = [identifier, 0];
}
}
break;
default:
throw new Error(`invalid increment argument: ${release}`);
}
this.format();
this.raw = this.version;
return this;
}
}
var semver$1 = SemVer$e;
const {
MAX_LENGTH
} = constants;
const {
re: re$3,
t: t$3
} = re$5.exports;
const SemVer$d = semver$1;
const parseOptions$2 = parseOptions_1;
const parse$5 = (version, options) => {
options = parseOptions$2(options);
if (version instanceof SemVer$d) {
return version;
}
if (typeof version !== 'string') {
return null;
}
if (version.length > MAX_LENGTH) {
return null;
}
const r = options.loose ? re$3[t$3.LOOSE] : re$3[t$3.FULL];
if (!r.test(version)) {
return null;
}
try {
return new SemVer$d(version, options);
} catch (er) {
return null;
}
};
var parse_1 = parse$5;
const parse$4 = parse_1;
const valid$1 = (version, options) => {
const v = parse$4(version, options);
return v ? v.version : null;
};
var valid_1 = valid$1;
const parse$3 = parse_1;
const clean = (version, options) => {
const s = parse$3(version.trim().replace(/^[=v]+/, ''), options);
return s ? s.version : null;
};
var clean_1 = clean;
const SemVer$c = semver$1;
const inc = (version, release, options, identifier) => {
if (typeof options === 'string') {
identifier = options;
options = undefined;
}
try {
return new SemVer$c(version, options).inc(release, identifier).version;
} catch (er) {
return null;
}
};
var inc_1 = inc;
const SemVer$b = semver$1;
const compare$a = (a, b, loose) => new SemVer$b(a, loose).compare(new SemVer$b(b, loose));
var compare_1 = compare$a;
const compare$9 = compare_1;
const eq$2 = (a, b, loose) => compare$9(a, b, loose) === 0;
var eq_1 = eq$2;
const parse$2 = parse_1;
const eq$1 = eq_1;
const diff = (version1, version2) => {
if (eq$1(version1, version2)) {
return null;
} else {
const v1 = parse$2(version1);
const v2 = parse$2(version2);
const hasPre = v1.prerelease.length || v2.prerelease.length;
const prefix = hasPre ? 'pre' : '';
const defaultResult = hasPre ? 'prerelease' : '';
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key;
}
}
}
return defaultResult; // may be undefined
}
};
var diff_1 = diff;
const SemVer$a = semver$1;
const major = (a, loose) => new SemVer$a(a, loose).major;
var major_1 = major;
const SemVer$9 = semver$1;
const minor = (a, loose) => new SemVer$9(a, loose).minor;
var minor_1 = minor;
const SemVer$8 = semver$1;
const patch = (a, loose) => new SemVer$8(a, loose).patch;
var patch_1 = patch;
const parse$1 = parse_1;
const prerelease = (version, options) => {
const parsed = parse$1(version, options);
return parsed && parsed.prerelease.length ? parsed.prerelease : null;
};
var prerelease_1 = prerelease;
const compare$8 = compare_1;
const rcompare = (a, b, loose) => compare$8(b, a, loose);
var rcompare_1 = rcompare;
const compare$7 = compare_1;
const compareLoose = (a, b) => compare$7(a, b, true);
var compareLoose_1 = compareLoose;
const SemVer$7 = semver$1;
const compareBuild$2 = (a, b, loose) => {
const versionA = new SemVer$7(a, loose);
const versionB = new SemVer$7(b, loose);
return versionA.compare(versionB) || versionA.compareBuild(versionB);
};
var compareBuild_1 = compareBuild$2;
const compareBuild$1 = compareBuild_1;
const sort = (list, loose) => list.sort((a, b) => compareBuild$1(a, b, loose));
var sort_1 = sort;
const compareBuild = compareBuild_1;
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose));
var rsort_1 = rsort;
const compare$6 = compare_1;
const gt$3 = (a, b, loose) => compare$6(a, b, loose) > 0;
var gt_1 = gt$3;
const compare$5 = compare_1;
const lt$2 = (a, b, loose) => compare$5(a, b, loose) < 0;
var lt_1 = lt$2;
const compare$4 = compare_1;
const neq$1 = (a, b, loose) => compare$4(a, b, loose) !== 0;
var neq_1 = neq$1;
const compare$3 = compare_1;
const gte$2 = (a, b, loose) => compare$3(a, b, loose) >= 0;
var gte_1 = gte$2;
const compare$2 = compare_1;
const lte$2 = (a, b, loose) => compare$2(a, b, loose) <= 0;
var lte_1 = lte$2;
const eq = eq_1;
const neq = neq_1;
const gt$2 = gt_1;
const gte$1 = gte_1;
const lt$1 = lt_1;
const lte$1 = lte_1;
const cmp$1 = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
return a === b;
case '!==':
if (typeof a === 'object') a = a.version;
if (typeof b === 'object') b = b.version;
return a !== b;
case '':
case '=':
case '==':
return eq(a, b, loose);
case '!=':
return neq(a, b, loose);
case '>':
return gt$2(a, b, loose);
case '>=':
return gte$1(a, b, loose);
case '<':
return lt$1(a, b, loose);
case '<=':
return lte$1(a, b, loose);
default:
throw new TypeError(`Invalid operator: ${op}`);
}
};
var cmp_1 = cmp$1;
const SemVer$6 = semver$1;
const parse = parse_1;
const {
re: re$2,
t: t$2
} = re$5.exports;
const coerce = (version, options) => {
if (version instanceof SemVer$6) {
return version;
}
if (typeof version === 'number') {
version = String(version);
}
if (typeof version !== 'string') {
return null;
}
options = options || {};
let match = null;
if (!options.rtl) {
match = version.match(re$2[t$2.COERCE]);
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next;
while ((next = re$2[t$2.COERCERTL].exec(version)) && (!match || match.index + match[0].length !== version.length)) {
if (!match || next.index + next[0].length !== match.index + match[0].length) {
match = next;
}
re$2[t$2.COERCERTL].lastIndex = next.index + next[1].length + next[2].length;
} // leave it in a clean state
re$2[t$2.COERCERTL].lastIndex = -1;
}
if (match === null) return null;
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options);
};
var coerce_1 = coerce;
var yallist = Yallist$1;
Yallist$1.Node = Node;
Yallist$1.create = Yallist$1;
function Yallist$1(list) {
var self = this;
if (!(self instanceof Yallist$1)) {
self = new Yallist$1();
}
self.tail = null;
self.head = null;
self.length = 0;
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item);
});
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i]);
}
}
return self;
}
Yallist$1.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list');
}
var next = node.next;
var prev = node.prev;
if (next) {
next.prev = prev;
}
if (prev) {
prev.next = next;
}
if (node === this.head) {
this.head = next;
}
if (node === this.tail) {
this.tail = prev;
}
node.list.length--;
node.next = null;
node.prev = null;
node.list = null;
return next;
};
Yallist$1.prototype.unshiftNode = function (node) {
if (node === this.head) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var head = this.head;
node.list = this;
node.next = head;
if (head) {
head.prev = node;
}
this.head = node;
if (!this.tail) {
this.tail = node;
}
this.length++;
};
Yallist$1.prototype.pushNode = function (node) {
if (node === this.tail) {
return;
}
if (node.list) {
node.list.removeNode(node);
}
var tail = this.tail;
node.list = this;
node.prev = tail;
if (tail) {
tail.next = node;
}
this.tail = node;
if (!this.head) {
this.head = node;
}
this.length++;
};
Yallist$1.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i]);
}
return this.length;
};
Yallist$1.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i]);
}
return this.length;
};
Yallist$1.prototype.pop = function () {
if (!this.tail) {
return undefined;
}
var res = this.tail.value;
this.tail = this.tail.prev;
if (this.tail) {
this.tail.next = null;
} else {
this.head = null;
}
this.length--;
return res;
};
Yallist$1.prototype.shift = function () {
if (!this.head) {
return undefined;
}
var res = this.head.value;
this.head = this.head.next;
if (this.head) {
this.head.prev = null;
} else {
this.tail = null;
}
this.length--;
return res;
};
Yallist$1.prototype.forEach = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this);
walker = walker.next;
}
};
Yallist$1.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this;
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this);
walker = walker.prev;
}
};
Yallist$1.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist$1.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev;
}
if (i === n && walker !== null) {
return walker.value;
}
};
Yallist$1.prototype.map = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist$1();
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.next;
}
return res;
};
Yallist$1.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this;
var res = new Yallist$1();
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this));
walker = walker.prev;
}
return res;
};
Yallist$1.prototype.reduce = function (fn, initial) {
var acc;
var walker = this.head;
if (arguments.length > 1) {
acc = initial;
} else if (this.head) {
walker = this.head.next;
acc = this.head.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i);
walker = walker.next;
}
return acc;
};
Yallist$1.prototype.reduceReverse = function (fn, initial) {
var acc;
var walker = this.tail;
if (arguments.length > 1) {
acc = initial;
} else if (this.tail) {
walker = this.tail.prev;
acc = this.tail.value;
} else {
throw new TypeError('Reduce of empty list with no initial value');
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i);
walker = walker.prev;
}
return acc;
};
Yallist$1.prototype.toArray = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.next;
}
return arr;
};
Yallist$1.prototype.toArrayReverse = function () {
var arr = new Array(this.length);
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value;
walker = walker.prev;
}
return arr;
};
Yallist$1.prototype.slice = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist$1();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next;
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value);
}
return ret;
};
Yallist$1.prototype.sliceReverse = function (from, to) {
to = to || this.length;
if (to < 0) {
to += this.length;
}
from = from || 0;
if (from < 0) {
from += this.length;
}
var ret = new Yallist$1();
if (to < from || to < 0) {
return ret;
}
if (from < 0) {
from = 0;
}
if (to > this.length) {
to = this.length;
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev;
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value);
}
return ret;
};
Yallist$1.prototype.splice = function (start, deleteCount, ...nodes) {
if (start > this.length) {
start = this.length - 1;
}
if (start < 0) {
start = this.length + start;
}
for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
walker = walker.next;
}
var ret = [];
for (var i = 0; walker && i < deleteCount; i++) {
ret.push(walker.value);
walker = this.removeNode(walker);
}
if (walker === null) {
walker = this.tail;
}
if (walker !== this.head && walker !== this.tail) {
walker = walker.prev;
}
for (var i = 0; i < nodes.length; i++) {
walker = insert(this, walker, nodes[i]);
}
return ret;
};
Yallist$1.prototype.reverse = function () {
var head = this.head;
var tail = this.tail;
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev;
walker.prev = walker.next;
walker.next = p;
}
this.head = tail;
this.tail = head;
return this;
};
function insert(self, node, value) {
var inserted = node === self.head ? new Node(value, null, node, self) : new Node(value, node, node.next, self);
if (inserted.next === null) {
self.tail = inserted;
}
if (inserted.prev === null) {
self.head = inserted;
}
self.length++;
return inserted;
}
function push(self, item) {
self.tail = new Node(item, self.tail, null, self);
if (!self.head) {
self.head = self.tail;
}
self.length++;
}
function unshift(self, item) {
self.head = new Node(item, null, self.head, self);
if (!self.tail) {
self.tail = self.head;
}
self.length++;
}
function Node(value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list);
}
this.list = list;
this.value = value;
if (prev) {
prev.next = this;
this.prev = prev;
} else {
this.prev = null;
}
if (next) {
next.prev = this;
this.next = next;
} else {
this.next = null;
}
}
try {
// add if support for Symbol.iterator is present
require('./iterator.js')(Yallist$1);
} catch (er) {}
const Yallist = yallist;
const MAX = Symbol('max');
const LENGTH = Symbol('length');
const LENGTH_CALCULATOR = Symbol('lengthCalculator');
const ALLOW_STALE = Symbol('allowStale');
const MAX_AGE = Symbol('maxAge');
const DISPOSE = Symbol('dispose');
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet');
const LRU_LIST = Symbol('lruList');
const CACHE = Symbol('cache');
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet');
const naiveLength = () => 1; // lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
class LRUCache {
constructor(options) {
if (typeof options === 'number') options = {
max: options
};
if (!options) options = {};
if (options.max && (typeof options.max !== 'number' || options.max < 0)) throw new TypeError('max must be a non-negative number'); // Kind of weird to have a default max of Infinity, but oh well.
this[MAX] = options.max || Infinity;
const lc = options.length || naiveLength;
this[LENGTH_CALCULATOR] = typeof lc !== 'function' ? naiveLength : lc;
this[ALLOW_STALE] = options.stale || false;
if (options.maxAge && typeof options.maxAge !== 'number') throw new TypeError('maxAge must be a number');
this[MAX_AGE] = options.maxAge || 0;
this[DISPOSE] = options.dispose;
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false;
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false;
this.reset();
} // resize the cache when the max changes.
set max(mL) {
if (typeof mL !== 'number' || mL < 0) throw new TypeError('max must be a non-negative number');
this[MAX] = mL || Infinity;
trim(this);
}
get max() {
return this[MAX];
}
set allowStale(allowStale) {
this[ALLOW_STALE] = !!allowStale;
}
get allowStale() {
return this[ALLOW_STALE];
}
set maxAge(mA) {
if (typeof mA !== 'number') throw new TypeError('maxAge must be a non-negative number');
this[MAX_AGE] = mA;
trim(this);
}
get maxAge() {
return this[MAX_AGE];
} // resize the cache when the lengthCalculator changes.
set lengthCalculator(lC) {
if (typeof lC !== 'function') lC = naiveLength;
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC;
this[LENGTH] = 0;
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key);
this[LENGTH] += hit.length;
});
}
trim(this);
}
get lengthCalculator() {
return this[LENGTH_CALCULATOR];
}
get length() {
return this[LENGTH];
}
get itemCount() {
return this[LRU_LIST].length;
}
rforEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev;
forEachStep(this, fn, walker, thisp);
walker = prev;
}
}
forEach(fn, thisp) {
thisp = thisp || this;
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next;
forEachStep(this, fn, walker, thisp);
walker = next;
}
}
keys() {
return this[LRU_LIST].toArray().map(k => k.key);
}
values() {
return this[LRU_LIST].toArray().map(k => k.value);
}
reset() {
if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value));
}
this[CACHE] = new Map(); // hash of items by key
this[LRU_LIST] = new Yallist(); // list of items in order of use recency
this[LENGTH] = 0; // length of items in the list
}
dump() {
return this[LRU_LIST].map(hit => isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h);
}
dumpLru() {
return this[LRU_LIST];
}
set(key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE];
if (maxAge && typeof maxAge !== 'number') throw new TypeError('maxAge must be a number');
const now = maxAge ? Date.now() : 0;
const len = this[LENGTH_CALCULATOR](value, key);
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key));
return false;
}
const node = this[CACHE].get(key);
const item = node.value; // dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET]) this[DISPOSE](key, item.value);
}
item.now = now;
item.maxAge = maxAge;
item.value = value;
this[LENGTH] += len - item.length;
item.length = len;
this.get(key);
trim(this);
return true;
}
const hit = new Entry(key, value, len, now, maxAge); // oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE]) this[DISPOSE](key, value);
return false;
}
this[LENGTH] += hit.length;
this[LRU_LIST].unshift(hit);
this[CACHE].set(key, this[LRU_LIST].head);
trim(this);
return true;
}
has(key) {
if (!this[CACHE].has(key)) return false;
const hit = this[CACHE].get(key).value;
return !isStale(this, hit);
}
get(key) {
return get(this, key, true);
}
peek(key) {
return get(this, key, false);
}
pop() {
const node = this[LRU_LIST].tail;
if (!node) return null;
del(this, node);
return node.value;
}
del(key) {
del(this, this[CACHE].get(key));
}
load(arr) {
// reset the cache
this.reset();
const now = Date.now(); // A previous serialized cache has the most recent items first
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l];
const expiresAt = hit.e || 0;
if (expiresAt === 0) // the item was created without expiration in a non aged cache
this.set(hit.k, hit.v);else {
const maxAge = expiresAt - now; // dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge);
}
}
}
}
prune() {
this[CACHE].forEach((value, key) => get(this, key, false));
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key);
if (node) {
const hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) return undefined;
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET]) node.value.now = Date.now();
self[LRU_LIST].unshiftNode(node);
}
}
return hit.value;
}
};
const isStale = (self, hit) => {
if (!hit || !hit.maxAge && !self[MAX_AGE]) return false;
const diff = Date.now() - hit.now;
return hit.maxAge ? diff > hit.maxAge : self[MAX_AGE] && diff > self[MAX_AGE];
};
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
const prev = walker.prev;
del(self, walker);
walker = prev;
}
}
};
const del = (self, node) => {
if (node) {
const hit = node.value;
if (self[DISPOSE]) self[DISPOSE](hit.key, hit.value);
self[LENGTH] -= hit.length;
self[CACHE].delete(hit.key);
self[LRU_LIST].removeNode(node);
}
};
class Entry {
constructor(key, value, length, now, maxAge) {
this.key = key;
this.value = value;
this.length = length;
this.now = now;
this.maxAge = maxAge || 0;
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value;
if (isStale(self, hit)) {
del(self, node);
if (!self[ALLOW_STALE]) hit = undefined;
}
if (hit) fn.call(thisp, hit.value, hit.key, self);
};
var lruCache = LRUCache;
class Range$a {
constructor(range, options) {
options = parseOptions$1(options);
if (range instanceof Range$a) {
if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) {
return range;
} else {
return new Range$a(range.raw, options);
}
}
if (range instanceof Comparator$3) {
// just put it in the set and return
this.raw = range.value;
this.set = [[range]];
this.format();
return this;
}
this.options = options;
this.loose = !!options.loose;
this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or ||
this.raw = range;
this.set = range.split(/\s*\|\|\s*/) // map the range to a 2d array of comparators
.map(range => this.parseRange(range.trim())) // throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length);
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`);
} // if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0];
this.set = this.set.filter(c => !isNullSet(c[0]));
if (this.set.length === 0) this.set = [first];else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c];
break;
}
}
}
}
this.format();
}
format() {
this.range = this.set.map(comps => {
return comps.join(' ').trim();
}).join('||').trim();
return this.range;
}
toString() {
return this.range;
}
parseRange(range) {
range = range.trim(); // memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',');
const memoKey = `parseRange:${memoOpts}:${range}`;
const cached = cache.get(memoKey);
if (cached) return cached;
const loose = this.options.loose; // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re$1[t$1.HYPHENRANGELOOSE] : re$1[t$1.HYPHENRANGE];
range = range.replace(hr, hyphenReplace(this.options.includePrerelease));
debug$1('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re$1[t$1.COMPARATORTRIM], comparatorTrimReplace);
debug$1('comparator trim', range, re$1[t$1.COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3`
range = range.replace(re$1[t$1.TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3`
range = range.replace(re$1[t$1.CARETTRIM], caretTrimReplace); // normalize spaces
range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and
// ready to be split into comparators.
const compRe = loose ? re$1[t$1.COMPARATORLOOSE] : re$1[t$1.COMPARATOR];
const rangeList = range.split(' ').map(comp => parseComparator(comp, this.options)).join(' ').split(/\s+/) // >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options)) // in loose mode, throw out any that are not valid comparators
.filter(this.options.loose ? comp => !!comp.match(compRe) : () => true).map(comp => new Comparator$3(comp, this.options)); // if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
rangeList.length;
const rangeMap = new Map();
for (const comp of rangeList) {
if (isNullSet(comp)) return [comp];
rangeMap.set(comp.value, comp);
}
if (rangeMap.size > 1 && rangeMap.has('')) rangeMap.delete('');
const result = [...rangeMap.values()];
cache.set(memoKey, result);
return result;
}
intersects(range, options) {
if (!(range instanceof Range$a)) {
throw new TypeError('a Range is required');
}
return this.set.some(thisComparators => {
return isSatisfiable(thisComparators, options) && range.set.some(rangeComparators => {
return isSatisfiable(rangeComparators, options) && thisComparators.every(thisComparator => {
return rangeComparators.every(rangeComparator => {
return thisComparator.intersects(rangeComparator, options);
});
});
});
});
} // if ANY of the sets match ALL of its comparators, then pass
test(version) {
if (!version) {
return false;
}
if (typeof version === 'string') {
try {
version = new SemVer$5(version, this.options);
} catch (er) {
return false;
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true;
}
}
return false;
}
}
var range = Range$a;
const LRU = lruCache;
const cache = new LRU({
max: 1000
});
const parseOptions$1 = parseOptions_1;
const Comparator$3 = comparator;
const debug$1 = debug_1;
const SemVer$5 = semver$1;
const {
re: re$1,
t: t$1,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace
} = re$5.exports;
const isNullSet = c => c.value === '<0.0.0-0';
const isAny = c => c.value === ''; // take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true;
const remainingComparators = comparators.slice();
let testComparator = remainingComparators.pop();
while (result && remainingComparators.length) {
result = remainingComparators.every(otherComparator => {
return testComparator.intersects(otherComparator, options);
});
testComparator = remainingComparators.pop();
}
return result;
}; // comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug$1('comp', comp, options);
comp = replaceCarets(comp, options);
debug$1('caret', comp);
comp = replaceTildes(comp, options);
debug$1('tildes', comp);
comp = replaceXRanges(comp, options);
debug$1('xrange', comp);
comp = replaceStars(comp, options);
debug$1('stars', comp);
return comp;
};
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'; // ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
const replaceTildes = (comp, options) => comp.trim().split(/\s+/).map(comp => {
return replaceTilde(comp, options);
}).join(' ');
const replaceTilde = (comp, options) => {
const r = options.loose ? re$1[t$1.TILDELOOSE] : re$1[t$1.TILDE];
return comp.replace(r, (_, M, m, p, pr) => {
debug$1('tilde', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
} else if (pr) {
debug$1('replaceTilde pr', pr);
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
}
debug$1('tilde return', ret);
return ret;
});
}; // ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
const replaceCarets = (comp, options) => comp.trim().split(/\s+/).map(comp => {
return replaceCaret(comp, options);
}).join(' ');
const replaceCaret = (comp, options) => {
debug$1('caret', comp, options);
const r = options.loose ? re$1[t$1.CARETLOOSE] : re$1[t$1.CARET];
const z = options.includePrerelease ? '-0' : '';
return comp.replace(r, (_, M, m, p, pr) => {
debug$1('caret', comp, _, M, m, p, pr);
let ret;
if (isX(M)) {
ret = '';
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`;
}
} else if (pr) {
debug$1('replaceCaret pr', pr);
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
}
} else {
debug$1('no pr');
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
} else {
ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
}
} else {
ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
}
}
debug$1('caret return', ret);
return ret;
});
};
const replaceXRanges = (comp, options) => {
debug$1('replaceXRanges', comp, options);
return comp.split(/\s+/).map(comp => {
return replaceXRange(comp, options);
}).join(' ');
};
const replaceXRange = (comp, options) => {
comp = comp.trim();
const r = options.loose ? re$1[t$1.XRANGELOOSE] : re$1[t$1.XRANGE];
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug$1('xRange', comp, ret, gtlt, M, m, p, pr);
const xM = isX(M);
const xm = xM || isX(m);
const xp = xm || isX(p);
const anyX = xp;
if (gtlt === '=' && anyX) {
gtlt = '';
} // if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : '';
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0';
} else {
// nothing is forbidden
ret = '*';
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0;
}
p = 0;
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>=';
if (xm) {
M = +M + 1;
m = 0;
p = 0;
} else {
m = +m + 1;
p = 0;
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<';
if (xm) {
M = +M + 1;
} else {
m = +m + 1;
}
}
if (gtlt === '<') pr = '-0';
ret = `${gtlt + M}.${m}.${p}${pr}`;
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
} else if (xp) {
ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`;
}
debug$1('xRange return', ret);
return ret;
});
}; // Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug$1('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re$1[t$1.STAR], '');
};
const replaceGTE0 = (comp, options) => {
debug$1('replaceGTE0', comp, options);
return comp.trim().replace(re$1[options.includePrerelease ? t$1.GTE0PRE : t$1.GTE0], '');
}; // This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = '';
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`;
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`;
} else if (fpr) {
from = `>=${from}`;
} else {
from = `>=${from}${incPr ? '-0' : ''}`;
}
if (isX(tM)) {
to = '';
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`;
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`;
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`;
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`;
} else {
to = `<=${to}`;
}
return `${from} ${to}`.trim();
};
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false;
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug$1(set[i].semver);
if (set[i].semver === Comparator$3.ANY) {
continue;
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver;
if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) {
return true;
}
}
} // Version has a -pre, but it's not one of the ones we like.
return false;
}
return true;
};
const ANY$2 = Symbol('SemVer ANY'); // hoisted class for cyclic dependency
class Comparator$2 {
static get ANY() {
return ANY$2;
}
constructor(comp, options) {
options = parseOptions(options);
if (comp instanceof Comparator$2) {
if (comp.loose === !!options.loose) {
return comp;
} else {
comp = comp.value;
}
}
debug('comparator', comp, options);
this.options = options;
this.loose = !!options.loose;
this.parse(comp);
if (this.semver === ANY$2) {
this.value = '';
} else {
this.value = this.operator + this.semver.version;
}
debug('comp', this);
}
parse(comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR];
const m = comp.match(r);
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`);
}
this.operator = m[1] !== undefined ? m[1] : '';
if (this.operator === '=') {
this.operator = '';
} // if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY$2;
} else {
this.semver = new SemVer$4(m[2], this.options.loose);
}
}
toString() {
return this.value;
}
test(version) {
debug('Comparator.test', version, this.options.loose);
if (this.semver === ANY$2 || version === ANY$2) {
return true;
}
if (typeof version === 'string') {
try {
version = new SemVer$4(version, this.options);
} catch (er) {
return false;
}
}
return cmp(version, this.operator, this.semver, this.options);
}
intersects(comp, options) {
if (!(comp instanceof Comparator$2)) {
throw new TypeError('a Comparator is required');
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false
};
}
if (this.operator === '') {
if (this.value === '') {
return true;
}
return new Range$9(comp.value, options).test(this.value);
} else if (comp.operator === '') {
if (comp.value === '') {
return true;
}
return new Range$9(this.value, options).test(comp.semver);
}
const sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>');
const sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<');
const sameSemVer = this.semver.version === comp.semver.version;
const differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<=');
const oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<');
const oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>');
return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan;
}
}
var comparator = Comparator$2;
const parseOptions = parseOptions_1;
const {
re,
t
} = re$5.exports;
const cmp = cmp_1;
const debug = debug_1;
const SemVer$4 = semver$1;
const Range$9 = range;
const Range$8 = range;
const satisfies$3 = (version, range, options) => {
try {
range = new Range$8(range, options);
} catch (er) {
return false;
}
return range.test(version);
};
var satisfies_1 = satisfies$3;
const Range$7 = range; // Mostly just for testing and legacy API reasons
const toComparators = (range, options) => new Range$7(range, options).set.map(comp => comp.map(c => c.value).join(' ').trim().split(' '));
var toComparators_1 = toComparators;
const SemVer$3 = semver$1;
const Range$6 = range;
const maxSatisfying = (versions, range, options) => {
let max = null;
let maxSV = null;
let rangeObj = null;
try {
rangeObj = new Range$6(range, options);
} catch (er) {
return null;
}
versions.forEach(v => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v;
maxSV = new SemVer$3(max, options);
}
}
});
return max;
};
var maxSatisfying_1 = maxSatisfying;
const SemVer$2 = semver$1;
const Range$5 = range;
const minSatisfying = (versions, range, options) => {
let min = null;
let minSV = null;
let rangeObj = null;
try {
rangeObj = new Range$5(range, options);
} catch (er) {
return null;
}
versions.forEach(v => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v;
minSV = new SemVer$2(min, options);
}
}
});
return min;
};
var minSatisfying_1 = minSatisfying;
const SemVer$1 = semver$1;
const Range$4 = range;
const gt$1 = gt_1;
const minVersion = (range, loose) => {
range = new Range$4(range, loose);
let minver = new SemVer$1('0.0.0');
if (range.test(minver)) {
return minver;
}
minver = new SemVer$1('0.0.0-0');
if (range.test(minver)) {
return minver;
}
minver = null;
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let setMin = null;
comparators.forEach(comparator => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer$1(comparator.semver.version);
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++;
} else {
compver.prerelease.push(0);
}
compver.raw = compver.format();
/* fallthrough */
case '':
case '>=':
if (!setMin || gt$1(compver, setMin)) {
setMin = compver;
}
break;
case '<':
case '<=':
/* Ignore maximum versions */
break;
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`);
}
});
if (setMin && (!minver || gt$1(minver, setMin))) minver = setMin;
}
if (minver && range.test(minver)) {
return minver;
}
return null;
};
var minVersion_1 = minVersion;
const Range$3 = range;
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range$3(range, options).range || '*';
} catch (er) {
return null;
}
};
var valid = validRange;
const SemVer = semver$1;
const Comparator$1 = comparator;
const {
ANY: ANY$1
} = Comparator$1;
const Range$2 = range;
const satisfies$2 = satisfies_1;
const gt = gt_1;
const lt = lt_1;
const lte = lte_1;
const gte = gte_1;
const outside$2 = (version, range, hilo, options) => {
version = new SemVer(version, options);
range = new Range$2(range, options);
let gtfn, ltefn, ltfn, comp, ecomp;
switch (hilo) {
case '>':
gtfn = gt;
ltefn = lte;
ltfn = lt;
comp = '>';
ecomp = '>=';
break;
case '<':
gtfn = lt;
ltefn = gte;
ltfn = gt;
comp = '<';
ecomp = '<=';
break;
default:
throw new TypeError('Must provide a hilo val of "<" or ">"');
} // If it satisfies the range it is not outside
if (satisfies$2(version, range, options)) {
return false;
} // From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i];
let high = null;
let low = null;
comparators.forEach(comparator => {
if (comparator.semver === ANY$1) {
comparator = new Comparator$1('>=0.0.0');
}
high = high || comparator;
low = low || comparator;
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator;
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator;
}
}); // If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false;
} // If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) {
return false;
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false;
}
}
return true;
};
var outside_1 = outside$2;
const outside$1 = outside_1;
const gtr = (version, range, options) => outside$1(version, range, '>', options);
var gtr_1 = gtr;
const outside = outside_1; // Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options);
var ltr_1 = ltr;
const Range$1 = range;
const intersects = (r1, r2, options) => {
r1 = new Range$1(r1, options);
r2 = new Range$1(r2, options);
return r1.intersects(r2);
};
var intersects_1 = intersects;
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies$1 = satisfies_1;
const compare$1 = compare_1;
var simplify = (versions, range, options) => {
const set = [];
let min = null;
let prev = null;
const v = versions.sort((a, b) => compare$1(a, b, options));
for (const version of v) {
const included = satisfies$1(version, range, options);
if (included) {
prev = version;
if (!min) min = version;
} else {
if (prev) {
set.push([min, prev]);
}
prev = null;
min = null;
}
}
if (min) set.push([min, null]);
const ranges = [];
for (const [min, max] of set) {
if (min === max) ranges.push(min);else if (!max && min === v[0]) ranges.push('*');else if (!max) ranges.push(`>=${min}`);else if (min === v[0]) ranges.push(`<=${max}`);else ranges.push(`${min} - ${max}`);
}
const simplified = ranges.join(' || ');
const original = typeof range.raw === 'string' ? range.raw : String(range);
return simplified.length < original.length ? simplified : range;
};
const Range = range;
const Comparator = comparator;
const {
ANY
} = Comparator;
const satisfies = satisfies_1;
const compare = compare_1; // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
// some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else if in prerelease mode, return false
// - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
// - if in prerelease mode, return true
// - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT.semver is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
// - If LT.semver is greater than any < or <= comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true
const subset = (sub, dom, options = {}) => {
if (sub === dom) return true;
sub = new Range(sub, options);
dom = new Range(dom, options);
let sawNonNull = false;
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options);
sawNonNull = sawNonNull || isSub !== null;
if (isSub) continue OUTER;
} // the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull) return false;
}
return true;
};
const simpleSubset = (sub, dom, options) => {
if (sub === dom) return true;
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) return true;else if (options.includePrerelease) sub = [new Comparator('>=0.0.0-0')];else sub = [new Comparator('>=0.0.0')];
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) return true;else dom = [new Comparator('>=0.0.0')];
}
const eqSet = new Set();
let gt, lt;
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') gt = higherGT(gt, c, options);else if (c.operator === '<' || c.operator === '<=') lt = lowerLT(lt, c, options);else eqSet.add(c.semver);
}
if (eqSet.size > 1) return null;
let gtltComp;
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options);
if (gtltComp > 0) return null;else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) return null;
} // will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) return null;
if (lt && !satisfies(eq, String(lt), options)) return null;
for (const c of dom) {
if (!satisfies(eq, String(c), options)) return false;
}
return true;
}
let higher, lower;
let hasDomLT, hasDomGT; // if the subset has a prerelease, we need a comparator in the superset
// with the same tuple and a prerelease, or it's not a subset
let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false;
let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false; // exception: <1.2.3-0 is the same as <1.2.3
if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false;
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=';
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=';
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false;
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options);
if (higher === c && higher !== gt) return false;
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) return false;
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false;
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options);
if (lower === c && lower !== lt) return false;
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) return false;
}
if (!c.operator && (lt || gt) && gtltComp !== 0) return false;
} // if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0) return false;
if (lt && hasDomGT && !gt && gtltComp !== 0) return false; // we needed a prerelease range in a specific tuple, but didn't get one
// then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
// because it includes prereleases in the 1.2.3 tuple
if (needDomGTPre || needDomLTPre) return false;
return true;
}; // >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a) return b;
const comp = compare(a.semver, b.semver, options);
return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a;
}; // <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a) return b;
const comp = compare(a.semver, b.semver, options);
return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a;
};
var subset_1 = subset;
const internalRe = re$5.exports;
var semver = {
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
SemVer: semver$1,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
parse: parse_1,
valid: valid_1,
clean: clean_1,
inc: inc_1,
diff: diff_1,
major: major_1,
minor: minor_1,
patch: patch_1,
prerelease: prerelease_1,
compare: compare_1,
rcompare: rcompare_1,
compareLoose: compareLoose_1,
compareBuild: compareBuild_1,
sort: sort_1,
rsort: rsort_1,
gt: gt_1,
lt: lt_1,
eq: eq_1,
neq: neq_1,
gte: gte_1,
lte: lte_1,
cmp: cmp_1,
coerce: coerce_1,
Comparator: comparator,
Range: range,
satisfies: satisfies_1,
toComparators: toComparators_1,
maxSatisfying: maxSatisfying_1,
minSatisfying: minSatisfying_1,
minVersion: minVersion_1,
validRange: valid,
outside: outside_1,
gtr: gtr_1,
ltr: ltr_1,
intersects: intersects_1,
simplifyRange: simplify,
subset: subset_1
};
function adjustSpatial(item, encode, swap) {
let t;
if (encode.x2) {
if (encode.x) {
if (swap && item.x > item.x2) {
t = item.x;
item.x = item.x2;
item.x2 = t;
}
item.width = item.x2 - item.x;
} else {
item.x = item.x2 - (item.width || 0);
}
}
if (encode.xc) {
item.x = item.xc - (item.width || 0) / 2;
}
if (encode.y2) {
if (encode.y) {
if (swap && item.y > item.y2) {
t = item.y;
item.y = item.y2;
item.y2 = t;
}
item.height = item.y2 - item.y;
} else {
item.y = item.y2 - (item.height || 0);
}
}
if (encode.yc) {
item.y = item.yc - (item.height || 0) / 2;
}
}
var Constants = {
NaN: NaN,
E: Math.E,
LN2: Math.LN2,
LN10: Math.LN10,
LOG2E: Math.LOG2E,
LOG10E: Math.LOG10E,
PI: Math.PI,
SQRT1_2: Math.SQRT1_2,
SQRT2: Math.SQRT2,
MIN_VALUE: Number.MIN_VALUE,
MAX_VALUE: Number.MAX_VALUE
};
var Ops = {
'*': (a, b) => a * b,
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'/': (a, b) => a / b,
'%': (a, b) => a % b,
'>': (a, b) => a > b,
'<': (a, b) => a < b,
'<=': (a, b) => a <= b,
'>=': (a, b) => a >= b,
'==': (a, b) => a == b,
'!=': (a, b) => a != b,
'===': (a, b) => a === b,
'!==': (a, b) => a !== b,
'&': (a, b) => a & b,
'|': (a, b) => a | b,
'^': (a, b) => a ^ b,
'<<': (a, b) => a << b,
'>>': (a, b) => a >> b,
'>>>': (a, b) => a >>> b
};
var Unary = {
'+': a => +a,
'-': a => -a,
'~': a => ~a,
'!': a => !a
};
const slice = Array.prototype.slice;
const apply = (m, args, cast) => {
const obj = cast ? cast(args[0]) : args[0];
return obj[m].apply(obj, slice.call(args, 1));
};
const datetime = (y, m, d, H, M, S, ms) => new Date(y, m || 0, d != null ? d : 1, H || 0, M || 0, S || 0, ms || 0);
var Functions = {
// math functions
isNaN: Number.isNaN,
isFinite: Number.isFinite,
abs: Math.abs,
acos: Math.acos,
asin: Math.asin,
atan: Math.atan,
atan2: Math.atan2,
ceil: Math.ceil,
cos: Math.cos,
exp: Math.exp,
floor: Math.floor,
log: Math.log,
max: Math.max,
min: Math.min,
pow: Math.pow,
random: Math.random,
round: Math.round,
sin: Math.sin,
sqrt: Math.sqrt,
tan: Math.tan,
clamp: (a, b, c) => Math.max(b, Math.min(c, a)),
// date functions
now: Date.now,
utc: Date.UTC,
datetime: datetime,
date: d => new Date(d).getDate(),
day: d => new Date(d).getDay(),
year: d => new Date(d).getFullYear(),
month: d => new Date(d).getMonth(),
hours: d => new Date(d).getHours(),
minutes: d => new Date(d).getMinutes(),
seconds: d => new Date(d).getSeconds(),
milliseconds: d => new Date(d).getMilliseconds(),
time: d => new Date(d).getTime(),
timezoneoffset: d => new Date(d).getTimezoneOffset(),
utcdate: d => new Date(d).getUTCDate(),
utcday: d => new Date(d).getUTCDay(),
utcyear: d => new Date(d).getUTCFullYear(),
utcmonth: d => new Date(d).getUTCMonth(),
utchours: d => new Date(d).getUTCHours(),
utcminutes: d => new Date(d).getUTCMinutes(),
utcseconds: d => new Date(d).getUTCSeconds(),
utcmilliseconds: d => new Date(d).getUTCMilliseconds(),
// sequence functions
length: x => x.length,
join: function () {
return apply('join', arguments);
},
indexof: function () {
return apply('indexOf', arguments);
},
lastindexof: function () {
return apply('lastIndexOf', arguments);
},
slice: function () {
return apply('slice', arguments);
},
reverse: x => x.slice().reverse(),
// string functions
parseFloat: parseFloat,
parseInt: parseInt,
upper: x => String(x).toUpperCase(),
lower: x => String(x).toLowerCase(),
substring: function () {
return apply('substring', arguments, String);
},
split: function () {
return apply('split', arguments, String);
},
replace: function () {
return apply('replace', arguments, String);
},
trim: x => String(x).trim(),
// regexp functions
regexp: RegExp,
test: (r, t) => RegExp(r).test(t)
};
const EventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y'];
const Visitors = {
Literal: ($, n) => n.value,
Identifier: ($, n) => {
const id = n.name;
return $.memberDepth > 0 ? id : id === 'datum' ? $.datum : id === 'event' ? $.event : id === 'item' ? $.item : Constants[id] || $.params['$' + id];
},
MemberExpression: ($, n) => {
const d = !n.computed,
o = $(n.object);
if (d) $.memberDepth += 1;
const p = $(n.property);
if (d) $.memberDepth -= 1;
return o[p];
},
CallExpression: ($, n) => {
const args = n.arguments;
let name = n.callee.name; // handle special internal functions used by encoders
// re-route to corresponding standard function
if (name.startsWith('_')) {
name = name.slice(1);
} // special case "if" due to conditional evaluation of branches
return name === 'if' ? $(args[0]) ? $(args[1]) : $(args[2]) : ($.fn[name] || Functions[name]).apply($.fn, args.map($));
},
ArrayExpression: ($, n) => n.elements.map($),
BinaryExpression: ($, n) => Ops[n.operator]($(n.left), $(n.right)),
UnaryExpression: ($, n) => Unary[n.operator]($(n.argument)),
ConditionalExpression: ($, n) => $(n.test) ? $(n.consequent) : $(n.alternate),
LogicalExpression: ($, n) => n.operator === '&&' ? $(n.left) && $(n.right) : $(n.left) || $(n.right),
ObjectExpression: ($, n) => n.properties.reduce((o, p) => {
$.memberDepth += 1;
const k = $(p.key);
$.memberDepth -= 1;
o[k] = $(p.value);
return o;
}, {})
};
function interpret(ast, fn, params, datum, event, item) {
const $ = n => Visitors[n.type]($, n);
$.memberDepth = 0;
$.fn = Object.create(fn);
$.params = params;
$.datum = datum;
$.event = event;
$.item = item; // route event functions to annotated vega event context
EventFunctions.forEach(f => $.fn[f] = (...args) => event.vega[f](...args));
return $(ast);
}
var expression = {
/**
* Parse an expression used to update an operator value.
*/
operator(ctx, expr) {
const ast = expr.ast,
fn = ctx.functions;
return _ => interpret(ast, fn, _);
},
/**
* Parse an expression provided as an operator parameter value.
*/
parameter(ctx, expr) {
const ast = expr.ast,
fn = ctx.functions;
return (datum, _) => interpret(ast, fn, _, datum);
},
/**
* Parse an expression applied to an event stream.
*/
event(ctx, expr) {
const ast = expr.ast,
fn = ctx.functions;
return event => interpret(ast, fn, undefined, undefined, event);
},
/**
* Parse an expression used to handle an event-driven operator update.
*/
handler(ctx, expr) {
const ast = expr.ast,
fn = ctx.functions;
return (_, event) => {
const datum = event.item && event.item.datum;
return interpret(ast, fn, _, datum, event);
};
},
/**
* Parse an expression that performs visual encoding.
*/
encode(ctx, encode) {
const {
marktype,
channels
} = encode,
fn = ctx.functions,
swap = marktype === 'group' || marktype === 'image' || marktype === 'rect';
return (item, _) => {
const datum = item.datum;
let m = 0,
v;
for (const name in channels) {
v = interpret(channels[name].ast, fn, _, datum, undefined, item);
if (item[name] !== v) {
item[name] = v;
m = 1;
}
}
if (marktype !== 'rule') {
adjustSpatial(item, channels, swap);
}
return m;
};
}
};
function e(e) {
const [n, r] = /schema\/([\w-]+)\/([\w\.\-]+)\.json$/g.exec(e).slice(1, 3);
return {
library: n,
version: r
};
}
var name$1 = "vega-themes";
var version$2 = "2.10.0";
var description$1 = "Themes for stylized Vega and Vega-Lite visualizations.";
var keywords$1 = ["vega", "vega-lite", "themes", "style"];
var license$1 = "BSD-3-Clause";
var author$1 = {
name: "UW Interactive Data Lab",
url: "https://idl.cs.washington.edu"
};
var contributors$1 = [{
name: "Emily Gu",
url: "https://github.com/emilygu"
}, {
name: "Arvind Satyanarayan",
url: "http://arvindsatya.com"
}, {
name: "Jeffrey Heer",
url: "https://idl.cs.washington.edu"
}, {
name: "Dominik Moritz",
url: "https://www.domoritz.de"
}];
var main$1 = "build/vega-themes.js";
var module$1 = "build/vega-themes.module.js";
var unpkg$1 = "build/vega-themes.min.js";
var jsdelivr$1 = "build/vega-themes.min.js";
var types$1 = "build/vega-themes.module.d.ts";
var repository$1 = {
type: "git",
url: "https://github.com/vega/vega-themes.git"
};
var files$1 = ["src", "build"];
var scripts$1 = {
prebuild: "yarn clean",
build: "rollup -c",
clean: "rimraf build && rimraf examples/build",
"copy:data": "rsync -r node_modules/vega-datasets/data/* examples/data",
"copy:build": "rsync -r build/* examples/build",
"deploy:gh": "yarn build && mkdir -p examples/build && rsync -r build/* examples/build && gh-pages -d examples",
prepublishOnly: "yarn clean && yarn build",
preversion: "yarn lint",
serve: "browser-sync start -s -f build examples --serveStatic examples",
start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'",
prepare: "beemo create-config",
eslintbase: "beemo eslint .",
format: "yarn eslintbase --fix",
lint: "yarn eslintbase"
};
var devDependencies$1 = {
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^11.2.0",
"@wessberg/rollup-plugin-ts": "^1.3.8",
"browser-sync": "^2.26.14",
concurrently: "^6.0.0",
"gh-pages": "^3.1.0",
rollup: "^2.39.1",
"rollup-plugin-bundle-size": "^1.0.3",
"rollup-plugin-terser": "^7.0.2",
typescript: "^4.2.2",
vega: "^5.19.1",
"vega-lite": "^5.0.0",
"vega-lite-dev-config": "^0.16.1"
};
var peerDependencies$1 = {
vega: "*",
"vega-lite": "*"
};
var pkg$1 = {
name: name$1,
version: version$2,
description: description$1,
keywords: keywords$1,
license: license$1,
author: author$1,
contributors: contributors$1,
main: main$1,
module: module$1,
unpkg: unpkg$1,
jsdelivr: jsdelivr$1,
types: types$1,
repository: repository$1,
files: files$1,
scripts: scripts$1,
devDependencies: devDependencies$1,
peerDependencies: peerDependencies$1
};
const lightColor = '#fff';
const medColor = '#888';
const darkTheme = {
background: '#333',
title: {
color: lightColor,
subtitleColor: lightColor
},
style: {
'guide-label': {
fill: lightColor
},
'guide-title': {
fill: lightColor
}
},
axis: {
domainColor: lightColor,
gridColor: medColor,
tickColor: lightColor
}
};
const markColor = '#4572a7';
const excelTheme = {
background: '#fff',
arc: {
fill: markColor
},
area: {
fill: markColor
},
line: {
stroke: markColor,
strokeWidth: 2
},
path: {
stroke: markColor
},
rect: {
fill: markColor
},
shape: {
stroke: markColor
},
symbol: {
fill: markColor,
strokeWidth: 1.5,
size: 50
},
axis: {
bandPosition: 0.5,
grid: true,
gridColor: '#000000',
gridOpacity: 1,
gridWidth: 0.5,
labelPadding: 10,
tickSize: 5,
tickWidth: 0.5
},
axisBand: {
grid: false,
tickExtra: true
},
legend: {
labelBaseline: 'middle',
labelFontSize: 11,
symbolSize: 50,
symbolType: 'square'
},
range: {
category: ['#4572a7', '#aa4643', '#8aa453', '#71598e', '#4598ae', '#d98445', '#94aace', '#d09393', '#b9cc98', '#a99cbc']
}
};
const markColor$1 = '#30a2da';
const axisColor = '#cbcbcb';
const guideLabelColor = '#999';
const guideTitleColor = '#333';
const backgroundColor = '#f0f0f0';
const blackTitle = '#333';
const fiveThirtyEightTheme = {
arc: {
fill: markColor$1
},
area: {
fill: markColor$1
},
axis: {
domainColor: axisColor,
grid: true,
gridColor: axisColor,
gridWidth: 1,
labelColor: guideLabelColor,
labelFontSize: 10,
titleColor: guideTitleColor,
tickColor: axisColor,
tickSize: 10,
titleFontSize: 14,
titlePadding: 10,
labelPadding: 4
},
axisBand: {
grid: false
},
background: backgroundColor,
group: {
fill: backgroundColor
},
legend: {
labelColor: blackTitle,
labelFontSize: 11,
padding: 1,
symbolSize: 30,
symbolType: 'square',
titleColor: blackTitle,
titleFontSize: 14,
titlePadding: 10
},
line: {
stroke: markColor$1,
strokeWidth: 2
},
path: {
stroke: markColor$1,
strokeWidth: 0.5
},
rect: {
fill: markColor$1
},
range: {
category: ['#30a2da', '#fc4f30', '#e5ae38', '#6d904f', '#8b8b8b', '#b96db8', '#ff9e27', '#56cc60', '#52d2ca', '#52689e', '#545454', '#9fe4f8'],
diverging: ['#cc0020', '#e77866', '#f6e7e1', '#d6e8ed', '#91bfd9', '#1d78b5'],
heatmap: ['#d6e8ed', '#cee0e5', '#91bfd9', '#549cc6', '#1d78b5']
},
point: {
filled: true,
shape: 'circle'
},
shape: {
stroke: markColor$1
},
bar: {
binSpacing: 2,
fill: markColor$1,
stroke: null
},
title: {
anchor: 'start',
fontSize: 24,
fontWeight: 600,
offset: 20
}
};
const markColor$2 = '#000';
const ggplot2Theme = {
group: {
fill: '#e5e5e5'
},
arc: {
fill: markColor$2
},
area: {
fill: markColor$2
},
line: {
stroke: markColor$2
},
path: {
stroke: markColor$2
},
rect: {
fill: markColor$2
},
shape: {
stroke: markColor$2
},
symbol: {
fill: markColor$2,
size: 40
},
axis: {
domain: false,
grid: true,
gridColor: '#FFFFFF',
gridOpacity: 1,
labelColor: '#7F7F7F',
labelPadding: 4,
tickColor: '#7F7F7F',
tickSize: 5.67,
titleFontSize: 16,
titleFontWeight: 'normal'
},
legend: {
labelBaseline: 'middle',
labelFontSize: 11,
symbolSize: 40
},
range: {
category: ['#000000', '#7F7F7F', '#1A1A1A', '#999999', '#333333', '#B0B0B0', '#4D4D4D', '#C9C9C9', '#666666', '#DCDCDC']
}
};
const headlineFontSize = 22;
const headlineFontWeight = 'normal';
const labelFont = 'Benton Gothic, sans-serif';
const labelFontSize = 11.5;
const labelFontWeight = 'normal';
const markColor$3 = '#82c6df'; // const markHighlight = '#006d8f';
// const markDemocrat = '#5789b8';
// const markRepublican = '#d94f54';
const titleFont = 'Benton Gothic Bold, sans-serif';
const titleFontWeight = 'normal';
const titleFontSize = 13;
const colorSchemes = {
'category-6': ['#ec8431', '#829eb1', '#c89d29', '#3580b1', '#adc839', '#ab7fb4'],
'fire-7': ['#fbf2c7', '#f9e39c', '#f8d36e', '#f4bb6a', '#e68a4f', '#d15a40', '#ab4232'],
'fireandice-6': ['#e68a4f', '#f4bb6a', '#f9e39c', '#dadfe2', '#a6b7c6', '#849eae'],
'ice-7': ['#edefee', '#dadfe2', '#c4ccd2', '#a6b7c6', '#849eae', '#607785', '#47525d']
};
const latimesTheme = {
background: '#ffffff',
title: {
anchor: 'start',
color: '#000000',
font: titleFont,
fontSize: headlineFontSize,
fontWeight: headlineFontWeight
},
arc: {
fill: markColor$3
},
area: {
fill: markColor$3
},
line: {
stroke: markColor$3,
strokeWidth: 2
},
path: {
stroke: markColor$3
},
rect: {
fill: markColor$3
},
shape: {
stroke: markColor$3
},
symbol: {
fill: markColor$3,
size: 30
},
axis: {
labelFont,
labelFontSize,
labelFontWeight,
titleFont,
titleFontSize,
titleFontWeight
},
axisX: {
labelAngle: 0,
labelPadding: 4,
tickSize: 3
},
axisY: {
labelBaseline: 'middle',
maxExtent: 45,
minExtent: 45,
tickSize: 2,
titleAlign: 'left',
titleAngle: 0,
titleX: -45,
titleY: -11
},
legend: {
labelFont,
labelFontSize,
symbolType: 'square',
titleFont,
titleFontSize,
titleFontWeight
},
range: {
category: colorSchemes['category-6'],
diverging: colorSchemes['fireandice-6'],
heatmap: colorSchemes['fire-7'],
ordinal: colorSchemes['fire-7'],
ramp: colorSchemes['fire-7']
}
};
const markColor$4 = '#ab5787';
const axisColor$1 = '#979797';
const quartzTheme = {
background: '#f9f9f9',
arc: {
fill: markColor$4
},
area: {
fill: markColor$4
},
line: {
stroke: markColor$4
},
path: {
stroke: markColor$4
},
rect: {
fill: markColor$4
},
shape: {
stroke: markColor$4
},
symbol: {
fill: markColor$4,
size: 30
},
axis: {
domainColor: axisColor$1,
domainWidth: 0.5,
gridWidth: 0.2,
labelColor: axisColor$1,
tickColor: axisColor$1,
tickWidth: 0.2,
titleColor: axisColor$1
},
axisBand: {
grid: false
},
axisX: {
grid: true,
tickSize: 10
},
axisY: {
domain: false,
grid: true,
tickSize: 0
},
legend: {
labelFontSize: 11,
padding: 1,
symbolSize: 30,
symbolType: 'square'
},
range: {
category: ['#ab5787', '#51b2e5', '#703c5c', '#168dd9', '#d190b6', '#00609f', '#d365ba', '#154866', '#666666', '#c4c4c4']
}
};
const markColor$5 = '#3e5c69';
const voxTheme = {
background: '#fff',
arc: {
fill: markColor$5
},
area: {
fill: markColor$5
},
line: {
stroke: markColor$5
},
path: {
stroke: markColor$5
},
rect: {
fill: markColor$5
},
shape: {
stroke: markColor$5
},
symbol: {
fill: markColor$5
},
axis: {
domainWidth: 0.5,
grid: true,
labelPadding: 2,
tickSize: 5,
tickWidth: 0.5,
titleFontWeight: 'normal'
},
axisBand: {
grid: false
},
axisX: {
gridWidth: 0.2
},
axisY: {
gridDash: [3],
gridWidth: 0.4
},
legend: {
labelFontSize: 11,
padding: 1,
symbolType: 'square'
},
range: {
category: ['#3e5c69', '#6793a6', '#182429', '#0570b0', '#3690c0', '#74a9cf', '#a6bddb', '#e2ddf2']
}
};
const markColor$6 = '#1696d2';
const axisColor$2 = '#000000';
const backgroundColor$1 = '#FFFFFF';
const font = 'Lato';
const labelFont$1 = 'Lato';
const sourceFont = 'Lato';
const gridColor = '#DEDDDD';
const titleFontSize$1 = 18;
const colorSchemes$1 = {
'main-colors': ['#1696d2', '#d2d2d2', '#000000', '#fdbf11', '#ec008b', '#55b748', '#5c5859', '#db2b27'],
'shades-blue': ['#CFE8F3', '#A2D4EC', '#73BFE2', '#46ABDB', '#1696D2', '#12719E', '#0A4C6A', '#062635'],
'shades-gray': ['#F5F5F5', '#ECECEC', '#E3E3E3', '#DCDBDB', '#D2D2D2', '#9D9D9D', '#696969', '#353535'],
'shades-yellow': ['#FFF2CF', '#FCE39E', '#FDD870', '#FCCB41', '#FDBF11', '#E88E2D', '#CA5800', '#843215'],
'shades-magenta': ['#F5CBDF', '#EB99C2', '#E46AA7', '#E54096', '#EC008B', '#AF1F6B', '#761548', '#351123'],
'shades-green': ['#DCEDD9', '#BCDEB4', '#98CF90', '#78C26D', '#55B748', '#408941', '#2C5C2D', '#1A2E19'],
'shades-black': ['#D5D5D4', '#ADABAC', '#848081', '#5C5859', '#332D2F', '#262223', '#1A1717', '#0E0C0D'],
'shades-red': ['#F8D5D4', '#F1AAA9', '#E9807D', '#E25552', '#DB2B27', '#A4201D', '#6E1614', '#370B0A'],
'one-group': ['#1696d2', '#000000'],
'two-groups-cat-1': ['#1696d2', '#000000'],
'two-groups-cat-2': ['#1696d2', '#fdbf11'],
'two-groups-cat-3': ['#1696d2', '#db2b27'],
'two-groups-seq': ['#a2d4ec', '#1696d2'],
'three-groups-cat': ['#1696d2', '#fdbf11', '#000000'],
'three-groups-seq': ['#a2d4ec', '#1696d2', '#0a4c6a'],
'four-groups-cat-1': ['#000000', '#d2d2d2', '#fdbf11', '#1696d2'],
'four-groups-cat-2': ['#1696d2', '#ec0008b', '#fdbf11', '#5c5859'],
'four-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a'],
'five-groups-cat-1': ['#1696d2', '#fdbf11', '#d2d2d2', '#ec008b', '#000000'],
'five-groups-cat-2': ['#1696d2', '#0a4c6a', '#d2d2d2', '#fdbf11', '#332d2f'],
'five-groups-seq': ['#cfe8f3', '#73bf42', '#1696d2', '#0a4c6a', '#000000'],
'six-groups-cat-1': ['#1696d2', '#ec008b', '#fdbf11', '#000000', '#d2d2d2', '#55b748'],
'six-groups-cat-2': ['#1696d2', '#d2d2d2', '#ec008b', '#fdbf11', '#332d2f', '#0a4c6a'],
'six-groups-seq': ['#cfe8f3', '#a2d4ec', '#73bfe2', '#46abdb', '#1696d2', '#12719e'],
'diverging-colors': ['#ca5800', '#fdbf11', '#fdd870', '#fff2cf', '#cfe8f3', '#73bfe2', '#1696d2', '#0a4c6a']
};
const urbanInstituteTheme = {
background: backgroundColor$1,
title: {
anchor: 'start',
fontSize: titleFontSize$1,
font: font
},
axisX: {
domain: true,
domainColor: axisColor$2,
domainWidth: 1,
grid: false,
labelFontSize: 12,
labelFont: labelFont$1,
labelAngle: 0,
tickColor: axisColor$2,
tickSize: 5,
titleFontSize: 12,
titlePadding: 10,
titleFont: font
},
axisY: {
domain: false,
domainWidth: 1,
grid: true,
gridColor: gridColor,
gridWidth: 1,
labelFontSize: 12,
labelFont: labelFont$1,
labelPadding: 8,
ticks: false,
titleFontSize: 12,
titlePadding: 10,
titleFont: font,
titleAngle: 0,
titleY: -10,
titleX: 18
},
legend: {
labelFontSize: 12,
labelFont: labelFont$1,
symbolSize: 100,
titleFontSize: 12,
titlePadding: 10,
titleFont: font,
orient: 'right',
offset: 10
},
view: {
stroke: 'transparent'
},
range: {
category: colorSchemes$1['six-groups-cat-1'],
diverging: colorSchemes$1['diverging-colors'],
heatmap: colorSchemes$1['diverging-colors'],
ordinal: colorSchemes$1['six-groups-seq'],
ramp: colorSchemes$1['shades-blue']
},
area: {
fill: markColor$6
},
rect: {
fill: markColor$6
},
line: {
color: markColor$6,
stroke: markColor$6,
strokeWidth: 5
},
trail: {
color: markColor$6,
stroke: markColor$6,
strokeWidth: 0,
size: 1
},
path: {
stroke: markColor$6,
strokeWidth: 0.5
},
point: {
filled: true
},
text: {
font: sourceFont,
color: markColor$6,
fontSize: 11,
align: 'center',
fontWeight: 400,
size: 11
},
style: {
bar: {
fill: markColor$6,
stroke: null
}
},
arc: {
fill: markColor$6
},
shape: {
stroke: markColor$6
},
symbol: {
fill: markColor$6,
size: 30
}
};
/**
* Copyright 2020 Google LLC.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
const markColor$7 = '#3366CC';
const gridColor$1 = '#ccc';
const defaultFont = 'Arial, sans-serif';
const googlechartsTheme = {
arc: {
fill: markColor$7
},
area: {
fill: markColor$7
},
path: {
stroke: markColor$7
},
rect: {
fill: markColor$7
},
shape: {
stroke: markColor$7
},
symbol: {
stroke: markColor$7
},
circle: {
fill: markColor$7
},
background: '#fff',
padding: {
top: 10,
right: 10,
bottom: 10,
left: 10
},
style: {
'guide-label': {
font: defaultFont,
fontSize: 12
},
'guide-title': {
font: defaultFont,
fontSize: 12
},
'group-title': {
font: defaultFont,
fontSize: 12
}
},
title: {
font: defaultFont,
fontSize: 14,
fontWeight: 'bold',
dy: -3,
anchor: 'start'
},
axis: {
gridColor: gridColor$1,
tickColor: gridColor$1,
domain: false,
grid: true
},
range: {
category: ['#4285F4', '#DB4437', '#F4B400', '#0F9D58', '#AB47BC', '#00ACC1', '#FF7043', '#9E9D24', '#5C6BC0', '#F06292', '#00796B', '#C2185B'],
heatmap: ['#c6dafc', '#5e97f6', '#2a56c6']
}
};
const version$1$1 = pkg$1.version;
var themes = /*#__PURE__*/Object.freeze({
__proto__: null,
dark: darkTheme,
excel: excelTheme,
fivethirtyeight: fiveThirtyEightTheme,
ggplot2: ggplot2Theme,
googlecharts: googlechartsTheme,
latimes: latimesTheme,
quartz: quartzTheme,
urbaninstitute: urbanInstituteTheme,
version: version$1$1,
vox: voxTheme
});
function accessor(fn, fields, name) {
fn.fields = fields || [];
fn.fname = name;
return fn;
}
function getter(path) {
return path.length === 1 ? get1(path[0]) : getN(path);
}
const get1 = field => function (obj) {
return obj[field];
};
const getN = path => {
const len = path.length;
return function (obj) {
for (let i = 0; i < len; ++i) {
obj = obj[path[i]];
}
return obj;
};
};
function error(message) {
throw Error(message);
}
function splitAccessPath(p) {
const path = [],
n = p.length;
let q = null,
b = 0,
s = '',
i,
j,
c;
p = p + '';
function push() {
path.push(s + p.substring(i, j));
s = '';
i = j + 1;
}
for (i = j = 0; j < n; ++j) {
c = p[j];
if (c === '\\') {
s += p.substring(i, j);
s += p.substring(++j, ++j);
i = j;
} else if (c === q) {
push();
q = null;
b = -1;
} else if (q) {
continue;
} else if (i === b && c === '"') {
i = j + 1;
q = c;
} else if (i === b && c === "'") {
i = j + 1;
q = c;
} else if (c === '.' && !b) {
if (j > i) {
push();
} else {
i = j + 1;
}
} else if (c === '[') {
if (j > i) push();
b = i = j + 1;
} else if (c === ']') {
if (!b) error('Access path missing open bracket: ' + p);
if (b > 0) push();
b = 0;
i = j + 1;
}
}
if (b) error('Access path missing closing bracket: ' + p);
if (q) error('Access path missing closing quote: ' + p);
if (j > i) {
j++;
push();
}
return path;
}
function field(field, name, opt) {
const path = splitAccessPath(field);
field = path.length === 1 ? path[0] : field;
return accessor((opt && opt.get || getter)(path), [field], name || field);
}
field('id');
accessor(_ => _, [], 'identity');
accessor(() => 0, [], 'zero');
accessor(() => 1, [], 'one');
accessor(() => true, [], 'true');
accessor(() => false, [], 'false');
var isArray = Array.isArray;
function isObject(_) {
return _ === Object(_);
}
function isString(_) {
return typeof _ === 'string';
}
/*! *****************************************************************************
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.
***************************************************************************** */
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
/**
* Format the value to be shown in the tooltip.
*
* @param value The value to show in the tooltip.
* @param valueToHtml Function to convert a single cell value to an HTML string
*/
function formatValue(value, valueToHtml, maxDepth) {
if (isArray(value)) {
return `[${value.map(v => valueToHtml(isString(v) ? v : stringify(v, maxDepth))).join(', ')}]`;
}
if (isObject(value)) {
let content = '';
const _a = value,
{
title,
image
} = _a,
rest = __rest(_a, ["title", "image"]);
if (title) {
content += `<h2>${valueToHtml(title)}</h2>`;
}
if (image) {
content += `<img src="${valueToHtml(image)}">`;
}
const keys = Object.keys(rest);
if (keys.length > 0) {
content += '<table>';
for (const key of keys) {
let val = rest[key]; // ignore undefined properties
if (val === undefined) {
continue;
}
if (isObject(val)) {
val = stringify(val, maxDepth);
}
content += `<tr><td class="key">${valueToHtml(key)}:</td><td class="value">${valueToHtml(val)}</td></tr>`;
}
content += `</table>`;
}
return content || '{}'; // show empty object if there are no properties
}
return valueToHtml(value);
}
function replacer(maxDepth) {
const stack = [];
return function (key, value) {
if (typeof value !== 'object' || value === null) {
return value;
}
const pos = stack.indexOf(this) + 1;
stack.length = pos;
if (stack.length > maxDepth) {
return '[Object]';
}
if (stack.indexOf(value) >= 0) {
return '[Circular]';
}
stack.push(value);
return value;
};
}
/**
* Stringify any JS object to valid JSON
*/
function stringify(obj, maxDepth) {
return JSON.stringify(obj, replacer(maxDepth));
} // generated with build-style.sh
var defaultStyle = `#vg-tooltip-element {
visibility: hidden;
padding: 8px;
position: fixed;
z-index: 1000;
font-family: sans-serif;
font-size: 11px;
border-radius: 3px;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
/* The default theme is the light theme. */
background-color: rgba(255, 255, 255, 0.95);
border: 1px solid #d9d9d9;
color: black; }
#vg-tooltip-element.visible {
visibility: visible; }
#vg-tooltip-element h2 {
margin-top: 0;
margin-bottom: 10px;
font-size: 13px; }
#vg-tooltip-element img {
max-width: 200px;
max-height: 200px; }
#vg-tooltip-element table {
border-spacing: 0; }
#vg-tooltip-element table tr {
border: none; }
#vg-tooltip-element table tr td {
overflow: hidden;
text-overflow: ellipsis;
padding-top: 2px;
padding-bottom: 2px; }
#vg-tooltip-element table tr td.key {
color: #808080;
max-width: 150px;
text-align: right;
padding-right: 4px; }
#vg-tooltip-element table tr td.value {
display: block;
max-width: 300px;
max-height: 7em;
text-align: left; }
#vg-tooltip-element.dark-theme {
background-color: rgba(32, 32, 32, 0.9);
border: 1px solid #f5f5f5;
color: white; }
#vg-tooltip-element.dark-theme td.key {
color: #bfbfbf; }
`;
const EL_ID = 'vg-tooltip-element';
const DEFAULT_OPTIONS = {
/**
* X offset.
*/
offsetX: 10,
/**
* Y offset.
*/
offsetY: 10,
/**
* ID of the tooltip element.
*/
id: EL_ID,
/**
* ID of the tooltip CSS style.
*/
styleId: 'vega-tooltip-style',
/**
* The name of the theme. You can use the CSS class called [THEME]-theme to style the tooltips.
*
* There are two predefined themes: "light" (default) and "dark".
*/
theme: 'light',
/**
* Do not use the default styles provided by Vega Tooltip. If you enable this option, you need to use your own styles. It is not necessary to disable the default style when using a custom theme.
*/
disableDefaultStyle: false,
/**
* HTML sanitizer function that removes dangerous HTML to prevent XSS.
*
* This should be a function from string to string. You may replace it with a formatter such as a markdown formatter.
*/
sanitize: escapeHTML,
/**
* The maximum recursion depth when printing objects in the tooltip.
*/
maxDepth: 2,
/**
* A function to customize the rendered HTML of the tooltip.
* @param value A value string, or object of value strings keyed by field
* @param sanitize The `sanitize` function from `options.sanitize`
* @returns {string} The returned string will become the `innerHTML` of the tooltip element
*/
formatTooltip: formatValue
};
/**
* Escape special HTML characters.
*
* @param value A value to convert to string and HTML-escape.
*/
function escapeHTML(value) {
return String(value).replace(/&/g, '&').replace(/</g, '<');
}
function createDefaultStyle(id) {
// Just in case this id comes from a user, ensure these is no security issues
if (!/^[A-Za-z]+[-:.\w]*$/.test(id)) {
throw new Error('Invalid HTML ID');
}
return defaultStyle.toString().replace(EL_ID, id);
}
/**
* Position the tooltip
*
* @param event The mouse event.
* @param tooltipBox
* @param offsetX Horizontal offset.
* @param offsetY Vertical offset.
*/
function calculatePosition(event, tooltipBox, offsetX, offsetY) {
let x = event.clientX + offsetX;
if (x + tooltipBox.width > window.innerWidth) {
x = +event.clientX - offsetX - tooltipBox.width;
}
let y = event.clientY + offsetY;
if (y + tooltipBox.height > window.innerHeight) {
y = +event.clientY - offsetY - tooltipBox.height;
}
return {
x,
y
};
}
/**
* The tooltip handler class.
*/
class Handler {
/**
* Create the tooltip handler and initialize the element and style.
*
* @param options Tooltip Options
*/
constructor(options) {
this.options = Object.assign(Object.assign({}, DEFAULT_OPTIONS), options);
const elementId = this.options.id;
this.el = null; // bind this to call
this.call = this.tooltipHandler.bind(this); // prepend a default stylesheet for tooltips to the head
if (!this.options.disableDefaultStyle && !document.getElementById(this.options.styleId)) {
const style = document.createElement('style');
style.setAttribute('id', this.options.styleId);
style.innerHTML = createDefaultStyle(elementId);
const head = document.head;
if (head.childNodes.length > 0) {
head.insertBefore(style, head.childNodes[0]);
} else {
head.appendChild(style);
}
}
}
/**
* The tooltip handler function.
*/
tooltipHandler(handler, event, item, value) {
// console.log(handler, event, item, value);
var _a; // append a div element that we use as a tooltip unless it already exists
this.el = document.getElementById(this.options.id);
if (!this.el) {
this.el = document.createElement('div');
this.el.setAttribute('id', this.options.id);
this.el.classList.add('vg-tooltip');
document.body.appendChild(this.el);
}
const tooltipContainer = (_a = document.fullscreenElement) !== null && _a !== void 0 ? _a : document.body;
tooltipContainer.appendChild(this.el); // hide tooltip for null, undefined, or empty string values
if (value == null || value === '') {
this.el.classList.remove('visible', `${this.options.theme}-theme`);
return;
} // set the tooltip content
this.el.innerHTML = this.options.formatTooltip(value, this.options.sanitize, this.options.maxDepth); // make the tooltip visible
this.el.classList.add('visible', `${this.options.theme}-theme`);
const {
x,
y
} = calculatePosition(event, this.el.getBoundingClientRect(), this.options.offsetX, this.options.offsetY);
this.el.setAttribute('style', `top: ${y}px; left: ${x}px`);
}
}
/**
* Open editor url in a new window, and pass a message.
*/
function post (window, url, data) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const editor = window.open(url);
const wait = 10000;
const step = 250;
const {
origin
} = new URL(url); // eslint-disable-next-line no-bitwise
let count = ~~(wait / step);
function listen(evt) {
if (evt.source === editor) {
count = 0;
window.removeEventListener('message', listen, false);
}
}
window.addEventListener('message', listen, false); // send message
// periodically resend until ack received or timeout
function send() {
if (count <= 0) {
return;
}
editor.postMessage(data, origin);
setTimeout(send, step);
count -= 1;
}
setTimeout(send, step);
}
// generated with build-style.sh
var embedStyle = `.vega-embed {
position: relative;
display: inline-block;
box-sizing: border-box; }
.vega-embed.has-actions {
padding-right: 38px; }
.vega-embed details:not([open]) > :not(summary) {
display: none !important; }
.vega-embed summary {
list-style: none;
position: absolute;
top: 0;
right: 0;
padding: 6px;
z-index: 1000;
background: white;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
color: #1b1e23;
border: 1px solid #aaa;
border-radius: 999px;
opacity: 0.2;
transition: opacity 0.4s ease-in;
outline: none;
cursor: pointer;
line-height: 0px; }
.vega-embed summary::-webkit-details-marker {
display: none; }
.vega-embed summary:active {
box-shadow: #aaa 0px 0px 0px 1px inset; }
.vega-embed summary svg {
width: 14px;
height: 14px; }
.vega-embed details[open] summary {
opacity: 0.7; }
.vega-embed:hover summary,
.vega-embed:focus summary {
opacity: 1 !important;
transition: opacity 0.2s ease; }
.vega-embed .vega-actions {
position: absolute;
z-index: 1001;
top: 35px;
right: -9px;
display: flex;
flex-direction: column;
padding-bottom: 8px;
padding-top: 8px;
border-radius: 4px;
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.2);
border: 1px solid #d9d9d9;
background: white;
animation-duration: 0.15s;
animation-name: scale-in;
animation-timing-function: cubic-bezier(0.2, 0, 0.13, 1.5);
text-align: left; }
.vega-embed .vega-actions a {
padding: 8px 16px;
font-family: sans-serif;
font-size: 14px;
font-weight: 600;
white-space: nowrap;
color: #434a56;
text-decoration: none; }
.vega-embed .vega-actions a:hover {
background-color: #f7f7f9;
color: black; }
.vega-embed .vega-actions::before, .vega-embed .vega-actions::after {
content: "";
display: inline-block;
position: absolute; }
.vega-embed .vega-actions::before {
left: auto;
right: 14px;
top: -16px;
border: 8px solid #0000;
border-bottom-color: #d9d9d9; }
.vega-embed .vega-actions::after {
left: auto;
right: 15px;
top: -14px;
border: 7px solid #0000;
border-bottom-color: #fff; }
.vega-embed .chart-wrapper.fit-x {
width: 100%; }
.vega-embed .chart-wrapper.fit-y {
height: 100%; }
.vega-embed-wrapper {
max-width: 100%;
overflow: auto;
padding-right: 14px; }
@keyframes scale-in {
from {
opacity: 0;
transform: scale(0.6); }
to {
opacity: 1;
transform: scale(1); } }
`;
if (!String.prototype.startsWith) {
// eslint-disable-next-line no-extend-native,func-names
String.prototype.startsWith = function (search, pos) {
return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
};
}
function isURL(s) {
return s.startsWith('http://') || s.startsWith('https://') || s.startsWith('//');
}
function mergeDeep(dest, ...src) {
for (const s of src) {
deepMerge_(dest, s);
}
return dest;
}
function deepMerge_(dest, src) {
for (const property of Object.keys(src)) {
vegaImport.writeConfig(dest, property, src[property], true);
}
}
var name = "vega-embed";
var version$1 = "6.20.0-next.0";
var description = "Publish Vega visualizations as embedded web components.";
var keywords = ["vega", "data", "visualization", "component", "embed"];
var repository = {
type: "git",
url: "http://github.com/vega/vega-embed.git"
};
var author = {
name: "UW Interactive Data Lab",
url: "http://idl.cs.washington.edu"
};
var contributors = [{
name: "Dominik Moritz",
url: "https://www.domoritz.de"
}];
var bugs = {
url: "https://github.com/vega/vega-embed/issues"
};
var homepage = "https://github.com/vega/vega-embed#readme";
var license = "BSD-3-Clause";
var main = "build/vega-embed.js";
var module = "build/vega-embed.module.js";
var unpkg = "build/vega-embed.min.js";
var jsdelivr = "build/vega-embed.min.js";
var types = "build/vega-embed.module.d.ts";
var files = ["src", "build", "build-es5"];
var devDependencies = {
"@auto-it/conventional-commits": "^10.32.0",
"@auto-it/first-time-contributor": "^10.32.0",
"@rollup/plugin-commonjs": "21.0.1",
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-node-resolve": "^13.0.4",
"@types/semver": "^7.3.8",
"@wessberg/rollup-plugin-ts": "^1.3.14",
auto: "^10.32.0",
"browser-sync": "^2.27.5",
concurrently: "^6.2.1",
"del-cli": "^4.0.1",
"jest-canvas-mock": "^2.3.1",
"node-sass": "^6.0.1",
"rollup-plugin-bundle-size": "^1.0.3",
"rollup-plugin-terser": "^7.0.2",
rollup: "2.58.1",
typescript: "^4.4.3",
"vega-lite-dev-config": "^0.18.0",
"vega-lite": "^5.0.0",
vega: "^5.19.1"
};
var peerDependencies = {
vega: "^5.20.2",
"vega-lite": "*"
};
var dependencies = {
"fast-json-patch": "^3.1.0",
"json-stringify-pretty-compact": "^3.0.0",
semver: "^7.3.5",
tslib: "^2.3.1",
"vega-interpreter": "^1.0.4",
"vega-schema-url-parser": "^2.2.0",
"vega-themes": "^2.10.0",
"vega-tooltip": "^0.27.0"
};
var scripts = {
prebuild: "yarn clean && yarn build:style",
build: "rollup -c",
"build:style": "./build-style.sh",
clean: "del-cli build build-es5 src/style.ts",
prepublishOnly: "yarn clean && yarn build",
preversion: "yarn lint && yarn test",
serve: "browser-sync start --directory -s -f build *.html",
start: "yarn build && concurrently --kill-others -n Server,Rollup 'yarn serve' 'rollup -c -w'",
pretest: "yarn build:style",
test: "beemo jest --stdio stream",
"test:inspect": "node --inspect-brk ./node_modules/.bin/jest --runInBand",
prepare: "beemo create-config",
prettierbase: "beemo prettier '*.{css,scss,html}'",
eslintbase: "beemo eslint .",
format: "yarn eslintbase --fix && yarn prettierbase --write",
lint: "yarn eslintbase && yarn prettierbase --check",
release: "auto shipit"
};
var pkg = {
name: name,
version: version$1,
description: description,
keywords: keywords,
repository: repository,
author: author,
contributors: contributors,
bugs: bugs,
homepage: homepage,
license: license,
main: main,
module: module,
unpkg: unpkg,
jsdelivr: jsdelivr,
types: types,
files: files,
devDependencies: devDependencies,
peerDependencies: peerDependencies,
dependencies: dependencies,
scripts: scripts
};
var _w$vl;
const version = pkg.version;
const vega = vegaImport__namespace;
let vegaLite = vegaLiteImport__namespace; // For backwards compatibility with Vega-Lite before v4.
const w = typeof window !== 'undefined' ? window : undefined;
if (vegaLite === undefined && w !== null && w !== void 0 && (_w$vl = w['vl']) !== null && _w$vl !== void 0 && _w$vl.compile) {
vegaLite = w['vl'];
}
const DEFAULT_ACTIONS = {
export: {
svg: true,
png: true
},
source: true,
compiled: true,
editor: true
};
const I18N = {
CLICK_TO_VIEW_ACTIONS: 'Click to view actions',
COMPILED_ACTION: 'View Compiled Vega',
EDITOR_ACTION: 'Open in Vega Editor',
PNG_ACTION: 'Save as PNG',
SOURCE_ACTION: 'View Source',
SVG_ACTION: 'Save as SVG'
};
const NAMES = {
vega: 'Vega',
'vega-lite': 'Vega-Lite'
};
const VERSION = {
vega: vega.version,
'vega-lite': vegaLite ? vegaLite.version : 'not available'
};
const PREPROCESSOR = {
vega: vgSpec => vgSpec,
'vega-lite': (vlSpec, config) => vegaLite.compile(vlSpec, {
config: config
}).spec
};
const SVG_CIRCLES = `
<svg viewBox="0 0 16 16" fill="currentColor" stroke="none" stroke-width="1" stroke-linecap="round" stroke-linejoin="round">
<circle r="2" cy="8" cx="2"></circle>
<circle r="2" cy="8" cx="8"></circle>
<circle r="2" cy="8" cx="14"></circle>
</svg>`;
const CHART_WRAPPER_CLASS = 'chart-wrapper';
function isTooltipHandler(h) {
return typeof h === 'function';
}
function viewSource(source, sourceHeader, sourceFooter, mode) {
const header = `<html><head>${sourceHeader}</head><body><pre><code class="json">`;
const footer = `</code></pre>${sourceFooter}</body></html>`; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const win = window.open('');
win.document.write(header + source + footer);
win.document.title = `${NAMES[mode]} JSON Source`;
}
/**
* Try to guess the type of spec.
*
* @param spec Vega or Vega-Lite spec.
*/
function guessMode(spec, providedMode) {
// Decide mode
if (spec.$schema) {
const parsed = e(spec.$schema);
if (providedMode && providedMode !== parsed.library) {
var _NAMES$providedMode;
console.warn(`The given visualization spec is written in ${NAMES[parsed.library]}, but mode argument sets ${(_NAMES$providedMode = NAMES[providedMode]) !== null && _NAMES$providedMode !== void 0 ? _NAMES$providedMode : providedMode}.`);
}
const mode = parsed.library;
if (!semver.satisfies(VERSION[mode], `^${parsed.version.slice(1)}`)) {
console.warn(`The input spec uses ${NAMES[mode]} ${parsed.version}, but the current version of ${NAMES[mode]} is v${VERSION[mode]}.`);
}
return mode;
} // try to guess from the provided spec
if ('mark' in spec || 'encoding' in spec || 'layer' in spec || 'hconcat' in spec || 'vconcat' in spec || 'facet' in spec || 'repeat' in spec) {
return 'vega-lite';
}
if ('marks' in spec || 'signals' in spec || 'scales' in spec || 'axes' in spec) {
return 'vega';
}
return providedMode !== null && providedMode !== void 0 ? providedMode : 'vega';
}
function isLoader(o) {
return !!(o && 'load' in o);
}
function createLoader(opts) {
return isLoader(opts) ? opts : vega.loader(opts);
}
function embedOptionsFromUsermeta(parsedSpec) {
var _ref;
return (_ref = parsedSpec.usermeta && parsedSpec.usermeta['embedOptions']) !== null && _ref !== void 0 ? _ref : {};
}
/**
* Embed a Vega visualization component in a web page. This function returns a promise.
*
* @param el DOM element in which to place component (DOM node or CSS selector).
* @param spec String : A URL string from which to load the Vega specification.
* Object : The Vega/Vega-Lite specification as a parsed JSON object.
* @param opts A JavaScript object containing options for embedding.
*/
async function embed(el, spec, opts = {}) {
var _parsedOpts$config, _usermetaOpts$config;
let parsedSpec;
let loader;
if (vegaImport.isString(spec)) {
loader = createLoader(opts.loader);
parsedSpec = JSON.parse(await loader.load(spec));
} else {
parsedSpec = spec;
}
const usermetaLoader = embedOptionsFromUsermeta(parsedSpec).loader; // either create the loader for the first time or create a new loader if the spec has new loader options
if (!loader || usermetaLoader) {
var _opts$loader;
loader = createLoader((_opts$loader = opts.loader) !== null && _opts$loader !== void 0 ? _opts$loader : usermetaLoader);
}
const usermetaOpts = await loadOpts(embedOptionsFromUsermeta(parsedSpec), loader);
const parsedOpts = await loadOpts(opts, loader);
const mergedOpts = { ...mergeDeep(parsedOpts, usermetaOpts),
config: vegaImport.mergeConfig((_parsedOpts$config = parsedOpts.config) !== null && _parsedOpts$config !== void 0 ? _parsedOpts$config : {}, (_usermetaOpts$config = usermetaOpts.config) !== null && _usermetaOpts$config !== void 0 ? _usermetaOpts$config : {})
};
return await _embed(el, parsedSpec, mergedOpts, loader);
}
async function loadOpts(opt, loader) {
var _opt$config;
const config = vegaImport.isString(opt.config) ? JSON.parse(await loader.load(opt.config)) : (_opt$config = opt.config) !== null && _opt$config !== void 0 ? _opt$config : {};
const patch = vegaImport.isString(opt.patch) ? JSON.parse(await loader.load(opt.patch)) : opt.patch;
return { ...opt,
...(patch ? {
patch
} : {}),
...(config ? {
config
} : {})
};
}
function getRoot(el) {
const possibleRoot = el.getRootNode ? el.getRootNode() : document;
if (possibleRoot instanceof ShadowRoot) {
return {
root: possibleRoot,
rootContainer: possibleRoot
};
} else {
var _document$head;
return {
root: document,
rootContainer: (_document$head = document.head) !== null && _document$head !== void 0 ? _document$head : document.body
};
}
}
async function _embed(el, spec, opts = {}, loader) {
var _opts$config, _opts$actions, _opts$renderer, _opts$logLevel, _opts$downloadFileNam, _ref2, _vega$expressionInter;
const config = opts.theme ? vegaImport.mergeConfig(themes[opts.theme], (_opts$config = opts.config) !== null && _opts$config !== void 0 ? _opts$config : {}) : opts.config;
const actions = vegaImport.isBoolean(opts.actions) ? opts.actions : mergeDeep({}, DEFAULT_ACTIONS, (_opts$actions = opts.actions) !== null && _opts$actions !== void 0 ? _opts$actions : {});
const i18n = { ...I18N,
...opts.i18n
};
const renderer = (_opts$renderer = opts.renderer) !== null && _opts$renderer !== void 0 ? _opts$renderer : 'canvas';
const logLevel = (_opts$logLevel = opts.logLevel) !== null && _opts$logLevel !== void 0 ? _opts$logLevel : vega.Warn;
const downloadFileName = (_opts$downloadFileNam = opts.downloadFileName) !== null && _opts$downloadFileNam !== void 0 ? _opts$downloadFileNam : 'visualization';
const element = typeof el === 'string' ? document.querySelector(el) : el;
if (!element) {
throw new Error(`${el} does not exist`);
}
if (opts.defaultStyle !== false) {
// Add a default stylesheet to the head of the document.
const ID = 'vega-embed-style';
const {
root,
rootContainer
} = getRoot(element);
if (!root.getElementById(ID)) {
const style = document.createElement('style');
style.id = ID;
style.innerText = opts.defaultStyle === undefined || opts.defaultStyle === true ? (embedStyle ).toString() : opts.defaultStyle;
rootContainer.appendChild(style);
}
}
const mode = guessMode(spec, opts.mode);
let vgSpec = PREPROCESSOR[mode](spec, config);
if (mode === 'vega-lite') {
if (vgSpec.$schema) {
const parsed = e(vgSpec.$schema);
if (!semver.satisfies(VERSION.vega, `^${parsed.version.slice(1)}`)) {
console.warn(`The compiled spec uses Vega ${parsed.version}, but current version is v${VERSION.vega}.`);
}
}
}
element.classList.add('vega-embed');
if (actions) {
element.classList.add('has-actions');
}
element.innerHTML = ''; // clear container
let container = element;
if (actions) {
const chartWrapper = document.createElement('div');
chartWrapper.classList.add(CHART_WRAPPER_CLASS);
element.appendChild(chartWrapper);
container = chartWrapper;
}
const patch = opts.patch;
if (patch) {
if (patch instanceof Function) {
vgSpec = patch(vgSpec);
} else {
vgSpec = applyPatch(vgSpec, patch, true, false).newDocument;
}
} // Set locale. Note that this is a global setting.
if (opts.formatLocale) {
vega.formatLocale(opts.formatLocale);
}
if (opts.timeFormatLocale) {
vega.timeFormatLocale(opts.timeFormatLocale);
}
const {
ast
} = opts; // Do not apply the config to Vega when we have already applied it to Vega-Lite.
// This call may throw an Error if parsing fails.
const runtime = vega.parse(vgSpec, mode === 'vega-lite' ? {} : config, {
ast
});
const view = new (opts.viewClass || vega.View)(runtime, {
loader,
logLevel,
renderer,
...(ast ? {
expr: (_ref2 = (_vega$expressionInter = vega.expressionInterpreter) !== null && _vega$expressionInter !== void 0 ? _vega$expressionInter : opts.expr) !== null && _ref2 !== void 0 ? _ref2 : expression
} : {})
});
view.addSignalListener('autosize', (_, autosize) => {
const {
type
} = autosize;
if (type == 'fit-x') {
container.classList.add('fit-x');
container.classList.remove('fit-y');
} else if (type == 'fit-y') {
container.classList.remove('fit-x');
container.classList.add('fit-y');
} else if (type == 'fit') {
container.classList.add('fit-x', 'fit-y');
} else {
container.classList.remove('fit-x', 'fit-y');
}
});
if (opts.tooltip !== false) {
let handler;
if (isTooltipHandler(opts.tooltip)) {
handler = opts.tooltip;
} else {
// user provided boolean true or tooltip options
handler = new Handler(opts.tooltip === true ? {} : opts.tooltip).call;
}
view.tooltip(handler);
}
let {
hover
} = opts;
if (hover === undefined) {
hover = mode === 'vega';
}
if (hover) {
const {
hoverSet,
updateSet
} = typeof hover === 'boolean' ? {} : hover;
view.hover(hoverSet, updateSet);
}
if (opts) {
if (opts.width != null) {
view.width(opts.width);
}
if (opts.height != null) {
view.height(opts.height);
}
if (opts.padding != null) {
view.padding(opts.padding);
}
}
await view.initialize(container, opts.bind).runAsync();
let documentClickHandler;
if (actions !== false) {
let wrapper = element;
if (opts.defaultStyle !== false) {
const details = document.createElement('details');
details.title = i18n.CLICK_TO_VIEW_ACTIONS;
element.append(details);
wrapper = details;
const summary = document.createElement('summary');
summary.innerHTML = SVG_CIRCLES;
details.append(summary);
documentClickHandler = ev => {
if (!details.contains(ev.target)) {
details.removeAttribute('open');
}
};
document.addEventListener('click', documentClickHandler);
}
const ctrl = document.createElement('div');
wrapper.append(ctrl);
ctrl.classList.add('vega-actions'); // add 'Export' action
if (actions === true || actions.export !== false) {
for (const ext of ['svg', 'png']) {
if (actions === true || actions.export === true || actions.export[ext]) {
const i18nExportAction = i18n[`${ext.toUpperCase()}_ACTION`];
const exportLink = document.createElement('a');
exportLink.text = i18nExportAction;
exportLink.href = '#';
exportLink.target = '_blank';
exportLink.download = `${downloadFileName}.${ext}`; // add link on mousedown so that it's correct when the click happens
exportLink.addEventListener('mousedown', async function (e) {
e.preventDefault();
const url = await view.toImageURL(ext, opts.scaleFactor);
this.href = url;
});
ctrl.append(exportLink);
}
}
} // add 'View Source' action
if (actions === true || actions.source !== false) {
const viewSourceLink = document.createElement('a');
viewSourceLink.text = i18n.SOURCE_ACTION;
viewSourceLink.href = '#';
viewSourceLink.addEventListener('click', function (e) {
var _opts$sourceHeader, _opts$sourceFooter;
viewSource(jsonStringifyPrettyCompact(spec), (_opts$sourceHeader = opts.sourceHeader) !== null && _opts$sourceHeader !== void 0 ? _opts$sourceHeader : '', (_opts$sourceFooter = opts.sourceFooter) !== null && _opts$sourceFooter !== void 0 ? _opts$sourceFooter : '', mode);
e.preventDefault();
});
ctrl.append(viewSourceLink);
} // add 'View Compiled' action
if (mode === 'vega-lite' && (actions === true || actions.compiled !== false)) {
const compileLink = document.createElement('a');
compileLink.text = i18n.COMPILED_ACTION;
compileLink.href = '#';
compileLink.addEventListener('click', function (e) {
var _opts$sourceHeader2, _opts$sourceFooter2;
viewSource(jsonStringifyPrettyCompact(vgSpec), (_opts$sourceHeader2 = opts.sourceHeader) !== null && _opts$sourceHeader2 !== void 0 ? _opts$sourceHeader2 : '', (_opts$sourceFooter2 = opts.sourceFooter) !== null && _opts$sourceFooter2 !== void 0 ? _opts$sourceFooter2 : '', 'vega');
e.preventDefault();
});
ctrl.append(compileLink);
} // add 'Open in Vega Editor' action
if (actions === true || actions.editor !== false) {
var _opts$editorUrl;
const editorUrl = (_opts$editorUrl = opts.editorUrl) !== null && _opts$editorUrl !== void 0 ? _opts$editorUrl : 'https://vega.github.io/editor/';
const editorLink = document.createElement('a');
editorLink.text = i18n.EDITOR_ACTION;
editorLink.href = '#';
editorLink.addEventListener('click', function (e) {
post(window, editorUrl, {
config: config,
mode,
renderer,
spec: jsonStringifyPrettyCompact(spec)
});
e.preventDefault();
});
ctrl.append(editorLink);
}
}
function finalize() {
if (documentClickHandler) {
document.removeEventListener('click', documentClickHandler);
}
view.finalize();
}
return {
view,
spec,
vgSpec,
finalize
};
}
/**
* Create a promise to an HTML Div element with an embedded Vega-Lite or Vega visualization.
* The element has a value property with the view. By default all actions except for the editor action are disabled.
*
* The main use case is in [Observable](https://observablehq.com/).
*/
async function container (spec, opt = {}) {
var _opt$actions;
const wrapper = document.createElement('div');
wrapper.classList.add('vega-embed-wrapper');
const div = document.createElement('div');
wrapper.appendChild(div);
const actions = opt.actions === true || opt.actions === false ? opt.actions : {
export: true,
source: false,
compiled: true,
editor: true,
...((_opt$actions = opt.actions) !== null && _opt$actions !== void 0 ? _opt$actions : {})
};
const result = await embed(div, spec, {
actions,
...(opt !== null && opt !== void 0 ? opt : {})
});
wrapper.value = result.view;
return wrapper;
}
/**
* Returns true if the object is an HTML element.
*/
function isElement(obj) {
return obj instanceof HTMLElement;
}
const wrapper = (...args) => {
if (args.length > 1 && (vegaImport.isString(args[0]) && !isURL(args[0]) || isElement(args[0]) || args.length === 3)) {
return embed(args[0], args[1], args[2]);
}
return container(args[0], args[1]);
};
wrapper.vegaLite = vegaLite;
wrapper.vl = vegaLite; // backwards compatibility
wrapper.container = container;
wrapper.embed = embed;
wrapper.vega = vega;
wrapper.default = embed;
wrapper.version = version;
return wrapper;
}));
//# sourceMappingURL=vega-embed.js.map
|
import propertyTest from '../../helpers/propertyTest'
propertyTest('DTEND', {
transformableValue: new Date('1991-03-07 09:00:00'),
transformedValue: '19910307T090000'
})
|
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
EXTEND_PROTOTYPES: false,
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
ENV.baseURL = '/ember-collection';
ENV.locationType = 'hash';
}
return ENV;
};
|
/**
* Created by fengyuanzemin on 17/2/15.
*/
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as mutations from './mutations';
Vue.use(Vuex);
const state = {
isShow: false,
msg: '出错了',
isBig: true,
token: localStorage.getItem('f-token'),
init: false
};
export default new Vuex.Store({
state,
actions,
mutations
});
|
/*global describe, it, expect, require*/
const nodeToBox = require('../../../src/core/layout/node-to-box');
describe('nodeToBox', function () {
'use strict';
it('should convert node to a box', function () {
expect(nodeToBox({x: 10, styles: ['blue'], y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['blue'], top: 20, width: 30, height: 40, level: 2});
});
it('should append default styles if not provided', function () {
expect(nodeToBox({x: 10, y: 20, width: 30, height: 40, level: 2})).toEqual({left: 10, styles: ['default'], top: 20, width: 30, height: 40, level: 2});
});
it('should return falsy for undefined', function () {
expect(nodeToBox()).toBeFalsy();
});
it('should return falsy for falsy', function () {
expect(nodeToBox(false)).toBeFalsy();
});
});
|
//= require redactor-rails/plugins/clips
//= require redactor-rails/plugins/fontcolor
//= require redactor-rails/plugins/fontfamily
//= require redactor-rails/plugins/fontsize
//= require redactor-rails/plugins/fullscreen
//= require redactor-rails/plugins/table
//= require redactor-rails/plugins/textdirection
//= require redactor-rails/plugins/video
|
import webpack from "webpack"
import { spawn } from "child_process"
import appRootDir from "app-root-dir"
import path from "path"
import { createNotification } from "./util"
import HotServerManager from "./HotServerManager"
import HotClientManager from "./HotClientManager"
import ConfigFactory from "../webpack/ConfigFactory"
import StatusPlugin from "../webpack/plugins/Status"
function safeDisposer(manager) {
return manager ? manager.dispose() : Promise.resolve()
}
/* eslint-disable arrow-body-style, no-console */
function createCompiler({ name, start, done })
{
try {
const webpackConfig = ConfigFactory({
target: name === "server" ? "node" : "web",
mode: "development"
})
// Offering a special status handling until Webpack offers a proper `done()` callback
// See also: https://github.com/webpack/webpack/issues/4243
webpackConfig.plugins.push(new StatusPlugin({ name, start, done }))
return webpack(webpackConfig)
}
catch (error)
{
createNotification({
title: "development",
level: "error",
message: "Webpack config is invalid, please check the console for more information.",
notify: true
})
console.error(error)
throw error
}
}
export default class HotController
{
constructor()
{
this.hotClientManager = null
this.hotServerManager = null
this.clientIsBuilding = false
this.serverIsBuilding = false
this.timeout = 0
const createClientManager = () =>
{
return new Promise((resolve) =>
{
const compiler = createCompiler({
name: "client",
start: () => {
this.clientIsBuilding = true
createNotification({
title: "Hot Client",
level: "info",
message: "Building new bundle..."
})
},
done: () =>
{
this.clientIsBuilding = false
createNotification({
title: "Hot Client",
level: "info",
message: "Bundle is ready.",
notify: true
})
resolve(compiler)
}
})
this.hotClientCompiler = compiler
this.hotClientManager = new HotClientManager(compiler)
})
}
const createServerManager = () =>
{
return new Promise((resolve) =>
{
const compiler = createCompiler({
name: "server",
start: () => {
this.serverIsBuilding = true
createNotification({
title: "Hot Server",
level: "info",
message: "Building new bundle..."
})
},
done: () => {
this.serverIsBuilding = false
createNotification({
title: "Hot Server",
level: "info",
message: "Bundle is ready.",
notify: true
})
this.tryStartServer()
resolve(compiler)
}
})
this.compiledServer = path.resolve(
appRootDir.get(),
compiler.options.output.path,
`${Object.keys(compiler.options.entry)[0]}.js`,
)
this.hotServerCompiler = compiler
this.hotServerManager = new HotServerManager(compiler, this.hotClientCompiler)
})
}
createClientManager().then(createServerManager).catch((error) => {
console.error("Error during build:", error)
})
}
tryStartServer = () =>
{
if (this.clientIsBuilding) {
if (this.serverTryTimeout) {
clearTimeout(this.serverTryTimeout)
}
this.serverTryTimeout = setTimeout(this.tryStartServer, this.timeout)
this.timeout += 100
return
}
this.startServer()
this.timeout = 0
}
startServer = () =>
{
if (this.server) {
this.server.kill()
this.server = null
createNotification({
title: "Hot Server",
level: "info",
message: "Restarting server..."
})
}
const newServer = spawn("node", [ "--inspect", this.compiledServer, "--colors" ], {
stdio: [ process.stdin, process.stdout, "pipe" ]
})
createNotification({
title: "Hot Server",
level: "info",
message: "Server running with latest changes.",
notify: true
})
newServer.stderr.on("data", (data) => {
createNotification({
title: "Hot Server",
level: "error",
message: "Error in server execution, check the console for more info."
})
process.stderr.write("\n")
process.stderr.write(data)
process.stderr.write("\n")
})
this.server = newServer
}
dispose()
{
// First the hot client server. Then dispose the hot node server.
return safeDisposer(this.hotClientManager).then(() => safeDisposer(this.hotServerManager)).catch((error) => {
console.error(error)
})
}
}
|
"use strict";
exports.__esModule = true;
// istanbul ignore next
var _createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ("value" in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor);
}
}return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor;
};
})();
// istanbul ignore next
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj["default"] = obj;return newObj;
}
}
// istanbul ignore next
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { "default": obj };
}
// istanbul ignore next
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _convertSourceMap = require("convert-source-map");
var _convertSourceMap2 = _interopRequireDefault(_convertSourceMap);
var _modules = require("../modules");
var _modules2 = _interopRequireDefault(_modules);
var _optionsOptionManager = require("./options/option-manager");
var _optionsOptionManager2 = _interopRequireDefault(_optionsOptionManager);
var _pluginManager = require("./plugin-manager");
var _pluginManager2 = _interopRequireDefault(_pluginManager);
var _shebangRegex = require("shebang-regex");
var _shebangRegex2 = _interopRequireDefault(_shebangRegex);
var _traversalPath = require("../../traversal/path");
var _traversalPath2 = _interopRequireDefault(_traversalPath);
var _lodashLangIsFunction = require("lodash/lang/isFunction");
var _lodashLangIsFunction2 = _interopRequireDefault(_lodashLangIsFunction);
var _sourceMap = require("source-map");
var _sourceMap2 = _interopRequireDefault(_sourceMap);
var _generation = require("../../generation");
var _generation2 = _interopRequireDefault(_generation);
var _helpersCodeFrame = require("../../helpers/code-frame");
var _helpersCodeFrame2 = _interopRequireDefault(_helpersCodeFrame);
var _lodashObjectDefaults = require("lodash/object/defaults");
var _lodashObjectDefaults2 = _interopRequireDefault(_lodashObjectDefaults);
var _lodashCollectionIncludes = require("lodash/collection/includes");
var _lodashCollectionIncludes2 = _interopRequireDefault(_lodashCollectionIncludes);
var _traversal = require("../../traversal");
var _traversal2 = _interopRequireDefault(_traversal);
var _tryResolve = require("try-resolve");
var _tryResolve2 = _interopRequireDefault(_tryResolve);
var _logger = require("./logger");
var _logger2 = _interopRequireDefault(_logger);
var _plugin = require("../plugin");
var _plugin2 = _interopRequireDefault(_plugin);
var _helpersParse = require("../../helpers/parse");
var _helpersParse2 = _interopRequireDefault(_helpersParse);
var _traversalHub = require("../../traversal/hub");
var _traversalHub2 = _interopRequireDefault(_traversalHub);
var _util = require("../../util");
var util = _interopRequireWildcard(_util);
var _path = require("path");
var _path2 = _interopRequireDefault(_path);
var _types = require("../../types");
var t = _interopRequireWildcard(_types);
/**
* [Please add a description.]
*/
var File = (function () {
function File(opts, pipeline) {
if (opts === undefined) opts = {};
_classCallCheck(this, File);
this.transformerDependencies = {};
this.dynamicImportTypes = {};
this.dynamicImportIds = {};
this.dynamicImports = [];
this.declarations = {};
this.usedHelpers = {};
this.dynamicData = {};
this.data = {};
this.ast = {};
this.metadata = {
modules: {
imports: [],
exports: {
exported: [],
specifiers: []
}
}
};
this.hub = new _traversalHub2["default"](this);
this.pipeline = pipeline;
this.log = new _logger2["default"](this, opts.filename || "unknown");
this.opts = this.initOptions(opts);
this.buildTransformers();
}
/**
* [Please add a description.]
*/
File.prototype.initOptions = function initOptions(opts) {
opts = new _optionsOptionManager2["default"](this.log, this.pipeline).init(opts);
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = _path2["default"].basename(opts.filename, _path2["default"].extname(opts.filename));
opts.ignore = util.arrayify(opts.ignore, util.regexify);
if (opts.only) opts.only = util.arrayify(opts.only, util.regexify);
_lodashObjectDefaults2["default"](opts, {
moduleRoot: opts.sourceRoot
});
_lodashObjectDefaults2["default"](opts, {
sourceRoot: opts.moduleRoot
});
_lodashObjectDefaults2["default"](opts, {
filenameRelative: opts.filename
});
_lodashObjectDefaults2["default"](opts, {
sourceFileName: opts.filenameRelative,
sourceMapTarget: opts.filenameRelative
});
//
if (opts.externalHelpers) {
this.set("helpersNamespace", t.identifier("babelHelpers"));
}
return opts;
};
/**
* [Please add a description.]
*/
File.prototype.isLoose = function isLoose(key) {
return _lodashCollectionIncludes2["default"](this.opts.loose, key);
};
/**
* [Please add a description.]
*/
File.prototype.buildTransformers = function buildTransformers() {
var file = this;
var transformers = this.transformers = {};
var secondaryStack = [];
var stack = [];
// build internal transformers
for (var key in this.pipeline.transformers) {
var transformer = this.pipeline.transformers[key];
var pass = transformers[key] = transformer.buildPass(file);
if (pass.canTransform()) {
stack.push(pass);
if (transformer.metadata.secondPass) {
secondaryStack.push(pass);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
}
// init plugins!
var beforePlugins = [];
var afterPlugins = [];
var pluginManager = new _pluginManager2["default"]({
file: this,
transformers: this.transformers,
before: beforePlugins,
after: afterPlugins
});
for (var i = 0; i < file.opts.plugins.length; i++) {
pluginManager.add(file.opts.plugins[i]);
}
stack = beforePlugins.concat(stack, afterPlugins);
// build transformer stack
this.uncollapsedTransformerStack = stack = stack.concat(secondaryStack);
// build dependency graph
var _arr = stack;
for (var _i = 0; _i < _arr.length; _i++) {
var pass = _arr[_i];var _arr2 = pass.plugin.dependencies;
for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
var dep = _arr2[_i2];
this.transformerDependencies[dep] = pass.key;
}
}
// collapse stack categories
this.transformerStack = this.collapseStack(stack);
};
/**
* [Please add a description.]
*/
File.prototype.collapseStack = function collapseStack(_stack) {
var stack = [];
var ignore = [];
var _arr3 = _stack;
for (var _i3 = 0; _i3 < _arr3.length; _i3++) {
var pass = _arr3[_i3];
// been merged
if (ignore.indexOf(pass) >= 0) continue;
var group = pass.plugin.metadata.group;
// can't merge
if (!pass.canTransform() || !group) {
stack.push(pass);
continue;
}
var mergeStack = [];
var _arr4 = _stack;
for (var _i4 = 0; _i4 < _arr4.length; _i4++) {
var _pass = _arr4[_i4];
if (_pass.plugin.metadata.group === group) {
mergeStack.push(_pass);
ignore.push(_pass);
}
}
var visitors = [];
var _arr5 = mergeStack;
for (var _i5 = 0; _i5 < _arr5.length; _i5++) {
var _pass2 = _arr5[_i5];
visitors.push(_pass2.plugin.visitor);
}
var visitor = _traversal2["default"].visitors.merge(visitors);
var mergePlugin = new _plugin2["default"](group, { visitor: visitor });
stack.push(mergePlugin.buildPass(this));
}
return stack;
};
/**
* [Please add a description.]
*/
File.prototype.set = function set(key, val) {
return this.data[key] = val;
};
/**
* [Please add a description.]
*/
File.prototype.setDynamic = function setDynamic(key, fn) {
this.dynamicData[key] = fn;
};
/**
* [Please add a description.]
*/
File.prototype.get = function get(key) {
var data = this.data[key];
if (data) {
return data;
} else {
var dynamic = this.dynamicData[key];
if (dynamic) {
return this.set(key, dynamic());
}
}
};
/**
* [Please add a description.]
*/
File.prototype.resolveModuleSource = function resolveModuleSource(source) {
var resolveModuleSource = this.opts.resolveModuleSource;
if (resolveModuleSource) source = resolveModuleSource(source, this.opts.filename);
return source;
};
/**
* [Please add a description.]
*/
File.prototype.addImport = function addImport(source, name, type) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
source = this.resolveModuleSource(source);
id = this.dynamicImportIds[name] = this.scope.generateUidIdentifier(name);
var specifiers = [t.importDefaultSpecifier(id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
if (type) {
var modules = this.dynamicImportTypes[type] = this.dynamicImportTypes[type] || [];
modules.push(declar);
}
if (this.transformers["es6.modules"].canTransform()) {
this.moduleFormatter.importSpecifier(specifiers[0], declar, this.dynamicImports, this.scope);
this.moduleFormatter.hasLocalImports = true;
} else {
this.dynamicImports.push(declar);
}
}
return id;
};
/**
* [Please add a description.]
*/
File.prototype.attachAuxiliaryComment = function attachAuxiliaryComment(node) {
var beforeComment = this.opts.auxiliaryCommentBefore;
if (beforeComment) {
node.leadingComments = node.leadingComments || [];
node.leadingComments.push({
type: "CommentLine",
value: " " + beforeComment
});
}
var afterComment = this.opts.auxiliaryCommentAfter;
if (afterComment) {
node.trailingComments = node.trailingComments || [];
node.trailingComments.push({
type: "CommentLine",
value: " " + afterComment
});
}
return node;
};
/**
* [Please add a description.]
*/
File.prototype.addHelper = function addHelper(name) {
var isSolo = _lodashCollectionIncludes2["default"](File.soloHelpers, name);
if (!isSolo && !_lodashCollectionIncludes2["default"](File.helpers, name)) {
throw new ReferenceError("Unknown helper " + name);
}
var declar = this.declarations[name];
if (declar) return declar;
this.usedHelpers[name] = true;
if (!isSolo) {
var generator = this.get("helperGenerator");
var runtime = this.get("helpersNamespace");
if (generator) {
return generator(name);
} else if (runtime) {
var id = t.identifier(t.toIdentifier(name));
return t.memberExpression(runtime, id);
}
}
var ref = util.template("helper-" + name);
var uid = this.declarations[name] = this.scope.generateUidIdentifier(name);
if (t.isFunctionExpression(ref) && !ref.id) {
ref.body._compact = true;
ref._generated = true;
ref.id = uid;
ref.type = "FunctionDeclaration";
this.attachAuxiliaryComment(ref);
this.path.unshiftContainer("body", ref);
} else {
ref._compact = true;
this.scope.push({
id: uid,
init: ref,
unique: true
});
}
return uid;
};
File.prototype.addTemplateObject = function addTemplateObject(helperName, strings, raw) {
// Generate a unique name based on the string literals so we dedupe
// identical strings used in the program.
var stringIds = raw.elements.map(function (string) {
return string.value;
});
var name = helperName + "_" + raw.elements.length + "_" + stringIds.join(",");
var declar = this.declarations[name];
if (declar) return declar;
var uid = this.declarations[name] = this.scope.generateUidIdentifier("templateObject");
var helperId = this.addHelper(helperName);
var init = t.callExpression(helperId, [strings, raw]);
init._compact = true;
this.scope.push({
id: uid,
init: init,
_blockHoist: 1.9 // This ensures that we don't fail if not using function expression helpers
});
return uid;
};
/**
* [Please add a description.]
*/
File.prototype.errorWithNode = function errorWithNode(node, msg) {
var Error = arguments.length <= 2 || arguments[2] === undefined ? SyntaxError : arguments[2];
var err;
var loc = node && (node.loc || node._loc);
if (loc) {
err = new Error("Line " + loc.start.line + ": " + msg);
err.loc = loc.start;
} else {
// todo: find errors with nodes inside to at least point to something
err = new Error("There's been an error on a dynamic node. This is almost certainly an internal error. Please report it.");
}
return err;
};
/**
* [Please add a description.]
*/
File.prototype.mergeSourceMap = function mergeSourceMap(map) {
var opts = this.opts;
var inputMap = opts.inputSourceMap;
if (inputMap) {
map.sources[0] = inputMap.file;
var inputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(inputMap);
var outputMapConsumer = new _sourceMap2["default"].SourceMapConsumer(map);
var outputMapGenerator = _sourceMap2["default"].SourceMapGenerator.fromSourceMap(outputMapConsumer);
outputMapGenerator.applySourceMap(inputMapConsumer);
var mergedMap = outputMapGenerator.toJSON();
mergedMap.sources = inputMap.sources;
mergedMap.file = inputMap.file;
return mergedMap;
}
return map;
};
/**
* [Please add a description.]
*/
File.prototype.getModuleFormatter = function getModuleFormatter(type) {
if (_lodashLangIsFunction2["default"](type) || !_modules2["default"][type]) {
this.log.deprecate("Custom module formatters are deprecated and will be removed in the next major. Please use Babel plugins instead.");
}
var ModuleFormatter = _lodashLangIsFunction2["default"](type) ? type : _modules2["default"][type];
if (!ModuleFormatter) {
var loc = _tryResolve2["default"].relative(type);
if (loc) ModuleFormatter = require(loc);
}
if (!ModuleFormatter) {
throw new ReferenceError("Unknown module formatter type " + JSON.stringify(type));
}
return new ModuleFormatter(this);
};
/**
* [Please add a description.]
*/
File.prototype.parse = function parse(code) {
var opts = this.opts;
//
var parseOpts = {
highlightCode: opts.highlightCode,
nonStandard: opts.nonStandard,
sourceType: opts.sourceType,
filename: opts.filename,
plugins: {}
};
var features = parseOpts.features = {};
for (var key in this.transformers) {
var transformer = this.transformers[key];
features[key] = transformer.canTransform();
}
parseOpts.looseModules = this.isLoose("es6.modules");
parseOpts.strictMode = features.strict;
this.log.debug("Parse start");
var ast = _helpersParse2["default"](code, parseOpts);
this.log.debug("Parse stop");
return ast;
};
/**
* [Please add a description.]
*/
File.prototype._addAst = function _addAst(ast) {
this.path = _traversalPath2["default"].get({
hub: this.hub,
parentPath: null,
parent: ast,
container: ast,
key: "program"
}).setContext();
this.scope = this.path.scope;
this.ast = ast;
};
/**
* [Please add a description.]
*/
File.prototype.addAst = function addAst(ast) {
this.log.debug("Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
this.log.debug("Start module formatter init");
var modFormatter = this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
if (modFormatter.init && this.transformers["es6.modules"].canTransform()) {
modFormatter.init();
}
this.log.debug("End module formatter init");
};
/**
* [Please add a description.]
*/
File.prototype.transform = function transform() {
this.call("pre");
var _arr6 = this.transformerStack;
for (var _i6 = 0; _i6 < _arr6.length; _i6++) {
var pass = _arr6[_i6];
pass.transform();
}
this.call("post");
return this.generate();
};
/**
* [Please add a description.]
*/
File.prototype.wrap = function wrap(code, callback) {
code = code + "";
try {
if (this.shouldIgnore()) {
return this.makeResult({ code: code, ignored: true });
} else {
return callback();
}
} catch (err) {
if (err._babel) {
throw err;
} else {
err._babel = true;
}
var message = err.message = this.opts.filename + ": " + err.message;
var loc = err.loc;
if (loc) {
err.codeFrame = _helpersCodeFrame2["default"](code, loc.line, loc.column + 1, this.opts);
message += "\n" + err.codeFrame;
}
if (process.browser) {
// chrome has it's own pretty stringifier which doesn't use the stack property
// https://github.com/babel/babel/issues/2175
err.message = message;
}
if (err.stack) {
var newStack = err.stack.replace(err.message, message);
try {
err.stack = newStack;
} catch (e) {
// `err.stack` may be a readonly property in some environments
}
}
throw err;
}
};
/**
* [Please add a description.]
*/
File.prototype.addCode = function addCode(code) {
code = (code || "") + "";
code = this.parseInputSourceMap(code);
this.code = code;
};
/**
* [Please add a description.]
*/
File.prototype.parseCode = function parseCode() {
this.parseShebang();
var ast = this.parse(this.code);
this.addAst(ast);
};
/**
* [Please add a description.]
*/
File.prototype.shouldIgnore = function shouldIgnore() {
var opts = this.opts;
return util.shouldIgnore(opts.filename, opts.ignore, opts.only);
};
/**
* [Please add a description.]
*/
File.prototype.call = function call(key) {
var _arr7 = this.uncollapsedTransformerStack;
for (var _i7 = 0; _i7 < _arr7.length; _i7++) {
var pass = _arr7[_i7];
var fn = pass.plugin[key];
if (fn) fn(this);
}
};
/**
* [Please add a description.]
*/
File.prototype.parseInputSourceMap = function parseInputSourceMap(code) {
var opts = this.opts;
if (opts.inputSourceMap !== false) {
var inputMap = _convertSourceMap2["default"].fromSource(code);
if (inputMap) {
opts.inputSourceMap = inputMap.toObject();
code = _convertSourceMap2["default"].removeComments(code);
}
}
return code;
};
/**
* [Please add a description.]
*/
File.prototype.parseShebang = function parseShebang() {
var shebangMatch = _shebangRegex2["default"].exec(this.code);
if (shebangMatch) {
this.shebang = shebangMatch[0];
this.code = this.code.replace(_shebangRegex2["default"], "");
}
};
/**
* [Please add a description.]
*/
File.prototype.makeResult = function makeResult(_ref) {
var code = _ref.code;
var _ref$map = _ref.map;
var map = _ref$map === undefined ? null : _ref$map;
var ast = _ref.ast;
var ignored = _ref.ignored;
var result = {
metadata: null,
ignored: !!ignored,
code: null,
ast: null,
map: map
};
if (this.opts.code) {
result.code = code;
}
if (this.opts.ast) {
result.ast = ast;
}
if (this.opts.metadata) {
result.metadata = this.metadata;
result.metadata.usedHelpers = Object.keys(this.usedHelpers);
}
return result;
};
/**
* [Please add a description.]
*/
File.prototype.generate = function generate() {
var opts = this.opts;
var ast = this.ast;
var result = { ast: ast };
if (!opts.code) return this.makeResult(result);
this.log.debug("Generation start");
var _result = _generation2["default"](ast, opts, this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
if (this.shebang) {
// add back shebang
result.code = this.shebang + "\n" + result.code;
}
if (result.map) {
result.map = this.mergeSourceMap(result.map);
}
if (opts.sourceMaps === "inline" || opts.sourceMaps === "both") {
result.code += "\n" + _convertSourceMap2["default"].fromObject(result.map).toComment();
}
if (opts.sourceMaps === "inline") {
result.map = null;
}
return this.makeResult(result);
};
_createClass(File, null, [{
key: "helpers",
/**
* [Please add a description.]
*/
value: ["inherits", "defaults", "create-class", "create-decorated-class", "create-decorated-object", "define-decorated-property-descriptor", "tagged-template-literal", "tagged-template-literal-loose", "to-array", "to-consumable-array", "sliced-to-array", "sliced-to-array-loose", "object-without-properties", "has-own", "slice", "bind", "define-property", "async-to-generator", "interop-export-wildcard", "interop-require-wildcard", "interop-require-default", "typeof", "extends", "get", "set", "new-arrow-check", "class-call-check", "object-destructuring-empty", "temporal-undefined", "temporal-assert-defined", "self-global", "typeof-react-element", "default-props", "instanceof",
// legacy
"interop-require"],
/**
* [Please add a description.]
*/
enumerable: true
}, {
key: "soloHelpers",
value: [],
enumerable: true
}]);
return File;
})();
exports["default"] = File;
module.exports = exports["default"];
//# sourceMappingURL=index-compiled.js.map |
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let SyncDisabled = props =>
<SvgIcon {...props}>
<path d="M10 6.35V4.26c-.8.21-1.55.54-2.23.96l1.46 1.46c.25-.12.5-.24.77-.33zm-7.14-.94l2.36 2.36C4.45 8.99 4 10.44 4 12c0 2.21.91 4.2 2.36 5.64L4 20h6v-6l-2.24 2.24C6.68 15.15 6 13.66 6 12c0-1 .25-1.94.68-2.77l8.08 8.08c-.25.13-.5.25-.77.34v2.09c.8-.21 1.55-.54 2.23-.96l2.36 2.36 1.27-1.27L4.14 4.14 2.86 5.41zM20 4h-6v6l2.24-2.24C17.32 8.85 18 10.34 18 12c0 1-.25 1.94-.68 2.77l1.46 1.46C19.55 15.01 20 13.56 20 12c0-2.21-.91-4.2-2.36-5.64L20 4z" />
</SvgIcon>;
SyncDisabled = pure(SyncDisabled);
SyncDisabled.muiName = 'SvgIcon';
export default SyncDisabled;
|
// Generated by CoffeeScript 1.6.3
(function() {
var Stl, stl_parser;
stl_parser = require('../parser/stl_parser');
Stl = (function() {
function Stl() {}
return Stl;
})();
Stl.PovRay = (function() {
function PovRay() {}
PovRay.prototype._povHeaders = function(name) {
return "#declare " + name + " = mesh {\n";
};
PovRay.prototype._povFooters = function() {
return "}";
};
PovRay.prototype.convertFile = function(filePath, callback, progressCb) {
var output,
_this = this;
output = "";
return stl_parser.parseFile(filePath, function(err, polygons, name) {
var unique_name;
if (err != null) {
callback(err);
return;
}
unique_name = '__' + name + '__';
output += _this._povFooters();
return callback(null, output, unique_name);
}, function(err, polygon, name) {
var povPolygon, unique_name;
unique_name = '__' + name + '__';
if (output.length === 0) {
output += _this._povHeaders(unique_name);
}
povPolygon = _this.convertPolygon(polygon);
output += povPolygon;
if (progressCb != null) {
return progressCb(err, povPolygon, unique_name);
}
});
};
PovRay.prototype.convertPolygon = function(polygon) {
var idx, output, vertex, _i, _len, _ref;
output = "";
output += " triangle {\n";
_ref = polygon.verticies;
for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) {
vertex = _ref[idx];
output += " <" + vertex[0] + ", " + (-vertex[1]) + ", " + vertex[2] + ">";
if (idx !== (polygon.verticies.length - 1)) {
output += ",\n";
}
}
output += " }\n";
return output;
};
return PovRay;
})();
module.exports = new Stl.PovRay();
}).call(this);
|
ace.define("ace/snippets/apache_conf",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText = "";
exports.scope = "apache_conf";
});
(function() {
ace.require(["ace/snippets/apache_conf"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
// @flow
var React = require('react')
var {assign} = require('lodash')
import {Source, emptySource} from './model/source'
import {displayIf, Colors} from './style'
// but get the images at 2x resolution so they can be retina yo
// or just get the photos at that ratio
// 200x320 x2
// 150x240
// 100x160
// Blank Image - http://i.imgur.com/bMwt85W.jpg
type Size = {
Width: number;
Height: number;
}
export var CoverSize = {
Width: 150,
Height: 240,
Ratio: 1.6
}
export var CoverThumb = {
Width: 50,
Height: 80,
}
export function coverStyle(url:string, size:Size = CoverSize):Object {
// otherwise it forgets about the cover. Wait until the image is ready
if (!url) {
return {}
}
return {
background: 'url('+url+') no-repeat center center',
backgroundSize: 'cover',
width: size.Width,
height: size.Height
}
}
export class CoverOverlay extends React.Component {
render():React.Element {
var style = assign(
displayIf(this.props.show !== false),
OverlayStyle,
CoverTextStyle,
this.props.style
)
return <div style={style}>
{this.props.children}
</div>
}
}
export class Cover extends React.Component {
props: {
src: string;
size?: Size;
children: Array<React.Element>;
};
render():React.Element {
var size = this.props.size || CoverSize
return <div style={assign(coverStyle(this.props.src, size), {position: 'relative'})}>
{this.props.children}
</div>
}
}
export class SourceCover extends React.Component {
render():React.Element {
var source:Source = this.props.source || emptySource()
var showTitle:bool = source.imageMissingTitle
return <Cover src={source.imageUrl}>
<CoverOverlay show={showTitle}>{source.name}</CoverOverlay>
</Cover>
}
}
// I could specify it in terms of percentages instead?
// that's a good idea.
// so do I want 2 or 3 across?
// definitely 3 :)
export var OverlayStyle = {
padding: 10,
color: Colors.light,
textAlign: 'center',
position: 'absolute',
bottom: 0,
fontSize: 18,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
width: CoverSize.Width
}
export var CoverTextStyle = {
fontSize: 18,
}
|
define([
'jquery',
'underscore',
'backbone',
'views/AdminView',
'authentication',
'models/Beach'
], function ( $, _, Backbone, AdminView, Authentication, BeachModel) {
var AdminRouter = Backbone.Router.extend({
routes: {
'admin' : 'index'
},
index: function () {
Authentication.authorize(function () {
$('#content').html("<p style='display: block; font-size: 15%; text-align: center; line-height: 100vh; margin: 0;'>LOADING</p>");
beaches = new BeachModel.Collection();
beaches.fetch( {
success: function( collection, response, options) {
var adminView = new AdminView({ collection: collection });
$('#content').html(adminView.el);
},
failure: function( collection, response, options) {
$('#content').html("An error has occured.");
}
});
}, true);
},
});
return AdminRouter;
}); |
const labels = {
collectionFilterLabels: {
edit: {
name: 'Event name',
event_type: 'Type of event',
address_country: 'Country',
uk_region: 'UK Region',
organiser: 'Organiser',
start_date_after: 'From',
start_date_before: 'To',
},
},
}
module.exports = labels
|
(function ($) {
var smileys = [
":(",
":)",
":O",
":D",
":p",
":*",
":-)",
":-(",
":-O",
":-D"
],
extras = {
"<3": true,
"<3": true
},
smileParts = {
"O": "middle-mouth",
"D": "middle-mouth",
"d": "middle-mouth",
"p": "low-mouth",
"*": "high-mouth",
"-": "nose"
},
oppositeSmileParts = {
"p": "d",
")": "(",
"(": ")"
},
reverseSmileys = [];
for (var i = 0; i < smileys.length; i++) {
var reverse = "";
for (var j = smileys[i].length - 1; j >= 0; j--) {
var character = smileys[i][j];
if (character in oppositeSmileParts) {
reverse += oppositeSmileParts[smileys[i][j]];
} else {
reverse += smileys[i][j];
}
}
reverseSmileys.push(reverse);
}
function toggleSmiley() {
$(this).toggleClass("active");
}
function prepareSmileys(html) {
for (var extra in extras) {
html = checkForSmiley(html, extra, extras[extra]);
}
for (var i = smileys.length - 1; i >= 0; i--) {
html = checkForSmiley(html, smileys[i], false);
}
for (var i = reverseSmileys.length - 1; i >= 0; i--) {
html = checkForSmiley(html, reverseSmileys[i], true);
}
return html;
}
function checkForSmiley(html, smiley, isReverse) {
var index = html.indexOf(smiley),
replace = null;
while (index >= 0) {
if (replace === null) {
replace = prepareSmiley(smiley, isReverse);
}
html = replaceString(html, replace, index, index + smiley.length);
index = html.indexOf(smiley, index + replace.length);
}
return html;
}
function prepareSmiley(smiley, isReverse) {
var html = '<span class="smiley-wrapper"><span class="smiley' +
(isReverse ? ' smiley-reverse' : '') +
'">';
for (var i = 0; i < smiley.length; i++) {
if (smiley[i] in smileParts) {
html += '<span class="' + smileParts[smiley[i]] + '">' + smiley[i] + '</span>';
} else {
html += smiley[i];
}
};
html += '</span></span>';
return html;
}
function replaceString(string, replace, from, to) {
return string.substring(0, from) + replace + string.substring(to);
}
function fixSmiles($el) {
var smiles = prepareSmileys($el.html());
$el.html(smiles);
}
$(document).on("click", ".smiley", toggleSmiley);
$.fn.smilify = function() {
var $els = $(this).each(function () {
fixSmiles($(this));
});
setTimeout(function () {
$els.find(".smiley").each(toggleSmiley);
}, 20);
return this;
};
}(jQuery)); |
/*
* jQuery UI 1.7.2
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
(function($) {
var _remove = $.fn.remove,
isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);
//Helper functions and ui object
$.ui = {
version: "1.7.2",
// $.ui.plugin is deprecated. Use the proxy pattern instead.
plugin: {
add: function(module, option, set) {
var proto = $.ui[module].prototype;
for(var i in set) {
proto.plugins[i] = proto.plugins[i] || [];
proto.plugins[i].push([option, set[i]]);
}
},
call: function(instance, name, args) {
var set = instance.plugins[name];
if(!set || !instance.element[0].parentNode) { return; }
for (var i = 0; i < set.length; i++) {
if (instance.options[set[i][0]]) {
set[i][1].apply(instance.element, args);
}
}
}
},
contains: function(a, b) {
return document.compareDocumentPosition
? a.compareDocumentPosition(b) & 16
: a !== b && a.contains(b);
},
hasScroll: function(el, a) {
//If overflow is hidden, the element might have extra content, but the user wants to hide it
if ($(el).css('overflow') == 'hidden') { return false; }
var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
has = false;
if (el[scroll] > 0) { return true; }
// TODO: determine which cases actually cause this to happen
// if the element doesn't have the scroll set, see if it's possible to
// set the scroll
el[scroll] = 1;
has = (el[scroll] > 0);
el[scroll] = 0;
return has;
},
isOverAxis: function(x, reference, size) {
//Determines when x coordinate is over "b" element axis
return (x > reference) && (x < (reference + size));
},
isOver: function(y, x, top, left, height, width) {
//Determines when x, y coordinates is over "b" element
return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
},
keyCode: {
BACKSPACE: 8,
CAPS_LOCK: 20,
COMMA: 188,
CONTROL: 17,
DELETE: 46,
DOWN: 40,
END: 35,
ENTER: 13,
ESCAPE: 27,
HOME: 36,
INSERT: 45,
LEFT: 37,
NUMPAD_ADD: 107,
NUMPAD_DECIMAL: 110,
NUMPAD_DIVIDE: 111,
NUMPAD_ENTER: 108,
NUMPAD_MULTIPLY: 106,
NUMPAD_SUBTRACT: 109,
PAGE_DOWN: 34,
PAGE_UP: 33,
PERIOD: 190,
RIGHT: 39,
SHIFT: 16,
SPACE: 32,
TAB: 9,
UP: 38
}
};
// WAI-ARIA normalization
if (isFF2) {
var attr = $.attr,
removeAttr = $.fn.removeAttr,
ariaNS = "http://www.w3.org/2005/07/aaa",
ariaState = /^aria-/,
ariaRole = /^wairole:/;
$.attr = function(elem, name, value) {
var set = value !== undefined;
return (name == 'role'
? (set
? attr.call(this, elem, name, "wairole:" + value)
: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
: (ariaState.test(name)
? (set
? elem.setAttributeNS(ariaNS,
name.replace(ariaState, "aaa:"), value)
: attr.call(this, elem, name.replace(ariaState, "aaa:")))
: attr.apply(this, arguments)));
};
$.fn.removeAttr = function(name) {
return (ariaState.test(name)
? this.each(function() {
this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
}) : removeAttr.call(this, name));
};
}
//jQuery plugins
$.fn.extend({
remove: function() {
// Safari has a native remove event which actually removes DOM elements,
// so we have to use triggerHandler instead of trigger (#3037).
$("*", this).add(this).each(function() {
$(this).triggerHandler("remove");
});
return _remove.apply(this, arguments );
},
enableSelection: function() {
return this
.attr('unselectable', 'off')
.css('MozUserSelect', '')
.unbind('selectstart.ui');
},
disableSelection: function() {
return this
.attr('unselectable', 'on')
.css('MozUserSelect', 'none')
.bind('selectstart.ui', function() { return false; });
},
scrollParent: function() {
var scrollParent;
if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
scrollParent = this.parents().filter(function() {
return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
} else {
scrollParent = this.parents().filter(function() {
return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
}).eq(0);
}
return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
}
});
//Additional selectors
$.extend($.expr[':'], {
data: function(elem, i, match) {
return !!$.data(elem, match[3]);
},
focusable: function(element) {
var nodeName = element.nodeName.toLowerCase(),
tabIndex = $.attr(element, 'tabindex');
return (/input|select|textarea|button|object/.test(nodeName)
? !element.disabled
: 'a' == nodeName || 'area' == nodeName
? element.href || !isNaN(tabIndex)
: !isNaN(tabIndex))
// the element and all of its ancestors must be visible
// the browser may report that the area is hidden
&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
},
tabbable: function(element) {
var tabIndex = $.attr(element, 'tabindex');
return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
}
});
// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
function getMethods(type) {
var methods = $[namespace][plugin][type] || [];
return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
}
var methods = getMethods('getter');
if (args.length == 1 && typeof args[0] == 'string') {
methods = methods.concat(getMethods('getterSetter'));
}
return ($.inArray(method, methods) != -1);
}
$.widget = function(name, prototype) {
var namespace = name.split(".")[0];
name = name.split(".")[1];
// create plugin method
$.fn[name] = function(options) {
var isMethodCall = (typeof options == 'string'),
args = Array.prototype.slice.call(arguments, 1);
// prevent calls to internal methods
if (isMethodCall && options.substring(0, 1) == '_') {
return this;
}
// handle getter methods
if (isMethodCall && getter(namespace, name, options, args)) {
var instance = $.data(this[0], name);
return (instance ? instance[options].apply(instance, args)
: undefined);
}
// handle initialization and non-getter methods
return this.each(function() {
var instance = $.data(this, name);
// constructor
(!instance && !isMethodCall &&
$.data(this, name, new $[namespace][name](this, options))._init());
// method call
(instance && isMethodCall && $.isFunction(instance[options]) &&
instance[options].apply(instance, args));
});
};
// create widget constructor
$[namespace] = $[namespace] || {};
$[namespace][name] = function(element, options) {
var self = this;
this.namespace = namespace;
this.widgetName = name;
this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
this.widgetBaseClass = namespace + '-' + name;
this.options = $.extend({},
$.widget.defaults,
$[namespace][name].defaults,
$.metadata && $.metadata.get(element)[name],
options);
this.element = $(element)
.bind('setData.' + name, function(event, key, value) {
if (event.target == element) {
return self._setData(key, value);
}
})
.bind('getData.' + name, function(event, key) {
if (event.target == element) {
return self._getData(key);
}
})
.bind('remove', function() {
return self.destroy();
});
};
// add widget prototype
$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
// TODO: merge getter and getterSetter properties from widget prototype
// and plugin prototype
$[namespace][name].getterSetter = 'option';
};
$.widget.prototype = {
_init: function() {},
destroy: function() {
this.element.removeData(this.widgetName)
.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
.removeAttr('aria-disabled');
},
option: function(key, value) {
var options = key,
self = this;
if (typeof key == "string") {
if (value === undefined) {
return this._getData(key);
}
options = {};
options[key] = value;
}
$.each(options, function(key, value) {
self._setData(key, value);
});
},
_getData: function(key) {
return this.options[key];
},
_setData: function(key, value) {
this.options[key] = value;
if (key == 'disabled') {
this.element
[value ? 'addClass' : 'removeClass'](
this.widgetBaseClass + '-disabled' + ' ' +
this.namespace + '-state-disabled')
.attr("aria-disabled", value);
}
},
enable: function() {
this._setData('disabled', false);
},
disable: function() {
this._setData('disabled', true);
},
_trigger: function(type, event, data) {
var callback = this.options[type],
eventName = (type == this.widgetEventPrefix
? type : this.widgetEventPrefix + type);
event = $.Event(event);
event.type = eventName;
// copy original event properties over to the new event
// this would happen if we could call $.event.fix instead of $.Event
// but we don't have a way to force an event to be fixed multiple times
if (event.originalEvent) {
for (var i = $.event.props.length, prop; i;) {
prop = $.event.props[--i];
event[prop] = event.originalEvent[prop];
}
}
this.element.trigger(event, data);
return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
|| event.isDefaultPrevented());
}
};
$.widget.defaults = {
disabled: false
};
/** Mouse Interaction Plugin **/
$.ui.mouse = {
_mouseInit: function() {
var self = this;
this.element
.bind('mousedown.'+this.widgetName, function(event) {
return self._mouseDown(event);
})
.bind('click.'+this.widgetName, function(event) {
if(self._preventClickEvent) {
self._preventClickEvent = false;
event.stopImmediatePropagation();
return false;
}
});
// Prevent text selection in IE
if ($.browser.msie) {
this._mouseUnselectable = this.element.attr('unselectable');
this.element.attr('unselectable', 'on');
}
this.started = false;
},
// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
_mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);
// Restore text selection in IE
($.browser.msie
&& this.element.attr('unselectable', this._mouseUnselectable));
},
_mouseDown: function(event) {
// don't let more than one widget handle mouseStart
// TODO: figure out why we have to use originalEvent
event.originalEvent = event.originalEvent || {};
if (event.originalEvent.mouseHandled) { return; }
// we may have missed mouseup (out of window)
(this._mouseStarted && this._mouseUp(event));
this._mouseDownEvent = event;
var self = this,
btnIsLeft = (event.which == 1),
elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
return true;
}
this.mouseDelayMet = !this.options.delay;
if (!this.mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self.mouseDelayMet = true;
}, this.options.delay);
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted = (this._mouseStart(event) !== false);
if (!this._mouseStarted) {
event.preventDefault();
return true;
}
}
// these delegates are required to keep context
this._mouseMoveDelegate = function(event) {
return self._mouseMove(event);
};
this._mouseUpDelegate = function(event) {
return self._mouseUp(event);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
// preventDefault() is used to prevent the selection of text here -
// however, in Safari, this causes select boxes not to be selectable
// anymore, so this fix is needed
($.browser.safari || event.preventDefault());
event.originalEvent.mouseHandled = true;
return true;
},
_mouseMove: function(event) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.browser.msie && !event.button) {
return this._mouseUp(event);
}
if (this._mouseStarted) {
this._mouseDrag(event);
return event.preventDefault();
}
if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
this._mouseStarted =
(this._mouseStart(this._mouseDownEvent, event) !== false);
(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
}
return !this._mouseStarted;
},
_mouseUp: function(event) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
if (this._mouseStarted) {
this._mouseStarted = false;
this._preventClickEvent = (event.target == this._mouseDownEvent.target);
this._mouseStop(event);
}
return false;
},
_mouseDistanceMet: function(event) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - event.pageX),
Math.abs(this._mouseDownEvent.pageY - event.pageY)
) >= this.options.distance
);
},
_mouseDelayMet: function(event) {
return this.mouseDelayMet;
},
// These are placeholder methods, to be overriden by extending plugin
_mouseStart: function(event) {},
_mouseDrag: function(event) {},
_mouseStop: function(event) {},
_mouseCapture: function(event) { return true; }
};
$.ui.mouse.defaults = {
cancel: null,
distance: 1,
delay: 0
};
})(jQuery);
/*
* jQuery UI Tabs 1.7.2
*
* Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI/Tabs
*
* Depends:
* ui.core.js
*/
(function($) {
$.widget("ui.tabs", {
_init: function() {
if (this.options.deselectable !== undefined) {
this.options.collapsible = this.options.deselectable;
}
this._tabify(true);
},
_setData: function(key, value) {
if (key == 'selected') {
if (this.options.collapsible && value == this.options.selected) {
return;
}
this.select(value);
}
else {
this.options[key] = value;
if (key == 'deselectable') {
this.options.collapsible = value;
}
this._tabify();
}
},
_tabId: function(a) {
return a.title && a.title.replace(/\s/g, '_').replace(/[^A-Za-z0-9\-_:\.]/g, '') ||
this.options.idPrefix + $.data(a);
},
_sanitizeSelector: function(hash) {
return hash.replace(/:/g, '\\:'); // we need this because an id may contain a ":"
},
_cookie: function() {
var cookie = this.cookie || (this.cookie = this.options.cookie.name || 'ui-tabs-' + $.data(this.list[0]));
return $.cookie.apply(null, [cookie].concat($.makeArray(arguments)));
},
_ui: function(tab, panel) {
return {
tab: tab,
panel: panel,
index: this.anchors.index(tab)
};
},
_cleanup: function() {
// restore all former loading tabs labels
this.lis.filter('.ui-state-processing').removeClass('ui-state-processing')
.find('span:data(label.tabs)')
.each(function() {
var el = $(this);
el.html(el.data('label.tabs')).removeData('label.tabs');
});
},
_tabify: function(init) {
this.list = this.element.children('ul:first');
this.lis = $('li:has(a[href])', this.list);
this.anchors = this.lis.map(function() { return $('a', this)[0]; });
this.panels = $([]);
var self = this, o = this.options;
var fragmentId = /^#.+/; // Safari 2 reports '#' for an empty hash
this.anchors.each(function(i, a) {
var href = $(a).attr('href');
// For dynamically created HTML that contains a hash as href IE < 8 expands
// such href to the full page url with hash and then misinterprets tab as ajax.
// Same consideration applies for an added tab with a fragment identifier
// since a[href=#fragment-identifier] does unexpectedly not match.
// Thus normalize href attribute...
var hrefBase = href.split('#')[0], baseEl;
if (hrefBase && (hrefBase === location.toString().split('#')[0] ||
(baseEl = $('base')[0]) && hrefBase === baseEl.href)) {
href = a.hash;
a.href = href;
}
// inline tab
if (fragmentId.test(href)) {
self.panels = self.panels.add(self._sanitizeSelector(href));
}
// remote tab
else if (href != '#') { // prevent loading the page itself if href is just "#"
$.data(a, 'href.tabs', href); // required for restore on destroy
// TODO until #3808 is fixed strip fragment identifier from url
// (IE fails to load from such url)
$.data(a, 'load.tabs', href.replace(/#.*$/, '')); // mutable data
var id = self._tabId(a);
a.href = '#' + id;
var $panel = $('#' + id);
if (!$panel.length) {
$panel = $(o.panelTemplate).attr('id', id).addClass('ui-tabs-panel ui-widget-content ui-corner-bottom')
.insertAfter(self.panels[i - 1] || self.list);
$panel.data('destroy.tabs', true);
}
self.panels = self.panels.add($panel);
}
// invalid tab href
else {
o.disabled.push(i);
}
});
// initialization from scratch
if (init) {
// attach necessary classes for styling
this.element.addClass('ui-tabs ui-widget ui-widget-content ui-corner-all');
this.list.addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
this.lis.addClass('ui-state-default ui-corner-top');
this.panels.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom');
// Selected tab
// use "selected" option or try to retrieve:
// 1. from fragment identifier in url
// 2. from cookie
// 3. from selected class attribute on <li>
if (o.selected === undefined) {
if (location.hash) {
this.anchors.each(function(i, a) {
if (a.hash == location.hash) {
o.selected = i;
return false; // break
}
});
}
if (typeof o.selected != 'number' && o.cookie) {
o.selected = parseInt(self._cookie(), 10);
}
if (typeof o.selected != 'number' && this.lis.filter('.ui-tabs-selected').length) {
o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
}
o.selected = o.selected || 0;
}
else if (o.selected === null) { // usage of null is deprecated, TODO remove in next release
o.selected = -1;
}
// sanity check - default to first tab...
o.selected = ((o.selected >= 0 && this.anchors[o.selected]) || o.selected < 0) ? o.selected : 0;
// Take disabling tabs via class attribute from HTML
// into account and update option properly.
// A selected tab cannot become disabled.
o.disabled = $.unique(o.disabled.concat(
$.map(this.lis.filter('.ui-state-disabled'),
function(n, i) { return self.lis.index(n); } )
)).sort();
if ($.inArray(o.selected, o.disabled) != -1) {
o.disabled.splice($.inArray(o.selected, o.disabled), 1);
}
// highlight selected tab
this.panels.addClass('ui-tabs-hide');
this.lis.removeClass('ui-tabs-selected ui-state-active');
if (o.selected >= 0 && this.anchors.length) { // check for length avoids error when initializing empty list
this.panels.eq(o.selected).removeClass('ui-tabs-hide');
this.lis.eq(o.selected).addClass('ui-tabs-selected ui-state-active');
// seems to be expected behavior that the show callback is fired
self.element.queue("tabs", function() {
self._trigger('show', null, self._ui(self.anchors[o.selected], self.panels[o.selected]));
});
this.load(o.selected);
}
// clean up to avoid memory leaks in certain versions of IE 6
$(window).bind('unload', function() {
self.lis.add(self.anchors).unbind('.tabs');
self.lis = self.anchors = self.panels = null;
});
}
// update selected after add/remove
else {
o.selected = this.lis.index(this.lis.filter('.ui-tabs-selected'));
}
// update collapsible
this.element[o.collapsible ? 'addClass' : 'removeClass']('ui-tabs-collapsible');
// set or update cookie after init and add/remove respectively
if (o.cookie) {
this._cookie(o.selected, o.cookie);
}
// disable tabs
for (var i = 0, li; (li = this.lis[i]); i++) {
$(li)[$.inArray(i, o.disabled) != -1 &&
!$(li).hasClass('ui-tabs-selected') ? 'addClass' : 'removeClass']('ui-state-disabled');
}
// reset cache if switching from cached to not cached
if (o.cache === false) {
this.anchors.removeData('cache.tabs');
}
// remove all handlers before, tabify may run on existing tabs after add or option change
this.lis.add(this.anchors).unbind('.tabs');
if (o.event != 'mouseover') {
var addState = function(state, el) {
if (el.is(':not(.ui-state-disabled)')) {
el.addClass('ui-state-' + state);
}
};
var removeState = function(state, el) {
el.removeClass('ui-state-' + state);
};
this.lis.bind('mouseover.tabs', function() {
addState('hover', $(this));
});
this.lis.bind('mouseout.tabs', function() {
removeState('hover', $(this));
});
this.anchors.bind('focus.tabs', function() {
addState('focus', $(this).closest('li'));
});
this.anchors.bind('blur.tabs', function() {
removeState('focus', $(this).closest('li'));
});
}
// set up animations
var hideFx, showFx;
if (o.fx) {
if ($.isArray(o.fx)) {
hideFx = o.fx[0];
showFx = o.fx[1];
}
else {
hideFx = showFx = o.fx;
}
}
// Reset certain styles left over from animation
// and prevent IE's ClearType bug...
function resetStyle($el, fx) {
$el.css({ display: '' });
if ($.browser.msie && fx.opacity) {
$el[0].style.removeAttribute('filter');
}
}
// Show a tab...
var showTab = showFx ?
function(clicked, $show) {
$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
$show.hide().removeClass('ui-tabs-hide') // avoid flicker that way
.animate(showFx, showFx.duration || 'normal', function() {
resetStyle($show, showFx);
self._trigger('show', null, self._ui(clicked, $show[0]));
});
} :
function(clicked, $show) {
$(clicked).closest('li').removeClass('ui-state-default').addClass('ui-tabs-selected ui-state-active');
$show.removeClass('ui-tabs-hide');
self._trigger('show', null, self._ui(clicked, $show[0]));
};
// Hide a tab, $show is optional...
var hideTab = hideFx ?
function(clicked, $hide) {
$hide.animate(hideFx, hideFx.duration || 'normal', function() {
self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
$hide.addClass('ui-tabs-hide');
resetStyle($hide, hideFx);
self.element.dequeue("tabs");
});
} :
function(clicked, $hide, $show) {
self.lis.removeClass('ui-tabs-selected ui-state-active').addClass('ui-state-default');
$hide.addClass('ui-tabs-hide');
self.element.dequeue("tabs");
};
// attach tab event handler, unbind to avoid duplicates from former tabifying...
this.anchors.bind(o.event + '.tabs', function() {
var el = this, $li = $(this).closest('li'), $hide = self.panels.filter(':not(.ui-tabs-hide)'),
$show = $(self._sanitizeSelector(this.hash));
// If tab is already selected and not collapsible or tab disabled or
// or is already loading or click callback returns false stop here.
// Check if click handler returns false last so that it is not executed
// for a disabled or loading tab!
if (($li.hasClass('ui-tabs-selected') && !o.collapsible) ||
$li.hasClass('ui-state-disabled') ||
$li.hasClass('ui-state-processing') ||
self._trigger('select', null, self._ui(this, $show[0])) === false) {
this.blur();
return false;
}
o.selected = self.anchors.index(this);
self.abort();
// if tab may be closed
if (o.collapsible) {
if ($li.hasClass('ui-tabs-selected')) {
o.selected = -1;
if (o.cookie) {
self._cookie(o.selected, o.cookie);
}
self.element.queue("tabs", function() {
hideTab(el, $hide);
}).dequeue("tabs");
this.blur();
return false;
}
else if (!$hide.length) {
if (o.cookie) {
self._cookie(o.selected, o.cookie);
}
self.element.queue("tabs", function() {
showTab(el, $show);
});
self.load(self.anchors.index(this)); // TODO make passing in node possible, see also http://dev.jqueryui.com/ticket/3171
this.blur();
return false;
}
}
if (o.cookie) {
self._cookie(o.selected, o.cookie);
}
// show new tab
if ($show.length) {
if ($hide.length) {
self.element.queue("tabs", function() {
hideTab(el, $hide);
});
}
self.element.queue("tabs", function() {
showTab(el, $show);
});
self.load(self.anchors.index(this));
}
else {
throw 'jQuery UI Tabs: Mismatching fragment identifier.';
}
// Prevent IE from keeping other link focussed when using the back button
// and remove dotted border from clicked link. This is controlled via CSS
// in modern browsers; blur() removes focus from address bar in Firefox
// which can become a usability and annoying problem with tabs('rotate').
if ($.browser.msie) {
this.blur();
}
});
// disable click in any case
this.anchors.bind('click.tabs', function(){return false;});
},
destroy: function() {
var o = this.options;
this.abort();
this.element.unbind('.tabs')
.removeClass('ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible')
.removeData('tabs');
this.list.removeClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
this.anchors.each(function() {
var href = $.data(this, 'href.tabs');
if (href) {
this.href = href;
}
var $this = $(this).unbind('.tabs');
$.each(['href', 'load', 'cache'], function(i, prefix) {
$this.removeData(prefix + '.tabs');
});
});
this.lis.unbind('.tabs').add(this.panels).each(function() {
if ($.data(this, 'destroy.tabs')) {
$(this).remove();
}
else {
$(this).removeClass([
'ui-state-default',
'ui-corner-top',
'ui-tabs-selected',
'ui-state-active',
'ui-state-hover',
'ui-state-focus',
'ui-state-disabled',
'ui-tabs-panel',
'ui-widget-content',
'ui-corner-bottom',
'ui-tabs-hide'
].join(' '));
}
});
if (o.cookie) {
this._cookie(null, o.cookie);
}
},
add: function(url, label, index) {
if (index === undefined) {
index = this.anchors.length; // append by default
}
var self = this, o = this.options,
$li = $(o.tabTemplate.replace(/#\{href\}/g, url).replace(/#\{label\}/g, label)),
id = !url.indexOf('#') ? url.replace('#', '') : this._tabId($('a', $li)[0]);
$li.addClass('ui-state-default ui-corner-top').data('destroy.tabs', true);
// try to find an existing element before creating a new one
var $panel = $('#' + id);
if (!$panel.length) {
$panel = $(o.panelTemplate).attr('id', id).data('destroy.tabs', true);
}
$panel.addClass('ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide');
if (index >= this.lis.length) {
$li.appendTo(this.list);
$panel.appendTo(this.list[0].parentNode);
}
else {
$li.insertBefore(this.lis[index]);
$panel.insertBefore(this.panels[index]);
}
o.disabled = $.map(o.disabled,
function(n, i) { return n >= index ? ++n : n; });
this._tabify();
if (this.anchors.length == 1) { // after tabify
$li.addClass('ui-tabs-selected ui-state-active');
$panel.removeClass('ui-tabs-hide');
this.element.queue("tabs", function() {
self._trigger('show', null, self._ui(self.anchors[0], self.panels[0]));
});
this.load(0);
}
// callback
this._trigger('add', null, this._ui(this.anchors[index], this.panels[index]));
},
remove: function(index) {
var o = this.options, $li = this.lis.eq(index).remove(),
$panel = this.panels.eq(index).remove();
// If selected tab was removed focus tab to the right or
// in case the last tab was removed the tab to the left.
if ($li.hasClass('ui-tabs-selected') && this.anchors.length > 1) {
this.select(index + (index + 1 < this.anchors.length ? 1 : -1));
}
o.disabled = $.map($.grep(o.disabled, function(n, i) { return n != index; }),
function(n, i) { return n >= index ? --n : n; });
this._tabify();
// callback
this._trigger('remove', null, this._ui($li.find('a')[0], $panel[0]));
},
enable: function(index) {
var o = this.options;
if ($.inArray(index, o.disabled) == -1) {
return;
}
this.lis.eq(index).removeClass('ui-state-disabled');
o.disabled = $.grep(o.disabled, function(n, i) { return n != index; });
// callback
this._trigger('enable', null, this._ui(this.anchors[index], this.panels[index]));
},
disable: function(index) {
var self = this, o = this.options;
if (index != o.selected) { // cannot disable already selected tab
this.lis.eq(index).addClass('ui-state-disabled');
o.disabled.push(index);
o.disabled.sort();
// callback
this._trigger('disable', null, this._ui(this.anchors[index], this.panels[index]));
}
},
select: function(index) {
if (typeof index == 'string') {
index = this.anchors.index(this.anchors.filter('[href$=' + index + ']'));
}
else if (index === null) { // usage of null is deprecated, TODO remove in next release
index = -1;
}
if (index == -1 && this.options.collapsible) {
index = this.options.selected;
}
this.anchors.eq(index).trigger(this.options.event + '.tabs');
},
load: function(index) {
var self = this, o = this.options, a = this.anchors.eq(index)[0], url = $.data(a, 'load.tabs');
this.abort();
// not remote or from cache
if (!url || this.element.queue("tabs").length !== 0 && $.data(a, 'cache.tabs')) {
this.element.dequeue("tabs");
return;
}
// load remote from here on
this.lis.eq(index).addClass('ui-state-processing');
if (o.spinner) {
var span = $('span', a);
span.data('label.tabs', span.html()).html(o.spinner);
}
this.xhr = $.ajax($.extend({}, o.ajaxOptions, {
url: url,
success: function(r, s) {
$(self._sanitizeSelector(a.hash)).html(r);
// take care of tab labels
self._cleanup();
if (o.cache) {
$.data(a, 'cache.tabs', true); // if loaded once do not load them again
}
// callbacks
self._trigger('load', null, self._ui(self.anchors[index], self.panels[index]));
try {
o.ajaxOptions.success(r, s);
}
catch (e) {}
// last, so that load event is fired before show...
self.element.dequeue("tabs");
}
}));
},
abort: function() {
// stop possibly running animations
this.element.queue([]);
this.panels.stop(false, true);
// terminate pending requests from other tabs
if (this.xhr) {
this.xhr.abort();
delete this.xhr;
}
// take care of tab labels
this._cleanup();
},
url: function(index, url) {
this.anchors.eq(index).removeData('cache.tabs').data('load.tabs', url);
},
length: function() {
return this.anchors.length;
}
});
$.extend($.ui.tabs, {
version: '1.7.2',
getter: 'length',
defaults: {
ajaxOptions: null,
cache: false,
cookie: null, // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
collapsible: false,
disabled: [],
event: 'click',
fx: null, // e.g. { height: 'toggle', opacity: 'toggle', duration: 200 }
idPrefix: 'ui-tabs-',
panelTemplate: '<div></div>',
spinner: '<em>Loading…</em>',
tabTemplate: '<li><a href="#{href}"><span>#{label}</span></a></li>'
}
});
/*
* Tabs Extensions
*/
/*
* Rotate
*/
$.extend($.ui.tabs.prototype, {
rotation: null,
rotate: function(ms, continuing) {
var self = this, o = this.options;
var rotate = self._rotate || (self._rotate = function(e) {
clearTimeout(self.rotation);
self.rotation = setTimeout(function() {
var t = o.selected;
self.select( ++t < self.anchors.length ? t : 0 );
}, ms);
if (e) {
e.stopPropagation();
}
});
var stop = self._unrotate || (self._unrotate = !continuing ?
function(e) {
if (e.clientX) { // in case of a true click
self.rotate(null);
}
} :
function(e) {
t = o.selected;
rotate();
});
// start rotation
if (ms) {
this.element.bind('tabsshow', rotate);
this.anchors.bind(o.event + '.tabs', stop);
rotate();
}
// stop rotation
else {
clearTimeout(self.rotation);
this.element.unbind('tabsshow', rotate);
this.anchors.unbind(o.event + '.tabs', stop);
delete this._rotate;
delete this._unrotate;
}
}
});
})(jQuery);
|
//@flow
var x = 42;
x = "true";
var y = 42;
if (x) {
y = "hello world";
}
(42: string); // should still have some errors!
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BeachAccess = props =>
<SvgIcon {...props}>
<path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z" />
</SvgIcon>;
BeachAccess = pure(BeachAccess);
BeachAccess.muiName = 'SvgIcon';
export default BeachAccess;
|
/*
A proxy for observing object state changes.
var obj={person:'Eddie',age:22};
_o.onUpdate(obj,{
age:function(value){
if(value>this.oldValue)
console.log('Happy birthday, Peter!')
},
person:function(value){
console.log(this.oldValue+' is now '+value);
}
});
_o(obj).person='Peter';
//> Eddie is now Peter
_o(obj).age++;
//> Happy birthday, Peter!
*/
!function(){
'use strict';
var tl=function(i,ln,ms){
return function(ms,f){
i++;
if(f()) ln='info',ms='Test '+i+' passed: '+ms;
else ln='error',ms='Test '+i+' failed: '+ms;
console[ln](ms)}}(0);
var cl=function(){
console.log.apply(console,arguments)};
var observingProxy=function(targetStack,proxyStack,changeStack,handlerStack,timeoutStack){
function getDeepPropertyDescriptors(o)
{
var ns;
if(o){
ns=getDeepPropertyDescriptors(Object.getPrototypeOf(o))||[];
Array.prototype.push.apply(ns,
Object.getOwnPropertyNames(o)
.filter(function(k){
return isNaN(parseInt(k))})
.map(function(k){
return {name:k,descriptor:Object.getOwnPropertyDescriptor(o,k)}}));
}
return ns;
}
function newProxy(t)
{
var p={},ns=getDeepPropertyDescriptors(t);
for(var i=ns.length;i--;){
delete ns[i].descriptor.value;
delete ns[i].descriptor.writable;
ns[i].descriptor.get=propertyGetter.bind({target:t,name:ns[i].name});
ns[i].descriptor.set=propertySetter.bind({target:t,name:ns[i].name});
try{
Object.defineProperty(p,ns[i].name,ns[i].descriptor);
}
catch(e){}
}
return p;
}
function notifyObservers(target)
{
var targetInd=targetIndex(target);
if(changeStack[targetInd].length){
for(var l=0;l<handlerStack[targetInd].length;l++)
handlerStack[targetInd][l].call({},changeStack[targetInd]);
changeStack[targetInd]=[];
}
}
function propertyGetter()
{
var r=this.target[this.name];
if(Array.isArray(this.target)&&['pop','push','shift','splice','unshift'].
indexOf(this.name)>-1)
r=function(){
var res=this.target[this.name].apply(this.target,arguments),
targetInd=targetIndex(this.target);
changeStack[targetInd].push(({
'pop':{object:this.target,type:'splice',index:this.target.length-1,
removed:[res],addedCount:0},
'push':{object:this.target,type:'splice',index:this.target.length-1,
removed:[],addedCount:1},
'shift':{object:this.target,type:'splice',index:0,removed:[res],
addedCount:0},
'splice':{object:this.target,type:'splice',index:arguments[0],
removed:res,addedCount:Array.prototype.slice.call(arguments,2).length},
'unshift':{object:this.target,type:'splice',index:0,removed:[],
addedCount:1}
})[this.name]);
clearTimeout(timeoutStack[targetInd]);
timeoutStack[targetInd]=setTimeout(function(){
notifyObservers(this.target)}.bind(this));
}.bind(this);
return r;
}
function propertySetter(userVal)
{
var val=this.target[this.name],
targetInd=targetIndex(this.target);
if(val!==userVal){
this.target[this.name]=userVal;
changeStack[targetInd].push(
{name:this.name,object:this.target,type:'update',oldValue:val});
clearTimeout(timeoutStack[targetInd]);
timeoutStack[targetInd]=setTimeout(function(){
notifyObservers(this.target)}.bind(this));
}
}
function targetIndex(t)
{
var i=targetStack.indexOf(t);
if(i===-1&&t){
i=targetStack.push(t)-1;
proxyStack.push(newProxy(t));
changeStack.push([]);
handlerStack.push([]);
timeoutStack.push(0);
}
return i;
}
if(this.test_o)
tl('getDeepPropertyDescriptors',function(){
return getDeepPropertyDescriptors([1,2,3]).reduce(function(hasPush,item){
return hasPush||item.name==='push';
},false)});
if(this.test_o)
tl('Property getter',function(){
var s={p1:1};
return newProxy(s).p1===s.p1});
if(this.test_o)
tl('Property setter',function(){
var s={p1:1};
newProxy(s).p1=2;
return s.p1===2});
if(this.test_o)
tl('Array splice',function(){
var s=[];
newProxy(s).push(1);
return s.length===1});
return {
addChangeHandler:function(target,changeHandler,callOnInit){
var targetInd=targetIndex(target);
handlerStack[targetInd].indexOf(changeHandler)===-1&&
handlerStack[targetInd].push(changeHandler);
if(callOnInit){
var changes=Array.isArray(target)
?target.map(function(_,index){
return {object:target,type:'splice',index:index,removed:[],
addedCount:1}})
:Object.getOwnPropertyNames(target).map(function(key){
return {name:key,object:target,type:'update',oldValue:target[key]}
});
changeHandler.call({},changes);
}
},
getProxy:function(target){
return proxyStack[targetIndex(target)]||target;
},
removeChangeHandler:function(target,changeHandler){
var targetInd=targetIndex(target),rmInd;
if((rmInd=handlerStack[targetInd].indexOf(changeHandler))>-1)
handlerStack[targetInd].splice(rmInd,1);
else if(!changeHandler)
handlerStack[targetInd]=[];
clearTimeout(timeoutStack[targetInd]);
}
}
}.bind(this)([],[],[],[],[]);
function _o(target)
{
return observingProxy.getProxy(target);
}
_o.observe=function(target,changeHandler,callOnInit){
if(!target)
throw 'Observing proxy error: cannot _o.observe '+target+' object';
return observingProxy.addChangeHandler.apply(observingProxy,arguments);
};
_o.unobserve=function(target,changeHandler){
if(!target)
throw 'Observing proxy error: cannot _o.unobserve '+target+' object';
return observingProxy.removeChangeHandler.apply(observingProxy,arguments);
};
_o.onUpdate=function(target,onChangeCollection,callOnInit){
var onPropertyChange;
if(typeof onChangeCollection==='string'){
onChangeCollection={};
onChangeCollection[arguments[1]]=arguments[2];
callOnInit=arguments[3];
}
callOnInit=callOnInit===undefined&&true||callOnInit;
if(target)
observingProxy.addChangeHandler(target,onPropertyChange=function(changes){
for(var key in onChangeCollection)
for(var i=changes.length;i--;)
if(changes[i].name===key&&changes[i].type==='update'){
onChangeCollection[key].call(changes[i],changes[i].object[changes[i].name]);
break;
}
},callOnInit);
return{
destroy:function(){
observingProxy.removeChangeHandler(target,onPropertyChange);
},
report:function(){
if(!target)
throw 'Observing proxy error: cannot _o.onUpdate '+target+' object';
},
restore:function(){
observingProxy.addChangeHandler(target,onPropertyChange,callOnInit);
}
};
};
if(typeof Object.defineProperty!=='function')
throw 'Object.defineProperty is not a function';
if(this.exports&&this.module)
this.module.exports=_o;
else if(this.define&&this.define.amd)
this.define(function(){return _o});
else
this._o=_o;
if(this.test_o)
tl('getProxy',function(){
var s={p1:1};
return observingProxy.getProxy(s).p1===s.p1});
if(this.test_o)
!function(){
var u;
var s={p1:1};
observingProxy.addChangeHandler(s,function(changes){
clearTimeout(u);
tl('addChangeHandler',function(){return true});
});
observingProxy.getProxy(s).p1=101;
u=setTimeout(function(){
tl('addChangeHandler',function(){return false});
});
}();
if(this.test_o)
!function(){
var u;
var f=function(){
clearTimeout(u);
tl('removeChangeHandler',function(){return false});
};
var s={p1:1};
observingProxy.addChangeHandler(s,f);
observingProxy.removeChangeHandler(s,f);
observingProxy.getProxy(s).p1=2;
u=setTimeout(function(){
tl('removeChangeHandler',function(){return true});
});
}();
if(this.test_o)
!function(){
var s={p1:1};
var u=setTimeout(function(){
tl('callOnInit',function(){return false});
});
observingProxy.addChangeHandler(s,function(changes){
clearTimeout(u);
tl('callOnInit',function(){return true});
},true);
}();
if(this.test_o)
!function(){
var s={p1:0},proxy=observingProxy.getProxy(s),n=0;
observingProxy.addChangeHandler(s,function(ch){
n++;
});
for(var i=10;i--;)
proxy.p1++;
setTimeout(function(){
tl('Delayed notify',function(){return n===1});
})
}();
if(this.test_o)
!function(){
var s={p1:1};
_o.onUpdate(s,'p1',function(value){
if(value===2){
clearTimeout(u);
tl('onUpdateHandler',function(){return value===2});
}
});
observingProxy.getProxy(s).p1=2;
var u=setTimeout(function(){
tl('onUpdateHandler',function(){return false});
});
}();
if(this.test_o)
!function(){
var s={p1:1},proxy=observingProxy.getProxy(s),i=0;
var observer=_o.onUpdate(s,'p1',function(value){
i++;
});
setTimeout(function(){
proxy.p1=2;
setTimeout(function(){
observer.destroy();
proxy.p1=3;
setTimeout(function(){
observer.restore();
proxy.p1=4;
setTimeout(function(){
tl('onUpdateHandler destructor',function(){return i==4});
});
});
});
});
}();
}.bind(this)()
|
module.exports={A:{A:{"2":"J C G E B A TB"},B:{"2":"D X g H L"},C:{"2":"1 2 3 RB F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z s r PB OB"},D:{"2":"1 2 7 9 F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z s r DB SB AB BB"},E:{"2":"6 F I J C G E B A CB EB FB GB HB IB JB"},F:{"2":"0 4 5 E A D H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q KB LB MB NB QB"},G:{"2":"6 8 G A u UB VB WB XB YB ZB aB bB"},H:{"2":"cB"},I:{"2":"3 F r dB eB fB gB u hB iB"},J:{"2":"C B"},K:{"2":"0 4 5 B A D K"},L:{"2":"7"},M:{"2":"s"},N:{"2":"B A"},O:{"2":"jB"},P:{"2":"F I"},Q:{"2":"kB"},R:{"2":"lB"}},B:7,C:":has() CSS relational pseudo-class"};
|
{
var x = f;
x = items[0];
x = items[1];
}
|
import xhr from './lib/xhr';
class ShowsModel {
constructor() {
this.shows = [];
}
fetch(cb) {
xhr('https://raw.githubusercontent.com/dashersw/erste.js-demo/master/src/static/data/shows.json', (err, data) => {
this.shows = data.slice(0, 20);
cb(this.shows);
});
};
}
export default new ShowsModel();
|
export default function calculateScore (subject, chosenId, time) {
const isCorrectAnswer = subject.id === chosenId
let score
if(isCorrectAnswer) {
if(time < 7) {
score = 3
} else {
// Needs review
score = .9 + (2 * (1/subject.seenCount))
}
} else {
// Degrees of failure
score = 1/subject.seenCount
}
subject.score = score
return [subject, score]
}
|
import { createRouter, createWebHistory } from "vue-router/dist/vue-router.esm.js";
import Home from "./views/Home.vue";
const routerHistory = createWebHistory("/");
let router = createRouter({
history: routerHistory,
routes: [
{ path: '/', component: Home, name: '' },
{ path: '/who', component: Home, name: 'who' },
{ path: '/what', component: Home, name: 'what' },
{ path: '/where', component: Home, name: 'where' },
{ path: '/when', component: Home, name: 'when' },
{ path: '/why', component: Home, name: 'why' }
]
});
router.afterEach((to, from) => {
console.info((to, from, window.location.pathname));
})
export default router;
|
'use strict';
var crypto = require('crypto');
exports.typeOf = function(obj) {
var classToType;
if (obj === void 0 || obj === null) {
return String(obj);
}
classToType = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regexp',
'[object Object]': 'object'
};
return classToType[Object.prototype.toString.call(obj)];
};
exports.unauthResp = function(res) {
res.statusCode = 401;
res.setHeader('content-type', 'application/json; charset=UTF-8');
return res.end(JSON.stringify({ code: 401, error: 'Unauthorized.' }));
};
exports.signHook = function(masterKey, hookName, ts) {
return ts + ',' + crypto.createHmac('sha1', masterKey).update(hookName + ':' + ts).digest('hex');
};
exports.verifyHookSign = function(masterKey, hookName, sign) {
if (sign) {
return exports.signHook(masterKey, hookName, sign.split(',')[0]) === sign;
} else {
return false;
}
};
/* options: req, user, params, object*/
exports.prepareRequestObject = function(options) {
var req = options.req;
var user = options.user;
var currentUser = user || (req && req.AV && req.AV.user);
return {
expressReq: req,
params: options.params,
object: options.object,
meta: {
remoteAddress: req && req.headers && getRemoteAddress(req)
},
user: user,
currentUser: currentUser,
sessionToken: (currentUser && currentUser.getSessionToken()) || (req && req.sessionToken)
};
};
exports.prepareResponseObject = function(res, callback) {
return {
success: function(result) {
callback(null, result);
},
error: function(error) {
callback(error);
}
};
};
var getRemoteAddress = exports.getRemoteAddress = function(req) {
return req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress
};
exports.endsWith = function(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
};
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M17 3H3v18h18V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"
}), 'SaveSharp'); |
import fulfillQuery from '../../../src/webserver/db/fulfillQuery' // eslint-disable-line
describe('webserver/db/fulfillQuery', () => {
it('should work')
})
|
'use strict';
var Foundationify = (function () {
// Initalize product image gallery function on product pages
function initProductImages() {
// Define the scope
var $productImages = $('#product-images', 'body.product');
// Select the thumbnails
var $thumbs = $('ul img', $productImages);
if ($thumbs.length) {
// Select the large image
var $largeImage = $('img', $productImages).first();
// Change the large image src and alt attributes on click
$thumbs.on('click', function (e) {
e.preventDefault();
// Skip if thumb matches large
if ($largeImage.attr('src') === $(this).parent('a').attr('href')) {
return;
}
// Change the cursor to the loading cursor
$('body').css('cursor', 'progress');
// Change the src and alt attributes of the large image
$largeImage.attr('src', $(this).parent('a').attr('href'))
.attr('alt', $(this).attr('alt'));
});
// Return the loading cursor to default after the large image has loaded
$largeImage.on('load', function () {
$('body').css('cursor', 'auto');
});
}
}
return {
init: function () {
initProductImages();
}
};
}());
$(document).ready(function () {
Foundationify.init();
});
|
"use strict";
var SourceLine_1 = require("../source/SourceLine");
var Prop_1 = require("../entities/Prop");
var Method_1 = require("../entities/Method");
var MethodKind_1 = require("../kind/MethodKind");
var ProgramError_1 = require("../errors/ProgramError");
var ClassDefn_1 = require("../define/ClassDefn");
var StructDefn_1 = require("../define/StructDefn");
var CONST_1 = require("../CONST");
var PropQual_1 = require("../entities/PropQual");
var ParamParser_1 = require("../parser/ParamParser");
/**
* Created by Nidin Vinayakan on 4/7/2016.
*/
var DefinitionService = (function () {
function DefinitionService() {
}
/**
* Collect all definitions from the source code
* */
DefinitionService.prototype.collectDefinitions = function (filename, lines) {
var _this = this;
var defs = [];
var turboLines = [];
var i = 0;
var numLines = lines.length;
var line;
while (i < numLines) {
line = lines[i++];
if (!CONST_1.Matcher.START.test(line)) {
turboLines.push(new SourceLine_1.SourceLine(filename, i, line));
continue;
}
var kind = "";
var name_1 = "";
var inherit = "";
var lineNumber = i;
var m = null;
if (m = CONST_1.Matcher.STRUCT.exec(line)) {
kind = "struct";
name_1 = m[1];
}
else if (m = CONST_1.Matcher.CLASS.exec(line)) {
kind = "class";
name_1 = m[1];
inherit = m[2] ? m[2] : "";
}
else {
throw new ProgramError_1.ProgramError(filename, i, "Syntax error: Malformed definition line");
}
var properties = [];
var methods = [];
var in_method = false;
var mbody = null;
var method_type = MethodKind_1.MethodKind.Virtual;
var method_name = "";
var method_line = 0;
var method_signature = null;
// Do not check for duplicate names here since that needs to
// take into account inheritance.
while (i < numLines) {
line = lines[i++];
if (CONST_1.Matcher.END.test(line)) {
break;
}
if (m = CONST_1.Matcher.METHOD.exec(line.trim())) {
if (kind != "class") {
throw new ProgramError_1.ProgramError(filename, i, "@method is only allowed in classes");
}
if (in_method) {
methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody));
}
in_method = true;
method_line = i;
method_type = (m[1] == "method" ? MethodKind_1.MethodKind.NonVirtual : MethodKind_1.MethodKind.Virtual);
method_name = m[2];
// Parse the signature. Just use the param parser for now,
// but note that what we get back will need postprocessing.
var pp = new ParamParser_1.ParamParser(filename, i, m[3], /* skip left paren */ 1);
var args = pp.allArgs();
args.shift(); // Discard SELF
// Issue #15: In principle there are two signatures here: there is the
// parameter signature, which we should keep intact in the
// virtual, and there is the set of arguments extracted from that,
// including any splat.
method_signature = args.map(function (x) {
return _this.parameterToArgument(filename, i, x);
});
mbody = [m[3]];
}
else if (m = CONST_1.Matcher.SPECIAL.exec(line.trim())) {
if (kind != "struct")
throw new ProgramError_1.ProgramError(filename, i, "@" + m[1] + " is only allowed in structs");
if (in_method)
methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody));
method_line = i;
in_method = true;
switch (m[1]) {
case "get":
method_type = MethodKind_1.MethodKind.Get;
break;
case "set":
method_type = MethodKind_1.MethodKind.Set;
break;
}
method_name = "";
method_signature = null;
mbody = [m[2]];
}
else if (in_method) {
// TODO: if we're going to be collecting random cruft
// then blank and comment lines at the end of a method
// really should be placed at the beginning of the
// next method. Also see hack in pasteupTypes() that
// removes blank lines from the end of a method body.
mbody.push(line);
}
else if (m = CONST_1.Matcher.PROP.exec(line)) {
var qual = PropQual_1.PropQual.None;
switch (m[3]) {
case "synchronic":
qual = PropQual_1.PropQual.Synchronic;
break;
case "atomic":
qual = PropQual_1.PropQual.Atomic;
break;
}
properties.push(new Prop_1.Prop(i, m[1], qual, m[4] == "Array", m[2]));
}
else if (CONST_1.blank_re.test(line)) {
}
else
throw new ProgramError_1.ProgramError(filename, i, "Syntax error: Not a property or method: " + line);
}
if (in_method)
methods.push(new Method_1.Method(method_line, method_type, method_name, method_signature, mbody));
if (kind == "class")
defs.push(new ClassDefn_1.ClassDefn(filename, lineNumber, name_1, inherit, properties, methods, turboLines.length));
else
defs.push(new StructDefn_1.StructDefn(filename, lineNumber, name_1, properties, methods, turboLines.length));
}
return [defs, turboLines];
};
// The input is Id, Id:Blah, or ...Id. Strip any :Blah annotations.
DefinitionService.prototype.parameterToArgument = function (file, line, s) {
if (/^\s*(?:\.\.\.)[A-Za-z_$][A-Za-z0-9_$]*\s*$/.test(s))
return s;
var m = /^\s*([A-Za-z_\$][A-Za-z0-9_\$]*)\s*:?/.exec(s);
if (!m)
throw new ProgramError_1.ProgramError(file, line, "Unable to understand argument to virtual function: " + s);
return m[1];
};
return DefinitionService;
}());
exports.DefinitionService = DefinitionService;
//# sourceMappingURL=DefinitionService.js.map |
/* eslint-env mocha */
import { Controller } from '../'
import assert from 'assert'
import { equals } from './'
import { state, props } from '../tags'
describe('operator.equals', () => {
it('should go down path based on props', () => {
let count = 0
const controller = Controller({
state: {
foo: 'bar',
},
signals: {
test: [
equals(props`foo`),
{
bar: [
() => {
count++
},
],
otherwise: [],
},
],
},
})
controller.getSignal('test')({ foo: 'bar' })
assert.equal(count, 1)
})
it('should go down path based on state', () => {
let count = 0
const controller = Controller({
state: {
foo: 'bar',
},
signals: {
test: [
equals(state`foo`),
{
bar: [
() => {
count++
},
],
otherwise: [],
},
],
},
})
controller.getSignal('test')()
assert.equal(count, 1)
})
it('should throw on bad argument', done => {
const controller = Controller({
state: {
foo: 'bar',
},
signals: {
test: [
equals('foo'),
{
bar: [() => {}],
otherwise: [],
},
],
},
})
controller.removeListener('error')
controller.once('error', error => {
assert.ok(error)
done()
})
controller.getSignal('test')()
})
})
|
module.exports = function(EmailAddress) {
};
|
import { create } from 'ember-cli-page-object';
import leadershipCollapsed from 'ilios-common/page-objects/components/leadership-collapsed';
import overview from './overview';
import header from './header';
import leadershipExpanded from './leadership-expanded';
const definition = {
scope: '[data-test-program-details]',
header,
overview,
leadershipCollapsed,
leadershipExpanded,
};
export default definition;
export const component = create(definition);
|
version https://git-lfs.github.com/spec/v1
oid sha256:07e25b6c05d06d085c2840d85f2966476dc38544be904c978d7c66dbe688decb
size 4672
|
/**
* Copyright 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule relayUnstableBatchedUpdates
*
* @format
*/
'use strict';
module.exports = require('react-dom').unstable_batchedUpdates; |
// support CommonJS, AMD & browser
/* istanbul ignore next */
if (typeof exports === T_OBJECT)
module.exports = riot
else if (typeof define === 'function' && define.amd)
define(function() { return (window.riot = riot) })
else
window.riot = riot
})(typeof window != 'undefined' ? window : void 0);
|
/*
$(document.body).ready(function() {
FormKit.install();
FormKit.initialize(document.body);
});
Inside Ajax Region:
$(document.body).ready(function() {
FormKit.initialize( div element );
});
*/
var FormKit = {
register: function(initHandler,installHandler) {
$(FormKit).bind('formkit.initialize',initHandler);
if( installHandler ) {
$(this).bind('formkit.install',installHandler);
}
},
initialize: function(scopeEl) {
if(!scopeEl)
scopeEl = document.body;
$(FormKit).trigger('formkit.initialize',[scopeEl]);
},
install: function() {
$(FormKit).trigger('formkit.install');
}
};
|
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 }
},
'postcss-loader'
]
}
]
}
}
|
/**
* Validates the inputted Firebase reference.
*
* @param {Firebase} firebaseRef The Firebase reference to validate.
*/
var _validateFirebaseRef = function(firebaseRef) {
var error;
if (typeof firebaseRef === "undefined") {
error = "no \"firebaseRef\" specified";
}
else if (firebaseRef instanceof Firebase === false) {
// TODO: can they pass in a limit query?
error = "\"firebaseRef\" must be an instance of Firebase";
}
if (typeof error !== "undefined") {
throw new Error("FireGrapher: " + error);
}
};
/**
* Validates the inputted CSS selector.
*
* @param {string} cssSelector The CSS selector to validate.
*/
var _validateCssSelector = function(cssSelector) {
var error;
if (typeof cssSelector === "undefined") {
error = "no \"cssSelector\" specified";
}
else if (typeof cssSelector !== "string") {
error = "\"cssSelector\" must be a string";
}
else {
var matchedElements = document.querySelectorAll(cssSelector);
if (matchedElements.length === 0) {
error = "no element matches the CSS selector '" + cssSelector + "'";
}
else if (matchedElements.length > 1) {
error = "multiple elements (" + matchedElements.length + " total) match the CSS selector '" + cssSelector + "'";
}
}
if (typeof error !== "undefined") {
throw new Error("FireGrapher: " + error);
}
};
/**
* Validates the inputted config object and makes sure no options have invalid values.
*
* @param {object} config The graph configuration object to validate.
*/
var _validateConfig = function(config) {
// TODO: upgrade
var error;
if (typeof config === "undefined") {
error = "no \"config\" specified";
}
else if (typeof config !== "object") {
error = "\"config\" must be an object";
}
// Every config needs to specify the graph type
var validGraphTypes = ["table", "line", "scatter", "bar", "map"];
if (typeof config.type === "undefined") {
error = "no graph \"type\" specified. Must be \"table\", \"line\", or \"scatter\"";
}
if (validGraphTypes.indexOf(config.type) === -1) {
error = "Invalid graph \"type\" specified. Must be \"table\", \"line\", or \"scatter\"";
}
// Every config needs to specify the path to an individual record
if (typeof config.path === "undefined") {
error = "no \"path\" to individual record specified";
}
// TODO: other validation for things like $, *, etc.
switch (config.type) {
case "map":
if (typeof config.marker === "undefined" ||
typeof config.marker.latitude === "undefined" ||
typeof config.marker.longitude === "undefined" ||
typeof config.marker.magnitude === "undefined") {
error = "incomplete \"marker\" definition specified. \nExpected: " + JSON.stringify(_getDefaultConfig().marker) + "\nActual: " + JSON.stringify(config.marker);
}
break;
case "table":
// Every table config needs to specify its column labels and values
if (typeof config.columns === "undefined") {
error = "no table \"columns\" specified";
}
config.columns.forEach(function(column) {
if (typeof column.label === "undefined") {
error = "missing \"columns\" label";
}
if (typeof column.value === "undefined") {
error = "missing \"columns\" value";
}
});
break;
case "line":
if (typeof config.xCoord === "undefined") {
error = "no \"xCoord\" specified";
}
if (typeof config.yCoord === "undefined") {
error = "no \"yCoord\" specified.";
}
break;
case "bar":
if (typeof config.value === "undefined") {
error = "no \"value\" specified.";
}
break;
case "scatter":
break;
}
if (typeof error !== "undefined") {
throw new Error("FireGrapher: " + error);
}
};
/**
* Validates the inputted grapher object.
*
* @param {object} grapher The grapher object to validate.
*/
var _validateGrapher = function(grapher) {
var error;
if (grapher === null || typeof grapher !== "object") {
error = "\"grapher\" must be an object";
}
// TODO: figure out what this should be to support both production and testing
/*if (grapher instanceof D3Graph === false &&
grapher instanceof D3Table === false &&
grapher instanceof D3Map === false) {
throw new Error("FireGrapher: \"grapher\" must be an instance of FireGrapherD3");
}*/
else if (typeof grapher.init !== "function") {
error = "\"grapher\" must have an init() method";
}
else if (typeof grapher.draw !== "function") {
error = "\"grapher\" must have a draw() method";
}
else if (typeof grapher.addDataPoint !== "function") {
error = "\"grapher\" must have a addDataPoint() method";
}
if (typeof error !== "undefined") {
throw new Error("FireGrapher: " + error);
}
};
/**
* Adds default values to the graph config object
*/
var _getDefaultConfig = function() {
// Default colors (turquoise, alizaren (red), amethyst (purple), peter river (blue), sunflower, pumpkin, emerald, carrot, midnight blue, pomegranate)
var defaultStrokeColors = ["#1ABC9C", "#E74C3C", "#9B59B6", "#3498DB", "#F1C40F", "#D35400", "#2ECC71", "#E67E22", "#2C3E50", "#C0392B"];
var defaultFillColors = ["#28E1BC", "#ED7469", "#B07CC6", "#5FAEE3", "#F4D03F", "#FF6607", "#54D98B", "#EB9850", "#3E5771", "#D65448"];
// Define a default config object
return {
"styles": {
"fillColor": "#DDDDDD",
"fillOpacity": 0.3,
"outerStrokeColor": "#000000",
"outerStrokeWidth": 2,
"innerStrokeColor": "#000000",
"innerStrokeWidth": 1,
/*"size": {
"width": 500,
"height": 300
},*/
"axes": {
"x": {
"ticks": {
"fillColor": "#000000",
"fontSize": "14px"
},
"label": {
"fillColor": "#000000",
"fontSize": "14px"
}
},
"y": {
"ticks": {
"fillColor": "#000000",
"fontSize": "14px"
},
"label": {
"fillColor": "#000000",
"fontSize": "14px"
}
}
},
"series": {
"strokeWidth": 2,
"strokeColors": defaultStrokeColors
},
"markers": {
"size": 3.5,
"strokeWidth": 2,
"style": "default",
"strokeColors": defaultStrokeColors,
"fillColors": defaultFillColors // What about if style is set to "flat"?
},
"legend": {
"fontSize": "16px",
"stroke": "#000000",
"strokeWidth": "2px",
"fill": "#AAAAAA",
"fillOpacity": 0.7
}
},
"xCoord": {
"label": ""
},
"yCoord": {
"label": ""
},
"marker": {
"label" : "label",
"latitude" : "latitude",
"longitude" : "longitude",
"magnitude" : "radius"
}
};
}; |
/**
* @module kat-cr/lib/fetch
* @description
* Wraps request in a Promise
*/
/**
* The HTTP response class provided by request
* @external HTTPResponse
* @see {@link http://github.com/request/request}
*/
"use strict";
const request = (function loadPrivate(module) {
let modulePath = require.resolve(module),
cached = require.cache[modulePath];
delete require.cache[modulePath];
let retval = require(module);
require.cache[modulePath] = cached;
return retval;
})('request'),
USER_AGENTS = require('../config/user-agents');
// Not necessary as of now, but in case Kickass Torrents requires cookies enabled in the future, and in case the library user needs to use request with his or her own cookie jar, we load a private copy of request so we can use our own cookie jar instead of overriding the global one
request.defaults({
jar: true
});
/**
* @description
* Wraps request in a Promise, also sets a random user agent
* @param {Object} config The details of the request as if it were passed to request directly
* @returns {Promise.<external:HTTPResponse>} A promise which resolves with the response, or rejects with an error
* @example
* // Make a request to a JSON API
* require('kat-cr/lib/fetch')({
* method: 'GET',
* url: 'http://server.com/json-endpoint',
* }).then(function (response) {
* JSON.parse(response.body);
* });
*/
module.exports = function fetch(config) {
if (!config) config = {};
if (!config.headers) config.headers = {};
config.headers['user-agent'] = USER_AGENTS[Math.floor(Math.random()*USER_AGENTS.length)];
return new Promise(function (resolve, reject) {
request(config, function (err, resp, body) {
if (err) reject(err);
resolve(resp);
});
});
};
/** Expose private request module for debugging */
module.exports._request = request;
|
/**
* Method to set dom events
*
* @example
* wysihtml.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... });
*/
wysihtml.dom.observe = function(element, eventNames, handler) {
eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames;
var handlerWrapper,
eventName,
i = 0,
length = eventNames.length;
for (; i<length; i++) {
eventName = eventNames[i];
if (element.addEventListener) {
element.addEventListener(eventName, handler, false);
} else {
handlerWrapper = function(event) {
if (!("target" in event)) {
event.target = event.srcElement;
}
event.preventDefault = event.preventDefault || function() {
this.returnValue = false;
};
event.stopPropagation = event.stopPropagation || function() {
this.cancelBubble = true;
};
handler.call(element, event);
};
element.attachEvent("on" + eventName, handlerWrapper);
}
}
return {
stop: function() {
var eventName,
i = 0,
length = eventNames.length;
for (; i<length; i++) {
eventName = eventNames[i];
if (element.removeEventListener) {
element.removeEventListener(eventName, handler, false);
} else {
element.detachEvent("on" + eventName, handlerWrapper);
}
}
}
};
};
|
import { includes } from './array_proxy'
/**
* Given a record and an update object, apply the update on the record. Note
* that the `operate` object is unapplied.
*
* @param {Object} record
* @param {Object} update
*/
export default function applyUpdate (record, update) {
for (let field in update.replace)
record[field] = update.replace[field]
for (let field in update.push) {
const value = update.push[field]
record[field] = record[field] ? record[field].slice() : []
if (Array.isArray(value)) record[field].push(...value)
else record[field].push(value)
}
for (let field in update.pull) {
const value = update.pull[field]
record[field] = record[field] ?
record[field].slice().filter(exclude.bind(null,
Array.isArray(value) ? value : [ value ])) : []
}
}
function exclude (values, value) {
return !includes(values, value)
}
|
#!/usr/bin/env node
var logger = require('../lib/logger')('test-logger');
var config = require('../lib/config');
var count = 1;
setInterval(function() {
logger.debug(count);
logger.info(count);
count += 1;
}, 1000);
|
/**
* Parse an array of chromsizes, for example that result
* from reading rows of a chromsizes CSV file.
* @param {array} data Array of [chrName, chrLen] "tuples".
* @returns {object} Object containing properties
* { cumPositions, chrPositions, totalLength, chromLengths }.
*/
function parseChromsizesRows(data) {
const cumValues = [];
const chromLengths = {};
const chrPositions = {};
let totalLength = 0;
for (let i = 0; i < data.length; i++) {
const length = Number(data[i][1]);
totalLength += length;
const newValue = {
id: i,
chr: data[i][0],
pos: totalLength - length,
};
cumValues.push(newValue);
chrPositions[newValue.chr] = newValue;
chromLengths[data[i][0]] = length;
}
return {
cumPositions: cumValues,
chrPositions,
totalLength,
chromLengths,
};
}
export default parseChromsizesRows;
|
'use strict';
/**
* Module dependencies
*/
var hbs = require('express-hbs');
function content(options) {
return new hbs.handlebars.SafeString(this.html || '');
}
module.exports = content;
// downsize = Tag-safe truncation for HTML and XML. Works by word! |
Subsets and Splits