code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
const fs = require('fs');
const de = require('./locale/de.json');
const en = require('./locale/en.json');
const esMX = require('./locale/esMX.json');
const es = require('./locale/es.json');
const fr = require('./locale/fr.json');
const it = require('./locale/it.json');
const ja = require('./locale/ja.json');
const ko = require('./locale/ko.json');
const pl = require('./locale/pl.json');
const ptBR = require('./locale/ptBR.json');
const ru = require('./locale/ru.json');
const zhCHS = require('./locale/zhCHS.json');
const zhCHT = require('./locale/zhCHT.json');
function getI18nKey(key) {
let key1 = key.split('.')[0];
let key2 = key.split('.')[1];
return ` en: "${en[key1][key2]}",
de: "${de[key1]?.[key2] ?? en[key1][key2]}",
es: "${es[key1]?.[key2] ?? en[key1][key2]}",
'es-mx': "${esMX[key1]?.[key2] ?? en[key1][key2]}",
fr: "${fr[key1]?.[key2] ?? en[key1][key2]}",
it: "${it[key1]?.[key2] ?? en[key1][key2]}",
ja: "${ja[key1]?.[key2] ?? en[key1][key2]}",
ko: "${ko[key1]?.[key2] ?? en[key1][key2]}",
pl: "${pl[key1]?.[key2] ?? en[key1][key2]}",
'pt-br': "${ptBR[key1]?.[key2] ?? en[key1][key2]}",
ru: "${ru[key1]?.[key2] ?? en[key1][key2]}",
'zh-chs': "${zhCHS[key1]?.[key2] ?? en[key1][key2]}",
'zh-cht': "${zhCHT[key1]?.[key2] ?? en[key1][key2]}",\n};\n`;
}
var browserCheckUtils = `export const supportedLanguages = [
'en',
'de',
'es',
'es-mx',
'fr',
'it',
'ja',
'ko',
'pl',
'pt-br',
'ru',
'zh-chs',
'zh-cht',
];
export const unsupported = {
${getI18nKey('Browsercheck.Unsupported')}
export const steamBrowser = {
${getI18nKey('Browsercheck.Steam')}`;
fs.writeFile('src/browsercheck-utils.js', browserCheckUtils, (err) => {
if (err) {
// console.log(err);
}
});
| DestinyItemManager/DIM | src/build-browsercheck-utils.js | JavaScript | mit | 1,744 |
/*
html2canvas 0.5.0-alpha2 <http://html2canvas.hertzen.com>
Copyright (c) 2015 Niklas von Hertzen
Released under MIT License
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.html2canvas=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
* @version 2.0.1
*/
(function() {
"use strict";
function $$utils$$objectOrFunction(x) {
return typeof x === 'function' || (typeof x === 'object' && x !== null);
}
function $$utils$$isFunction(x) {
return typeof x === 'function';
}
function $$utils$$isMaybeThenable(x) {
return typeof x === 'object' && x !== null;
}
var $$utils$$_isArray;
if (!Array.isArray) {
$$utils$$_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
} else {
$$utils$$_isArray = Array.isArray;
}
var $$utils$$isArray = $$utils$$_isArray;
var $$utils$$now = Date.now || function() { return new Date().getTime(); };
function $$utils$$F() { }
var $$utils$$o_create = (Object.create || function (o) {
if (arguments.length > 1) {
throw new Error('Second argument not supported');
}
if (typeof o !== 'object') {
throw new TypeError('Argument must be an object');
}
$$utils$$F.prototype = o;
return new $$utils$$F();
});
var $$asap$$len = 0;
var $$asap$$default = function asap(callback, arg) {
$$asap$$queue[$$asap$$len] = callback;
$$asap$$queue[$$asap$$len + 1] = arg;
$$asap$$len += 2;
if ($$asap$$len === 2) {
// If len is 1, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
$$asap$$scheduleFlush();
}
};
var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {};
var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver;
// test for web worker but not in IE10
var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function $$asap$$useNextTick() {
return function() {
process.nextTick($$asap$$flush);
};
}
function $$asap$$useMutationObserver() {
var iterations = 0;
var observer = new $$asap$$BrowserMutationObserver($$asap$$flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function() {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function $$asap$$useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = $$asap$$flush;
return function () {
channel.port2.postMessage(0);
};
}
function $$asap$$useSetTimeout() {
return function() {
setTimeout($$asap$$flush, 1);
};
}
var $$asap$$queue = new Array(1000);
function $$asap$$flush() {
for (var i = 0; i < $$asap$$len; i+=2) {
var callback = $$asap$$queue[i];
var arg = $$asap$$queue[i+1];
callback(arg);
$$asap$$queue[i] = undefined;
$$asap$$queue[i+1] = undefined;
}
$$asap$$len = 0;
}
var $$asap$$scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
$$asap$$scheduleFlush = $$asap$$useNextTick();
} else if ($$asap$$BrowserMutationObserver) {
$$asap$$scheduleFlush = $$asap$$useMutationObserver();
} else if ($$asap$$isWorker) {
$$asap$$scheduleFlush = $$asap$$useMessageChannel();
} else {
$$asap$$scheduleFlush = $$asap$$useSetTimeout();
}
function $$$internal$$noop() {}
var $$$internal$$PENDING = void 0;
var $$$internal$$FULFILLED = 1;
var $$$internal$$REJECTED = 2;
var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$selfFullfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function $$$internal$$cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.')
}
function $$$internal$$getThen(promise) {
try {
return promise.then;
} catch(error) {
$$$internal$$GET_THEN_ERROR.error = error;
return $$$internal$$GET_THEN_ERROR;
}
}
function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function $$$internal$$handleForeignThenable(promise, thenable, then) {
$$asap$$default(function(promise) {
var sealed = false;
var error = $$$internal$$tryThen(then, thenable, function(value) {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
$$$internal$$resolve(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}, function(reason) {
if (sealed) { return; }
sealed = true;
$$$internal$$reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
$$$internal$$reject(promise, error);
}
}, promise);
}
function $$$internal$$handleOwnThenable(promise, thenable) {
if (thenable._state === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, thenable._result);
} else if (promise._state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, thenable._result);
} else {
$$$internal$$subscribe(thenable, undefined, function(value) {
$$$internal$$resolve(promise, value);
}, function(reason) {
$$$internal$$reject(promise, reason);
});
}
}
function $$$internal$$handleMaybeThenable(promise, maybeThenable) {
if (maybeThenable.constructor === promise.constructor) {
$$$internal$$handleOwnThenable(promise, maybeThenable);
} else {
var then = $$$internal$$getThen(maybeThenable);
if (then === $$$internal$$GET_THEN_ERROR) {
$$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error);
} else if (then === undefined) {
$$$internal$$fulfill(promise, maybeThenable);
} else if ($$utils$$isFunction(then)) {
$$$internal$$handleForeignThenable(promise, maybeThenable, then);
} else {
$$$internal$$fulfill(promise, maybeThenable);
}
}
}
function $$$internal$$resolve(promise, value) {
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$selfFullfillment());
} else if ($$utils$$objectOrFunction(value)) {
$$$internal$$handleMaybeThenable(promise, value);
} else {
$$$internal$$fulfill(promise, value);
}
}
function $$$internal$$publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
$$$internal$$publish(promise);
}
function $$$internal$$fulfill(promise, value) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._result = value;
promise._state = $$$internal$$FULFILLED;
if (promise._subscribers.length === 0) {
} else {
$$asap$$default($$$internal$$publish, promise);
}
}
function $$$internal$$reject(promise, reason) {
if (promise._state !== $$$internal$$PENDING) { return; }
promise._state = $$$internal$$REJECTED;
promise._result = reason;
$$asap$$default($$$internal$$publishRejection, promise);
}
function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
parent._onerror = null;
subscribers[length] = child;
subscribers[length + $$$internal$$FULFILLED] = onFulfillment;
subscribers[length + $$$internal$$REJECTED] = onRejection;
if (length === 0 && parent._state) {
$$asap$$default($$$internal$$publish, parent);
}
}
function $$$internal$$publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) { return; }
var child, callback, detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
$$$internal$$invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function $$$internal$$ErrorObject() {
this.error = null;
}
var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject();
function $$$internal$$tryCatch(callback, detail) {
try {
return callback(detail);
} catch(e) {
$$$internal$$TRY_CATCH_ERROR.error = e;
return $$$internal$$TRY_CATCH_ERROR;
}
}
function $$$internal$$invokeCallback(settled, promise, callback, detail) {
var hasCallback = $$utils$$isFunction(callback),
value, error, succeeded, failed;
if (hasCallback) {
value = $$$internal$$tryCatch(callback, detail);
if (value === $$$internal$$TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value = null;
} else {
succeeded = true;
}
if (promise === value) {
$$$internal$$reject(promise, $$$internal$$cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== $$$internal$$PENDING) {
// noop
} else if (hasCallback && succeeded) {
$$$internal$$resolve(promise, value);
} else if (failed) {
$$$internal$$reject(promise, error);
} else if (settled === $$$internal$$FULFILLED) {
$$$internal$$fulfill(promise, value);
} else if (settled === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
}
}
function $$$internal$$initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value){
$$$internal$$resolve(promise, value);
}, function rejectPromise(reason) {
$$$internal$$reject(promise, reason);
});
} catch(e) {
$$$internal$$reject(promise, e);
}
}
function $$$enumerator$$makeSettledResult(state, position, value) {
if (state === $$$internal$$FULFILLED) {
return {
state: 'fulfilled',
value: value
};
} else {
return {
state: 'rejected',
reason: value
};
}
}
function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) {
this._instanceConstructor = Constructor;
this.promise = new Constructor($$$internal$$noop, label);
this._abortOnReject = abortOnReject;
if (this._validateInput(input)) {
this._input = input;
this.length = input.length;
this._remaining = input.length;
this._init();
if (this.length === 0) {
$$$internal$$fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate();
if (this._remaining === 0) {
$$$internal$$fulfill(this.promise, this._result);
}
}
} else {
$$$internal$$reject(this.promise, this._validationError());
}
}
$$$enumerator$$Enumerator.prototype._validateInput = function(input) {
return $$utils$$isArray(input);
};
$$$enumerator$$Enumerator.prototype._validationError = function() {
return new Error('Array Methods must be provided an Array');
};
$$$enumerator$$Enumerator.prototype._init = function() {
this._result = new Array(this.length);
};
var $$$enumerator$$default = $$$enumerator$$Enumerator;
$$$enumerator$$Enumerator.prototype._enumerate = function() {
var length = this.length;
var promise = this.promise;
var input = this._input;
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
this._eachEntry(input[i], i);
}
};
$$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
var c = this._instanceConstructor;
if ($$utils$$isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== $$$internal$$PENDING) {
entry._onerror = null;
this._settledAt(entry._state, i, entry._result);
} else {
this._willSettleAt(c.resolve(entry), i);
}
} else {
this._remaining--;
this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry);
}
};
$$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
var promise = this.promise;
if (promise._state === $$$internal$$PENDING) {
this._remaining--;
if (this._abortOnReject && state === $$$internal$$REJECTED) {
$$$internal$$reject(promise, value);
} else {
this._result[i] = this._makeResult(state, i, value);
}
}
if (this._remaining === 0) {
$$$internal$$fulfill(promise, this._result);
}
};
$$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) {
return value;
};
$$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
var enumerator = this;
$$$internal$$subscribe(promise, undefined, function(value) {
enumerator._settledAt($$$internal$$FULFILLED, i, value);
}, function(reason) {
enumerator._settledAt($$$internal$$REJECTED, i, reason);
});
};
var $$promise$all$$default = function all(entries, label) {
return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise;
};
var $$promise$race$$default = function race(entries, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
if (!$$utils$$isArray(entries)) {
$$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
return promise;
}
var length = entries.length;
function onFulfillment(value) {
$$$internal$$resolve(promise, value);
}
function onRejection(reason) {
$$$internal$$reject(promise, reason);
}
for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) {
$$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
}
return promise;
};
var $$promise$resolve$$default = function resolve(object, label) {
/*jshint validthis:true */
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$resolve(promise, object);
return promise;
};
var $$promise$reject$$default = function reject(reason, label) {
/*jshint validthis:true */
var Constructor = this;
var promise = new Constructor($$$internal$$noop, label);
$$$internal$$reject(promise, reason);
return promise;
};
var $$es6$promise$promise$$counter = 0;
function $$es6$promise$promise$$needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function $$es6$promise$promise$$needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise;
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise’s eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
var promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {function} resolver
Useful for tooling.
@constructor
*/
function $$es6$promise$promise$$Promise(resolver) {
this._id = $$es6$promise$promise$$counter++;
this._state = undefined;
this._result = undefined;
this._subscribers = [];
if ($$$internal$$noop !== resolver) {
if (!$$utils$$isFunction(resolver)) {
$$es6$promise$promise$$needsResolver();
}
if (!(this instanceof $$es6$promise$promise$$Promise)) {
$$es6$promise$promise$$needsNew();
}
$$$internal$$initializePromise(this, resolver);
}
}
$$es6$promise$promise$$Promise.all = $$promise$all$$default;
$$es6$promise$promise$$Promise.race = $$promise$race$$default;
$$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default;
$$es6$promise$promise$$Promise.reject = $$promise$reject$$default;
$$es6$promise$promise$$Promise.prototype = {
constructor: $$es6$promise$promise$$Promise,
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
var result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
var author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
then: function(onFulfillment, onRejection) {
var parent = this;
var state = parent._state;
if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) {
return this;
}
var child = new this.constructor($$$internal$$noop);
var result = parent._result;
if (state) {
var callback = arguments[state - 1];
$$asap$$default(function(){
$$$internal$$invokeCallback(state, child, callback, result);
});
} else {
$$$internal$$subscribe(parent, child, onFulfillment, onRejection);
}
return child;
},
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
'catch': function(onRejection) {
return this.then(null, onRejection);
}
};
var $$es6$promise$polyfill$$default = function polyfill() {
var local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof window !== 'undefined' && window.document) {
local = window;
} else {
local = self;
}
var es6PromiseSupport =
"Promise" in local &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
"resolve" in local.Promise &&
"reject" in local.Promise &&
"all" in local.Promise &&
"race" in local.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new local.Promise(function(r) { resolve = r; });
return $$utils$$isFunction(resolve);
}());
if (!es6PromiseSupport) {
local.Promise = $$es6$promise$promise$$default;
}
};
var es6$promise$umd$$ES6Promise = {
'Promise': $$es6$promise$promise$$default,
'polyfill': $$es6$promise$polyfill$$default
};
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return es6$promise$umd$$ES6Promise; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = es6$promise$umd$$ES6Promise;
} else if (typeof this !== 'undefined') {
this['ES6Promise'] = es6$promise$umd$$ES6Promise;
}
}).call(this);
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
function drainQueue() {
if (draining) {
return;
}
draining = true;
var currentQueue;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
var i = -1;
while (++i < len) {
currentQueue[i]();
}
len = queue.length;
}
draining = false;
}
process.nextTick = function (fun) {
queue.push(fun);
if (!draining) {
setTimeout(drainQueue, 0);
}
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
// TODO(shtylman)
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],3:[function(require,module,exports){
(function (global){
/*! http://mths.be/punycode v1.2.4 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports;
var freeModule = typeof module == 'object' && module &&
module.exports == freeExports && module;
var freeGlobal = typeof global == 'object' && global;
if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^ -~]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /\x2E|\u3002|\uFF0E|\uFF61/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
while (length--) {
array[length] = fn(array[length]);
}
return array;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings.
* @private
* @param {String} domain The domain name.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
return map(string.split(regexSeparators), fn).join('.');
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* http://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols to a Punycode string of ASCII-only
* symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name to Unicode. Only the
* Punycoded parts of the domain name will be converted, i.e. it doesn't
* matter if you call it on a string that has already been converted to
* Unicode.
* @memberOf punycode
* @param {String} domain The Punycode domain name to convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(domain) {
return mapDomain(domain, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name to Punycode. Only the
* non-ASCII parts of the domain name will be converted, i.e. it doesn't
* matter if you call it with a domain that's already in ASCII.
* @memberOf punycode
* @param {String} domain The domain name to convert, as a Unicode string.
* @returns {String} The Punycode representation of the given domain name.
*/
function toASCII(domain) {
return mapDomain(domain, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.2.4',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <http://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
typeof define == 'function' &&
typeof define.amd == 'object' &&
define.amd
) {
define('punycode', function() {
return punycode;
});
} else if (freeExports && !freeExports.nodeType) {
if (freeModule) { // in Node.js or RingoJS v0.8.0+
freeModule.exports = punycode;
} else { // in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else { // in Rhino or a web browser
root.punycode = punycode;
}
}(this));
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(require,module,exports){
var log = require('./log');
var Promise = require('./promise');
function restoreOwnerScroll(ownerDocument, x, y) {
if (ownerDocument.defaultView && (x !== ownerDocument.defaultView.pageXOffset || y !== ownerDocument.defaultView.pageYOffset)) {
ownerDocument.defaultView.scrollTo(x, y);
}
}
function cloneCanvasContents(canvas, clonedCanvas) {
try {
if (clonedCanvas) {
clonedCanvas.width = canvas.width;
clonedCanvas.height = canvas.height;
clonedCanvas.getContext("2d").putImageData(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height), 0, 0);
}
} catch(e) {
log("Unable to copy canvas content from", canvas, e);
}
}
function cloneNode(node, javascriptEnabled) {
var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
var child = node.firstChild;
while(child) {
if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
clone.appendChild(cloneNode(child, javascriptEnabled));
}
child = child.nextSibling;
}
if (node.nodeType === 1) {
clone._scrollTop = node.scrollTop;
clone._scrollLeft = node.scrollLeft;
if (node.nodeName === "CANVAS") {
cloneCanvasContents(node, clone);
} else if (node.nodeName === "TEXTAREA" || node.nodeName === "SELECT") {
clone.value = node.value;
}
}
return clone;
}
function initNode(node) {
if (node.nodeType === 1) {
node.scrollTop = node._scrollTop;
node.scrollLeft = node._scrollLeft;
var child = node.firstChild;
while(child) {
initNode(child);
child = child.nextSibling;
}
}
}
module.exports = function(ownerDocument, containerDocument, width, height, options, x ,y) {
var documentElement = cloneNode(ownerDocument.documentElement, options.javascriptEnabled);
var container = containerDocument.createElement("iframe");
container.className = "html2canvas-container";
container.style.visibility = "hidden";
container.style.position = "fixed";
container.style.left = "-10000px";
container.style.top = "0px";
container.style.border = "0";
container.width = width;
container.height = height;
container.scrolling = "no"; // ios won't scroll without it
containerDocument.body.appendChild(container);
return new Promise(function(resolve) {
var documentClone = container.contentWindow.document;
/* Chrome doesn't detect relative background-images assigned in inline <style> sheets when fetched through getComputedStyle
if window url is about:blank, we can assign the url to current by writing onto the document
*/
container.contentWindow.onload = container.onload = function() {
var interval = setInterval(function() {
if (documentClone.body.childNodes.length > 0) {
initNode(documentClone.documentElement);
clearInterval(interval);
if (options.type === "view") {
container.contentWindow.scrollTo(x, y);
if ((/(iPad|iPhone|iPod)/g).test(navigator.userAgent) && (container.contentWindow.scrollY !== y || container.contentWindow.scrollX !== x)) {
documentClone.documentElement.style.top = (-y) + "px";
documentClone.documentElement.style.left = (-x) + "px";
documentClone.documentElement.style.position = 'absolute';
}
}
resolve(container);
}
}, 50);
};
documentClone.open();
documentClone.write("<!DOCTYPE html><html></html>");
// Chrome scrolls the parent document for some reason after the write to the cloned window???
restoreOwnerScroll(ownerDocument, x, y);
documentClone.replaceChild(documentClone.adoptNode(documentElement), documentClone.documentElement);
documentClone.close();
});
};
},{"./log":15,"./promise":18}],5:[function(require,module,exports){
// http://dev.w3.org/csswg/css-color/
function Color(value) {
this.r = 0;
this.g = 0;
this.b = 0;
this.a = null;
var result = this.fromArray(value) ||
this.namedColor(value) ||
this.rgb(value) ||
this.rgba(value) ||
this.hex6(value) ||
this.hex3(value);
}
Color.prototype.darken = function(amount) {
var a = 1 - amount;
return new Color([
Math.round(this.r * a),
Math.round(this.g * a),
Math.round(this.b * a),
this.a
]);
};
Color.prototype.isTransparent = function() {
return this.a === 0;
};
Color.prototype.isBlack = function() {
return this.r === 0 && this.g === 0 && this.b === 0;
};
Color.prototype.fromArray = function(array) {
if (Array.isArray(array)) {
this.r = Math.min(array[0], 255);
this.g = Math.min(array[1], 255);
this.b = Math.min(array[2], 255);
if (array.length > 3) {
this.a = array[3];
}
}
return (Array.isArray(array));
};
var _hex3 = /^#([a-f0-9]{3})$/i;
Color.prototype.hex3 = function(value) {
var match = null;
if ((match = value.match(_hex3)) !== null) {
this.r = parseInt(match[1][0] + match[1][0], 16);
this.g = parseInt(match[1][1] + match[1][1], 16);
this.b = parseInt(match[1][2] + match[1][2], 16);
}
return match !== null;
};
var _hex6 = /^#([a-f0-9]{6})$/i;
Color.prototype.hex6 = function(value) {
var match = null;
if ((match = value.match(_hex6)) !== null) {
this.r = parseInt(match[1].substring(0, 2), 16);
this.g = parseInt(match[1].substring(2, 4), 16);
this.b = parseInt(match[1].substring(4, 6), 16);
}
return match !== null;
};
var _rgb = /^rgb\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})\)$/;
Color.prototype.rgb = function(value) {
var match = null;
if ((match = value.match(_rgb)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
}
return match !== null;
};
var _rgba = /^rgba\((\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3}) *, *(\d+\.?\d*)\)$/;
Color.prototype.rgba = function(value) {
var match = null;
if ((match = value.match(_rgba)) !== null) {
this.r = Number(match[1]);
this.g = Number(match[2]);
this.b = Number(match[3]);
this.a = Number(match[4]);
}
return match !== null;
};
Color.prototype.toString = function() {
return this.a !== null && this.a !== 1 ?
"rgba(" + [this.r, this.g, this.b, this.a].join(",") + ")" :
"rgb(" + [this.r, this.g, this.b].join(",") + ")";
};
Color.prototype.namedColor = function(value) {
var color = colors[value.toLowerCase()];
if (color) {
this.r = color[0];
this.g = color[1];
this.b = color[2];
} else if (value.toLowerCase() === "transparent") {
this.r = this.g = this.b = this.a = 0;
return true;
}
return !!color;
};
Color.prototype.isColor = true;
// JSON.stringify([].slice.call($$('.named-color-table tr'), 1).map(function(row) { return [row.childNodes[3].textContent, row.childNodes[5].textContent.trim().split(",").map(Number)] }).reduce(function(data, row) {data[row[0]] = row[1]; return data}, {}))
var colors = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};
module.exports = Color;
},{}],6:[function(require,module,exports){
var Promise = require('./promise');
var Support = require('./support');
var CanvasRenderer = require('./renderers/canvas');
var ImageLoader = require('./imageloader');
var NodeParser = require('./nodeparser');
var NodeContainer = require('./nodecontainer');
var log = require('./log');
var utils = require('./utils');
var createWindowClone = require('./clone');
var loadUrlDocument = require('./proxy').loadUrlDocument;
var getBounds = utils.getBounds;
var html2canvasNodeAttribute = "data-html2canvas-node";
var html2canvasCloneIndex = 0;
function html2canvas(nodeList, options) {
var index = html2canvasCloneIndex++;
options = options || {};
if (options.logging) {
window.html2canvas.logging = true;
window.html2canvas.start = Date.now();
window.html2canvas.logmessage = '';
}
options.async = typeof(options.async) === "undefined" ? true : options.async;
options.allowTaint = typeof(options.allowTaint) === "undefined" ? false : options.allowTaint;
options.removeContainer = typeof(options.removeContainer) === "undefined" ? true : options.removeContainer;
options.javascriptEnabled = typeof(options.javascriptEnabled) === "undefined" ? false : options.javascriptEnabled;
options.imageTimeout = typeof(options.imageTimeout) === "undefined" ? 10000 : options.imageTimeout;
options.renderer = typeof(options.renderer) === "function" ? options.renderer : CanvasRenderer;
options.strict = !!options.strict;
if (typeof(nodeList) === "string") {
if (typeof(options.proxy) !== "string") {
return Promise.reject("Proxy must be used when rendering url");
}
var width = options.width != null ? options.width : window.innerWidth;
var height = options.height != null ? options.height : window.innerHeight;
return loadUrlDocument(absoluteUrl(nodeList), options.proxy, document, width, height, options).then(function(container) {
return renderWindow(container.contentWindow.document.documentElement, container, options, width, height);
});
}
var node = ((nodeList === undefined) ? [document.documentElement] : ((nodeList.length) ? nodeList : [nodeList]))[0];
node.setAttribute(html2canvasNodeAttribute + index, index);
return renderDocument(node.ownerDocument, options, node.ownerDocument.defaultView.innerWidth, node.ownerDocument.defaultView.innerHeight, index).then(function(canvas) {
if (typeof(options.onrendered) === "function") {
log("options.onrendered is deprecated, html2canvas returns a Promise containing the canvas");
options.onrendered(canvas);
}
return canvas;
});
}
html2canvas.Promise = Promise;
html2canvas.CanvasRenderer = CanvasRenderer;
html2canvas.NodeContainer = NodeContainer;
html2canvas.log = log;
html2canvas.utils = utils;
module.exports = (typeof(document) === "undefined" || typeof(Object.create) !== "function" || typeof(document.createElement("canvas").getContext) !== "function") ? function() {
return Promise.reject("No canvas support");
} : html2canvas;
function renderDocument(document, options, windowWidth, windowHeight, html2canvasIndex) {
return createWindowClone(document, document, windowWidth, windowHeight, options, document.defaultView.pageXOffset, document.defaultView.pageYOffset).then(function(container) {
log("Document cloned");
var attributeName = html2canvasNodeAttribute + html2canvasIndex;
var selector = "[" + attributeName + "='" + html2canvasIndex + "']";
document.querySelector(selector).removeAttribute(attributeName);
var clonedWindow = container.contentWindow;
var node = clonedWindow.document.querySelector(selector);
var oncloneHandler = (typeof(options.onclone) === "function") ? Promise.resolve(options.onclone(clonedWindow.document)) : Promise.resolve(true);
return oncloneHandler.then(function() {
return renderWindow(node, container, options, windowWidth, windowHeight);
});
});
}
function renderWindow(node, container, options, windowWidth, windowHeight) {
var clonedWindow = container.contentWindow;
var support = new Support(clonedWindow.document);
var imageLoader = new ImageLoader(options, support);
var bounds = getBounds(node);
var width = options.type === "view" ? windowWidth : documentWidth(clonedWindow.document);
var height = options.type === "view" ? windowHeight : documentHeight(clonedWindow.document);
var renderer = new options.renderer(width, height, imageLoader, options, document);
var parser = new NodeParser(node, renderer, support, imageLoader, options);
return parser.ready.then(function() {
log("Finished rendering");
var canvas;
if (options.type === "view") {
canvas = crop(renderer.canvas, {width: renderer.canvas.width, height: renderer.canvas.height, top: 0, left: 0, x: 0, y: 0});
} else if (node === clonedWindow.document.body || node === clonedWindow.document.documentElement || options.canvas != null) {
canvas = renderer.canvas;
} else {
canvas = crop(renderer.canvas, {width: options.width != null ? options.width : bounds.width, height: options.height != null ? options.height : bounds.height, top: bounds.top, left: bounds.left, x: clonedWindow.pageXOffset, y: clonedWindow.pageYOffset});
}
cleanupContainer(container, options);
return canvas;
});
}
function cleanupContainer(container, options) {
if (options.removeContainer) {
container.parentNode.removeChild(container);
log("Cleaned up container");
}
}
function crop(canvas, bounds) {
var croppedCanvas = document.createElement("canvas");
var x1 = Math.min(canvas.width - 1, Math.max(0, bounds.left));
var x2 = Math.min(canvas.width, Math.max(1, bounds.left + bounds.width));
var y1 = Math.min(canvas.height - 1, Math.max(0, bounds.top));
var y2 = Math.min(canvas.height, Math.max(1, bounds.top + bounds.height));
croppedCanvas.width = bounds.width;
croppedCanvas.height = bounds.height;
log("Cropping canvas at:", "left:", bounds.left, "top:", bounds.top, "width:", (x2-x1), "height:", (y2-y1));
log("Resulting crop with width", bounds.width, "and height", bounds.height, " with x", x1, "and y", y1);
croppedCanvas.getContext("2d").drawImage(canvas, x1, y1, x2-x1, y2-y1, bounds.x, bounds.y, x2-x1, y2-y1);
return croppedCanvas;
}
function documentWidth (doc) {
return Math.max(
Math.max(doc.body.scrollWidth, doc.documentElement.scrollWidth),
Math.max(doc.body.offsetWidth, doc.documentElement.offsetWidth),
Math.max(doc.body.clientWidth, doc.documentElement.clientWidth)
);
}
function documentHeight (doc) {
return Math.max(
Math.max(doc.body.scrollHeight, doc.documentElement.scrollHeight),
Math.max(doc.body.offsetHeight, doc.documentElement.offsetHeight),
Math.max(doc.body.clientHeight, doc.documentElement.clientHeight)
);
}
function absoluteUrl(url) {
var link = document.createElement("a");
link.href = url;
link.href = link.href;
return link;
}
},{"./clone":4,"./imageloader":13,"./log":15,"./nodecontainer":16,"./nodeparser":17,"./promise":18,"./proxy":19,"./renderers/canvas":23,"./support":25,"./utils":29}],7:[function(require,module,exports){
var Promise = require('./promise');
var log = require('./log');
var smallImage = require('./utils').smallImage;
function DummyImageContainer(src) {
this.src = src;
log("DummyImageContainer for", src);
if (!this.promise || !this.image) {
log("Initiating DummyImageContainer");
DummyImageContainer.prototype.image = new Image();
var image = this.image;
DummyImageContainer.prototype.promise = new Promise(function(resolve, reject) {
image.onload = resolve;
image.onerror = reject;
image.src = smallImage();
if (image.complete === true) {
resolve(image);
}
});
}
}
module.exports = DummyImageContainer;
},{"./log":15,"./promise":18,"./utils":29}],8:[function(require,module,exports){
var smallImage = require('./utils').smallImage;
function Font(family, size) {
var container = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span'),
sampleText = 'Hidden Text',
baseline,
middle;
container.style.visibility = "hidden";
container.style.fontFamily = family;
container.style.fontSize = size;
container.style.margin = 0;
container.style.padding = 0;
document.body.appendChild(container);
img.src = smallImage();
img.width = 1;
img.height = 1;
img.style.margin = 0;
img.style.padding = 0;
img.style.verticalAlign = "baseline";
span.style.fontFamily = family;
span.style.fontSize = size;
span.style.margin = 0;
span.style.padding = 0;
span.appendChild(document.createTextNode(sampleText));
container.appendChild(span);
container.appendChild(img);
baseline = (img.offsetTop - span.offsetTop) + 1;
container.removeChild(span);
container.appendChild(document.createTextNode(sampleText));
container.style.lineHeight = "normal";
img.style.verticalAlign = "super";
middle = (img.offsetTop-container.offsetTop) + 1;
document.body.removeChild(container);
this.baseline = baseline;
this.lineWidth = 1;
this.middle = middle;
}
module.exports = Font;
},{"./utils":29}],9:[function(require,module,exports){
var Font = require('./font');
function FontMetrics() {
this.data = {};
}
FontMetrics.prototype.getMetrics = function(family, size) {
if (this.data[family + "-" + size] === undefined) {
this.data[family + "-" + size] = new Font(family, size);
}
return this.data[family + "-" + size];
};
module.exports = FontMetrics;
},{"./font":8}],10:[function(require,module,exports){
var utils = require('./utils');
var Promise = require('./promise');
var getBounds = utils.getBounds;
var loadUrlDocument = require('./proxy').loadUrlDocument;
function FrameContainer(container, sameOrigin, options) {
this.image = null;
this.src = container;
var self = this;
var bounds = getBounds(container);
this.promise = (!sameOrigin ? this.proxyLoad(options.proxy, bounds, options) : new Promise(function(resolve) {
if (container.contentWindow.document.URL === "about:blank" || container.contentWindow.document.documentElement == null) {
container.contentWindow.onload = container.onload = function() {
resolve(container);
};
} else {
resolve(container);
}
})).then(function(container) {
var html2canvas = require('./core');
return html2canvas(container.contentWindow.document.documentElement, {type: 'view', width: container.width, height: container.height, proxy: options.proxy, javascriptEnabled: options.javascriptEnabled, removeContainer: options.removeContainer, allowTaint: options.allowTaint, imageTimeout: options.imageTimeout / 2});
}).then(function(canvas) {
return self.image = canvas;
});
}
FrameContainer.prototype.proxyLoad = function(proxy, bounds, options) {
var container = this.src;
return loadUrlDocument(container.src, proxy, container.ownerDocument, bounds.width, bounds.height, options);
};
module.exports = FrameContainer;
},{"./core":6,"./promise":18,"./proxy":19,"./utils":29}],11:[function(require,module,exports){
var Promise = require('./promise');
function GradientContainer(imageData) {
this.src = imageData.value;
this.colorStops = [];
this.type = null;
this.x0 = 0.5;
this.y0 = 0.5;
this.x1 = 0.5;
this.y1 = 0.5;
this.promise = Promise.resolve(true);
}
GradientContainer.prototype.TYPES = {
LINEAR: 1,
RADIAL: 2
};
module.exports = GradientContainer;
},{"./promise":18}],12:[function(require,module,exports){
var Promise = require('./promise');
function ImageContainer(src, cors) {
this.src = src;
this.image = new Image();
var self = this;
this.tainted = null;
this.promise = new Promise(function(resolve, reject) {
self.image.onload = resolve;
self.image.onerror = reject;
if (cors) {
self.image.crossOrigin = "anonymous";
}
self.image.src = src;
if (self.image.complete === true) {
resolve(self.image);
}
});
}
module.exports = ImageContainer;
},{"./promise":18}],13:[function(require,module,exports){
var Promise = require('./promise');
var log = require('./log');
var ImageContainer = require('./imagecontainer');
var DummyImageContainer = require('./dummyimagecontainer');
var ProxyImageContainer = require('./proxyimagecontainer');
var FrameContainer = require('./framecontainer');
var SVGContainer = require('./svgcontainer');
var SVGNodeContainer = require('./svgnodecontainer');
var LinearGradientContainer = require('./lineargradientcontainer');
var WebkitGradientContainer = require('./webkitgradientcontainer');
var bind = require('./utils').bind;
function ImageLoader(options, support) {
this.link = null;
this.options = options;
this.support = support;
this.origin = this.getOrigin(window.location.href);
}
ImageLoader.prototype.findImages = function(nodes) {
var images = [];
nodes.reduce(function(imageNodes, container) {
switch(container.node.nodeName) {
case "IMG":
return imageNodes.concat([{
args: [container.node.src],
method: "url"
}]);
case "svg":
case "IFRAME":
return imageNodes.concat([{
args: [container.node],
method: container.node.nodeName
}]);
}
return imageNodes;
}, []).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.findBackgroundImage = function(images, container) {
container.parseBackgroundImages().filter(this.hasImageBackground).forEach(this.addImage(images, this.loadImage), this);
return images;
};
ImageLoader.prototype.addImage = function(images, callback) {
return function(newImage) {
newImage.args.forEach(function(image) {
if (!this.imageExists(images, image)) {
images.splice(0, 0, callback.call(this, newImage));
log('Added image #' + (images.length), typeof(image) === "string" ? image.substring(0, 100) : image);
}
}, this);
};
};
ImageLoader.prototype.hasImageBackground = function(imageData) {
return imageData.method !== "none";
};
ImageLoader.prototype.loadImage = function(imageData) {
if (imageData.method === "url") {
var src = imageData.args[0];
if (this.isSVG(src) && !this.support.svg && !this.options.allowTaint) {
return new SVGContainer(src);
} else if (src.match(/data:image\/.*;base64,/i)) {
return new ImageContainer(src.replace(/url\(['"]{0,}|['"]{0,}\)$/ig, ''), false);
} else if (this.isSameOrigin(src) || this.options.allowTaint === true || this.isSVG(src)) {
return new ImageContainer(src, false);
} else if (this.support.cors && !this.options.allowTaint && this.options.useCORS) {
return new ImageContainer(src, true);
} else if (this.options.proxy) {
return new ProxyImageContainer(src, this.options.proxy);
} else {
return new DummyImageContainer(src);
}
} else if (imageData.method === "linear-gradient") {
return new LinearGradientContainer(imageData);
} else if (imageData.method === "gradient") {
return new WebkitGradientContainer(imageData);
} else if (imageData.method === "svg") {
return new SVGNodeContainer(imageData.args[0], this.support.svg);
} else if (imageData.method === "IFRAME") {
return new FrameContainer(imageData.args[0], this.isSameOrigin(imageData.args[0].src), this.options);
} else {
return new DummyImageContainer(imageData);
}
};
ImageLoader.prototype.isSVG = function(src) {
return src.substring(src.length - 3).toLowerCase() === "svg" || SVGContainer.prototype.isInline(src);
};
ImageLoader.prototype.imageExists = function(images, src) {
return images.some(function(image) {
return image.src === src;
});
};
ImageLoader.prototype.isSameOrigin = function(url) {
return (this.getOrigin(url) === this.origin);
};
ImageLoader.prototype.getOrigin = function(url) {
var link = this.link || (this.link = document.createElement("a"));
link.href = url;
link.href = link.href; // IE9, LOL! - http://jsfiddle.net/niklasvh/2e48b/
return link.protocol + link.hostname + link.port;
};
ImageLoader.prototype.getPromise = function(container) {
return this.timeout(container, this.options.imageTimeout)['catch'](function() {
var dummy = new DummyImageContainer(container.src);
return dummy.promise.then(function(image) {
container.image = image;
});
});
};
ImageLoader.prototype.get = function(src) {
var found = null;
return this.images.some(function(img) {
return (found = img).src === src;
}) ? found : null;
};
ImageLoader.prototype.fetch = function(nodes) {
this.images = nodes.reduce(bind(this.findBackgroundImage, this), this.findImages(nodes));
this.images.forEach(function(image, index) {
image.promise.then(function() {
log("Succesfully loaded image #"+ (index+1), image);
}, function(e) {
log("Failed loading image #"+ (index+1), image, e);
});
});
this.ready = Promise.all(this.images.map(this.getPromise, this));
log("Finished searching images");
return this;
};
ImageLoader.prototype.timeout = function(container, timeout) {
var timer;
var promise = Promise.race([container.promise, new Promise(function(res, reject) {
timer = setTimeout(function() {
log("Timed out loading image", container);
reject(container);
}, timeout);
})]).then(function(container) {
clearTimeout(timer);
return container;
});
promise['catch'](function() {
clearTimeout(timer);
});
return promise;
};
module.exports = ImageLoader;
},{"./dummyimagecontainer":7,"./framecontainer":10,"./imagecontainer":12,"./lineargradientcontainer":14,"./log":15,"./promise":18,"./proxyimagecontainer":20,"./svgcontainer":26,"./svgnodecontainer":27,"./utils":29,"./webkitgradientcontainer":30}],14:[function(require,module,exports){
var GradientContainer = require('./gradientcontainer');
var Color = require('./color');
function LinearGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = this.TYPES.LINEAR;
var hasDirection = imageData.args[0].match(this.stepRegExp) === null;
if (hasDirection) {
imageData.args[0].split(" ").reverse().forEach(function(position) {
switch(position) {
case "left":
this.x0 = 0;
this.x1 = 1;
break;
case "top":
this.y0 = 0;
this.y1 = 1;
break;
case "right":
this.x0 = 1;
this.x1 = 0;
break;
case "bottom":
this.y0 = 1;
this.y1 = 0;
break;
case "to":
var y0 = this.y0;
var x0 = this.x0;
this.y0 = this.y1;
this.x0 = this.x1;
this.x1 = x0;
this.y1 = y0;
break;
}
}, this);
} else {
this.y0 = 0;
this.y1 = 1;
}
this.colorStops = imageData.args.slice(hasDirection ? 1 : 0).map(function(colorStop) {
var colorStopMatch = colorStop.match(/((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\)|\w+)\s*(\d{1,3})?(%|px)?/);
return {
color: new Color(colorStopMatch[1]),
stop: colorStopMatch[3] === "%" ? colorStopMatch[2] / 100 : null
};
}, this);
if (this.colorStops[0].stop === null) {
this.colorStops[0].stop = 0;
}
if (this.colorStops[this.colorStops.length - 1].stop === null) {
this.colorStops[this.colorStops.length - 1].stop = 1;
}
this.colorStops.forEach(function(colorStop, index) {
if (colorStop.stop === null) {
this.colorStops.slice(index).some(function(find, count) {
if (find.stop !== null) {
colorStop.stop = ((find.stop - this.colorStops[index - 1].stop) / (count + 1)) + this.colorStops[index - 1].stop;
return true;
} else {
return false;
}
}, this);
}
}, this);
}
LinearGradientContainer.prototype = Object.create(GradientContainer.prototype);
LinearGradientContainer.prototype.stepRegExp = /((?:rgb|rgba)\(\d{1,3},\s\d{1,3},\s\d{1,3}(?:,\s[0-9\.]+)?\))\s*(\d{1,3})?(%|px)?/;
module.exports = LinearGradientContainer;
},{"./color":5,"./gradientcontainer":11}],15:[function(require,module,exports){
module.exports = function() {
if (window.html2canvas.logging && window.console && window.console.log) {
window.html2canvas.logmessage = String.prototype.call(arguments, 0);
Function.prototype.bind.call(window.console.log, (window.console)).apply(window.console, [(Date.now() - window.html2canvas.start) + "ms", "html2canvas:"].concat([].slice.call(arguments, 0)));
}
};
},{}],16:[function(require,module,exports){
var Color = require('./color');
var utils = require('./utils');
var getBounds = utils.getBounds;
var parseBackgrounds = utils.parseBackgrounds;
var offsetBounds = utils.offsetBounds;
function NodeContainer(node, parent) {
this.node = node;
this.parent = parent;
this.stack = null;
this.bounds = null;
this.borders = null;
this.clip = [];
this.backgroundClip = [];
this.offsetBounds = null;
this.visible = null;
this.computedStyles = null;
this.colors = {};
this.styles = {};
this.backgroundImages = null;
this.transformData = null;
this.transformMatrix = null;
this.isPseudoElement = false;
this.opacity = null;
}
NodeContainer.prototype.cloneTo = function(stack) {
stack.visible = this.visible;
stack.borders = this.borders;
stack.bounds = this.bounds;
stack.clip = this.clip;
stack.backgroundClip = this.backgroundClip;
stack.computedStyles = this.computedStyles;
stack.styles = this.styles;
stack.backgroundImages = this.backgroundImages;
stack.opacity = this.opacity;
};
NodeContainer.prototype.getOpacity = function() {
return this.opacity === null ? (this.opacity = this.cssFloat('opacity')) : this.opacity;
};
NodeContainer.prototype.assignStack = function(stack) {
this.stack = stack;
stack.children.push(this);
};
NodeContainer.prototype.isElementVisible = function() {
return this.node.nodeType === Node.TEXT_NODE ? this.parent.visible : (
this.css('display') !== "none" &&
this.css('visibility') !== "hidden" &&
!this.node.hasAttribute("data-html2canvas-ignore") &&
(this.node.nodeName !== "INPUT" || this.node.getAttribute("type") !== "hidden")
);
};
NodeContainer.prototype.css = function(attribute) {
if (!this.computedStyles) {
this.computedStyles = this.isPseudoElement ? this.parent.computedStyle(this.before ? ":before" : ":after") : this.computedStyle(null);
}
return this.styles[attribute] || (this.styles[attribute] = this.computedStyles[attribute]);
};
NodeContainer.prototype.prefixedCss = function(attribute) {
var prefixes = ["webkit", "moz", "ms", "o"];
var value = this.css(attribute);
if (value === undefined) {
prefixes.some(function(prefix) {
value = this.css(prefix + attribute.substr(0, 1).toUpperCase() + attribute.substr(1));
return value !== undefined;
}, this);
}
return value === undefined ? null : value;
};
NodeContainer.prototype.computedStyle = function(type) {
return this.node.ownerDocument.defaultView.getComputedStyle(this.node, type);
};
NodeContainer.prototype.cssInt = function(attribute) {
var value = parseInt(this.css(attribute), 10);
return (isNaN(value)) ? 0 : value; // borders in old IE are throwing 'medium' for demo.html
};
NodeContainer.prototype.color = function(attribute) {
return this.colors[attribute] || (this.colors[attribute] = new Color(this.css(attribute)));
};
NodeContainer.prototype.cssFloat = function(attribute) {
var value = parseFloat(this.css(attribute));
return (isNaN(value)) ? 0 : value;
};
NodeContainer.prototype.fontWeight = function() {
var weight = this.css("fontWeight");
switch(parseInt(weight, 10)){
case 401:
weight = "bold";
break;
case 400:
weight = "normal";
break;
}
return weight;
};
NodeContainer.prototype.parseClip = function() {
var matches = this.css('clip').match(this.CLIP);
if (matches) {
return {
top: parseInt(matches[1], 10),
right: parseInt(matches[2], 10),
bottom: parseInt(matches[3], 10),
left: parseInt(matches[4], 10)
};
}
return null;
};
NodeContainer.prototype.parseBackgroundImages = function() {
return this.backgroundImages || (this.backgroundImages = parseBackgrounds(this.css("backgroundImage")));
};
NodeContainer.prototype.cssList = function(property, index) {
var value = (this.css(property) || '').split(',');
value = value[index || 0] || value[0] || 'auto';
value = value.trim().split(' ');
if (value.length === 1) {
value = [value[0], isPercentage(value[0]) ? 'auto' : value[0]];
}
return value;
};
NodeContainer.prototype.parseBackgroundSize = function(bounds, image, index) {
var size = this.cssList("backgroundSize", index);
var width, height;
if (isPercentage(size[0])) {
width = bounds.width * parseFloat(size[0]) / 100;
} else if (/contain|cover/.test(size[0])) {
var targetRatio = bounds.width / bounds.height, currentRatio = image.width / image.height;
return (targetRatio < currentRatio ^ size[0] === 'contain') ? {width: bounds.height * currentRatio, height: bounds.height} : {width: bounds.width, height: bounds.width / currentRatio};
} else {
width = parseInt(size[0], 10);
}
if (size[0] === 'auto' && size[1] === 'auto') {
height = image.height;
} else if (size[1] === 'auto') {
height = width / image.width * image.height;
} else if (isPercentage(size[1])) {
height = bounds.height * parseFloat(size[1]) / 100;
} else {
height = parseInt(size[1], 10);
}
if (size[0] === 'auto') {
width = height / image.height * image.width;
}
return {width: width, height: height};
};
NodeContainer.prototype.parseBackgroundPosition = function(bounds, image, index, backgroundSize) {
var position = this.cssList('backgroundPosition', index);
var left, top;
if (isPercentage(position[0])){
left = (bounds.width - (backgroundSize || image).width) * (parseFloat(position[0]) / 100);
} else {
left = parseInt(position[0], 10);
}
if (position[1] === 'auto') {
top = left / image.width * image.height;
} else if (isPercentage(position[1])){
top = (bounds.height - (backgroundSize || image).height) * parseFloat(position[1]) / 100;
} else {
top = parseInt(position[1], 10);
}
if (position[0] === 'auto') {
left = top / image.height * image.width;
}
return {left: left, top: top};
};
NodeContainer.prototype.parseBackgroundRepeat = function(index) {
return this.cssList("backgroundRepeat", index)[0];
};
NodeContainer.prototype.parseTextShadows = function() {
var textShadow = this.css("textShadow");
var results = [];
if (textShadow && textShadow !== 'none') {
var shadows = textShadow.match(this.TEXT_SHADOW_PROPERTY);
for (var i = 0; shadows && (i < shadows.length); i++) {
var s = shadows[i].match(this.TEXT_SHADOW_VALUES);
results.push({
color: new Color(s[0]),
offsetX: s[1] ? parseFloat(s[1].replace('px', '')) : 0,
offsetY: s[2] ? parseFloat(s[2].replace('px', '')) : 0,
blur: s[3] ? s[3].replace('px', '') : 0
});
}
}
return results;
};
NodeContainer.prototype.parseTransform = function() {
if (!this.transformData) {
if (this.hasTransform()) {
var offset = this.parseBounds();
var origin = this.prefixedCss("transformOrigin").split(" ").map(removePx).map(asFloat);
origin[0] += offset.left;
origin[1] += offset.top;
this.transformData = {
origin: origin,
matrix: this.parseTransformMatrix()
};
} else {
this.transformData = {
origin: [0, 0],
matrix: [1, 0, 0, 1, 0, 0]
};
}
}
return this.transformData;
};
NodeContainer.prototype.parseTransformMatrix = function() {
if (!this.transformMatrix) {
var transform = this.prefixedCss("transform");
var matrix = transform ? parseMatrix(transform.match(this.MATRIX_PROPERTY)) : null;
this.transformMatrix = matrix ? matrix : [1, 0, 0, 1, 0, 0];
}
return this.transformMatrix;
};
NodeContainer.prototype.parseBounds = function() {
return this.bounds || (this.bounds = this.hasTransform() ? offsetBounds(this.node) : getBounds(this.node));
};
NodeContainer.prototype.hasTransform = function() {
return this.parseTransformMatrix().join(",") !== "1,0,0,1,0,0" || (this.parent && this.parent.hasTransform());
};
NodeContainer.prototype.getValue = function() {
var value = this.node.value || "";
if (this.node.tagName === "SELECT") {
value = selectionValue(this.node);
} else if (this.node.type === "password") {
value = Array(value.length + 1).join('\u2022'); // jshint ignore:line
}
return value.length === 0 ? (this.node.placeholder || "") : value;
};
NodeContainer.prototype.MATRIX_PROPERTY = /(matrix|matrix3d)\((.+)\)/;
NodeContainer.prototype.TEXT_SHADOW_PROPERTY = /((rgba|rgb)\([^\)]+\)(\s-?\d+px){0,})/g;
NodeContainer.prototype.TEXT_SHADOW_VALUES = /(-?\d+px)|(#.+)|(rgb\(.+\))|(rgba\(.+\))/g;
NodeContainer.prototype.CLIP = /^rect\((\d+)px,? (\d+)px,? (\d+)px,? (\d+)px\)$/;
function selectionValue(node) {
var option = node.options[node.selectedIndex || 0];
return option ? (option.text || "") : "";
}
function parseMatrix(match) {
if (match && match[1] === "matrix") {
return match[2].split(",").map(function(s) {
return parseFloat(s.trim());
});
} else if (match && match[1] === "matrix3d") {
var matrix3d = match[2].split(",").map(function(s) {
return parseFloat(s.trim());
});
return [matrix3d[0], matrix3d[1], matrix3d[4], matrix3d[5], matrix3d[12], matrix3d[13]];
}
}
function isPercentage(value) {
return value.toString().indexOf("%") !== -1;
}
function removePx(str) {
return str.replace("px", "");
}
function asFloat(str) {
return parseFloat(str);
}
module.exports = NodeContainer;
},{"./color":5,"./utils":29}],17:[function(require,module,exports){
var log = require('./log');
var punycode = require('punycode');
var NodeContainer = require('./nodecontainer');
var TextContainer = require('./textcontainer');
var PseudoElementContainer = require('./pseudoelementcontainer');
var FontMetrics = require('./fontmetrics');
var Color = require('./color');
var Promise = require('./promise');
var StackingContext = require('./stackingcontext');
var utils = require('./utils');
var bind = utils.bind;
var getBounds = utils.getBounds;
var parseBackgrounds = utils.parseBackgrounds;
var offsetBounds = utils.offsetBounds;
function NodeParser(element, renderer, support, imageLoader, options) {
log("Starting NodeParser");
this.renderer = renderer;
this.options = options;
this.range = null;
this.support = support;
this.renderQueue = [];
this.stack = new StackingContext(true, 1, element.ownerDocument, null);
var parent = new NodeContainer(element, null);
if (options.background) {
renderer.rectangle(0, 0, renderer.width, renderer.height, new Color(options.background));
}
if (element === element.ownerDocument.documentElement) {
// http://www.w3.org/TR/css3-background/#special-backgrounds
var canvasBackground = new NodeContainer(parent.color('backgroundColor').isTransparent() ? element.ownerDocument.body : element.ownerDocument.documentElement, null);
renderer.rectangle(0, 0, renderer.width, renderer.height, canvasBackground.color('backgroundColor'));
}
parent.visibile = parent.isElementVisible();
this.createPseudoHideStyles(element.ownerDocument);
this.disableAnimations(element.ownerDocument);
this.nodes = flatten([parent].concat(this.getChildren(parent)).filter(function(container) {
return container.visible = container.isElementVisible();
}).map(this.getPseudoElements, this));
this.fontMetrics = new FontMetrics();
log("Fetched nodes, total:", this.nodes.length);
log("Calculate overflow clips");
this.calculateOverflowClips();
log("Start fetching images");
this.images = imageLoader.fetch(this.nodes.filter(isElement));
this.ready = this.images.ready.then(bind(function() {
log("Images loaded, starting parsing");
log("Creating stacking contexts");
this.createStackingContexts();
log("Sorting stacking contexts");
this.sortStackingContexts(this.stack);
this.parse(this.stack);
log("Render queue created with " + this.renderQueue.length + " items");
return new Promise(bind(function(resolve) {
if (!options.async) {
this.renderQueue.forEach(this.paint, this);
resolve();
} else if (typeof(options.async) === "function") {
options.async.call(this, this.renderQueue, resolve);
} else if (this.renderQueue.length > 0){
this.renderIndex = 0;
this.asyncRenderer(this.renderQueue, resolve);
} else {
resolve();
}
}, this));
}, this));
}
NodeParser.prototype.calculateOverflowClips = function() {
this.nodes.forEach(function(container) {
if (isElement(container)) {
if (isPseudoElement(container)) {
container.appendToDOM();
}
container.borders = this.parseBorders(container);
var clip = (container.css('overflow') === "hidden") ? [container.borders.clip] : [];
var cssClip = container.parseClip();
if (cssClip && ["absolute", "fixed"].indexOf(container.css('position')) !== -1) {
clip.push([["rect",
container.bounds.left + cssClip.left,
container.bounds.top + cssClip.top,
cssClip.right - cssClip.left,
cssClip.bottom - cssClip.top
]]);
}
container.clip = hasParentClip(container) ? container.parent.clip.concat(clip) : clip;
container.backgroundClip = (container.css('overflow') !== "hidden") ? container.clip.concat([container.borders.clip]) : container.clip;
if (isPseudoElement(container)) {
container.cleanDOM();
}
} else if (isTextNode(container)) {
container.clip = hasParentClip(container) ? container.parent.clip : [];
}
if (!isPseudoElement(container)) {
container.bounds = null;
}
}, this);
};
function hasParentClip(container) {
return container.parent && container.parent.clip.length;
}
NodeParser.prototype.asyncRenderer = function(queue, resolve, asyncTimer) {
asyncTimer = asyncTimer || Date.now();
this.paint(queue[this.renderIndex++]);
if (queue.length === this.renderIndex) {
resolve();
} else if (asyncTimer + 20 > Date.now()) {
this.asyncRenderer(queue, resolve, asyncTimer);
} else {
setTimeout(bind(function() {
this.asyncRenderer(queue, resolve);
}, this), 0);
}
};
NodeParser.prototype.createPseudoHideStyles = function(document) {
this.createStyles(document, '.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + ':before { content: "" !important; display: none !important; }' +
'.' + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER + ':after { content: "" !important; display: none !important; }');
};
NodeParser.prototype.disableAnimations = function(document) {
this.createStyles(document, '* { -webkit-animation: none !important; -moz-animation: none !important; -o-animation: none !important; animation: none !important; ' +
'-webkit-transition: none !important; -moz-transition: none !important; -o-transition: none !important; transition: none !important;}');
};
NodeParser.prototype.createStyles = function(document, styles) {
var hidePseudoElements = document.createElement('style');
hidePseudoElements.innerHTML = styles;
document.body.appendChild(hidePseudoElements);
};
NodeParser.prototype.getPseudoElements = function(container) {
var nodes = [[container]];
if (container.node.nodeType === Node.ELEMENT_NODE) {
var before = this.getPseudoElement(container, ":before");
var after = this.getPseudoElement(container, ":after");
if (before) {
nodes.push(before);
}
if (after) {
nodes.push(after);
}
}
return flatten(nodes);
};
function toCamelCase(str) {
return str.replace(/(\-[a-z])/g, function(match){
return match.toUpperCase().replace('-','');
});
}
NodeParser.prototype.getPseudoElement = function(container, type) {
var style = container.computedStyle(type);
if(!style || !style.content || style.content === "none" || style.content === "-moz-alt-content" || style.display === "none") {
return null;
}
var content = stripQuotes(style.content);
var isImage = content.substr(0, 3) === 'url';
var pseudoNode = document.createElement(isImage ? 'img' : 'html2canvaspseudoelement');
var pseudoContainer = new PseudoElementContainer(pseudoNode, container, type);
for (var i = style.length-1; i >= 0; i--) {
var property = toCamelCase(style.item(i));
pseudoNode.style[property] = style[property];
}
pseudoNode.className = PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE + " " + PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER;
if (isImage) {
pseudoNode.src = parseBackgrounds(content)[0].args[0];
return [pseudoContainer];
} else {
var text = document.createTextNode(content);
pseudoNode.appendChild(text);
return [pseudoContainer, new TextContainer(text, pseudoContainer)];
}
};
NodeParser.prototype.getChildren = function(parentContainer) {
return flatten([].filter.call(parentContainer.node.childNodes, renderableNode).map(function(node) {
var container = [node.nodeType === Node.TEXT_NODE ? new TextContainer(node, parentContainer) : new NodeContainer(node, parentContainer)].filter(nonIgnoredElement);
return node.nodeType === Node.ELEMENT_NODE && container.length && node.tagName !== "TEXTAREA" ? (container[0].isElementVisible() ? container.concat(this.getChildren(container[0])) : []) : container;
}, this));
};
NodeParser.prototype.newStackingContext = function(container, hasOwnStacking) {
var stack = new StackingContext(hasOwnStacking, container.getOpacity(), container.node, container.parent);
container.cloneTo(stack);
var parentStack = hasOwnStacking ? stack.getParentStack(this) : stack.parent.stack;
parentStack.contexts.push(stack);
container.stack = stack;
};
NodeParser.prototype.createStackingContexts = function() {
this.nodes.forEach(function(container) {
if (isElement(container) && (this.isRootElement(container) || hasOpacity(container) || isPositionedForStacking(container) || this.isBodyWithTransparentRoot(container) || container.hasTransform())) {
this.newStackingContext(container, true);
} else if (isElement(container) && ((isPositioned(container) && zIndex0(container)) || isInlineBlock(container) || isFloating(container))) {
this.newStackingContext(container, false);
} else {
container.assignStack(container.parent.stack);
}
}, this);
};
NodeParser.prototype.isBodyWithTransparentRoot = function(container) {
return container.node.nodeName === "BODY" && container.parent.color('backgroundColor').isTransparent();
};
NodeParser.prototype.isRootElement = function(container) {
return container.parent === null;
};
NodeParser.prototype.sortStackingContexts = function(stack) {
stack.contexts.sort(zIndexSort(stack.contexts.slice(0)));
stack.contexts.forEach(this.sortStackingContexts, this);
};
NodeParser.prototype.parseTextBounds = function(container) {
return function(text, index, textList) {
if (container.parent.css("textDecoration").substr(0, 4) !== "none" || text.trim().length !== 0) {
if (this.support.rangeBounds && !container.parent.hasTransform()) {
var offset = textList.slice(0, index).join("").length;
return this.getRangeBounds(container.node, offset, text.length);
} else if (container.node && typeof(container.node.data) === "string") {
var replacementNode = container.node.splitText(text.length);
var bounds = this.getWrapperBounds(container.node, container.parent.hasTransform());
container.node = replacementNode;
return bounds;
}
} else if(!this.support.rangeBounds || container.parent.hasTransform()){
container.node = container.node.splitText(text.length);
}
return {};
};
};
NodeParser.prototype.getWrapperBounds = function(node, transform) {
var wrapper = node.ownerDocument.createElement('html2canvaswrapper');
var parent = node.parentNode,
backupText = node.cloneNode(true);
wrapper.appendChild(node.cloneNode(true));
parent.replaceChild(wrapper, node);
var bounds = transform ? offsetBounds(wrapper) : getBounds(wrapper);
parent.replaceChild(backupText, wrapper);
return bounds;
};
NodeParser.prototype.getRangeBounds = function(node, offset, length) {
var range = this.range || (this.range = node.ownerDocument.createRange());
range.setStart(node, offset);
range.setEnd(node, offset + length);
return range.getBoundingClientRect();
};
function ClearTransform() {}
NodeParser.prototype.parse = function(stack) {
// http://www.w3.org/TR/CSS21/visuren.html#z-index
var negativeZindex = stack.contexts.filter(negativeZIndex); // 2. the child stacking contexts with negative stack levels (most negative first).
var descendantElements = stack.children.filter(isElement);
var descendantNonFloats = descendantElements.filter(not(isFloating));
var nonInlineNonPositionedDescendants = descendantNonFloats.filter(not(isPositioned)).filter(not(inlineLevel)); // 3 the in-flow, non-inline-level, non-positioned descendants.
var nonPositionedFloats = descendantElements.filter(not(isPositioned)).filter(isFloating); // 4. the non-positioned floats.
var inFlow = descendantNonFloats.filter(not(isPositioned)).filter(inlineLevel); // 5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.
var stackLevel0 = stack.contexts.concat(descendantNonFloats.filter(isPositioned)).filter(zIndex0); // 6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.
var text = stack.children.filter(isTextNode).filter(hasText);
var positiveZindex = stack.contexts.filter(positiveZIndex); // 7. the child stacking contexts with positive stack levels (least positive first).
negativeZindex.concat(nonInlineNonPositionedDescendants).concat(nonPositionedFloats)
.concat(inFlow).concat(stackLevel0).concat(text).concat(positiveZindex).forEach(function(container) {
this.renderQueue.push(container);
if (isStackingContext(container)) {
this.parse(container);
this.renderQueue.push(new ClearTransform());
}
}, this);
};
NodeParser.prototype.paint = function(container) {
try {
if (container instanceof ClearTransform) {
this.renderer.ctx.restore();
} else if (isTextNode(container)) {
if (isPseudoElement(container.parent)) {
container.parent.appendToDOM();
}
this.paintText(container);
if (isPseudoElement(container.parent)) {
container.parent.cleanDOM();
}
} else {
this.paintNode(container);
}
} catch(e) {
log(e);
if (this.options.strict) {
throw e;
}
}
};
NodeParser.prototype.paintNode = function(container) {
if (isStackingContext(container)) {
this.renderer.setOpacity(container.opacity);
this.renderer.ctx.save();
if (container.hasTransform()) {
this.renderer.setTransform(container.parseTransform());
}
}
if (container.node.nodeName === "INPUT" && container.node.type === "checkbox") {
this.paintCheckbox(container);
} else if (container.node.nodeName === "INPUT" && container.node.type === "radio") {
this.paintRadio(container);
} else {
this.paintElement(container);
}
};
NodeParser.prototype.paintElement = function(container) {
var bounds = container.parseBounds();
this.renderer.clip(container.backgroundClip, function() {
this.renderer.renderBackground(container, bounds, container.borders.borders.map(getWidth));
}, this);
this.renderer.clip(container.clip, function() {
this.renderer.renderBorders(container.borders.borders);
}, this);
this.renderer.clip(container.backgroundClip, function() {
switch (container.node.nodeName) {
case "svg":
case "IFRAME":
var imgContainer = this.images.get(container.node);
if (imgContainer) {
this.renderer.renderImage(container, bounds, container.borders, imgContainer);
} else {
log("Error loading <" + container.node.nodeName + ">", container.node);
}
break;
case "IMG":
var imageContainer = this.images.get(container.node.src);
if (imageContainer) {
this.renderer.renderImage(container, bounds, container.borders, imageContainer);
} else {
log("Error loading <img>", container.node.src);
}
break;
case "CANVAS":
this.renderer.renderImage(container, bounds, container.borders, {image: container.node});
break;
case "SELECT":
case "INPUT":
case "TEXTAREA":
this.paintFormValue(container);
break;
}
}, this);
};
NodeParser.prototype.paintCheckbox = function(container) {
var b = container.parseBounds();
var size = Math.min(b.width, b.height);
var bounds = {width: size - 1, height: size - 1, top: b.top, left: b.left};
var r = [3, 3];
var radius = [r, r, r, r];
var borders = [1,1,1,1].map(function(w) {
return {color: new Color('#A5A5A5'), width: w};
});
var borderPoints = calculateCurvePoints(bounds, radius, borders);
this.renderer.clip(container.backgroundClip, function() {
this.renderer.rectangle(bounds.left + 1, bounds.top + 1, bounds.width - 2, bounds.height - 2, new Color("#DEDEDE"));
this.renderer.renderBorders(calculateBorders(borders, bounds, borderPoints, radius));
if (container.node.checked) {
this.renderer.font(new Color('#424242'), 'normal', 'normal', 'bold', (size - 3) + "px", 'arial');
this.renderer.text("\u2714", bounds.left + size / 6, bounds.top + size - 1);
}
}, this);
};
NodeParser.prototype.paintRadio = function(container) {
var bounds = container.parseBounds();
var size = Math.min(bounds.width, bounds.height) - 2;
this.renderer.clip(container.backgroundClip, function() {
this.renderer.circleStroke(bounds.left + 1, bounds.top + 1, size, new Color('#DEDEDE'), 1, new Color('#A5A5A5'));
if (container.node.checked) {
this.renderer.circle(Math.ceil(bounds.left + size / 4) + 1, Math.ceil(bounds.top + size / 4) + 1, Math.floor(size / 2), new Color('#424242'));
}
}, this);
};
NodeParser.prototype.paintFormValue = function(container) {
var value = container.getValue();
if (value.length > 0) {
var document = container.node.ownerDocument;
var wrapper = document.createElement('html2canvaswrapper');
var properties = ['lineHeight', 'textAlign', 'fontFamily', 'fontWeight', 'fontSize', 'color',
'paddingLeft', 'paddingTop', 'paddingRight', 'paddingBottom',
'width', 'height', 'borderLeftStyle', 'borderTopStyle', 'borderLeftWidth', 'borderTopWidth',
'boxSizing', 'whiteSpace', 'wordWrap'];
properties.forEach(function(property) {
try {
wrapper.style[property] = container.css(property);
} catch(e) {
// Older IE has issues with "border"
log("html2canvas: Parse: Exception caught in renderFormValue: " + e.message);
}
});
var bounds = container.parseBounds();
wrapper.style.position = "fixed";
wrapper.style.left = bounds.left + "px";
wrapper.style.top = bounds.top + "px";
wrapper.textContent = value;
document.body.appendChild(wrapper);
this.paintText(new TextContainer(wrapper.firstChild, container));
document.body.removeChild(wrapper);
}
};
NodeParser.prototype.paintText = function(container) {
container.applyTextTransform();
var characters = punycode.ucs2.decode(container.node.data);
var textList = (!this.options.letterRendering || noLetterSpacing(container)) && !hasUnicode(container.node.data) ? getWords(characters) : characters.map(function(character) {
return punycode.ucs2.encode([character]);
});
var weight = container.parent.fontWeight();
var size = container.parent.css('fontSize');
var family = container.parent.css('fontFamily');
var shadows = container.parent.parseTextShadows();
this.renderer.font(container.parent.color('color'), container.parent.css('fontStyle'), container.parent.css('fontVariant'), weight, size, family);
if (shadows.length) {
// TODO: support multiple text shadows
this.renderer.fontShadow(shadows[0].color, shadows[0].offsetX, shadows[0].offsetY, shadows[0].blur);
} else {
this.renderer.clearShadow();
}
this.renderer.clip(container.parent.clip, function() {
textList.map(this.parseTextBounds(container), this).forEach(function(bounds, index) {
if (bounds) {
this.renderer.text(textList[index], bounds.left, bounds.bottom);
this.renderTextDecoration(container.parent, bounds, this.fontMetrics.getMetrics(family, size));
}
}, this);
}, this);
};
NodeParser.prototype.renderTextDecoration = function(container, bounds, metrics) {
switch(container.css("textDecoration").split(" ")[0]) {
case "underline":
// Draws a line at the baseline of the font
// TODO As some browsers display the line as more than 1px if the font-size is big, need to take that into account both in position and size
this.renderer.rectangle(bounds.left, Math.round(bounds.top + metrics.baseline + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
case "overline":
this.renderer.rectangle(bounds.left, Math.round(bounds.top), bounds.width, 1, container.color("color"));
break;
case "line-through":
// TODO try and find exact position for line-through
this.renderer.rectangle(bounds.left, Math.ceil(bounds.top + metrics.middle + metrics.lineWidth), bounds.width, 1, container.color("color"));
break;
}
};
var borderColorTransforms = {
inset: [
["darken", 0.60],
["darken", 0.10],
["darken", 0.10],
["darken", 0.60]
]
};
NodeParser.prototype.parseBorders = function(container) {
var nodeBounds = container.parseBounds();
var radius = getBorderRadiusData(container);
var borders = ["Top", "Right", "Bottom", "Left"].map(function(side, index) {
var style = container.css('border' + side + 'Style');
var color = container.color('border' + side + 'Color');
if (style === "inset" && color.isBlack()) {
color = new Color([255, 255, 255, color.a]); // this is wrong, but
}
var colorTransform = borderColorTransforms[style] ? borderColorTransforms[style][index] : null;
return {
width: container.cssInt('border' + side + 'Width'),
color: colorTransform ? color[colorTransform[0]](colorTransform[1]) : color,
args: null
};
});
var borderPoints = calculateCurvePoints(nodeBounds, radius, borders);
return {
clip: this.parseBackgroundClip(container, borderPoints, borders, radius, nodeBounds),
borders: calculateBorders(borders, nodeBounds, borderPoints, radius)
};
};
function calculateBorders(borders, nodeBounds, borderPoints, radius) {
return borders.map(function(border, borderSide) {
if (border.width > 0) {
var bx = nodeBounds.left;
var by = nodeBounds.top;
var bw = nodeBounds.width;
var bh = nodeBounds.height - (borders[2].width);
switch(borderSide) {
case 0:
// top border
bh = borders[0].width;
border.args = drawSide({
c1: [bx, by],
c2: [bx + bw, by],
c3: [bx + bw - borders[1].width, by + bh],
c4: [bx + borders[3].width, by + bh]
}, radius[0], radius[1],
borderPoints.topLeftOuter, borderPoints.topLeftInner, borderPoints.topRightOuter, borderPoints.topRightInner);
break;
case 1:
// right border
bx = nodeBounds.left + nodeBounds.width - (borders[1].width);
bw = borders[1].width;
border.args = drawSide({
c1: [bx + bw, by],
c2: [bx + bw, by + bh + borders[2].width],
c3: [bx, by + bh],
c4: [bx, by + borders[0].width]
}, radius[1], radius[2],
borderPoints.topRightOuter, borderPoints.topRightInner, borderPoints.bottomRightOuter, borderPoints.bottomRightInner);
break;
case 2:
// bottom border
by = (by + nodeBounds.height) - (borders[2].width);
bh = borders[2].width;
border.args = drawSide({
c1: [bx + bw, by + bh],
c2: [bx, by + bh],
c3: [bx + borders[3].width, by],
c4: [bx + bw - borders[3].width, by]
}, radius[2], radius[3],
borderPoints.bottomRightOuter, borderPoints.bottomRightInner, borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner);
break;
case 3:
// left border
bw = borders[3].width;
border.args = drawSide({
c1: [bx, by + bh + borders[2].width],
c2: [bx, by],
c3: [bx + bw, by + borders[0].width],
c4: [bx + bw, by + bh]
}, radius[3], radius[0],
borderPoints.bottomLeftOuter, borderPoints.bottomLeftInner, borderPoints.topLeftOuter, borderPoints.topLeftInner);
break;
}
}
return border;
});
}
NodeParser.prototype.parseBackgroundClip = function(container, borderPoints, borders, radius, bounds) {
var backgroundClip = container.css('backgroundClip'),
borderArgs = [];
switch(backgroundClip) {
case "content-box":
case "padding-box":
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftInner, borderPoints.topRightInner, bounds.left + borders[3].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightInner, borderPoints.bottomRightInner, bounds.left + bounds.width - borders[1].width, bounds.top + borders[0].width);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightInner, borderPoints.bottomLeftInner, bounds.left + bounds.width - borders[1].width, bounds.top + bounds.height - borders[2].width);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftInner, borderPoints.topLeftInner, bounds.left + borders[3].width, bounds.top + bounds.height - borders[2].width);
break;
default:
parseCorner(borderArgs, radius[0], radius[1], borderPoints.topLeftOuter, borderPoints.topRightOuter, bounds.left, bounds.top);
parseCorner(borderArgs, radius[1], radius[2], borderPoints.topRightOuter, borderPoints.bottomRightOuter, bounds.left + bounds.width, bounds.top);
parseCorner(borderArgs, radius[2], radius[3], borderPoints.bottomRightOuter, borderPoints.bottomLeftOuter, bounds.left + bounds.width, bounds.top + bounds.height);
parseCorner(borderArgs, radius[3], radius[0], borderPoints.bottomLeftOuter, borderPoints.topLeftOuter, bounds.left, bounds.top + bounds.height);
break;
}
return borderArgs;
};
function getCurvePoints(x, y, r1, r2) {
var kappa = 4 * ((Math.sqrt(2) - 1) / 3);
var ox = (r1) * kappa, // control point offset horizontal
oy = (r2) * kappa, // control point offset vertical
xm = x + r1, // x-middle
ym = y + r2; // y-middle
return {
topLeft: bezierCurve({x: x, y: ym}, {x: x, y: ym - oy}, {x: xm - ox, y: y}, {x: xm, y: y}),
topRight: bezierCurve({x: x, y: y}, {x: x + ox,y: y}, {x: xm, y: ym - oy}, {x: xm, y: ym}),
bottomRight: bezierCurve({x: xm, y: y}, {x: xm, y: y + oy}, {x: x + ox, y: ym}, {x: x, y: ym}),
bottomLeft: bezierCurve({x: xm, y: ym}, {x: xm - ox, y: ym}, {x: x, y: y + oy}, {x: x, y:y})
};
}
function calculateCurvePoints(bounds, borderRadius, borders) {
var x = bounds.left,
y = bounds.top,
width = bounds.width,
height = bounds.height,
tlh = borderRadius[0][0],
tlv = borderRadius[0][1],
trh = borderRadius[1][0],
trv = borderRadius[1][1],
brh = borderRadius[2][0],
brv = borderRadius[2][1],
blh = borderRadius[3][0],
blv = borderRadius[3][1];
var topWidth = width - trh,
rightHeight = height - brv,
bottomWidth = width - brh,
leftHeight = height - blv;
return {
topLeftOuter: getCurvePoints(x, y, tlh, tlv).topLeft.subdivide(0.5),
topLeftInner: getCurvePoints(x + borders[3].width, y + borders[0].width, Math.max(0, tlh - borders[3].width), Math.max(0, tlv - borders[0].width)).topLeft.subdivide(0.5),
topRightOuter: getCurvePoints(x + topWidth, y, trh, trv).topRight.subdivide(0.5),
topRightInner: getCurvePoints(x + Math.min(topWidth, width + borders[3].width), y + borders[0].width, (topWidth > width + borders[3].width) ? 0 :trh - borders[3].width, trv - borders[0].width).topRight.subdivide(0.5),
bottomRightOuter: getCurvePoints(x + bottomWidth, y + rightHeight, brh, brv).bottomRight.subdivide(0.5),
bottomRightInner: getCurvePoints(x + Math.min(bottomWidth, width - borders[3].width), y + Math.min(rightHeight, height + borders[0].width), Math.max(0, brh - borders[1].width), brv - borders[2].width).bottomRight.subdivide(0.5),
bottomLeftOuter: getCurvePoints(x, y + leftHeight, blh, blv).bottomLeft.subdivide(0.5),
bottomLeftInner: getCurvePoints(x + borders[3].width, y + leftHeight, Math.max(0, blh - borders[3].width), blv - borders[2].width).bottomLeft.subdivide(0.5)
};
}
function bezierCurve(start, startControl, endControl, end) {
var lerp = function (a, b, t) {
return {
x: a.x + (b.x - a.x) * t,
y: a.y + (b.y - a.y) * t
};
};
return {
start: start,
startControl: startControl,
endControl: endControl,
end: end,
subdivide: function(t) {
var ab = lerp(start, startControl, t),
bc = lerp(startControl, endControl, t),
cd = lerp(endControl, end, t),
abbc = lerp(ab, bc, t),
bccd = lerp(bc, cd, t),
dest = lerp(abbc, bccd, t);
return [bezierCurve(start, ab, abbc, dest), bezierCurve(dest, bccd, cd, end)];
},
curveTo: function(borderArgs) {
borderArgs.push(["bezierCurve", startControl.x, startControl.y, endControl.x, endControl.y, end.x, end.y]);
},
curveToReversed: function(borderArgs) {
borderArgs.push(["bezierCurve", endControl.x, endControl.y, startControl.x, startControl.y, start.x, start.y]);
}
};
}
function drawSide(borderData, radius1, radius2, outer1, inner1, outer2, inner2) {
var borderArgs = [];
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", outer1[1].start.x, outer1[1].start.y]);
outer1[1].curveTo(borderArgs);
} else {
borderArgs.push([ "line", borderData.c1[0], borderData.c1[1]]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", outer2[0].start.x, outer2[0].start.y]);
outer2[0].curveTo(borderArgs);
borderArgs.push(["line", inner2[0].end.x, inner2[0].end.y]);
inner2[0].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c2[0], borderData.c2[1]]);
borderArgs.push(["line", borderData.c3[0], borderData.c3[1]]);
}
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", inner1[1].end.x, inner1[1].end.y]);
inner1[1].curveToReversed(borderArgs);
} else {
borderArgs.push(["line", borderData.c4[0], borderData.c4[1]]);
}
return borderArgs;
}
function parseCorner(borderArgs, radius1, radius2, corner1, corner2, x, y) {
if (radius1[0] > 0 || radius1[1] > 0) {
borderArgs.push(["line", corner1[0].start.x, corner1[0].start.y]);
corner1[0].curveTo(borderArgs);
corner1[1].curveTo(borderArgs);
} else {
borderArgs.push(["line", x, y]);
}
if (radius2[0] > 0 || radius2[1] > 0) {
borderArgs.push(["line", corner2[0].start.x, corner2[0].start.y]);
}
}
function negativeZIndex(container) {
return container.cssInt("zIndex") < 0;
}
function positiveZIndex(container) {
return container.cssInt("zIndex") > 0;
}
function zIndex0(container) {
return container.cssInt("zIndex") === 0;
}
function inlineLevel(container) {
return ["inline", "inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function isStackingContext(container) {
return (container instanceof StackingContext);
}
function hasText(container) {
return container.node.data.trim().length > 0;
}
function noLetterSpacing(container) {
return (/^(normal|none|0px)$/.test(container.parent.css("letterSpacing")));
}
function getBorderRadiusData(container) {
return ["TopLeft", "TopRight", "BottomRight", "BottomLeft"].map(function(side) {
var value = container.css('border' + side + 'Radius');
var arr = value.split(" ");
if (arr.length <= 1) {
arr[1] = arr[0];
}
return arr.map(asInt);
});
}
function renderableNode(node) {
return (node.nodeType === Node.TEXT_NODE || node.nodeType === Node.ELEMENT_NODE);
}
function isPositionedForStacking(container) {
var position = container.css("position");
var zIndex = (["absolute", "relative", "fixed"].indexOf(position) !== -1) ? container.css("zIndex") : "auto";
return zIndex !== "auto";
}
function isPositioned(container) {
return container.css("position") !== "static";
}
function isFloating(container) {
return container.css("float") !== "none";
}
function isInlineBlock(container) {
return ["inline-block", "inline-table"].indexOf(container.css("display")) !== -1;
}
function not(callback) {
var context = this;
return function() {
return !callback.apply(context, arguments);
};
}
function isElement(container) {
return container.node.nodeType === Node.ELEMENT_NODE;
}
function isPseudoElement(container) {
return container.isPseudoElement === true;
}
function isTextNode(container) {
return container.node.nodeType === Node.TEXT_NODE;
}
function zIndexSort(contexts) {
return function(a, b) {
return (a.cssInt("zIndex") + (contexts.indexOf(a) / contexts.length)) - (b.cssInt("zIndex") + (contexts.indexOf(b) / contexts.length));
};
}
function hasOpacity(container) {
return container.getOpacity() < 1;
}
function asInt(value) {
return parseInt(value, 10);
}
function getWidth(border) {
return border.width;
}
function nonIgnoredElement(nodeContainer) {
return (nodeContainer.node.nodeType !== Node.ELEMENT_NODE || ["SCRIPT", "HEAD", "TITLE", "OBJECT", "BR", "OPTION"].indexOf(nodeContainer.node.nodeName) === -1);
}
function flatten(arrays) {
return [].concat.apply([], arrays);
}
function stripQuotes(content) {
var first = content.substr(0, 1);
return (first === content.substr(content.length - 1) && first.match(/'|"/)) ? content.substr(1, content.length - 2) : content;
}
function getWords(characters) {
var words = [], i = 0, onWordBoundary = false, word;
while(characters.length) {
if (isWordBoundary(characters[i]) === onWordBoundary) {
word = characters.splice(0, i);
if (word.length) {
words.push(punycode.ucs2.encode(word));
}
onWordBoundary =! onWordBoundary;
i = 0;
} else {
i++;
}
if (i >= characters.length) {
word = characters.splice(0, i);
if (word.length) {
words.push(punycode.ucs2.encode(word));
}
}
}
return words;
}
function isWordBoundary(characterCode) {
return [
32, // <space>
13, // \r
10, // \n
9, // \t
45 // -
].indexOf(characterCode) !== -1;
}
function hasUnicode(string) {
return (/[^\u0000-\u00ff]/).test(string);
}
module.exports = NodeParser;
},{"./color":5,"./fontmetrics":9,"./log":15,"./nodecontainer":16,"./promise":18,"./pseudoelementcontainer":21,"./stackingcontext":24,"./textcontainer":28,"./utils":29,"punycode":3}],18:[function(require,module,exports){
module.exports = require('es6-promise').Promise;
},{"es6-promise":1}],19:[function(require,module,exports){
var Promise = require('./promise');
var XHR = require('./xhr');
var utils = require('./utils');
var log = require('./log');
var createWindowClone = require('./clone');
var decode64 = utils.decode64;
function Proxy(src, proxyUrl, document) {
var supportsCORS = ('withCredentials' in new XMLHttpRequest());
if (!proxyUrl) {
return Promise.reject("No proxy configured");
}
var callback = createCallback(supportsCORS);
var url = createProxyUrl(proxyUrl, src, callback);
return supportsCORS ? XHR(url) : (jsonp(document, url, callback).then(function(response) {
return decode64(response.content);
}));
}
var proxyCount = 0;
function ProxyURL(src, proxyUrl, document) {
var supportsCORSImage = ('crossOrigin' in new Image());
var callback = createCallback(supportsCORSImage);
var url = createProxyUrl(proxyUrl, src, callback);
return (supportsCORSImage ? Promise.resolve(url) : jsonp(document, url, callback).then(function(response) {
return "data:" + response.type + ";base64," + response.content;
}));
}
function jsonp(document, url, callback) {
return new Promise(function(resolve, reject) {
var s = document.createElement("script");
var cleanup = function() {
delete window.html2canvas.proxy[callback];
document.body.removeChild(s);
};
window.html2canvas.proxy[callback] = function(response) {
cleanup();
resolve(response);
};
s.src = url;
s.onerror = function(e) {
cleanup();
reject(e);
};
document.body.appendChild(s);
});
}
function createCallback(useCORS) {
return !useCORS ? "html2canvas_" + Date.now() + "_" + (++proxyCount) + "_" + Math.round(Math.random() * 100000) : "";
}
function createProxyUrl(proxyUrl, src, callback) {
return proxyUrl + "?url=" + encodeURIComponent(src) + (callback.length ? "&callback=html2canvas.proxy." + callback : "");
}
function documentFromHTML(src) {
return function(html) {
var parser = new DOMParser(), doc;
try {
doc = parser.parseFromString(html, "text/html");
} catch(e) {
log("DOMParser not supported, falling back to createHTMLDocument");
doc = document.implementation.createHTMLDocument("");
try {
doc.open();
doc.write(html);
doc.close();
} catch(ee) {
log("createHTMLDocument write not supported, falling back to document.body.innerHTML");
doc.body.innerHTML = html; // ie9 doesnt support writing to documentElement
}
}
var b = doc.querySelector("base");
if (!b || !b.href.host) {
var base = doc.createElement("base");
base.href = src;
doc.head.insertBefore(base, doc.head.firstChild);
}
return doc;
};
}
function loadUrlDocument(src, proxy, document, width, height, options) {
return new Proxy(src, proxy, window.document).then(documentFromHTML(src)).then(function(doc) {
return createWindowClone(doc, document, width, height, options, 0, 0);
});
}
exports.Proxy = Proxy;
exports.ProxyURL = ProxyURL;
exports.loadUrlDocument = loadUrlDocument;
},{"./clone":4,"./log":15,"./promise":18,"./utils":29,"./xhr":31}],20:[function(require,module,exports){
var ProxyURL = require('./proxy').ProxyURL;
var Promise = require('./promise');
function ProxyImageContainer(src, proxy) {
var link = document.createElement("a");
link.href = src;
src = link.href;
this.src = src;
this.image = new Image();
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.image.crossOrigin = "Anonymous";
self.image.onload = resolve;
self.image.onerror = reject;
new ProxyURL(src, proxy, document).then(function(url) {
self.image.src = url;
})['catch'](reject);
});
}
module.exports = ProxyImageContainer;
},{"./promise":18,"./proxy":19}],21:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function PseudoElementContainer(node, parent, type) {
NodeContainer.call(this, node, parent);
this.isPseudoElement = true;
this.before = type === ":before";
}
PseudoElementContainer.prototype.cloneTo = function(stack) {
PseudoElementContainer.prototype.cloneTo.call(this, stack);
stack.isPseudoElement = true;
stack.before = this.before;
};
PseudoElementContainer.prototype = Object.create(NodeContainer.prototype);
PseudoElementContainer.prototype.appendToDOM = function() {
if (this.before) {
this.parent.node.insertBefore(this.node, this.parent.node.firstChild);
} else {
this.parent.node.appendChild(this.node);
}
this.parent.node.className += " " + this.getHideClass();
};
PseudoElementContainer.prototype.cleanDOM = function() {
this.node.parentNode.removeChild(this.node);
this.parent.node.className = this.parent.node.className.replace(this.getHideClass(), "");
};
PseudoElementContainer.prototype.getHideClass = function() {
return this["PSEUDO_HIDE_ELEMENT_CLASS_" + (this.before ? "BEFORE" : "AFTER")];
};
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_BEFORE = "___html2canvas___pseudoelement_before";
PseudoElementContainer.prototype.PSEUDO_HIDE_ELEMENT_CLASS_AFTER = "___html2canvas___pseudoelement_after";
module.exports = PseudoElementContainer;
},{"./nodecontainer":16}],22:[function(require,module,exports){
var log = require('./log');
function Renderer(width, height, images, options, document) {
this.width = width;
this.height = height;
this.images = images;
this.options = options;
this.document = document;
}
Renderer.prototype.renderImage = function(container, bounds, borderData, imageContainer) {
var paddingLeft = container.cssInt('paddingLeft'),
paddingTop = container.cssInt('paddingTop'),
paddingRight = container.cssInt('paddingRight'),
paddingBottom = container.cssInt('paddingBottom'),
borders = borderData.borders;
var width = bounds.width - (borders[1].width + borders[3].width + paddingLeft + paddingRight);
var height = bounds.height - (borders[0].width + borders[2].width + paddingTop + paddingBottom);
this.drawImage(
imageContainer,
0,
0,
imageContainer.image.width || width,
imageContainer.image.height || height,
bounds.left + paddingLeft + borders[3].width,
bounds.top + paddingTop + borders[0].width,
width,
height
);
};
Renderer.prototype.renderBackground = function(container, bounds, borderData) {
if (bounds.height > 0 && bounds.width > 0) {
this.renderBackgroundColor(container, bounds);
this.renderBackgroundImage(container, bounds, borderData);
}
};
Renderer.prototype.renderBackgroundColor = function(container, bounds) {
var color = container.color("backgroundColor");
if (!color.isTransparent()) {
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, color);
}
};
Renderer.prototype.renderBorders = function(borders) {
borders.forEach(this.renderBorder, this);
};
Renderer.prototype.renderBorder = function(data) {
if (!data.color.isTransparent() && data.args !== null) {
this.drawShape(data.args, data.color);
}
};
Renderer.prototype.renderBackgroundImage = function(container, bounds, borderData) {
var backgroundImages = container.parseBackgroundImages();
backgroundImages.reverse().forEach(function(backgroundImage, index, arr) {
switch(backgroundImage.method) {
case "url":
var image = this.images.get(backgroundImage.args[0]);
if (image) {
this.renderBackgroundRepeating(container, bounds, image, arr.length - (index+1), borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "linear-gradient":
case "gradient":
var gradientImage = this.images.get(backgroundImage.value);
if (gradientImage) {
this.renderBackgroundGradient(gradientImage, bounds, borderData);
} else {
log("Error loading background-image", backgroundImage.args[0]);
}
break;
case "none":
break;
default:
log("Unknown background-image type", backgroundImage.args[0]);
}
}, this);
};
Renderer.prototype.renderBackgroundRepeating = function(container, bounds, imageContainer, index, borderData) {
var size = container.parseBackgroundSize(bounds, imageContainer.image, index);
var position = container.parseBackgroundPosition(bounds, imageContainer.image, index, size);
var repeat = container.parseBackgroundRepeat(index);
switch (repeat) {
case "repeat-x":
case "repeat no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + borderData[3], bounds.top + position.top + borderData[0], 99999, size.height, borderData);
break;
case "repeat-y":
case "no-repeat repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + borderData[0], size.width, 99999, borderData);
break;
case "no-repeat":
this.backgroundRepeatShape(imageContainer, position, size, bounds, bounds.left + position.left + borderData[3], bounds.top + position.top + borderData[0], size.width, size.height, borderData);
break;
default:
this.renderBackgroundRepeat(imageContainer, position, size, {top: bounds.top, left: bounds.left}, borderData[3], borderData[0]);
break;
}
};
module.exports = Renderer;
},{"./log":15}],23:[function(require,module,exports){
var Renderer = require('../renderer');
var LinearGradientContainer = require('../lineargradientcontainer');
var log = require('../log');
function CanvasRenderer(width, height) {
Renderer.apply(this, arguments);
this.canvas = this.options.canvas || this.document.createElement("canvas");
if (!this.options.canvas) {
this.canvas.width = width;
this.canvas.height = height;
}
this.ctx = this.canvas.getContext("2d");
this.taintCtx = this.document.createElement("canvas").getContext("2d");
this.ctx.textBaseline = "bottom";
this.variables = {};
log("Initialized CanvasRenderer with size", width, "x", height);
}
CanvasRenderer.prototype = Object.create(Renderer.prototype);
CanvasRenderer.prototype.setFillStyle = function(fillStyle) {
this.ctx.fillStyle = typeof(fillStyle) === "object" && !!fillStyle.isColor ? fillStyle.toString() : fillStyle;
return this.ctx;
};
CanvasRenderer.prototype.rectangle = function(left, top, width, height, color) {
this.setFillStyle(color).fillRect(left, top, width, height);
};
CanvasRenderer.prototype.circle = function(left, top, size, color) {
this.setFillStyle(color);
this.ctx.beginPath();
this.ctx.arc(left + size / 2, top + size / 2, size / 2, 0, Math.PI*2, true);
this.ctx.closePath();
this.ctx.fill();
};
CanvasRenderer.prototype.circleStroke = function(left, top, size, color, stroke, strokeColor) {
this.circle(left, top, size, color);
this.ctx.strokeStyle = strokeColor.toString();
this.ctx.stroke();
};
CanvasRenderer.prototype.drawShape = function(shape, color) {
this.shape(shape);
this.setFillStyle(color).fill();
};
CanvasRenderer.prototype.taints = function(imageContainer) {
if (imageContainer.tainted === null) {
this.taintCtx.drawImage(imageContainer.image, 0, 0);
try {
this.taintCtx.getImageData(0, 0, 1, 1);
imageContainer.tainted = false;
} catch(e) {
this.taintCtx = document.createElement("canvas").getContext("2d");
imageContainer.tainted = true;
}
}
return imageContainer.tainted;
};
CanvasRenderer.prototype.drawImage = function(imageContainer, sx, sy, sw, sh, dx, dy, dw, dh) {
if (!this.taints(imageContainer) || this.options.allowTaint) {
this.ctx.drawImage(imageContainer.image, sx, sy, sw, sh, dx, dy, dw, dh);
}
};
CanvasRenderer.prototype.clip = function(shapes, callback, context) {
this.ctx.save();
shapes.filter(hasEntries).forEach(function(shape) {
this.shape(shape).clip();
}, this);
callback.call(context);
this.ctx.restore();
};
CanvasRenderer.prototype.shape = function(shape) {
this.ctx.beginPath();
shape.forEach(function(point, index) {
if (point[0] === "rect") {
this.ctx.rect.apply(this.ctx, point.slice(1));
} else {
this.ctx[(index === 0) ? "moveTo" : point[0] + "To" ].apply(this.ctx, point.slice(1));
}
}, this);
this.ctx.closePath();
return this.ctx;
};
CanvasRenderer.prototype.font = function(color, style, variant, weight, size, family) {
this.setFillStyle(color).font = [style, variant, weight, size, family].join(" ").split(",")[0];
};
CanvasRenderer.prototype.fontShadow = function(color, offsetX, offsetY, blur) {
this.setVariable("shadowColor", color.toString())
.setVariable("shadowOffsetY", offsetX)
.setVariable("shadowOffsetX", offsetY)
.setVariable("shadowBlur", blur);
};
CanvasRenderer.prototype.clearShadow = function() {
this.setVariable("shadowColor", "rgba(0,0,0,0)");
};
CanvasRenderer.prototype.setOpacity = function(opacity) {
this.ctx.globalAlpha = opacity;
};
CanvasRenderer.prototype.setTransform = function(transform) {
this.ctx.translate(transform.origin[0], transform.origin[1]);
this.ctx.transform.apply(this.ctx, transform.matrix);
this.ctx.translate(-transform.origin[0], -transform.origin[1]);
};
CanvasRenderer.prototype.setVariable = function(property, value) {
if (this.variables[property] !== value) {
this.variables[property] = this.ctx[property] = value;
}
return this;
};
CanvasRenderer.prototype.text = function(text, left, bottom) {
this.ctx.fillText(text, left, bottom);
};
CanvasRenderer.prototype.backgroundRepeatShape = function(imageContainer, backgroundPosition, size, bounds, left, top, width, height, borderData) {
var shape = [
["line", Math.round(left), Math.round(top)],
["line", Math.round(left + width), Math.round(top)],
["line", Math.round(left + width), Math.round(height + top)],
["line", Math.round(left), Math.round(height + top)]
];
this.clip([shape], function() {
this.renderBackgroundRepeat(imageContainer, backgroundPosition, size, bounds, borderData[3], borderData[0]);
}, this);
};
CanvasRenderer.prototype.renderBackgroundRepeat = function(imageContainer, backgroundPosition, size, bounds, borderLeft, borderTop) {
var offsetX = Math.round(bounds.left + backgroundPosition.left + borderLeft), offsetY = Math.round(bounds.top + backgroundPosition.top + borderTop);
this.setFillStyle(this.ctx.createPattern(this.resizeImage(imageContainer, size), "repeat"));
this.ctx.translate(offsetX, offsetY);
this.ctx.fill();
this.ctx.translate(-offsetX, -offsetY);
};
CanvasRenderer.prototype.renderBackgroundGradient = function(gradientImage, bounds) {
if (gradientImage instanceof LinearGradientContainer) {
var gradient = this.ctx.createLinearGradient(
bounds.left + bounds.width * gradientImage.x0,
bounds.top + bounds.height * gradientImage.y0,
bounds.left + bounds.width * gradientImage.x1,
bounds.top + bounds.height * gradientImage.y1);
gradientImage.colorStops.forEach(function(colorStop) {
gradient.addColorStop(colorStop.stop, colorStop.color.toString());
});
this.rectangle(bounds.left, bounds.top, bounds.width, bounds.height, gradient);
}
};
CanvasRenderer.prototype.resizeImage = function(imageContainer, size) {
var image = imageContainer.image;
if(image.width === size.width && image.height === size.height) {
return image;
}
var ctx, canvas = document.createElement('canvas');
canvas.width = size.width;
canvas.height = size.height;
ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, image.width, image.height, 0, 0, size.width, size.height );
return canvas;
};
function hasEntries(array) {
return array.length > 0;
}
module.exports = CanvasRenderer;
},{"../lineargradientcontainer":14,"../log":15,"../renderer":22}],24:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function StackingContext(hasOwnStacking, opacity, element, parent) {
NodeContainer.call(this, element, parent);
this.ownStacking = hasOwnStacking;
this.contexts = [];
this.children = [];
this.opacity = (this.parent ? this.parent.stack.opacity : 1) * opacity;
}
StackingContext.prototype = Object.create(NodeContainer.prototype);
StackingContext.prototype.getParentStack = function(context) {
var parentStack = (this.parent) ? this.parent.stack : null;
return parentStack ? (parentStack.ownStacking ? parentStack : parentStack.getParentStack(context)) : context.stack;
};
module.exports = StackingContext;
},{"./nodecontainer":16}],25:[function(require,module,exports){
function Support(document) {
this.rangeBounds = this.testRangeBounds(document);
this.cors = this.testCORS();
this.svg = this.testSVG();
}
Support.prototype.testRangeBounds = function(document) {
var range, testElement, rangeBounds, rangeHeight, support = false;
if (document.createRange) {
range = document.createRange();
if (range.getBoundingClientRect) {
testElement = document.createElement('boundtest');
testElement.style.height = "123px";
testElement.style.display = "block";
document.body.appendChild(testElement);
range.selectNode(testElement);
rangeBounds = range.getBoundingClientRect();
rangeHeight = rangeBounds.height;
if (rangeHeight === 123) {
support = true;
}
document.body.removeChild(testElement);
}
}
return support;
};
Support.prototype.testCORS = function() {
return typeof((new Image()).crossOrigin) !== "undefined";
};
Support.prototype.testSVG = function() {
var img = new Image();
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
img.src = "data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg'></svg>";
try {
ctx.drawImage(img, 0, 0);
canvas.toDataURL();
} catch(e) {
return false;
}
return true;
};
module.exports = Support;
},{}],26:[function(require,module,exports){
var Promise = require('./promise');
var XHR = require('./xhr');
var decode64 = require('./utils').decode64;
function SVGContainer(src) {
this.src = src;
this.image = null;
var self = this;
this.promise = this.hasFabric().then(function() {
return (self.isInline(src) ? Promise.resolve(self.inlineFormatting(src)) : XHR(src));
}).then(function(svg) {
return new Promise(function(resolve) {
window.html2canvas.svg.fabric.loadSVGFromString(svg, self.createCanvas.call(self, resolve));
});
});
}
SVGContainer.prototype.hasFabric = function() {
return !window.html2canvas.svg || !window.html2canvas.svg.fabric ? Promise.reject(new Error("html2canvas.svg.js is not loaded, cannot render svg")) : Promise.resolve();
};
SVGContainer.prototype.inlineFormatting = function(src) {
return (/^data:image\/svg\+xml;base64,/.test(src)) ? this.decode64(this.removeContentType(src)) : this.removeContentType(src);
};
SVGContainer.prototype.removeContentType = function(src) {
return src.replace(/^data:image\/svg\+xml(;base64)?,/,'');
};
SVGContainer.prototype.isInline = function(src) {
return (/^data:image\/svg\+xml/i.test(src));
};
SVGContainer.prototype.createCanvas = function(resolve) {
var self = this;
return function (objects, options) {
var canvas = new window.html2canvas.svg.fabric.StaticCanvas('c');
self.image = canvas.lowerCanvasEl;
canvas
.setWidth(options.width)
.setHeight(options.height)
.add(window.html2canvas.svg.fabric.util.groupSVGElements(objects, options))
.renderAll();
resolve(canvas.lowerCanvasEl);
};
};
SVGContainer.prototype.decode64 = function(str) {
return (typeof(window.atob) === "function") ? window.atob(str) : decode64(str);
};
module.exports = SVGContainer;
},{"./promise":18,"./utils":29,"./xhr":31}],27:[function(require,module,exports){
var SVGContainer = require('./svgcontainer');
var Promise = require('./promise');
function SVGNodeContainer(node, _native) {
this.src = node;
this.image = null;
var self = this;
this.promise = _native ? new Promise(function(resolve, reject) {
self.image = new Image();
self.image.onload = resolve;
self.image.onerror = reject;
self.image.src = "data:image/svg+xml," + (new XMLSerializer()).serializeToString(node);
if (self.image.complete === true) {
resolve(self.image);
}
}) : this.hasFabric().then(function() {
return new Promise(function(resolve) {
window.html2canvas.svg.fabric.parseSVGDocument(node, self.createCanvas.call(self, resolve));
});
});
}
SVGNodeContainer.prototype = Object.create(SVGContainer.prototype);
module.exports = SVGNodeContainer;
},{"./promise":18,"./svgcontainer":26}],28:[function(require,module,exports){
var NodeContainer = require('./nodecontainer');
function TextContainer(node, parent) {
NodeContainer.call(this, node, parent);
}
TextContainer.prototype = Object.create(NodeContainer.prototype);
TextContainer.prototype.applyTextTransform = function() {
this.node.data = this.transform(this.parent.css("textTransform"));
};
TextContainer.prototype.transform = function(transform) {
var text = this.node.data;
switch(transform){
case "lowercase":
return text.toLowerCase();
case "capitalize":
return text.replace(/(^|\s|:|-|\(|\))([a-z])/g, capitalize);
case "uppercase":
return text.toUpperCase();
default:
return text;
}
};
function capitalize(m, p1, p2) {
if (m.length > 0) {
return p1 + p2.toUpperCase();
}
}
module.exports = TextContainer;
},{"./nodecontainer":16}],29:[function(require,module,exports){
exports.smallImage = function smallImage() {
return "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";
};
exports.bind = function(callback, context) {
return function() {
return callback.apply(context, arguments);
};
};
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
exports.decode64 = function(base64) {
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var len = base64.length, i, encoded1, encoded2, encoded3, encoded4, byte1, byte2, byte3;
var output = "";
for (i = 0; i < len; i+=4) {
encoded1 = chars.indexOf(base64[i]);
encoded2 = chars.indexOf(base64[i+1]);
encoded3 = chars.indexOf(base64[i+2]);
encoded4 = chars.indexOf(base64[i+3]);
byte1 = (encoded1 << 2) | (encoded2 >> 4);
byte2 = ((encoded2 & 15) << 4) | (encoded3 >> 2);
byte3 = ((encoded3 & 3) << 6) | encoded4;
if (encoded3 === 64) {
output += String.fromCharCode(byte1);
} else if (encoded4 === 64 || encoded4 === -1) {
output += String.fromCharCode(byte1, byte2);
} else{
output += String.fromCharCode(byte1, byte2, byte3);
}
}
return output;
};
exports.getBounds = function(node) {
if (node.getBoundingClientRect) {
var clientRect = node.getBoundingClientRect();
var width = node.offsetWidth == null ? clientRect.width : node.offsetWidth;
return {
top: clientRect.top,
bottom: clientRect.bottom || (clientRect.top + clientRect.height),
right: clientRect.left + width,
left: clientRect.left,
width: width,
height: node.offsetHeight == null ? clientRect.height : node.offsetHeight
};
}
return {};
};
exports.offsetBounds = function(node) {
var parent = node.offsetParent ? exports.offsetBounds(node.offsetParent) : {top: 0, left: 0};
return {
top: node.offsetTop + parent.top,
bottom: node.offsetTop + node.offsetHeight + parent.top,
right: node.offsetLeft + parent.left + node.offsetWidth,
left: node.offsetLeft + parent.left,
width: node.offsetWidth,
height: node.offsetHeight
};
};
exports.parseBackgrounds = function(backgroundImage) {
var whitespace = ' \r\n\t',
method, definition, prefix, prefix_i, block, results = [],
mode = 0, numParen = 0, quote, args;
var appendResult = function() {
if(method) {
if (definition.substr(0, 1) === '"') {
definition = definition.substr(1, definition.length - 2);
}
if (definition) {
args.push(definition);
}
if (method.substr(0, 1) === '-' && (prefix_i = method.indexOf('-', 1 ) + 1) > 0) {
prefix = method.substr(0, prefix_i);
method = method.substr(prefix_i);
}
results.push({
prefix: prefix,
method: method.toLowerCase(),
value: block,
args: args,
image: null
});
}
args = [];
method = prefix = definition = block = '';
};
args = [];
method = prefix = definition = block = '';
backgroundImage.split("").forEach(function(c) {
if (mode === 0 && whitespace.indexOf(c) > -1) {
return;
}
switch(c) {
case '"':
if(!quote) {
quote = c;
} else if(quote === c) {
quote = null;
}
break;
case '(':
if(quote) {
break;
} else if(mode === 0) {
mode = 1;
block += c;
return;
} else {
numParen++;
}
break;
case ')':
if (quote) {
break;
} else if(mode === 1) {
if(numParen === 0) {
mode = 0;
block += c;
appendResult();
return;
} else {
numParen--;
}
}
break;
case ',':
if (quote) {
break;
} else if(mode === 0) {
appendResult();
return;
} else if (mode === 1) {
if (numParen === 0 && !method.match(/^url$/i)) {
args.push(definition);
definition = '';
block += c;
return;
}
}
break;
}
block += c;
if (mode === 0) {
method += c;
} else {
definition += c;
}
});
appendResult();
return results;
};
},{}],30:[function(require,module,exports){
var GradientContainer = require('./gradientcontainer');
function WebkitGradientContainer(imageData) {
GradientContainer.apply(this, arguments);
this.type = (imageData.args[0] === "linear") ? this.TYPES.LINEAR : this.TYPES.RADIAL;
}
WebkitGradientContainer.prototype = Object.create(GradientContainer.prototype);
module.exports = WebkitGradientContainer;
},{"./gradientcontainer":11}],31:[function(require,module,exports){
var Promise = require('./promise');
function XHR(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.statusText));
}
};
xhr.onerror = function() {
reject(new Error("Network Error"));
};
xhr.send();
});
}
module.exports = XHR;
},{"./promise":18}]},{},[6])(6)
});
| ao-dexter/html2canvas | dist/html2canvas.js | JavaScript | mit | 154,883 |
/**
* @author weism
* copyright 2015 Qcplay All Rights Reserved.
*/
qc.RoundedRectangle = Phaser.RoundedRectangle;
/**
* 类名
*/
Object.defineProperty(qc.RoundedRectangle.prototype, 'class', {
get : function() { return 'qc.RoundedRectangle'; }
});
/**
* 序列化
*/
qc.RoundedRectangle.prototype.toJson = function() {
return [this.x, this.y, this.width, this.height, this.radius];
}
/**
* 反序列化
*/
qc.RoundedRectangle.prototype.fromJson = function(v) {
this.x = v[0];
this.y = v[1];
this.width = v[2];
this.height = v[3];
this.radius = v[4];
}
| qiciengine/qiciengine-core | src/geom/RoundedRectangle.js | JavaScript | mit | 594 |
import Ember from "ember";
import ENV from '../../config/environment';
export default Ember.Route.extend({
model: function() {
return this.store.find('clip');
},
afterModel: function(){
this.metaTags.setTags({
title: "Clips • " + ENV.name,
description: ENV.description,
url: this.get('router.url')
});
}
}); | APMG/audio-backpack | app/routes/clips/index.js | JavaScript | mit | 387 |
'use strict';
var _ = require('lodash');
var desireds = require('./desireds');
var runner = require('./runconfig');
var gruntConfig = {
env: {
options:{
}
},
simplemocha: {
ltr: {
options: {
timeout: 60000,
captureFile: 'reports.xml',
reporter: 'spec'
},
src: ['test/sauce/sanity/studentCreat*.js','test/sauce/sanity/studentAssign*.js']
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/**/*.js']
}
},
concurrent: {
'test-sauce': []// dynamically filled
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test']
}
},
exec: {
generate_report: {
cmd: function(firstName, lastName) {
return 'xmljade -o reportjade.html report.jade jadexml.xml';
}
}
}
};
//console.log(gruntConfig);
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig(gruntConfig);
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-env');
grunt.loadNpmTasks('grunt-simple-mocha');
grunt.loadNpmTasks('grunt-concurrent');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-exec');
var target = grunt.option('target') || 'staging';
var product = grunt.option('product') || 'default';
var course = grunt.option('course') || 'default';
var student_userid = grunt.option('student_userid') || 'default';
var instructor_userid = grunt.option('instructor_userid') || 'default';
var coursekey = grunt.option('coursekey') || 'default';
var cs = grunt.option('cs') || 'no';
var rc = grunt.option('rc') || 'no';
var sel_grid = grunt.option('grid') || 'http://127.0.0.1:4444/wd/hub';
var browser = grunt.option('browser') || 'chrome';
gruntConfig.env.common = {
RUNNER: JSON.stringify(runner),
RUN_ENV: JSON.stringify(target),
RUN_IN_GRID: JSON.stringify(sel_grid),
RUN_IN_BROWSER:JSON.stringify(browser),
RUN_FOR_PRODUCT: JSON.stringify(product),
RUN_FOR_COURSE: JSON.stringify(course),
RUN_FOR_STUDENT_USERID: JSON.stringify(student_userid),
RUN_FOR_INSTRUCTOR_USERID: JSON.stringify(instructor_userid),
RUN_FOR_COURSEKEY:JSON.stringify(coursekey),
CREATE_STUDENT: JSON.stringify(cs),
REGISTER_COURSE:JSON.stringify(rc)
};
grunt.registerTask('default', ['env:common','simplemocha:ltr']);
};
| Devanshu1991/4LTRProject | GF_CreateStudentAndRunStudentSubmission.js | JavaScript | mit | 2,979 |
version https://git-lfs.github.com/spec/v1
oid sha256:d99fc51072a5fe30289f7dc885457700f9b08ae17fe81d034245aba73c408033
size 34706
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.17.1/model/model.js | JavaScript | mit | 130 |
'use strict';
const isUriStringCheck = require('../strCheck');
/**
* First test if the argument passed in is a String. If true, get page version from uri.
* Otherwise throw an error.
* @example /pages/foo/@published returns published
* @param {string} uri
* @return {string|null}
*/
module.exports = function (uri) {
isUriStringCheck.strCheck(uri);
const result = /\/pages\/.+?@(.+)/.exec(uri);
return result && result[1];
};
| nymag/clay-utils | lib/getPageVersion/index.js | JavaScript | mit | 442 |
//# sourceMappingURL=request-constructor.js.map | jlberrocal/ng2-dynatable | src/interfaces/request-constructor.js | JavaScript | mit | 47 |
/*
* jQuery File Upload Plugin 5.0.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://creativecommons.org/licenses/MIT/
*/
/*jslint nomen: false, unparam: true, regexp: false */
/*global document, XMLHttpRequestUpload, Blob, File, FormData, location, jQuery */
(function ($) {
'use strict';
// The fileupload widget listens for change events on file input fields
// defined via fileInput setting and drop events of the given dropZone.
// In addition to the default jQuery Widget methods, the fileupload widget
// exposes the "add" and "send" methods, to add or directly send files
// using the fileupload API.
// By default, files added via file input selection, drag & drop or
// "add" method are uploaded immediately, but it is possible to override
// the "add" callback option to queue file uploads.
$.widget('blueimp.fileupload', {
options: {
// The namespace used for event handler binding on the dropZone and
// fileInput collections.
// If not set, the name of the widget ("fileupload") is used.
namespace: undefined,
// The drop target collection, by the default the complete document.
// Set to null or an empty collection to disable drag & drop support:
dropZone: $(document),
// The file input field collection, that is listened for change events.
// If undefined, it is set to the file input fields inside
// of the widget element on plugin initialization.
// Set to null or an empty collection to disable the change listener.
fileInput: undefined,
// By default, the file input field is replaced with a clone after
// each input field change event. This is required for iframe transport
// queues and allows change events to be fired for the same file
// selection, but can be disabled by setting the following option to false:
replaceFileInput: true,
// The parameter name for the file form data (the request argument name).
// If undefined or empty, the name property of the file input field is
// used, or "files[]" if the file input name property is also empty:
paramName: undefined,
// By default, each file of a selection is uploaded using an individual
// request for XHR type uploads. Set to false to upload file
// selections in one request each:
singleFileUploads: true,
// Set the following option to true to issue all file upload requests
// in a sequential order:
sequentialUploads: false,
// Set the following option to true to force iframe transport uploads:
forceIframeTransport: false,
// By default, XHR file uploads are sent as multipart/form-data.
// The iframe transport is always using multipart/form-data.
// Set to false to enable non-multipart XHR uploads:
multipart: true,
// To upload large files in smaller chunks, set the following option
// to a preferred maximum chunk size. If set to 0, null or undefined,
// or the browser does not support the required Blob API, files will
// be uploaded as a whole.
maxChunkSize: undefined,
// When a non-multipart upload or a chunked multipart upload has been
// aborted, this option can be used to resume the upload by setting
// it to the size of the already uploaded bytes. This option is most
// useful when modifying the options object inside of the "add" or
// "send" callbacks, as the options are cloned for each file upload.
uploadedBytes: undefined,
// By default, failed (abort or error) file uploads are removed from the
// global progress calculation. Set the following option to false to
// prevent recalculating the global progress data:
recalculateProgress: true,
// Additional form data to be sent along with the file uploads can be set
// using this option, which accepts an array of objects with name and
// value properties, a function returning such an array, a FormData
// object (for XHR file uploads), or a simple object.
// The form of the first fileInput is given as parameter to the function:
formData: function (form) {
return form.serializeArray();
},
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// If the singleFileUploads option is enabled, this callback will be
// called once for each file in the selection for XHR file uplaods, else
// once for each file selection.
// The upload starts when the submit method is invoked on the data parameter.
// The data object contains a files property holding the added files
// and allows to override plugin options as well as define ajax settings.
// Listeners for this callback can also be bound the following way:
// .bind('fileuploadadd', func);
// data.submit() returns a Promise object and allows to attach additional
// handlers using jQuery's Deferred callbacks:
// data.submit().done(func).fail(func).always(func);
add: function (e, data) {
data.submit();
},
// Other callbacks:
// Callback for the start of each file upload request:
// send: function (e, data) {}, // .bind('fileuploadsend', func);
// Callback for successful uploads:
// done: function (e, data) {}, // .bind('fileuploaddone', func);
// Callback for failed (abort or error) uploads:
// fail: function (e, data) {}, // .bind('fileuploadfail', func);
// Callback for completed (success, abort or error) requests:
// always: function (e, data) {}, // .bind('fileuploadalways', func);
// Callback for upload progress events:
// progress: function (e, data) {}, // .bind('fileuploadprogress', func);
// Callback for global upload progress events:
// progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);
// Callback for uploads start, equivalent to the global ajaxStart event:
// start: function (e) {}, // .bind('fileuploadstart', func);
// Callback for uploads stop, equivalent to the global ajaxStop event:
// stop: function (e) {}, // .bind('fileuploadstop', func);
// Callback for change events of the fileInput collection:
// change: function (e, data) {}, // .bind('fileuploadchange', func);
// Callback for drop events of the dropZone collection:
// drop: function (e, data) {}, // .bind('fileuploaddrop', func);
// Callback for dragover events of the dropZone collection:
// dragover: function (e) {}, // .bind('fileuploaddragover', func);
// The plugin options are used as settings object for the ajax calls.
// The following are jQuery ajax settings required for the file uploads:
processData: false,
contentType: false,
cache: false
},
// A list of options that require a refresh after assigning a new value:
_refreshOptionsList: ['namespace', 'dropZone', 'fileInput'],
_isXHRUpload: function (options) {
var undef = 'undefined';
return !options.forceIframeTransport &&
typeof XMLHttpRequestUpload !== undef && typeof File !== undef &&
(!options.multipart || typeof FormData !== undef);
},
_getFormData: function (options) {
var formData;
if (typeof options.formData === 'function') {
return options.formData(options.form);
} else if ($.isArray(options.formData)) {
return options.formData;
} else if (options.formData) {
formData = [];
$.each(options.formData, function (name, value) {
formData.push({name: name, value: value});
});
return formData;
}
return [];
},
_getTotal: function (files) {
var total = 0;
$.each(files, function (index, file) {
total += file.size || 1;
});
return total;
},
_onProgress: function (e, data) {
if (e.lengthComputable) {
var total = data.total || this._getTotal(data.files),
loaded = parseInt(
e.loaded / e.total * (data.chunkSize || total),
10
) + (data.uploadedBytes || 0);
this._loaded += loaded - (data.loaded || data.uploadedBytes || 0);
data.lengthComputable = true;
data.loaded = loaded;
data.total = total;
// Trigger a custom progress event with a total data property set
// to the file size(s) of the current upload and a loaded data
// property calculated accordingly:
this._trigger('progress', e, data);
// Trigger a global progress event for all current file uploads,
// including ajax calls queued for sequential file uploads:
this._trigger('progressall', e, {
lengthComputable: true,
loaded: this._loaded,
total: this._total
});
}
},
_initProgressListener: function (options) {
var that = this,
xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
// Accesss to the native XHR object is required to add event listeners
// for the upload progress event:
if (xhr.upload && xhr.upload.addEventListener) {
xhr.upload.addEventListener('progress', function (e) {
that._onProgress(e, options);
}, false);
options.xhr = function () {
return xhr;
};
}
},
_initXHRData: function (options) {
var formData,
file = options.files[0];
if (!options.multipart || options.blob) {
// For non-multipart uploads and chunked uploads,
// file meta data is not part of the request body,
// so we transmit this data as part of the HTTP headers.
// For cross domain requests, these headers must be allowed
// via Access-Control-Allow-Headers or removed using
// the beforeSend callback:
options.headers = $.extend(options.headers, {
'X-File-Name': file.name,
'X-File-Type': file.type,
'X-File-Size': file.size
});
if (!options.blob) {
// Non-chunked non-multipart upload:
options.contentType = file.type;
options.data = file;
} else if (!options.multipart) {
// Chunked non-multipart upload:
options.contentType = 'application/octet-stream';
options.data = options.blob;
}
}
if (options.multipart) {
if (options.formData instanceof FormData) {
formData = options.formData;
} else {
formData = new FormData();
$.each(this._getFormData(options), function (index, field) {
formData.append(field.name, field.value);
});
}
if (options.blob) {
formData.append(options.paramName, options.blob);
} else {
$.each(options.files, function (index, file) {
// File objects are also Blob instances.
// This check allows the tests to run with
// dummy objects:
if (file instanceof Blob) {
formData.append(options.paramName, file);
}
});
}
options.data = formData;
}
// Blob reference is not needed anymore, free memory:
options.blob = null;
},
_initIframeSettings: function (options) {
// Setting the dataType to iframe enables the iframe transport:
options.dataType = 'iframe ' + (options.dataType || '');
// The iframe transport accepts a serialized array as form data:
options.formData = this._getFormData(options);
},
_initDataSettings: function (options) {
if (this._isXHRUpload(options)) {
if (!this._chunkedUpload(options, true)) {
if (!options.data) {
this._initXHRData(options);
}
this._initProgressListener(options);
}
} else {
this._initIframeSettings(options);
}
},
_initFormSettings: function (options) {
// Retrieve missing options from the input field and the
// associated form, if available:
if (!options.form || !options.form.length) {
options.form = $(options.fileInput.prop('form'));
}
if (!options.paramName) {
options.paramName = options.fileInput.prop('name') ||
'files[]';
}
if (!options.url) {
options.url = options.form.prop('action') || location.href;
}
// The HTTP request method must be "POST" or "PUT":
options.type = (options.type || options.form.prop('method') || '')
.toUpperCase();
if (options.type !== 'POST' && options.type !== 'PUT') {
options.type = 'POST';
}
},
_getAJAXSettings: function (data) {
var options = $.extend({}, this.options, data);
this._initFormSettings(options);
this._initDataSettings(options);
return options;
},
// Maps jqXHR callbacks to the equivalent
// methods of the given Promise object:
_enhancePromise: function (promise) {
promise.success = promise.done;
promise.error = promise.fail;
promise.complete = promise.always;
return promise;
},
// Creates and returns a Promise object enhanced with
// the jqXHR methods abort, success, error and complete:
_getXHRPromise: function (resolveOrReject, context) {
var dfd = $.Deferred(),
promise = dfd.promise();
context = context || this.options.context || promise;
if (resolveOrReject === true) {
dfd.resolveWith(context);
} else if (resolveOrReject === false) {
dfd.rejectWith(context);
}
promise.abort = dfd.promise;
return this._enhancePromise(promise);
},
// Uploads a file in multiple, sequential requests
// by splitting the file up in multiple blob chunks.
// If the second parameter is true, only tests if the file
// should be uploaded in chunks, but does not invoke any
// upload requests:
_chunkedUpload: function (options, testOnly) {
var that = this,
file = options.files[0],
fs = file.size,
ub = options.uploadedBytes = options.uploadedBytes || 0,
mcs = options.maxChunkSize || fs,
// Use the Blob methods with the slice implementation
// according to the W3C Blob API specification:
slice = file.webkitSlice || file.mozSlice || file.slice,
upload,
n,
jqXHR,
pipe;
if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
options.data) {
return false;
}
if (testOnly) {
return true;
}
if (ub >= fs) {
file.error = 'uploadedBytes';
return this._getXHRPromise(false);
}
// n is the number of blobs to upload,
// calculated via filesize, uploaded bytes and max chunk size:
n = Math.ceil((fs - ub) / mcs);
// The chunk upload method accepting the chunk number as parameter:
upload = function (i) {
if (!i) {
return that._getXHRPromise(true);
}
// Upload the blobs in sequential order:
return upload(i -= 1).pipe(function () {
// Clone the options object for each chunk upload:
var o = $.extend({}, options);
o.blob = slice.call(
file,
ub + i * mcs,
ub + (i + 1) * mcs
);
// Store the current chunk size, as the blob itself
// will be dereferenced after data processing:
o.chunkSize = o.blob.size;
// Process the upload data (the blob and potential form data):
that._initXHRData(o);
// Add progress listeners for this chunk upload:
that._initProgressListener(o);
jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context))
.done(function () {
// Create a progress event if upload is done and
// no progress event has been invoked for this chunk:
if (!o.loaded) {
that._onProgress($.Event('progress', {
lengthComputable: true,
loaded: o.chunkSize,
total: o.chunkSize
}), o);
}
options.uploadedBytes = o.uploadedBytes
+= o.chunkSize;
});
return jqXHR;
});
};
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = upload(n);
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
},
_beforeSend: function (e, data) {
if (this._active === 0) {
// the start callback is triggered when an upload starts
// and no other uploads are currently running,
// equivalent to the global ajaxStart event:
this._trigger('start');
}
this._active += 1;
// Initialize the global progress values:
this._loaded += data.uploadedBytes || 0;
this._total += this._getTotal(data.files);
},
_onDone: function (result, textStatus, jqXHR, options) {
if (!this._isXHRUpload(options)) {
// Create a progress event for each iframe load:
this._onProgress($.Event('progress', {
lengthComputable: true,
loaded: 1,
total: 1
}), options);
}
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('done', null, options);
},
_onFail: function (jqXHR, textStatus, errorThrown, options) {
options.jqXHR = jqXHR;
options.textStatus = textStatus;
options.errorThrown = errorThrown;
this._trigger('fail', null, options);
if (options.recalculateProgress) {
// Remove the failed (error or abort) file upload from
// the global progress calculation:
this._loaded -= options.loaded || options.uploadedBytes || 0;
this._total -= options.total || this._getTotal(options.files);
}
},
_onAlways: function (result, textStatus, jqXHR, options) {
this._active -= 1;
options.result = result;
options.textStatus = textStatus;
options.jqXHR = jqXHR;
this._trigger('always', null, options);
if (this._active === 0) {
// The stop callback is triggered when all uploads have
// been completed, equivalent to the global ajaxStop event:
this._trigger('stop');
// Reset the global progress values:
this._loaded = this._total = 0;
}
},
_onSend: function (e, data) {
var that = this,
jqXHR,
pipe,
options = that._getAJAXSettings(data),
send = function () {
jqXHR = ((that._trigger('send', e, options) !== false && (
that._chunkedUpload(options) ||
$.ajax(options)
)) || that._getXHRPromise(false, options.context)
).done(function (result, textStatus, jqXHR) {
that._onDone(result, textStatus, jqXHR, options);
}).fail(function (jqXHR, textStatus, errorThrown) {
that._onFail(jqXHR, textStatus, errorThrown, options);
}).always(function (result, textStatus, jqXHR) {
that._onAlways(result, textStatus, jqXHR, options);
});
return jqXHR;
};
this._beforeSend(e, options);
if (this.options.sequentialUploads) {
// Return the piped Promise object, enhanced with an abort method,
// which is delegated to the jqXHR object of the current upload,
// and jqXHR callbacks mapped to the equivalent Promise methods:
pipe = (this._sequence = this._sequence.pipe(send, send));
pipe.abort = function () {
return jqXHR.abort();
};
return this._enhancePromise(pipe);
}
return send();
},
_onAdd: function (e, data) {
var that = this,
result = true,
options = $.extend({}, this.options, data);
if (options.singleFileUploads && this._isXHRUpload(options)) {
$.each(data.files, function (index, file) {
var newData = $.extend({}, data, {files: [file]});
newData.submit = function () {
return that._onSend(e, newData);
};
return (result = that._trigger('add', e, newData));
});
return result;
} else if (data.files.length) {
data = $.extend({}, data);
data.submit = function () {
return that._onSend(e, data);
};
return this._trigger('add', e, data);
}
},
// File Normalization for Gecko 1.9.1 (Firefox 3.5) support:
_normalizeFile: function (index, file) {
if (file.name === undefined && file.size === undefined) {
file.name = file.fileName;
file.size = file.fileSize;
}
},
_replaceFileInput: function (input) {
var inputClone = input.clone(true);
$('<form></form>').append(inputClone)[0].reset();
// Detaching allows to insert the fileInput on another form
// without loosing the file input value:
input.after(inputClone).detach();
// Replace the original file input element in the fileInput
// collection with the clone, which has been copied including
// event handlers:
this.options.fileInput = this.options.fileInput.map(function (i, el) {
if (el === input[0]) {
return inputClone[0];
}
return el;
});
},
_onChange: function (e) {
var that = e.data.fileupload,
data = {
files: $.each($.makeArray(e.target.files), that._normalizeFile),
fileInput: $(e.target),
form: $(e.target.form)
};
if (!data.files.length) {
// If the files property is not available, the browser does not
// support the File API and we add a pseudo File object with
// the input value as name with path information removed:
data.files = [{name: e.target.value.replace(/^.*\\/, '')}];
}
// Store the form reference as jQuery data for other event handlers,
// as the form property is not available after replacing the file input:
if (data.form.length) {
data.fileInput.data('blueimp.fileupload.form', data.form);
} else {
data.form = data.fileInput.data('blueimp.fileupload.form');
}
if (that.options.replaceFileInput) {
that._replaceFileInput(data.fileInput);
}
if (that._trigger('change', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
},
_onDrop: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer,
data = {
files: $.each(
$.makeArray(dataTransfer && dataTransfer.files),
that._normalizeFile
)
};
if (that._trigger('drop', e, data) === false ||
that._onAdd(e, data) === false) {
return false;
}
e.preventDefault();
},
_onDragOver: function (e) {
var that = e.data.fileupload,
dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer;
if (that._trigger('dragover', e) === false) {
return false;
}
if (dataTransfer) {
dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy';
}
e.preventDefault();
},
_initEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.bind('dragover.' + ns, {fileupload: this}, this._onDragOver)
.bind('drop.' + ns, {fileupload: this}, this._onDrop);
this.options.fileInput
.bind('change.' + ns, {fileupload: this}, this._onChange);
},
_destroyEventHandlers: function () {
var ns = this.options.namespace || this.name;
this.options.dropZone
.unbind('dragover.' + ns, this._onDragOver)
.unbind('drop.' + ns, this._onDrop);
this.options.fileInput
.unbind('change.' + ns, this._onChange);
},
_beforeSetOption: function (key, value) {
this._destroyEventHandlers();
},
_afterSetOption: function (key, value) {
var options = this.options;
if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._initEventHandlers();
},
_setOption: function (key, value) {
var refresh = $.inArray(key, this._refreshOptionsList) !== -1;
if (refresh) {
this._beforeSetOption(key, value);
}
$.Widget.prototype._setOption.call(this, key, value);
if (refresh) {
this._afterSetOption(key, value);
}
},
_create: function () {
var options = this.options;
if (options.fileInput === undefined) {
options.fileInput = this.element.is('input:file') ?
this.element : this.element.find('input:file');
} else if (!options.fileInput) {
options.fileInput = $();
}
if (!options.dropZone) {
options.dropZone = $();
}
this._sequence = this._getXHRPromise(true);
this._active = this._loaded = this._total = 0;
this._initEventHandlers();
},
destroy: function () {
this._destroyEventHandlers();
$.Widget.prototype.destroy.call(this);
},
enable: function () {
$.Widget.prototype.enable.call(this);
this._initEventHandlers();
},
disable: function () {
this._destroyEventHandlers();
$.Widget.prototype.disable.call(this);
},
// This method is exposed to the widget API and allows adding files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('add', {files: filesList});
add: function (data) {
if (!data || this.options.disabled) {
return;
}
data.files = $.each($.makeArray(data.files), this._normalizeFile);
this._onAdd(null, data);
},
// This method is exposed to the widget API and allows sending files
// using the fileupload API. The data parameter accepts an object which
// must have a files property and can contain additional options:
// .fileupload('send', {files: filesList});
// The method returns a Promise object for the file upload call.
send: function (data) {
if (data && !this.options.disabled) {
data.files = $.each($.makeArray(data.files), this._normalizeFile);
if (data.files.length) {
return this._onSend(null, data);
}
}
return this._getXHRPromise(false, data && data.context);
}
});
}(jQuery)); | ilyakatz/cucumber-cinema | public/javascripts/jquery.fileupload.js | JavaScript | mit | 31,875 |
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosPint extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</g>;
} return <IconBase>
<path d="M368,170.085c0-21.022-0.973-88.554-19.308-125.013C344.244,36.228,336.25,32,316.999,32H195.001
c-19.25,0-27.246,4.197-31.693,13.041C144.973,81.5,144,149.25,144,170.272c0,98,32,100.353,32,180.853c0,39.5-16,71.402-16,99.402
c0,27,9,29.473,32,29.473h128c23,0,32-2.535,32-29.535c0-28-16-59.715-16-99.215C336,270.75,368,268.085,368,170.085z
M177.602,51.983c0.778-1.546,1.339-1.763,2.53-2.295c1.977-0.884,6.161-1.688,14.869-1.688h121.998
c8.708,0,12.893,0.803,14.869,1.687c1.19,0.532,1.752,0.872,2.53,2.418c8.029,15.967,13.601,42.611,16.105,75.896H161.496
C164.001,94.653,169.572,67.951,177.602,51.983z"></path>
</IconBase>;
}
};IosPint.defaultProps = {bare: false} | fbfeix/react-icons | src/icons/IosPint.js | JavaScript | mit | 1,517 |
/**
* Wheel, copyright (c) 2020 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const $ = require('../../program/commands');
const errors = require('../errors');
const err = require('../errors').errors;
const t = require('../tokenizer/tokenizer');
const Objct = require('../types/Objct').Objct;
const Var = require('../types/Var');
const CompileRecord = require('./CompileRecord').CompileRecord;
exports.CompileObjct = class extends CompileRecord {
getDataType() {
let token = this._token;
let objct = new Objct(null, this.getNamespacedRecordName(token.lexeme), false, this._compiler.getNamespace()).setToken(token);
objct.setCompiler(this._compiler);
return objct;
}
addLinterItem(token) {
this._linter && this._linter.addObject(this._token);
}
compileExtends(iterator, dataType) {
let token = iterator.skipWhiteSpace().peek();
if (token.lexeme === t.LEXEME_EXTENDS) {
iterator.next();
iterator.skipWhiteSpace();
token = iterator.next();
if (token.cls !== t.TOKEN_IDENTIFIER) {
throw errors.createError(err.IDENTIFIER_EXPECTED, token, 'Identifier expected.');
}
let superObjct = this._scope.findIdentifier(token.lexeme);
if (!superObjct) {
throw errors.createError(err.UNDEFINED_IDENTIFIER, token, 'Undefined identifier.');
}
if (!(superObjct instanceof Objct)) {
throw errors.createError(err.OBJECT_TYPE_EXPECTED, token, 'Object type expected.');
}
dataType.extend(superObjct, this._compiler);
}
}
compileMethodTable(objct, methodTable) {
let compiler = this._compiler;
let program = this._program;
let methods = compiler.getUseInfo().getUseObjct(objct.getName());
// Move the self pointer to the pointer register...
program.addCommand($.CMD_SET, $.T_NUM_G, $.REG_PTR, $.T_NUM_L, 0);
// Get the methods from the super objects...
let superObjct = objct.getParentScope();
while (superObjct instanceof Objct) {
let superMethods = compiler.getUseInfo().getUseObjct(superObjct.getName());
for (let i = 0; i < superMethods; i++) {
methodTable.push(program.getLength());
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
superObjct = superObjct.getParentScope();
}
// Create the virtual method table...
for (let i = 0; i < methods; i++) {
methodTable.push(program.getLength());
// The offset relative to the self pointer and the method offset will be set when the main procedure is found!
program.addCommand($.CMD_SET, $.T_NUM_P, 0, $.T_NUM_C, 0);
}
program.addCommand($.CMD_RET, $.T_NUM_C, 0, 0, 0);
}
compile(iterator) {
let objct = super.compile(iterator);
let compiler = this._compiler;
compiler.getUseInfo().setUseObjct(objct.getName());
if (compiler.getPass() === 0) {
return;
}
let program = this._program;
let codeUsed = program.getCodeUsed();
let methodTable = [];
program.setCodeUsed(true);
objct
.setConstructorCodeOffset(program.getLength())
.setMethodTable(methodTable);
this.compileMethodTable(objct, methodTable);
program.addCommand($.CMD_RET, 0, 0, 0, 0);
program.setCodeUsed(codeUsed);
}
};
| ArnoVanDerVegt/wheel | js/frontend/compiler/keyword/CompileObjct.js | JavaScript | mit | 3,710 |
const assert = require('assert');
const MockServer = require('../../../../lib/mockserver.js');
const CommandGlobals = require('../../../../lib/globals/commands.js');
const Nightwatch = require('../../../../lib/nightwatch.js');
describe('browser.getFirstElementChild', function(){
before(function(done) {
CommandGlobals.beforeEach.call(this, done);
});
after(function(done) {
CommandGlobals.afterEach.call(this, done);
});
it('.getFirstElementChild', function(done){
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
value: {
'ELEMENT': '1'
}
}
}, true);
this.client.api.getFirstElementChild('#weblogin', function callback(result){
assert.strictEqual(result.value.getId(), '1');
});
this.client.start(done);
});
it('.getFirstElementChild - no such element', function(done) {
MockServer.addMock({
url: '/wd/hub/session/1352110219202/elements',
method: 'POST',
postdata: {
using: 'css selector',
value: '#badDriver'
},
response: {
status: 0,
sessionId: '1352110219202',
value: [{
ELEMENT: '2'
}]
}
});
MockServer.addMock({
url: '/wd/hub/session/1352110219202/execute',
method: 'POST',
response: {
status: 0,
value: null
}
});
this.client.api.getFirstElementChild('#badDriver', function callback(result){
assert.strictEqual(result.value, null);
});
this.client.start(done);
});
it('.getFirstElementChild - webdriver protcol', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: {
'element-6066-11e4-a52e-4f735466cecf': 'f54dc0ef-c84f-424a-bad0-16fef6595a70'
}
}
}, true);
client.api.getFirstElementChild('#webdriver', function(result) {
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
}).getFirstElementChild('#webdriver', function callback(result){
assert.ok(result.value);
assert.strictEqual(result.value.getId(), 'f54dc0ef-c84f-424a-bad0-16fef6595a70');
});
client.start(done);
});
});
it('.getFirstElementChild - webdriver protcol no such element', function(done){
Nightwatch.initW3CClient({
silent: true,
output: false
}).then(client => {
MockServer.addMock({
url: '/session/13521-10219-202/execute/sync',
response: {
value: null
}
});
client.api.getFirstElementChild('#webdriver', function(result) {
assert.strictEqual(result.value, null);
});
client.start(done);
});
});
}); | nightwatchjs/nightwatch | test/src/api/commands/element/testGetFirstElementChild.js | JavaScript | mit | 3,229 |
version https://git-lfs.github.com/spec/v1
oid sha256:e63ec89c8bce1f67a79c0a8042e7ad0f2197f9bf615c88fd1ce36266c4050e1b
size 5126
| yogeshsaroya/new-cdnjs | ajax/libs/backbone.layoutmanager/0.7.0/backbone.layoutmanager.min.js | JavaScript | mit | 129 |
//-----------------------------------------
// Grunt configuration
//-----------------------------------------
module.exports = function(grunt) {
// Init config
grunt.initConfig({
// environment constant
ngconstant: {
options: {
space: ' ',
name: 'envConstant',
dest: 'public/js/envConstant.js'
},
dev: {
constants: {
ENV: {
appURI: 'http://localhost:3000/',
instagramClientId: 'yourDevClientId'
}
}
},
prod:{
constants: {
ENV: {
appURI: 'http://instalurker-andreavitali.rhcloud.com/',
instagramClientId: 'yourProdClientId'
}
}
}
},
// concat
concat: {
options: {
separator: ';' // useful for following uglify
},
app: {
src: 'public/js/**/*.js',
dest: 'public/instalurker.js'
},
vendor: {
src: ['public/vendor/jquery.min.js','public/vendor/angular.min.js','public/vendor/*.min.js'], // order is important!
dest: 'public/vendor.min.js'
}
},
// uglify (only app JS because vendor's are already minified)
uglify: {
options: {
mangle: false
},
app: {
src: 'public/instalurker.js',
dest: 'public/instalurker.min.js',
ext: '.min.js'
}
},
// CSS minification
cssmin: {
prod: {
files: {
'public/stylesheets/app.min.css' : ['public/stylesheets/app.css']
}
}
},
// Change index.html to use minified files
targethtml: {
prod: {
files: {
'public/index.html': 'public/index.html'
}
}
}
// SASS compilation made by IDE
});
// Load plugins
grunt.loadNpmTasks('grunt-ng-constant');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-targethtml');
// Dev task
grunt.registerTask('dev', ['ngconstant:dev']); // no
// Default (prod) task
grunt.registerTask('default', ['ngconstant:prod','concat:vendor','concat:app','uglify:app','cssmin','targethtml']);
}
| andreavitali/instalurker | gruntfile.js | JavaScript | mit | 2,712 |
/*!
* vue-i18n v9.0.0-beta.13
* (c) 2020 kazuya kawaguchi
* Released under the MIT License.
*/
import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue';
/**
* Original Utilities
* written by kazuya kawaguchi
*/
const inBrowser = typeof window !== 'undefined';
let mark;
let measure;
{
const perf = inBrowser && window.performance;
if (perf &&
perf.mark &&
perf.measure &&
perf.clearMarks &&
perf.clearMeasures) {
mark = (tag) => perf.mark(tag);
measure = (name, startTag, endTag) => {
perf.measure(name, startTag, endTag);
perf.clearMarks(startTag);
perf.clearMarks(endTag);
};
}
}
const RE_ARGS = /\{([0-9a-zA-Z]+)\}/g;
/* eslint-disable */
function format(message, ...args) {
if (args.length === 1 && isObject(args[0])) {
args = args[0];
}
if (!args || !args.hasOwnProperty) {
args = {};
}
return message.replace(RE_ARGS, (match, identifier) => {
return args.hasOwnProperty(identifier) ? args[identifier] : '';
});
}
const hasSymbol = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
/** @internal */
const makeSymbol = (name) => hasSymbol ? Symbol(name) : name;
/** @internal */
const generateFormatCacheKey = (locale, key, source) => friendlyJSONstringify({ l: locale, k: key, s: source });
/** @internal */
const friendlyJSONstringify = (json) => JSON.stringify(json)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/\u0027/g, '\\u0027');
const isNumber = (val) => typeof val === 'number' && isFinite(val);
const isDate = (val) => toTypeString(val) === '[object Date]';
const isRegExp = (val) => toTypeString(val) === '[object RegExp]';
const isEmptyObject = (val) => isPlainObject(val) && Object.keys(val).length === 0;
function warn(msg, err) {
if (typeof console !== 'undefined') {
const label = 'vue-i18n' ;
console.warn(`[${label}] ` + msg);
/* istanbul ignore if */
if (err) {
console.warn(err.stack);
}
}
}
let _globalThis;
const getGlobalThis = () => {
// prettier-ignore
return (_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {}));
};
function escapeHtml(rawText) {
return rawText
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
/* eslint-enable */
/**
* Useful Utilites By Evan you
* Modified by kazuya kawaguchi
* MIT License
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts
* https://github.com/vuejs/vue-next/blob/master/packages/shared/src/codeframe.ts
*/
const isArray = Array.isArray;
const isFunction = (val) => typeof val === 'function';
const isString = (val) => typeof val === 'string';
const isBoolean = (val) => typeof val === 'boolean';
const isObject = (val) => // eslint-disable-line
val !== null && typeof val === 'object';
const objectToString = Object.prototype.toString;
const toTypeString = (value) => objectToString.call(value);
const isPlainObject = (val) => toTypeString(val) === '[object Object]';
// for converting list and named values to displayed strings.
const toDisplayString = (val) => {
return val == null
? ''
: isArray(val) || (isPlainObject(val) && val.toString === objectToString)
? JSON.stringify(val, null, 2)
: String(val);
};
const RANGE = 2;
function generateCodeFrame(source, start = 0, end = source.length) {
const lines = source.split(/\r?\n/);
let count = 0;
const res = [];
for (let i = 0; i < lines.length; i++) {
count += lines[i].length + 1;
if (count >= start) {
for (let j = i - RANGE; j <= i + RANGE || end > count; j++) {
if (j < 0 || j >= lines.length)
continue;
const line = j + 1;
res.push(`${line}${' '.repeat(3 - String(line).length)}| ${lines[j]}`);
const lineLength = lines[j].length;
if (j === i) {
// push underline
const pad = start - (count - lineLength) + 1;
const length = Math.max(1, end > count ? lineLength - pad : end - start);
res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length));
}
else if (j > i) {
if (end > count) {
const length = Math.max(Math.min(end - count, lineLength), 1);
res.push(` | ` + '^'.repeat(length));
}
count += lineLength + 1;
}
}
break;
}
}
return res.join('\n');
}
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, basedir, module) {
return module = {
path: basedir,
exports: {},
require: function (path, base) {
return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
}
}, fn(module, module.exports), module.exports;
}
function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
var env = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.hook = exports.target = exports.isBrowser = void 0;
exports.isBrowser = typeof navigator !== 'undefined';
exports.target = exports.isBrowser
? window
: typeof commonjsGlobal !== 'undefined'
? commonjsGlobal
: {};
exports.hook = exports.target.__VUE_DEVTOOLS_GLOBAL_HOOK__;
});
var _const = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApiHookEvents = void 0;
var ApiHookEvents;
(function (ApiHookEvents) {
ApiHookEvents["SETUP_DEVTOOLS_PLUGIN"] = "devtools-plugin:setup";
})(ApiHookEvents = exports.ApiHookEvents || (exports.ApiHookEvents = {}));
});
var api = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var app = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var component = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var context = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
});
var hooks = createCommonjsModule(function (module, exports) {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Hooks = void 0;
var Hooks;
(function (Hooks) {
Hooks["TRANSFORM_CALL"] = "transformCall";
Hooks["GET_APP_RECORD_NAME"] = "getAppRecordName";
Hooks["GET_APP_ROOT_INSTANCE"] = "getAppRootInstance";
Hooks["REGISTER_APPLICATION"] = "registerApplication";
Hooks["WALK_COMPONENT_TREE"] = "walkComponentTree";
Hooks["WALK_COMPONENT_PARENTS"] = "walkComponentParents";
Hooks["INSPECT_COMPONENT"] = "inspectComponent";
Hooks["GET_COMPONENT_BOUNDS"] = "getComponentBounds";
Hooks["GET_COMPONENT_NAME"] = "getComponentName";
Hooks["GET_ELEMENT_COMPONENT"] = "getElementComponent";
Hooks["GET_INSPECTOR_TREE"] = "getInspectorTree";
Hooks["GET_INSPECTOR_STATE"] = "getInspectorState";
})(Hooks = exports.Hooks || (exports.Hooks = {}));
});
var api$1 = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(api, exports);
__exportStar(app, exports);
__exportStar(component, exports);
__exportStar(context, exports);
__exportStar(hooks, exports);
});
var lib = createCommonjsModule(function (module, exports) {
var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupDevtoolsPlugin = void 0;
__exportStar(api$1, exports);
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
if (env.hook) {
env.hook.emit(_const.ApiHookEvents.SETUP_DEVTOOLS_PLUGIN, pluginDescriptor, setupFn);
}
else {
const list = env.target.__VUE_DEVTOOLS_PLUGINS__ = env.target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor,
setupFn
});
}
}
exports.setupDevtoolsPlugin = setupDevtoolsPlugin;
});
const pathStateMachine = [];
pathStateMachine[0 /* BEFORE_PATH */] = {
["w" /* WORKSPACE */]: [0 /* BEFORE_PATH */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[1 /* IN_PATH */] = {
["w" /* WORKSPACE */]: [1 /* IN_PATH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */]
};
pathStateMachine[2 /* BEFORE_IDENT */] = {
["w" /* WORKSPACE */]: [2 /* BEFORE_IDENT */],
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */]
};
pathStateMachine[3 /* IN_IDENT */] = {
["i" /* IDENT */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["0" /* ZERO */]: [3 /* IN_IDENT */, 0 /* APPEND */],
["w" /* WORKSPACE */]: [1 /* IN_PATH */, 1 /* PUSH */],
["." /* DOT */]: [2 /* BEFORE_IDENT */, 1 /* PUSH */],
["[" /* LEFT_BRACKET */]: [4 /* IN_SUB_PATH */, 1 /* PUSH */],
["o" /* END_OF_FAIL */]: [7 /* AFTER_PATH */, 1 /* PUSH */]
};
pathStateMachine[4 /* IN_SUB_PATH */] = {
["'" /* SINGLE_QUOTE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */],
["\"" /* DOUBLE_QUOTE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */],
["[" /* LEFT_BRACKET */]: [
4 /* IN_SUB_PATH */,
2 /* INC_SUB_PATH_DEPTH */
],
["]" /* RIGHT_BRACKET */]: [1 /* IN_PATH */, 3 /* PUSH_SUB_PATH */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */]
};
pathStateMachine[5 /* IN_SINGLE_QUOTE */] = {
["'" /* SINGLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [5 /* IN_SINGLE_QUOTE */, 0 /* APPEND */]
};
pathStateMachine[6 /* IN_DOUBLE_QUOTE */] = {
["\"" /* DOUBLE_QUOTE */]: [4 /* IN_SUB_PATH */, 0 /* APPEND */],
["o" /* END_OF_FAIL */]: 8 /* ERROR */,
["l" /* ELSE */]: [6 /* IN_DOUBLE_QUOTE */, 0 /* APPEND */]
};
/**
* Check if an expression is a literal value.
*/
const literalValueRE = /^\s?(?:true|false|-?[\d.]+|'[^']*'|"[^"]*")\s?$/;
function isLiteral(exp) {
return literalValueRE.test(exp);
}
/**
* Strip quotes from a string
*/
function stripQuotes(str) {
const a = str.charCodeAt(0);
const b = str.charCodeAt(str.length - 1);
return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str;
}
/**
* Determine the type of a character in a keypath.
*/
function getPathCharType(ch) {
if (ch === undefined || ch === null) {
return "o" /* END_OF_FAIL */;
}
const code = ch.charCodeAt(0);
switch (code) {
case 0x5b: // [
case 0x5d: // ]
case 0x2e: // .
case 0x22: // "
case 0x27: // '
return ch;
case 0x5f: // _
case 0x24: // $
case 0x2d: // -
return "i" /* IDENT */;
case 0x09: // Tab (HT)
case 0x0a: // Newline (LF)
case 0x0d: // Return (CR)
case 0xa0: // No-break space (NBSP)
case 0xfeff: // Byte Order Mark (BOM)
case 0x2028: // Line Separator (LS)
case 0x2029: // Paragraph Separator (PS)
return "w" /* WORKSPACE */;
}
return "i" /* IDENT */;
}
/**
* Format a subPath, return its plain form if it is
* a literal string or number. Otherwise prepend the
* dynamic indicator (*).
*/
function formatSubPath(path) {
const trimmed = path.trim();
// invalid leading 0
if (path.charAt(0) === '0' && isNaN(parseInt(path))) {
return false;
}
return isLiteral(trimmed)
? stripQuotes(trimmed)
: "*" /* ASTARISK */ + trimmed;
}
/**
* Parse a string path into an array of segments
*/
function parse(path) {
const keys = [];
let index = -1;
let mode = 0 /* BEFORE_PATH */;
let subPathDepth = 0;
let c;
let key; // eslint-disable-line
let newChar;
let type;
let transition;
let action;
let typeMap;
const actions = [];
actions[0 /* APPEND */] = () => {
if (key === undefined) {
key = newChar;
}
else {
key += newChar;
}
};
actions[1 /* PUSH */] = () => {
if (key !== undefined) {
keys.push(key);
key = undefined;
}
};
actions[2 /* INC_SUB_PATH_DEPTH */] = () => {
actions[0 /* APPEND */]();
subPathDepth++;
};
actions[3 /* PUSH_SUB_PATH */] = () => {
if (subPathDepth > 0) {
subPathDepth--;
mode = 4 /* IN_SUB_PATH */;
actions[0 /* APPEND */]();
}
else {
subPathDepth = 0;
if (key === undefined) {
return false;
}
key = formatSubPath(key);
if (key === false) {
return false;
}
else {
actions[1 /* PUSH */]();
}
}
};
function maybeUnescapeQuote() {
const nextChar = path[index + 1];
if ((mode === 5 /* IN_SINGLE_QUOTE */ &&
nextChar === "'" /* SINGLE_QUOTE */) ||
(mode === 6 /* IN_DOUBLE_QUOTE */ &&
nextChar === "\"" /* DOUBLE_QUOTE */)) {
index++;
newChar = '\\' + nextChar;
actions[0 /* APPEND */]();
return true;
}
}
while (mode !== null) {
index++;
c = path[index];
if (c === '\\' && maybeUnescapeQuote()) {
continue;
}
type = getPathCharType(c);
typeMap = pathStateMachine[mode];
transition = typeMap[type] || typeMap["l" /* ELSE */] || 8 /* ERROR */;
// check parse error
if (transition === 8 /* ERROR */) {
return;
}
mode = transition[0];
if (transition[1] !== undefined) {
action = actions[transition[1]];
if (action) {
newChar = c;
if (action() === false) {
return;
}
}
}
// check parse finish
if (mode === 7 /* AFTER_PATH */) {
return keys;
}
}
}
// path token cache
const cache = new Map();
function resolveValue(obj, path) {
// check object
if (!isObject(obj)) {
return null;
}
// parse path
let hit = cache.get(path);
if (!hit) {
hit = parse(path);
if (hit) {
cache.set(path, hit);
}
}
// check hit
if (!hit) {
return null;
}
// resolve path value
const len = hit.length;
let last = obj;
let i = 0;
while (i < len) {
const val = last[hit[i]];
if (val === undefined) {
return null;
}
last = val;
i++;
}
return last;
}
const DEFAULT_MODIFIER = (str) => str;
const DEFAULT_MESSAGE = (ctx) => ''; // eslint-disable-line
const DEFAULT_MESSAGE_DATA_TYPE = 'text';
const DEFAULT_NORMALIZE = (values) => values.length === 0 ? '' : values.join('');
const DEFAULT_INTERPOLATE = toDisplayString;
function pluralDefault(choice, choicesLength) {
choice = Math.abs(choice);
if (choicesLength === 2) {
// prettier-ignore
return choice
? choice > 1
? 1
: 0
: 1;
}
return choice ? Math.min(choice, 2) : 0;
}
function getPluralIndex(options) {
// prettier-ignore
const index = isNumber(options.pluralIndex)
? options.pluralIndex
: -1;
// prettier-ignore
return options.named && (isNumber(options.named.count) || isNumber(options.named.n))
? isNumber(options.named.count)
? options.named.count
: isNumber(options.named.n)
? options.named.n
: index
: index;
}
function normalizeNamed(pluralIndex, props) {
if (!props.count) {
props.count = pluralIndex;
}
if (!props.n) {
props.n = pluralIndex;
}
}
function createMessageContext(options = {}) {
const locale = options.locale;
const pluralIndex = getPluralIndex(options);
const pluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? options.pluralRules[locale]
: pluralDefault;
const orgPluralRule = isObject(options.pluralRules) &&
isString(locale) &&
isFunction(options.pluralRules[locale])
? pluralDefault
: undefined;
const plural = (messages) => messages[pluralRule(pluralIndex, messages.length, orgPluralRule)];
const _list = options.list || [];
const list = (index) => _list[index];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _named = options.named || {};
isNumber(options.pluralIndex) && normalizeNamed(pluralIndex, _named);
const named = (key) => _named[key];
// TODO: need to design resolve message function?
function message(key) {
// prettier-ignore
const msg = isFunction(options.messages)
? options.messages(key)
: isObject(options.messages)
? options.messages[key]
: false;
return !msg
? options.parent
? options.parent.message(key) // resolve from parent messages
: DEFAULT_MESSAGE
: msg;
}
const _modifier = (name) => options.modifiers
? options.modifiers[name]
: DEFAULT_MODIFIER;
const normalize = isPlainObject(options.processor) && isFunction(options.processor.normalize)
? options.processor.normalize
: DEFAULT_NORMALIZE;
const interpolate = isPlainObject(options.processor) &&
isFunction(options.processor.interpolate)
? options.processor.interpolate
: DEFAULT_INTERPOLATE;
const type = isPlainObject(options.processor) && isString(options.processor.type)
? options.processor.type
: DEFAULT_MESSAGE_DATA_TYPE;
const ctx = {
["list" /* LIST */]: list,
["named" /* NAMED */]: named,
["plural" /* PLURAL */]: plural,
["linked" /* LINKED */]: (key, modifier) => {
// TODO: should check `key`
const msg = message(key)(ctx);
return isString(modifier) ? _modifier(modifier)(msg) : msg;
},
["message" /* MESSAGE */]: message,
["type" /* TYPE */]: type,
["interpolate" /* INTERPOLATE */]: interpolate,
["normalize" /* NORMALIZE */]: normalize
};
return ctx;
}
/** @internal */
const errorMessages = {
// tokenizer error messages
[0 /* EXPECTED_TOKEN */]: `Expected token: '{0}'`,
[1 /* INVALID_TOKEN_IN_PLACEHOLDER */]: `Invalid token in placeholder: '{0}'`,
[2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */]: `Unterminated single quote in placeholder`,
[3 /* UNKNOWN_ESCAPE_SEQUENCE */]: `Unknown escape sequence: \\{0}`,
[4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */]: `Invalid unicode escape sequence: {0}`,
[5 /* UNBALANCED_CLOSING_BRACE */]: `Unbalanced closing brace`,
[6 /* UNTERMINATED_CLOSING_BRACE */]: `Unterminated closing brace`,
[7 /* EMPTY_PLACEHOLDER */]: `Empty placeholder`,
[8 /* NOT_ALLOW_NEST_PLACEHOLDER */]: `Not allowed nest placeholder`,
[9 /* INVALID_LINKED_FORMAT */]: `Invalid linked format`,
// parser error messages
[10 /* MUST_HAVE_MESSAGES_IN_PLURAL */]: `Plural must have messages`,
[11 /* UNEXPECTED_LEXICAL_ANALYSIS */]: `Unexpected lexical analysis in token: '{0}'`
};
/** @internal */
function createCompileError(code, loc, optinos = {}) {
const { domain, messages, args } = optinos;
const msg = format((messages || errorMessages)[code] || '', ...(args || []))
;
const error = new SyntaxError(String(msg));
error.code = code;
if (loc) {
error.location = loc;
}
error.domain = domain;
return error;
}
/** @internal */
function defaultOnError(error) {
throw error;
}
function createPosition(line, column, offset) {
return { line, column, offset };
}
function createLocation(start, end, source) {
const loc = { start, end };
if (source != null) {
loc.source = source;
}
return loc;
}
const CHAR_SP = ' ';
const CHAR_CR = '\r';
const CHAR_LF = '\n';
const CHAR_LS = String.fromCharCode(0x2028);
const CHAR_PS = String.fromCharCode(0x2029);
function createScanner(str) {
const _buf = str;
let _index = 0;
let _line = 1;
let _column = 1;
let _peekOffset = 0;
const isCRLF = (index) => _buf[index] === CHAR_CR && _buf[index + 1] === CHAR_LF;
const isLF = (index) => _buf[index] === CHAR_LF;
const isPS = (index) => _buf[index] === CHAR_PS;
const isLS = (index) => _buf[index] === CHAR_LS;
const isLineEnd = (index) => isCRLF(index) || isLF(index) || isPS(index) || isLS(index);
const index = () => _index;
const line = () => _line;
const column = () => _column;
const peekOffset = () => _peekOffset;
const charAt = (offset) => isCRLF(offset) || isPS(offset) || isLS(offset) ? CHAR_LF : _buf[offset];
const currentChar = () => charAt(_index);
const currentPeek = () => charAt(_index + _peekOffset);
function next() {
_peekOffset = 0;
if (isLineEnd(_index)) {
_line++;
_column = 0;
}
if (isCRLF(_index)) {
_index++;
}
_index++;
_column++;
return _buf[_index];
}
function peek() {
if (isCRLF(_index + _peekOffset)) {
_peekOffset++;
}
_peekOffset++;
return _buf[_index + _peekOffset];
}
function reset() {
_index = 0;
_line = 1;
_column = 1;
_peekOffset = 0;
}
function resetPeek(offset = 0) {
_peekOffset = offset;
}
function skipToPeek() {
const target = _index + _peekOffset;
// eslint-disable-next-line no-unmodified-loop-condition
while (target !== _index) {
next();
}
_peekOffset = 0;
}
return {
index,
line,
column,
peekOffset,
charAt,
currentChar,
currentPeek,
next,
peek,
reset,
resetPeek,
skipToPeek
};
}
const EOF = undefined;
const LITERAL_DELIMITER = "'";
const ERROR_DOMAIN = 'tokenizer';
function createTokenizer(source, options = {}) {
const location = !options.location;
const _scnr = createScanner(source);
const currentOffset = () => _scnr.index();
const currentPosition = () => createPosition(_scnr.line(), _scnr.column(), _scnr.index());
const _initLoc = currentPosition();
const _initOffset = currentOffset();
const _context = {
currentType: 14 /* EOF */,
offset: _initOffset,
startLoc: _initLoc,
endLoc: _initLoc,
lastType: 14 /* EOF */,
lastOffset: _initOffset,
lastStartLoc: _initLoc,
lastEndLoc: _initLoc,
braceNest: 0,
inLinked: false,
text: ''
};
const context = () => _context;
const { onError } = options;
function emitError(code, pos, offset, ...args) {
const ctx = context();
pos.column += offset;
pos.offset += offset;
if (onError) {
const loc = createLocation(ctx.startLoc, pos);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN,
args
});
onError(err);
}
}
function getToken(context, type, value) {
context.endLoc = currentPosition();
context.currentType = type;
const token = { type };
if (location) {
token.loc = createLocation(context.startLoc, context.endLoc);
}
if (value != null) {
token.value = value;
}
return token;
}
const getEndToken = (context) => getToken(context, 14 /* EOF */);
function eat(scnr, ch) {
if (scnr.currentChar() === ch) {
scnr.next();
return ch;
}
else {
emitError(0 /* EXPECTED_TOKEN */, currentPosition(), 0, ch);
return '';
}
}
function peekSpaces(scnr) {
let buf = '';
while (scnr.currentPeek() === CHAR_SP || scnr.currentPeek() === CHAR_LF) {
buf += scnr.currentPeek();
scnr.peek();
}
return buf;
}
function skipSpaces(scnr) {
const buf = peekSpaces(scnr);
scnr.skipToPeek();
return buf;
}
function isIdentifierStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90)); // A-Z
}
function isNumberStart(ch) {
if (ch === EOF) {
return false;
}
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
}
function isNamedIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isListIdentifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ch = scnr.currentPeek() === '-' ? scnr.peek() : scnr.currentPeek();
const ret = isNumberStart(ch);
scnr.resetPeek();
return ret;
}
function isLiteralStart(scnr, context) {
const { currentType } = context;
if (currentType !== 2 /* BraceLeft */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === LITERAL_DELIMITER;
scnr.resetPeek();
return ret;
}
function isLinkedDotStart(scnr, context) {
const { currentType } = context;
if (currentType !== 8 /* LinkedAlias */) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === "." /* LinkedDot */;
scnr.resetPeek();
return ret;
}
function isLinkedModifierStart(scnr, context) {
const { currentType } = context;
if (currentType !== 9 /* LinkedDot */) {
return false;
}
peekSpaces(scnr);
const ret = isIdentifierStart(scnr.currentPeek());
scnr.resetPeek();
return ret;
}
function isLinkedDelimiterStart(scnr, context) {
const { currentType } = context;
if (!(currentType === 8 /* LinkedAlias */ ||
currentType === 12 /* LinkedModifier */)) {
return false;
}
peekSpaces(scnr);
const ret = scnr.currentPeek() === ":" /* LinkedDelimiter */;
scnr.resetPeek();
return ret;
}
function isLinkedReferStart(scnr, context) {
const { currentType } = context;
if (currentType !== 10 /* LinkedDelimiter */) {
return false;
}
const fn = () => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return isIdentifierStart(scnr.peek());
}
else if (ch === "@" /* LinkedAlias */ ||
ch === "%" /* Modulo */ ||
ch === "|" /* Pipe */ ||
ch === ":" /* LinkedDelimiter */ ||
ch === "." /* LinkedDot */ ||
ch === CHAR_SP ||
!ch) {
return false;
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn();
}
else {
// other charactors
return isIdentifierStart(ch);
}
};
const ret = fn();
scnr.resetPeek();
return ret;
}
function isPluralStart(scnr) {
peekSpaces(scnr);
const ret = scnr.currentPeek() === "|" /* Pipe */;
scnr.resetPeek();
return ret;
}
function isTextStart(scnr, reset = true) {
const fn = (hasSpace = false, prev = '', detectModulo = false) => {
const ch = scnr.currentPeek();
if (ch === "{" /* BraceLeft */) {
return prev === "%" /* Modulo */ ? false : hasSpace;
}
else if (ch === "@" /* LinkedAlias */ || !ch) {
return prev === "%" /* Modulo */ ? true : hasSpace;
}
else if (ch === "%" /* Modulo */) {
scnr.peek();
return fn(hasSpace, "%" /* Modulo */, true);
}
else if (ch === "|" /* Pipe */) {
return prev === "%" /* Modulo */ || detectModulo
? true
: !(prev === CHAR_SP || prev === CHAR_LF);
}
else if (ch === CHAR_SP) {
scnr.peek();
return fn(true, CHAR_SP, detectModulo);
}
else if (ch === CHAR_LF) {
scnr.peek();
return fn(true, CHAR_LF, detectModulo);
}
else {
return true;
}
};
const ret = fn();
reset && scnr.resetPeek();
return ret;
}
function takeChar(scnr, fn) {
const ch = scnr.currentChar();
if (ch === EOF) {
return EOF;
}
if (fn(ch)) {
scnr.next();
return ch;
}
return null;
}
function takeIdentifierChar(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 97 && cc <= 122) || // a-z
(cc >= 65 && cc <= 90) || // A-Z
(cc >= 48 && cc <= 57) || // 0-9
cc === 95 ||
cc === 36); // _ $
};
return takeChar(scnr, closure);
}
function takeDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return cc >= 48 && cc <= 57; // 0-9
};
return takeChar(scnr, closure);
}
function takeHexDigit(scnr) {
const closure = (ch) => {
const cc = ch.charCodeAt(0);
return ((cc >= 48 && cc <= 57) || // 0-9
(cc >= 65 && cc <= 70) || // A-F
(cc >= 97 && cc <= 102)); // a-f
};
return takeChar(scnr, closure);
}
function getDigits(scnr) {
let ch = '';
let num = '';
while ((ch = takeDigit(scnr))) {
num += ch;
}
return num;
}
function readText(scnr) {
const fn = (buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "}" /* BraceRight */ ||
ch === "@" /* LinkedAlias */ ||
!ch) {
return buf;
}
else if (ch === "%" /* Modulo */) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else {
return buf;
}
}
else if (ch === "|" /* Pipe */) {
return buf;
}
else if (ch === CHAR_SP || ch === CHAR_LF) {
if (isTextStart(scnr)) {
buf += ch;
scnr.next();
return fn(buf);
}
else if (isPluralStart(scnr)) {
return buf;
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
}
else {
buf += ch;
scnr.next();
return fn(buf);
}
};
return fn('');
}
function readNamedIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return name;
}
function readListIdentifier(scnr) {
skipSpaces(scnr);
let value = '';
if (scnr.currentChar() === '-') {
scnr.next();
value += `-${getDigits(scnr)}`;
}
else {
value += getDigits(scnr);
}
if (scnr.currentChar() === EOF) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
return value;
}
function readLiteral(scnr) {
skipSpaces(scnr);
eat(scnr, `\'`);
let ch = '';
let literal = '';
const fn = (x) => x !== LITERAL_DELIMITER && x !== CHAR_LF;
while ((ch = takeChar(scnr, fn))) {
if (ch === '\\') {
literal += readEscapeSequence(scnr);
}
else {
literal += ch;
}
}
const current = scnr.currentChar();
if (current === CHAR_LF || current === EOF) {
emitError(2 /* UNTERMINATED_SINGLE_QUOTE_IN_PLACEHOLDER */, currentPosition(), 0);
// TODO: Is it correct really?
if (current === CHAR_LF) {
scnr.next();
eat(scnr, `\'`);
}
return literal;
}
eat(scnr, `\'`);
return literal;
}
function readEscapeSequence(scnr) {
const ch = scnr.currentChar();
switch (ch) {
case '\\':
case `\'`:
scnr.next();
return `\\${ch}`;
case 'u':
return readUnicodeEscapeSequence(scnr, ch, 4);
case 'U':
return readUnicodeEscapeSequence(scnr, ch, 6);
default:
emitError(3 /* UNKNOWN_ESCAPE_SEQUENCE */, currentPosition(), 0, ch);
return '';
}
}
function readUnicodeEscapeSequence(scnr, unicode, digits) {
eat(scnr, unicode);
let sequence = '';
for (let i = 0; i < digits; i++) {
const ch = takeHexDigit(scnr);
if (!ch) {
emitError(4 /* INVALID_UNICODE_ESCAPE_SEQUENCE */, currentPosition(), 0, `\\${unicode}${sequence}${scnr.currentChar()}`);
break;
}
sequence += ch;
}
return `\\${unicode}${sequence}`;
}
function readInvalidIdentifier(scnr) {
skipSpaces(scnr);
let ch = '';
let identifiers = '';
const closure = (ch) => ch !== "{" /* BraceLeft */ &&
ch !== "}" /* BraceRight */ &&
ch !== CHAR_SP &&
ch !== CHAR_LF;
while ((ch = takeChar(scnr, closure))) {
identifiers += ch;
}
return identifiers;
}
function readLinkedModifier(scnr) {
let ch = '';
let name = '';
while ((ch = takeIdentifierChar(scnr))) {
name += ch;
}
return name;
}
function readLinkedRefer(scnr) {
const fn = (detect = false, buf) => {
const ch = scnr.currentChar();
if (ch === "{" /* BraceLeft */ ||
ch === "%" /* Modulo */ ||
ch === "@" /* LinkedAlias */ ||
ch === "|" /* Pipe */ ||
!ch) {
return buf;
}
else if (ch === CHAR_SP) {
return buf;
}
else if (ch === CHAR_LF) {
buf += ch;
scnr.next();
return fn(detect, buf);
}
else {
buf += ch;
scnr.next();
return fn(true, buf);
}
};
return fn(false, '');
}
function readPlural(scnr) {
skipSpaces(scnr);
const plural = eat(scnr, "|" /* Pipe */);
skipSpaces(scnr);
return plural;
}
// TODO: We need refactoring of token parsing ...
function readTokenInPlaceholder(scnr, context) {
let token = null;
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
if (context.braceNest >= 1) {
emitError(8 /* NOT_ALLOW_NEST_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 2 /* BraceLeft */, "{" /* BraceLeft */);
skipSpaces(scnr);
context.braceNest++;
return token;
case "}" /* BraceRight */:
if (context.braceNest > 0 &&
context.currentType === 2 /* BraceLeft */) {
emitError(7 /* EMPTY_PLACEHOLDER */, currentPosition(), 0);
}
scnr.next();
token = getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
context.braceNest--;
context.braceNest > 0 && skipSpaces(scnr);
if (context.inLinked && context.braceNest === 0) {
context.inLinked = false;
}
return token;
case "@" /* LinkedAlias */:
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = readTokenInLinked(scnr, context) || getEndToken(context);
context.braceNest = 0;
return token;
default:
let validNamedIdentifier = true;
let validListIdentifier = true;
let validLeteral = true;
if (isPluralStart(scnr)) {
if (context.braceNest > 0) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
}
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (context.braceNest > 0 &&
(context.currentType === 5 /* Named */ ||
context.currentType === 6 /* List */ ||
context.currentType === 7 /* Literal */)) {
emitError(6 /* UNTERMINATED_CLOSING_BRACE */, currentPosition(), 0);
context.braceNest = 0;
return readToken(scnr, context);
}
if ((validNamedIdentifier = isNamedIdentifierStart(scnr, context))) {
token = getToken(context, 5 /* Named */, readNamedIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validListIdentifier = isListIdentifierStart(scnr, context))) {
token = getToken(context, 6 /* List */, readListIdentifier(scnr));
skipSpaces(scnr);
return token;
}
if ((validLeteral = isLiteralStart(scnr, context))) {
token = getToken(context, 7 /* Literal */, readLiteral(scnr));
skipSpaces(scnr);
return token;
}
if (!validNamedIdentifier && !validListIdentifier && !validLeteral) {
// TODO: we should be re-designed invalid cases, when we will extend message syntax near the future ...
token = getToken(context, 13 /* InvalidPlace */, readInvalidIdentifier(scnr));
emitError(1 /* INVALID_TOKEN_IN_PLACEHOLDER */, currentPosition(), 0, token.value);
skipSpaces(scnr);
return token;
}
break;
}
return token;
}
// TODO: We need refactoring of token parsing ...
function readTokenInLinked(scnr, context) {
const { currentType } = context;
let token = null;
const ch = scnr.currentChar();
if ((currentType === 8 /* LinkedAlias */ ||
currentType === 9 /* LinkedDot */ ||
currentType === 12 /* LinkedModifier */ ||
currentType === 10 /* LinkedDelimiter */) &&
(ch === CHAR_LF || ch === CHAR_SP)) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
switch (ch) {
case "@" /* LinkedAlias */:
scnr.next();
token = getToken(context, 8 /* LinkedAlias */, "@" /* LinkedAlias */);
context.inLinked = true;
return token;
case "." /* LinkedDot */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 9 /* LinkedDot */, "." /* LinkedDot */);
case ":" /* LinkedDelimiter */:
skipSpaces(scnr);
scnr.next();
return getToken(context, 10 /* LinkedDelimiter */, ":" /* LinkedDelimiter */);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isLinkedDotStart(scnr, context) ||
isLinkedDelimiterStart(scnr, context)) {
skipSpaces(scnr);
return readTokenInLinked(scnr, context);
}
if (isLinkedModifierStart(scnr, context)) {
skipSpaces(scnr);
return getToken(context, 12 /* LinkedModifier */, readLinkedModifier(scnr));
}
if (isLinkedReferStart(scnr, context)) {
skipSpaces(scnr);
if (ch === "{" /* BraceLeft */) {
// scan the placeholder
return readTokenInPlaceholder(scnr, context) || token;
}
else {
return getToken(context, 11 /* LinkedKey */, readLinkedRefer(scnr));
}
}
if (currentType === 8 /* LinkedAlias */) {
emitError(9 /* INVALID_LINKED_FORMAT */, currentPosition(), 0);
}
context.braceNest = 0;
context.inLinked = false;
return readToken(scnr, context);
}
}
// TODO: We need refactoring of token parsing ...
function readToken(scnr, context) {
let token = { type: 14 /* EOF */ };
if (context.braceNest > 0) {
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
}
if (context.inLinked) {
return readTokenInLinked(scnr, context) || getEndToken(context);
}
const ch = scnr.currentChar();
switch (ch) {
case "{" /* BraceLeft */:
return readTokenInPlaceholder(scnr, context) || getEndToken(context);
case "}" /* BraceRight */:
emitError(5 /* UNBALANCED_CLOSING_BRACE */, currentPosition(), 0);
scnr.next();
return getToken(context, 3 /* BraceRight */, "}" /* BraceRight */);
case "@" /* LinkedAlias */:
return readTokenInLinked(scnr, context) || getEndToken(context);
default:
if (isPluralStart(scnr)) {
token = getToken(context, 1 /* Pipe */, readPlural(scnr));
// reset
context.braceNest = 0;
context.inLinked = false;
return token;
}
if (isTextStart(scnr)) {
return getToken(context, 0 /* Text */, readText(scnr));
}
if (ch === "%" /* Modulo */) {
scnr.next();
return getToken(context, 4 /* Modulo */, "%" /* Modulo */);
}
break;
}
return token;
}
function nextToken() {
const { currentType, offset, startLoc, endLoc } = _context;
_context.lastType = currentType;
_context.lastOffset = offset;
_context.lastStartLoc = startLoc;
_context.lastEndLoc = endLoc;
_context.offset = currentOffset();
_context.startLoc = currentPosition();
if (_scnr.currentChar() === EOF) {
return getToken(_context, 14 /* EOF */);
}
return readToken(_scnr, _context);
}
return {
nextToken,
currentOffset,
currentPosition,
context
};
}
const ERROR_DOMAIN$1 = 'parser';
// Backslash backslash, backslash quote, uHHHH, UHHHHHH.
const KNOWN_ESCAPES = /(?:\\\\|\\'|\\u([0-9a-fA-F]{4})|\\U([0-9a-fA-F]{6}))/g;
function fromEscapeSequence(match, codePoint4, codePoint6) {
switch (match) {
case `\\\\`:
return `\\`;
case `\\\'`:
return `\'`;
default: {
const codePoint = parseInt(codePoint4 || codePoint6, 16);
if (codePoint <= 0xd7ff || codePoint >= 0xe000) {
return String.fromCodePoint(codePoint);
}
// invalid ...
// Replace them with U+FFFD REPLACEMENT CHARACTER.
return '�';
}
}
}
function createParser(options = {}) {
const location = !options.location;
const { onError } = options;
function emitError(tokenzer, code, start, offset, ...args) {
const end = tokenzer.currentPosition();
end.offset += offset;
end.column += offset;
if (onError) {
const loc = createLocation(start, end);
const err = createCompileError(code, loc, {
domain: ERROR_DOMAIN$1,
args
});
onError(err);
}
}
function startNode(type, offset, loc) {
const node = {
type,
start: offset,
end: offset
};
if (location) {
node.loc = { start: loc, end: loc };
}
return node;
}
function endNode(node, offset, pos, type) {
node.end = offset;
if (type) {
node.type = type;
}
if (location && node.loc) {
node.loc.end = pos;
}
}
function parseText(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(3 /* Text */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseList(tokenizer, index) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(5 /* List */, offset, loc);
node.index = parseInt(index, 10);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseNamed(tokenizer, key) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(4 /* Named */, offset, loc);
node.key = key;
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLiteral(tokenizer, value) {
const context = tokenizer.context();
const { lastOffset: offset, lastStartLoc: loc } = context; // get brace left loc
const node = startNode(9 /* Literal */, offset, loc);
node.value = value.replace(KNOWN_ESCAPES, fromEscapeSequence);
tokenizer.nextToken(); // skip brach right
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedModifier(tokenizer) {
const token = tokenizer.nextToken();
const context = tokenizer.context();
// check token
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
const { lastOffset: offset, lastStartLoc: loc } = context; // get linked dot loc
const node = startNode(8 /* LinkedModifier */, offset, loc);
node.value = token.value || '';
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinkedKey(tokenizer, value) {
const context = tokenizer.context();
const node = startNode(7 /* LinkedKey */, context.offset, context.startLoc);
node.value = value;
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseLinked(tokenizer) {
const context = tokenizer.context();
const linkedNode = startNode(6 /* Linked */, context.offset, context.startLoc);
let token = tokenizer.nextToken();
if (token.type === 9 /* LinkedDot */) {
linkedNode.modifier = parseLinkedModifier(tokenizer);
token = tokenizer.nextToken();
}
// asset check token
if (token.type !== 10 /* LinkedDelimiter */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
token = tokenizer.nextToken();
// skip brace left
if (token.type === 2 /* BraceLeft */) {
token = tokenizer.nextToken();
}
switch (token.type) {
case 11 /* LinkedKey */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLinkedKey(tokenizer, token.value || '');
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseNamed(tokenizer, token.value || '');
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseList(tokenizer, token.value || '');
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
linkedNode.key = parseLiteral(tokenizer, token.value || '');
break;
}
endNode(linkedNode, tokenizer.currentOffset(), tokenizer.currentPosition());
return linkedNode;
}
function parseMessage(tokenizer) {
const context = tokenizer.context();
const startOffset = context.currentType === 1 /* Pipe */
? tokenizer.currentOffset()
: context.offset;
const startLoc = context.currentType === 1 /* Pipe */
? context.endLoc
: context.startLoc;
const node = startNode(2 /* Message */, startOffset, startLoc);
node.items = [];
do {
const token = tokenizer.nextToken();
switch (token.type) {
case 0 /* Text */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseText(tokenizer, token.value || ''));
break;
case 6 /* List */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseList(tokenizer, token.value || ''));
break;
case 5 /* Named */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseNamed(tokenizer, token.value || ''));
break;
case 7 /* Literal */:
if (token.value == null) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, token.type);
}
node.items.push(parseLiteral(tokenizer, token.value || ''));
break;
case 8 /* LinkedAlias */:
node.items.push(parseLinked(tokenizer));
break;
}
} while (context.currentType !== 14 /* EOF */ &&
context.currentType !== 1 /* Pipe */);
// adjust message node loc
const endOffset = context.currentType === 1 /* Pipe */
? context.lastOffset
: tokenizer.currentOffset();
const endLoc = context.currentType === 1 /* Pipe */
? context.lastEndLoc
: tokenizer.currentPosition();
endNode(node, endOffset, endLoc);
return node;
}
function parsePlural(tokenizer, offset, loc, msgNode) {
const context = tokenizer.context();
let hasEmptyMessage = msgNode.items.length === 0;
const node = startNode(1 /* Plural */, offset, loc);
node.cases = [];
node.cases.push(msgNode);
do {
const msg = parseMessage(tokenizer);
if (!hasEmptyMessage) {
hasEmptyMessage = msg.items.length === 0;
}
node.cases.push(msg);
} while (context.currentType !== 14 /* EOF */);
if (hasEmptyMessage) {
emitError(tokenizer, 10 /* MUST_HAVE_MESSAGES_IN_PLURAL */, loc, 0);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
function parseResource(tokenizer) {
const context = tokenizer.context();
const { offset, startLoc } = context;
const msgNode = parseMessage(tokenizer);
if (context.currentType === 14 /* EOF */) {
return msgNode;
}
else {
return parsePlural(tokenizer, offset, startLoc, msgNode);
}
}
function parse(source) {
const tokenizer = createTokenizer(source, { ...options });
const context = tokenizer.context();
const node = startNode(0 /* Resource */, context.offset, context.startLoc);
if (location && node.loc) {
node.loc.source = source;
}
node.body = parseResource(tokenizer);
// assert wheather achieved to EOF
if (context.currentType !== 14 /* EOF */) {
emitError(tokenizer, 11 /* UNEXPECTED_LEXICAL_ANALYSIS */, context.lastStartLoc, 0, context.currentType);
}
endNode(node, tokenizer.currentOffset(), tokenizer.currentPosition());
return node;
}
return { parse };
}
function createTransformer(ast, options = {} // eslint-disable-line
) {
const _context = {
ast,
helpers: new Set()
};
const context = () => _context;
const helper = (name) => {
_context.helpers.add(name);
return name;
};
return { context, helper };
}
function traverseNodes(nodes, transformer) {
for (let i = 0; i < nodes.length; i++) {
traverseNode(nodes[i], transformer);
}
}
function traverseNode(node, transformer) {
// TODO: if we need pre-hook of transform, should be implemeted to here
switch (node.type) {
case 1 /* Plural */:
traverseNodes(node.cases, transformer);
transformer.helper("plural" /* PLURAL */);
break;
case 2 /* Message */:
traverseNodes(node.items, transformer);
break;
case 6 /* Linked */:
const linked = node;
traverseNode(linked.key, transformer);
transformer.helper("linked" /* LINKED */);
break;
case 5 /* List */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("list" /* LIST */);
break;
case 4 /* Named */:
transformer.helper("interpolate" /* INTERPOLATE */);
transformer.helper("named" /* NAMED */);
break;
}
// TODO: if we need post-hook of transform, should be implemeted to here
}
// transform AST
function transform(ast, options = {} // eslint-disable-line
) {
const transformer = createTransformer(ast);
transformer.helper("normalize" /* NORMALIZE */);
// traverse
ast.body && traverseNode(ast.body, transformer);
// set meta information
const context = transformer.context();
ast.helpers = [...context.helpers];
}
function createCodeGenerator(ast, options) {
const { sourceMap, filename } = options;
const _context = {
source: ast.loc.source,
filename,
code: '',
column: 1,
line: 1,
offset: 0,
map: undefined,
indentLevel: 0
};
const context = () => _context;
function push(code, node) {
_context.code += code;
}
function _newline(n) {
push('\n' + ` `.repeat(n));
}
function indent() {
_newline(++_context.indentLevel);
}
function deindent(withoutNewLine) {
if (withoutNewLine) {
--_context.indentLevel;
}
else {
_newline(--_context.indentLevel);
}
}
function newline() {
_newline(_context.indentLevel);
}
const helper = (key) => `_${key}`;
return {
context,
push,
indent,
deindent,
newline,
helper
};
}
function generateLinkedNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("linked" /* LINKED */)}(`);
generateNode(generator, node.key);
if (node.modifier) {
generator.push(`, `);
generateNode(generator, node.modifier);
}
generator.push(`)`);
}
function generateMessageNode(generator, node) {
const { helper } = generator;
generator.push(`${helper("normalize" /* NORMALIZE */)}([`);
generator.indent();
const length = node.items.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.items[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push('])');
}
function generatePluralNode(generator, node) {
const { helper } = generator;
if (node.cases.length > 1) {
generator.push(`${helper("plural" /* PLURAL */)}([`);
generator.indent();
const length = node.cases.length;
for (let i = 0; i < length; i++) {
generateNode(generator, node.cases[i]);
if (i === length - 1) {
break;
}
generator.push(', ');
}
generator.deindent();
generator.push(`])`);
}
}
function generateResource(generator, node) {
if (node.body) {
generateNode(generator, node.body);
}
else {
generator.push('null');
}
}
function generateNode(generator, node) {
const { helper } = generator;
switch (node.type) {
case 0 /* Resource */:
generateResource(generator, node);
break;
case 1 /* Plural */:
generatePluralNode(generator, node);
break;
case 2 /* Message */:
generateMessageNode(generator, node);
break;
case 6 /* Linked */:
generateLinkedNode(generator, node);
break;
case 8 /* LinkedModifier */:
generator.push(JSON.stringify(node.value), node);
break;
case 7 /* LinkedKey */:
generator.push(JSON.stringify(node.value), node);
break;
case 5 /* List */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("list" /* LIST */)}(${node.index}))`, node);
break;
case 4 /* Named */:
generator.push(`${helper("interpolate" /* INTERPOLATE */)}(${helper("named" /* NAMED */)}(${JSON.stringify(node.key)}))`, node);
break;
case 9 /* Literal */:
generator.push(JSON.stringify(node.value), node);
break;
case 3 /* Text */:
generator.push(JSON.stringify(node.value), node);
break;
default:
{
throw new Error(`unhandled codegen node type: ${node.type}`);
}
}
}
// generate code from AST
const generate = (ast, options = {} // eslint-disable-line
) => {
const mode = isString(options.mode) ? options.mode : 'normal';
const filename = isString(options.filename)
? options.filename
: 'message.intl';
const sourceMap = isBoolean(options.sourceMap) ? options.sourceMap : false;
const helpers = ast.helpers || [];
const generator = createCodeGenerator(ast, { mode, filename, sourceMap });
generator.push(mode === 'normal' ? `function __msg__ (ctx) {` : `(ctx) => {`);
generator.indent();
if (helpers.length > 0) {
generator.push(`const { ${helpers.map(s => `${s}: _${s}`).join(', ')} } = ctx`);
generator.newline();
}
generator.push(`return `);
generateNode(generator, ast);
generator.deindent();
generator.push(`}`);
const { code, map } = generator.context();
return {
ast,
code,
map: map ? map.toJSON() : undefined // eslint-disable-line @typescript-eslint/no-explicit-any
};
};
function baseCompile(source, options = {}) {
// parse source codes
const parser = createParser({ ...options });
const ast = parser.parse(source);
// transform ASTs
transform(ast, { ...options });
// generate javascript codes
return generate(ast, { ...options });
}
/** @internal */
const warnMessages = {
[0 /* NOT_FOUND_KEY */]: `Not found '{key}' key in '{locale}' locale messages.`,
[1 /* FALLBACK_TO_TRANSLATE */]: `Fall back to translate '{key}' key with '{target}' locale.`,
[2 /* CANNOT_FORMAT_NUMBER */]: `Cannot format a number value due to not supported Intl.NumberFormat.`,
[3 /* FALLBACK_TO_NUMBER_FORMAT */]: `Fall back to number format '{key}' key with '{target}' locale.`,
[4 /* CANNOT_FORMAT_DATE */]: `Cannot format a date value due to not supported Intl.DateTimeFormat.`,
[5 /* FALLBACK_TO_DATE_FORMAT */]: `Fall back to datetime format '{key}' key with '{target}' locale.`
};
/** @internal */
function getWarnMessage(code, ...args) {
return format(warnMessages[code], ...args);
}
/** @internal */
const NOT_REOSLVED = -1;
/** @internal */
const MISSING_RESOLVE_VALUE = '';
function getDefaultLinkedModifiers() {
return {
upper: (val) => (isString(val) ? val.toUpperCase() : val),
lower: (val) => (isString(val) ? val.toLowerCase() : val),
// prettier-ignore
capitalize: (val) => (isString(val)
? `${val.charAt(0).toLocaleUpperCase()}${val.substr(1)}`
: val)
};
}
let _compiler;
/** @internal */
function registerMessageCompiler(compiler) {
_compiler = compiler;
}
/** @internal */
function createCoreContext(options = {}) {
// setup options
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
isString(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const messages = isPlainObject(options.messages)
? options.messages
: { [locale]: {} };
const datetimeFormats = isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [locale]: {} };
const numberFormats = isPlainObject(options.numberFormats)
? options.numberFormats
: { [locale]: {} };
const modifiers = Object.assign({}, options.modifiers || {}, getDefaultLinkedModifiers());
const pluralRules = options.pluralRules || {};
const missing = isFunction(options.missing) ? options.missing : null;
const missingWarn = isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
const fallbackWarn = isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
const fallbackFormat = !!options.fallbackFormat;
const unresolving = !!options.unresolving;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
const processor = isPlainObject(options.processor) ? options.processor : null;
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
const escapeParameter = !!options.escapeParameter;
const messageCompiler = isFunction(options.messageCompiler)
? options.messageCompiler
: _compiler;
const onWarn = isFunction(options.onWarn) ? options.onWarn : warn;
// setup internal options
const internalOptions = options;
const __datetimeFormatters = isObject(internalOptions.__datetimeFormatters)
? internalOptions.__datetimeFormatters
: new Map();
const __numberFormatters = isObject(internalOptions.__numberFormatters)
? internalOptions.__numberFormatters
: new Map();
const context = {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
modifiers,
pluralRules,
missing,
missingWarn,
fallbackWarn,
fallbackFormat,
unresolving,
postTranslation,
processor,
warnHtmlMessage,
escapeParameter,
messageCompiler,
onWarn,
__datetimeFormatters,
__numberFormatters
};
// for vue-devtools timeline event
{
context.__emitter =
internalOptions.__emitter != null ? internalOptions.__emitter : undefined;
}
return context;
}
/** @internal */
function isTranslateFallbackWarn(fallback, key) {
return fallback instanceof RegExp ? fallback.test(key) : fallback;
}
/** @internal */
function isTranslateMissingWarn(missing, key) {
return missing instanceof RegExp ? missing.test(key) : missing;
}
/** @internal */
function handleMissing(context, key, locale, missingWarn, type) {
const { missing, onWarn } = context;
// for vue-devtools timeline event
{
const emitter = context.__emitter;
if (emitter) {
emitter.emit("missing" /* MISSING */, {
locale,
key,
type
});
}
}
if (missing !== null) {
const ret = missing(context, locale, key, type);
return isString(ret) ? ret : key;
}
else {
if ( isTranslateMissingWarn(missingWarn, key)) {
onWarn(getWarnMessage(0 /* NOT_FOUND_KEY */, { key, locale }));
}
return key;
}
}
/** @internal */
function getLocaleChain(ctx, fallback, start = '') {
const context = ctx;
if (start === '') {
return [];
}
if (!context.__localeChainCache) {
context.__localeChainCache = new Map();
}
let chain = context.__localeChainCache.get(start);
if (!chain) {
chain = [];
// first block defined by start
let block = [start];
// while any intervening block found
while (isArray(block)) {
block = appendBlockToChain(chain, block, fallback);
}
// prettier-ignore
// last block defined by default
const defaults = isArray(fallback)
? fallback
: isPlainObject(fallback)
? fallback['default']
? fallback['default']
: null
: fallback;
// convert defaults to array
block = isString(defaults) ? [defaults] : defaults;
if (isArray(block)) {
appendBlockToChain(chain, block, false);
}
context.__localeChainCache.set(start, chain);
}
return chain;
}
function appendBlockToChain(chain, block, blocks) {
let follow = true;
for (let i = 0; i < block.length && isBoolean(follow); i++) {
const locale = block[i];
if (isString(locale)) {
follow = appendLocaleToChain(chain, block[i], blocks);
}
}
return follow;
}
function appendLocaleToChain(chain, locale, blocks) {
let follow;
const tokens = locale.split('-');
do {
const target = tokens.join('-');
follow = appendItemToChain(chain, target, blocks);
tokens.splice(-1, 1);
} while (tokens.length && follow === true);
return follow;
}
function appendItemToChain(chain, target, blocks) {
let follow = false;
if (!chain.includes(target)) {
follow = true;
if (target) {
follow = target[target.length - 1] !== '!';
const locale = target.replace(/!/g, '');
chain.push(locale);
if ((isArray(blocks) || isPlainObject(blocks)) &&
blocks[locale] // eslint-disable-line @typescript-eslint/no-explicit-any
) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
follow = blocks[locale];
}
}
}
return follow;
}
/** @internal */
function updateFallbackLocale(ctx, locale, fallback) {
const context = ctx;
context.__localeChainCache = new Map();
getLocaleChain(ctx, fallback, locale);
}
const RE_HTML_TAG = /<\/?[\w\s="/.':;#-\/]+>/;
const WARN_MESSAGE = `Detected HTML in '{source}' message. Recommend not using HTML messages to avoid XSS.`;
function checkHtmlMessage(source, options) {
const warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
if (warnHtmlMessage && RE_HTML_TAG.test(source)) {
warn(format(WARN_MESSAGE, { source }));
}
}
const defaultOnCacheKey = (source) => source;
let compileCache = Object.create(null);
/** @internal */
function compileToFunction(source, options = {}) {
{
// check HTML message
checkHtmlMessage(source, options);
// check caches
const onCacheKey = options.onCacheKey || defaultOnCacheKey;
const key = onCacheKey(source);
const cached = compileCache[key];
if (cached) {
return cached;
}
// compile error detecting
let occured = false;
const onError = options.onError || defaultOnError;
options.onError = (err) => {
occured = true;
onError(err);
};
// compile
const { code } = baseCompile(source, options);
// evaluate function
const msg = new Function(`return ${code}`)();
// if occured compile error, don't cache
return !occured ? (compileCache[key] = msg) : msg;
}
}
/** @internal */
function createCoreError(code) {
return createCompileError(code, null, { messages: errorMessages$1 } );
}
/** @internal */
const errorMessages$1 = {
[12 /* INVALID_ARGUMENT */]: 'Invalid arguments',
[13 /* INVALID_DATE_ARGUMENT */]: 'The date provided is an invalid Date object.' +
'Make sure your Date represents a valid date.',
[14 /* INVALID_ISO_DATE_ARGUMENT */]: 'The argument provided is not a valid ISO date string'
};
const NOOP_MESSAGE_FUNCTION = () => '';
const isMessageFunction = (val) => isFunction(val);
// implementationo of `translate` function
/** @internal */
function translate(context, ...args) {
const { fallbackFormat, postTranslation, unresolving, fallbackLocale } = context;
const [key, options] = parseTranslateArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const escapeParameter = isBoolean(options.escapeParameter)
? options.escapeParameter
: context.escapeParameter;
// prettier-ignore
const defaultMsgOrKey = isString(options.default) || isBoolean(options.default) // default by function option
? !isBoolean(options.default)
? options.default
: key
: fallbackFormat // default by `fallbackFormat` option
? key
: '';
const enableDefaultMsg = fallbackFormat || defaultMsgOrKey !== '';
const locale = isString(options.locale) ? options.locale : context.locale;
// escape params
escapeParameter && escapeParams(options);
// resolve message format
// eslint-disable-next-line prefer-const
let [format, targetLocale, message] = resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn);
// if you use default message, set it as message format!
let cacheBaseKey = key;
if (!(isString(format) || isMessageFunction(format))) {
if (enableDefaultMsg) {
format = defaultMsgOrKey;
cacheBaseKey = format;
}
}
// checking message format and target locale
if (!(isString(format) || isMessageFunction(format)) ||
!isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
// setup compile error detecting
let occured = false;
const errorDetector = () => {
occured = true;
};
// compile message format
const msg = compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector);
// if occured compile error, return the message format
if (occured) {
return format;
}
// evaluate message with context
const ctxOptions = getMessageContextOptions(context, targetLocale, message, options);
const msgContext = createMessageContext(ctxOptions);
const messaged = evaluateMessage(context, msg, msgContext);
// if use post translation option, procee it with handler
return postTranslation ? postTranslation(messaged) : messaged;
}
function escapeParams(options) {
if (isArray(options.list)) {
options.list = options.list.map(item => isString(item) ? escapeHtml(item) : item);
}
else if (isObject(options.named)) {
Object.keys(options.named).forEach(key => {
if (isString(options.named[key])) {
options.named[key] = escapeHtml(options.named[key]);
}
});
}
}
function resolveMessageFormat(context, key, locale, fallbackLocale, fallbackWarn, missingWarn) {
const { messages, onWarn } = context;
const locales = getLocaleChain(context, fallbackLocale, locale);
let message = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'translate';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(1 /* FALLBACK_TO_TRANSLATE */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
message =
messages[targetLocale] || {};
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-resolve-start';
endTag = 'intlify-message-resolve-end';
mark && mark(startTag);
}
if ((format = resolveValue(message, key)) === null) {
// if null, resolve with object key path
format = message[key]; // eslint-disable-line @typescript-eslint/no-explicit-any
}
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start && format) {
emitter.emit("message-resolve" /* MESSAGE_RESOLVE */, {
type: "message-resolve" /* MESSAGE_RESOLVE */,
key,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message resolve', startTag, endTag);
}
}
if (isString(format) || isFunction(format))
break;
const missingRet = handleMissing(context, key, targetLocale, missingWarn, type);
if (missingRet !== key) {
format = missingRet;
}
from = to;
}
return [format, targetLocale, message];
}
function compileMessasgeFormat(context, key, targetLocale, format, cacheBaseKey, errorDetector) {
const { messageCompiler, warnHtmlMessage } = context;
if (isMessageFunction(format)) {
const msg = format;
msg.locale = msg.locale || targetLocale;
msg.key = msg.key || key;
return msg;
}
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-compilation-start';
endTag = 'intlify-message-compilation-end';
mark && mark(startTag);
}
const msg = messageCompiler(format, getCompileOptions(context, targetLocale, cacheBaseKey, format, warnHtmlMessage, errorDetector));
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-compilation" /* MESSAGE_COMPILATION */, {
type: "message-compilation" /* MESSAGE_COMPILATION */,
message: format,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message compilation', startTag, endTag);
}
}
msg.locale = targetLocale;
msg.key = key;
msg.source = format;
return msg;
}
function evaluateMessage(context, msg, msgCtx) {
// for vue-devtools timeline event
let start = null;
let startTag;
let endTag;
if ( inBrowser) {
start = window.performance.now();
startTag = 'intlify-message-evaluation-start';
endTag = 'intlify-message-evaluation-end';
mark && mark(startTag);
}
const messaged = msg(msgCtx);
// for vue-devtools timeline event
if ( inBrowser) {
const end = window.performance.now();
const emitter = context.__emitter;
if (emitter && start) {
emitter.emit("message-evaluation" /* MESSAGE_EVALUATION */, {
type: "message-evaluation" /* MESSAGE_EVALUATION */,
value: messaged,
time: end - start
});
}
if (startTag && endTag && mark && measure) {
mark(endTag);
measure('intlify message evaluation', startTag, endTag);
}
}
return messaged;
}
/** @internal */
function parseTranslateArgs(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
if (!isString(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isString(arg2)) {
options.default = arg2;
}
else if (isPlainObject(arg2) && !isEmptyObject(arg2)) {
options.named = arg2;
}
else if (isArray(arg2)) {
options.list = arg2;
}
if (isNumber(arg3)) {
options.plural = arg3;
}
else if (isString(arg3)) {
options.default = arg3;
}
else if (isPlainObject(arg3)) {
Object.assign(options, arg3);
}
return [key, options];
}
function getCompileOptions(context, locale, key, source, warnHtmlMessage, errorDetector) {
return {
warnHtmlMessage,
onError: (err) => {
errorDetector && errorDetector(err);
{
const message = `Message compilation error: ${err.message}`;
const codeFrame = err.location &&
generateCodeFrame(source, err.location.start.offset, err.location.end.offset);
const emitter = context.__emitter;
if (emitter) {
emitter.emit("compile-error" /* COMPILE_ERROR */, {
message: source,
error: err.message,
start: err.location && err.location.start.offset,
end: err.location && err.location.end.offset
});
}
console.error(codeFrame ? `${message}\n${codeFrame}` : message);
}
},
onCacheKey: (source) => generateFormatCacheKey(locale, key, source)
};
}
function getMessageContextOptions(context, locale, message, options) {
const { modifiers, pluralRules } = context;
const resolveMessage = (key) => {
const val = resolveValue(message, key);
if (isString(val)) {
let occured = false;
const errorDetector = () => {
occured = true;
};
const msg = compileMessasgeFormat(context, key, locale, val, key, errorDetector);
return !occured
? msg
: NOOP_MESSAGE_FUNCTION;
}
else if (isMessageFunction(val)) {
return val;
}
else {
// TODO: should be implemented warning message
return NOOP_MESSAGE_FUNCTION;
}
};
const ctxOptions = {
locale,
modifiers,
pluralRules,
messages: resolveMessage
};
if (context.processor) {
ctxOptions.processor = context.processor;
}
if (options.list) {
ctxOptions.list = options.list;
}
if (options.named) {
ctxOptions.named = options.named;
}
if (isNumber(options.plural)) {
ctxOptions.pluralIndex = options.plural;
}
return ctxOptions;
}
const intlDefined = typeof Intl !== 'undefined';
const Availabilities = {
dateTimeFormat: intlDefined && typeof Intl.DateTimeFormat !== 'undefined',
numberFormat: intlDefined && typeof Intl.NumberFormat !== 'undefined'
};
// implementation of `datetime` function
/** @internal */
function datetime(context, ...args) {
const { datetimeFormats, unresolving, fallbackLocale, onWarn } = context;
const { __datetimeFormatters } = context;
if ( !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(4 /* CANNOT_FORMAT_DATE */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseDateTimeArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value);
}
// resolve format
let datetimeFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'datetime format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(5 /* FALLBACK_TO_DATE_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
datetimeFormat =
datetimeFormats[targetLocale] || {};
format = datetimeFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __datetimeFormatters.get(id);
if (!formatter) {
formatter = new Intl.DateTimeFormat(targetLocale, Object.assign({}, format, orverrides));
__datetimeFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseDateTimeArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
let value;
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
value = new Date(arg1);
try {
// This will fail if the date is not valid
value.toISOString();
}
catch (e) {
throw createCoreError(14 /* INVALID_ISO_DATE_ARGUMENT */);
}
}
else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(13 /* INVALID_DATE_ARGUMENT */);
}
value = arg1;
}
else if (isNumber(arg1)) {
value = arg1;
}
else {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearDateTimeFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__datetimeFormatters.has(id)) {
continue;
}
context.__datetimeFormatters.delete(id);
}
}
// implementation of `number` function
/** @internal */
function number(context, ...args) {
const { numberFormats, unresolving, fallbackLocale, onWarn } = context;
const { __numberFormatters } = context;
if ( !Availabilities.numberFormat) {
onWarn(getWarnMessage(2 /* CANNOT_FORMAT_NUMBER */));
return MISSING_RESOLVE_VALUE;
}
const [key, value, options, orverrides] = parseNumberArgs(...args);
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn;
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn;
const part = !!options.part;
const locale = isString(options.locale) ? options.locale : context.locale;
const locales = getLocaleChain(context, fallbackLocale, locale);
if (!isString(key) || key === '') {
return new Intl.NumberFormat(locale).format(value);
}
// resolve format
let numberFormat = {};
let targetLocale;
let format = null;
let from = locale;
let to = null;
const type = 'number format';
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i];
if (
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)) {
onWarn(getWarnMessage(3 /* FALLBACK_TO_NUMBER_FORMAT */, {
key,
target: targetLocale
}));
}
// for vue-devtools timeline event
if ( locale !== targetLocale) {
const emitter = context.__emitter;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type,
key,
from,
to
});
}
}
numberFormat =
numberFormats[targetLocale] || {};
format = numberFormat[key];
if (isPlainObject(format))
break;
handleMissing(context, key, targetLocale, missingWarn, type);
from = to;
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key;
}
let id = `${targetLocale}__${key}`;
if (!isEmptyObject(orverrides)) {
id = `${id}__${JSON.stringify(orverrides)}`;
}
let formatter = __numberFormatters.get(id);
if (!formatter) {
formatter = new Intl.NumberFormat(targetLocale, Object.assign({}, format, orverrides));
__numberFormatters.set(id, formatter);
}
return !part ? formatter.format(value) : formatter.formatToParts(value);
}
/** @internal */
function parseNumberArgs(...args) {
const [arg1, arg2, arg3, arg4] = args;
let options = {};
let orverrides = {};
if (!isNumber(arg1)) {
throw createCoreError(12 /* INVALID_ARGUMENT */);
}
const value = arg1;
if (isString(arg2)) {
options.key = arg2;
}
else if (isPlainObject(arg2)) {
options = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isPlainObject(arg3)) {
orverrides = arg3;
}
if (isPlainObject(arg4)) {
orverrides = arg4;
}
return [options.key || '', value, options, orverrides];
}
/** @internal */
function clearNumberFormat(ctx, locale, format) {
const context = ctx;
for (const key in format) {
const id = `${locale}__${key}`;
if (!context.__numberFormatters.has(id)) {
continue;
}
context.__numberFormatters.delete(id);
}
}
const DevToolsLabels = {
["vue-devtools-plugin-vue-i18n" /* PLUGIN */]: 'Vue I18n devtools',
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'I18n Resources',
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 'Vue I18n: Compile Errors',
["vue-i18n-missing" /* TIMELINE_MISSING */]: 'Vue I18n: Missing',
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 'Vue I18n: Fallback',
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 'Vue I18n: Performance'
};
const DevToolsPlaceholders = {
["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]: 'Search for scopes ...'
};
const DevToolsTimelineColors = {
["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]: 0xff0000,
["vue-i18n-missing" /* TIMELINE_MISSING */]: 0xffcd19,
["vue-i18n-fallback" /* TIMELINE_FALLBACK */]: 0xffcd19,
["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]: 0xffcd19
};
const DevToolsTimelineLayerMaps = {
["compile-error" /* COMPILE_ERROR */]: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
["missing" /* MISSING */]: "vue-i18n-missing" /* TIMELINE_MISSING */,
["fallback" /* FALBACK */]: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
["message-resolve" /* MESSAGE_RESOLVE */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-compilation" /* MESSAGE_COMPILATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
["message-evaluation" /* MESSAGE_EVALUATION */]: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */
};
/**
* Event emitter, forked from the below:
* - original repository url: https://github.com/developit/mitt
* - code url: https://github.com/developit/mitt/blob/master/src/index.ts
* - author: Jason Miller (https://github.com/developit)
* - license: MIT
*/
/**
* Create a event emitter
*
* @returns An event emitter
*/
function createEmitter() {
const events = new Map();
const emitter = {
events,
on(event, handler) {
const handlers = events.get(event);
const added = handlers && handlers.push(handler);
if (!added) {
events.set(event, [handler]);
}
},
off(event, handler) {
const handlers = events.get(event);
if (handlers) {
handlers.splice(handlers.indexOf(handler) >>> 0, 1);
}
},
emit(event, payload) {
(events.get(event) || [])
.slice()
.map(handler => handler(payload));
(events.get('*') || [])
.slice()
.map(handler => handler(event, payload));
}
};
return emitter;
}
let devtools;
function setDevtoolsHook(hook) {
devtools = hook;
}
function devtoolsRegisterI18n(i18n, version) {
if (!devtools) {
return;
}
devtools.emit("intlify:register" /* REGISTER */, i18n, version);
}
let devtoolsApi;
async function enableDevTools(app, i18n) {
return new Promise((resolve, reject) => {
try {
lib.setupDevtoolsPlugin({
id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */,
label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */],
app
}, api => {
devtoolsApi = api;
api.on.inspectComponent(payload => {
const componentInstance = payload.componentInstance;
if (componentInstance.vnode.el.__INTLIFY__ &&
payload.instanceData) {
inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__);
}
});
api.addInspector({
id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */,
label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */],
icon: 'language',
treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */]
});
api.on.getInspectorTree(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
registerScope(payload, i18n);
}
});
api.on.getInspectorState(payload => {
if (payload.app === app &&
payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) {
inspectScope(payload, i18n);
}
});
api.addTimelineLayer({
id: "vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */,
label: DevToolsLabels["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */],
color: DevToolsTimelineColors["vue-i18n-compile-error" /* TIMELINE_COMPILE_ERROR */]
});
api.addTimelineLayer({
id: "vue-i18n-performance" /* TIMELINE_PERFORMANCE */,
label: DevToolsLabels["vue-i18n-performance" /* TIMELINE_PERFORMANCE */],
color: DevToolsTimelineColors["vue-i18n-performance" /* TIMELINE_PERFORMANCE */]
});
api.addTimelineLayer({
id: "vue-i18n-missing" /* TIMELINE_MISSING */,
label: DevToolsLabels["vue-i18n-missing" /* TIMELINE_MISSING */],
color: DevToolsTimelineColors["vue-i18n-missing" /* TIMELINE_MISSING */]
});
api.addTimelineLayer({
id: "vue-i18n-fallback" /* TIMELINE_FALLBACK */,
label: DevToolsLabels["vue-i18n-fallback" /* TIMELINE_FALLBACK */],
color: DevToolsTimelineColors["vue-i18n-fallback" /* TIMELINE_FALLBACK */]
});
resolve(true);
});
}
catch (e) {
console.error(e);
reject(false);
}
});
}
function inspectComposer(instanceData, composer) {
const type = 'vue-i18n: composer properties';
instanceData.state.push({
type,
key: 'locale',
editable: false,
value: composer.locale.value
});
instanceData.state.push({
type,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
});
instanceData.state.push({
type,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
});
instanceData.state.push({
type,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
});
instanceData.state.push({
type,
key: 'messages',
editable: false,
value: composer.messages.value
});
instanceData.state.push({
type,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
});
instanceData.state.push({
type,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
});
}
function registerScope(payload, i18n) {
const children = [];
for (const [keyInstance, instance] of i18n.__instances) {
// prettier-ignore
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
const label = keyInstance.type.name ||
keyInstance.type.displayName ||
keyInstance.type.__file;
children.push({
id: composer.id.toString(),
label: `${label} Scope`
});
}
payload.rootNodes.push({
id: 'global',
label: 'Global Scope',
children
});
}
function inspectScope(payload, i18n) {
if (payload.nodeId === 'global') {
payload.state = makeScopeInspectState(i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer);
}
else {
const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId);
if (instance) {
const composer = i18n.mode === 'composition'
? instance
: instance.__composer;
payload.state = makeScopeInspectState(composer);
}
}
}
function makeScopeInspectState(composer) {
const state = {};
const localeType = 'Locale related info';
const localeStates = [
{
type: localeType,
key: 'locale',
editable: false,
value: composer.locale.value
},
{
type: localeType,
key: 'fallbackLocale',
editable: false,
value: composer.fallbackLocale.value
},
{
type: localeType,
key: 'availableLocales',
editable: false,
value: composer.availableLocales
},
{
type: localeType,
key: 'inheritLocale',
editable: false,
value: composer.inheritLocale
}
];
state[localeType] = localeStates;
const localeMessagesType = 'Locale messages info';
const localeMessagesStates = [
{
type: localeMessagesType,
key: 'messages',
editable: false,
value: composer.messages.value
}
];
state[localeMessagesType] = localeMessagesStates;
const datetimeFormatsType = 'Datetime formats info';
const datetimeFormatsStates = [
{
type: datetimeFormatsType,
key: 'datetimeFormats',
editable: false,
value: composer.datetimeFormats.value
}
];
state[datetimeFormatsType] = datetimeFormatsStates;
const numberFormatsType = 'Datetime formats info';
const numberFormatsStates = [
{
type: numberFormatsType,
key: 'numberFormats',
editable: false,
value: composer.numberFormats.value
}
];
state[numberFormatsType] = numberFormatsStates;
return state;
}
function addTimelineEvent(event, payload) {
if (devtoolsApi) {
devtoolsApi.addTimelineEvent({
layerId: DevToolsTimelineLayerMaps[event],
event: {
time: Date.now(),
meta: {},
data: payload || {}
}
});
}
}
/**
* Vue I18n Version
*
* @remarks
* Semver format. Same format as the package.json `version` field.
*
* @VueI18nGeneral
*/
const VERSION = '9.0.0-beta.13';
/**
* This is only called development env
* istanbul-ignore-next
*/
function initDev() {
const target = getGlobalThis();
target.__INTLIFY__ = true;
setDevtoolsHook(target.__INTLIFY_DEVTOOLS_GLOBAL_HOOK__);
{
console.info(`You are running a development build of vue-i18n.\n` +
`Make sure to use the production build (*.prod.js) when deploying for production.`);
}
}
const warnMessages$1 = {
[6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`,
[7 /* NOT_SUPPORTED_PRESERVE */]: `Not supportted 'preserve'.`,
[8 /* NOT_SUPPORTED_FORMATTER */]: `Not supportted 'formatter'.`,
[9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supportted 'preserveDirectiveContent'.`,
[10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supportted 'getChoiceIndex'.`,
[11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`,
[12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.`
};
function getWarnMessage$1(code, ...args) {
return format(warnMessages$1[code], ...args);
}
function createI18nError(code, ...args) {
return createCompileError(code, null, { messages: errorMessages$2, args } );
}
const errorMessages$2 = {
[12 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer',
[13 /* INVALID_ARGUMENT */]: 'Invalid argument',
[14 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function',
[15 /* NOT_INSLALLED */]: 'Need to install with `app.use` function',
[20 /* UNEXPECTED_ERROR */]: 'Unexpected error',
[16 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode',
[17 /* REQUIRED_VALUE */]: `Required in value: {0}`,
[18 /* INVALID_VALUE */]: `Invalid value`,
[19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin`
};
/**
* Composer
*
* Composer is offered composable API for Vue 3
* This module is offered new style vue-i18n API
*/
const TransrateVNodeSymbol = makeSymbol('__transrateVNode');
const DatetimePartsSymbol = makeSymbol('__datetimeParts');
const NumberPartsSymbol = makeSymbol('__numberParts');
const EnableEmitter = makeSymbol('__enableEmitter');
const DisableEmitter = makeSymbol('__disableEmitter');
let composerID = 0;
function defineCoreMissingHandler(missing) {
return ((ctx, locale, key, type) => {
return missing(locale, key, getCurrentInstance() || undefined, type);
});
}
function getLocaleMessages(locale, options) {
const { messages, __i18n } = options;
// prettier-ignore
const ret = isPlainObject(messages)
? messages
: isArray(__i18n)
? {}
: { [locale]: {} };
// merge locale messages of i18n custom block
if (isArray(__i18n)) {
__i18n.forEach(raw => {
deepCopy(isString(raw) ? JSON.parse(raw) : raw, ret);
});
return ret;
}
if (isFunction(__i18n)) {
const { functions } = __i18n();
addPreCompileMessages(ret, functions);
}
return ret;
}
const hasOwnProperty = Object.prototype.hasOwnProperty;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasOwn(obj, key) {
return hasOwnProperty.call(obj, key);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function deepCopy(source, destination) {
for (const key in source) {
if (hasOwn(source, key)) {
if (!isObject(source[key])) {
destination[key] = destination[key] != null ? destination[key] : {};
destination[key] = source[key];
}
else {
destination[key] = destination[key] != null ? destination[key] : {};
deepCopy(source[key], destination[key]);
}
}
}
}
function addPreCompileMessages(messages, functions) {
const keys = Object.keys(functions);
keys.forEach(key => {
const compiled = functions[key];
const { l, k } = JSON.parse(key);
if (!messages[l]) {
messages[l] = {};
}
const targetLocaleMessage = messages[l];
const paths = parse(k);
if (paths != null) {
const len = paths.length;
let last = targetLocaleMessage; // eslint-disable-line @typescript-eslint/no-explicit-any
let i = 0;
while (i < len) {
const path = paths[i];
if (i === len - 1) {
last[path] = compiled;
break;
}
else {
let val = last[path];
if (!val) {
last[path] = val = {};
}
last = val;
i++;
}
}
}
});
}
/**
* Create composer interface factory
*
* @internal
*/
function createComposer(options = {}) {
const { __root } = options;
const _isGlobal = __root === undefined;
let _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true;
const _locale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.locale.value
: isString(options.locale)
? options.locale
: 'en-US');
const _fallbackLocale = ref(
// prettier-ignore
__root && _inheritLocale
? __root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value);
const _messages = ref(getLocaleMessages(_locale.value, options));
const _datetimeFormats = ref(isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} });
const _numberFormats = ref(isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} });
// warning suppress options
// prettier-ignore
let _missingWarn = __root
? __root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true;
// prettier-ignore
let _fallbackWarn = __root
? __root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true;
let _fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
// configure fall bakck to root
let _fallbackFormat = !!options.fallbackFormat;
// runtime missing
let _missing = isFunction(options.missing) ? options.missing : null;
let _runtimeMissing = isFunction(options.missing)
? defineCoreMissingHandler(options.missing)
: null;
// postTranslation handler
let _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null;
let _warnHtmlMessage = isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true;
let _escapeParameter = !!options.escapeParameter;
// custom linked modifiers
// prettier-ignore
const _modifiers = __root
? __root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {};
// pluralRules
const _pluralRules = options.pluralRules;
// runtime context
// eslint-disable-next-line prefer-const
let _context;
function getCoreContext() {
return createCoreContext({
locale: _locale.value,
fallbackLocale: _fallbackLocale.value,
messages: _messages.value,
datetimeFormats: _datetimeFormats.value,
numberFormats: _numberFormats.value,
modifiers: _modifiers,
pluralRules: _pluralRules,
missing: _runtimeMissing === null ? undefined : _runtimeMissing,
missingWarn: _missingWarn,
fallbackWarn: _fallbackWarn,
fallbackFormat: _fallbackFormat,
unresolving: true,
postTranslation: _postTranslation === null ? undefined : _postTranslation,
warnHtmlMessage: _warnHtmlMessage,
escapeParameter: _escapeParameter,
__datetimeFormatters: isPlainObject(_context)
? _context.__datetimeFormatters
: undefined,
__numberFormatters: isPlainObject(_context)
? _context.__numberFormatters
: undefined,
__emitter: isPlainObject(_context)
? _context.__emitter
: undefined
});
}
_context = getCoreContext();
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
/*!
* define properties
*/
// locale
const locale = computed({
get: () => _locale.value,
set: val => {
_locale.value = val;
_context.locale = _locale.value;
}
});
// fallbackLocale
const fallbackLocale = computed({
get: () => _fallbackLocale.value,
set: val => {
_fallbackLocale.value = val;
_context.fallbackLocale = _fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, val);
}
});
// messages
const messages = computed(() => _messages.value);
// datetimeFormats
const datetimeFormats = computed(() => _datetimeFormats.value);
// numberFormats
const numberFormats = computed(() => _numberFormats.value);
/**
* define methods
*/
// getPostTranslationHandler
function getPostTranslationHandler() {
return isFunction(_postTranslation) ? _postTranslation : null;
}
// setPostTranslationHandler
function setPostTranslationHandler(handler) {
_postTranslation = handler;
_context.postTranslation = handler;
}
// getMissingHandler
function getMissingHandler() {
return _missing;
}
// setMissingHandler
function setMissingHandler(handler) {
if (handler !== null) {
_runtimeMissing = defineCoreMissingHandler(handler);
}
_missing = handler;
_context.missing = _runtimeMissing;
}
function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) {
const context = getCoreContext();
const ret = fn(context); // track reactive dependency, see the getRuntimeContext
if (isNumber(ret) && ret === NOT_REOSLVED) {
const key = argumentParser();
if ( _fallbackRoot && __root) {
warn(getWarnMessage$1(6 /* FALLBACK_TO_ROOT */, {
key,
type: warnType
}));
// for vue-devtools timeline event
{
const { __emitter: emitter } = context;
if (emitter) {
emitter.emit("fallback" /* FALBACK */, {
type: warnType,
key,
to: 'global'
});
}
}
}
return _fallbackRoot && __root
? fallbackSuccess(__root)
: fallbackFail(key);
}
else if (successCondition(ret)) {
return ret;
}
else {
/* istanbul ignore next */
throw createI18nError(12 /* UNEXPECTED_RETURN_TYPE */);
}
}
// t
function t(...args) {
return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val));
}
// d
function d(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// n
function n(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val));
}
// for custom processor
function normalize(values) {
return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val);
}
const interpolate = (val) => val;
const processor = {
normalize,
interpolate,
type: 'vnode'
};
// __transrateVNode, using for `i18n-t` component
function __transrateVNode(...args) {
return wrapWithDeps(context => {
let ret;
const _context = context;
try {
_context.processor = processor;
ret = translate(_context, ...args);
}
finally {
_context.processor = null;
}
return ret;
}, () => parseTranslateArgs(...args)[0], 'translate',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val));
}
// __numberParts, using for `i18n-n` component
function __numberParts(...args) {
return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// __datetimeParts, using for `i18n-d` component
function __datetimeParts(...args) {
return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val));
}
// te
function te(key, locale) {
const targetLocale = isString(locale) ? locale : _locale.value;
const message = getLocaleMessage(targetLocale);
return resolveValue(message, key) !== null;
}
// tm
function tm(key) {
const messages = _messages.value[_locale.value] || {};
const target = resolveValue(messages, key);
// prettier-ignore
return target != null
? target
: __root
? __root.tm(key) || {}
: {};
}
// getLocaleMessage
function getLocaleMessage(locale) {
return (_messages.value[locale] || {});
}
// setLocaleMessage
function setLocaleMessage(locale, message) {
_messages.value[locale] = message;
_context.messages = _messages.value;
}
// mergeLocaleMessage
function mergeLocaleMessage(locale, message) {
_messages.value[locale] = Object.assign(_messages.value[locale] || {}, message);
_context.messages = _messages.value;
}
// getDateTimeFormat
function getDateTimeFormat(locale) {
return _datetimeFormats.value[locale] || {};
}
// setDateTimeFormat
function setDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = format;
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// mergeDateTimeFormat
function mergeDateTimeFormat(locale, format) {
_datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format);
_context.datetimeFormats = _datetimeFormats.value;
clearDateTimeFormat(_context, locale, format);
}
// getNumberFormat
function getNumberFormat(locale) {
return _numberFormats.value[locale] || {};
}
// setNumberFormat
function setNumberFormat(locale, format) {
_numberFormats.value[locale] = format;
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// mergeNumberFormat
function mergeNumberFormat(locale, format) {
_numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format);
_context.numberFormats = _numberFormats.value;
clearNumberFormat(_context, locale, format);
}
// for debug
composerID++;
// watch root locale & fallbackLocale
if (__root) {
watch(__root.locale, (val) => {
if (_inheritLocale) {
_locale.value = val;
_context.locale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
watch(__root.fallbackLocale, (val) => {
if (_inheritLocale) {
_fallbackLocale.value = val;
_context.fallbackLocale = val;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
});
}
// export composition API!
const composer = {
// properties
id: composerID,
locale,
fallbackLocale,
get inheritLocale() {
return _inheritLocale;
},
set inheritLocale(val) {
_inheritLocale = val;
if (val && __root) {
_locale.value = __root.locale.value;
_fallbackLocale.value = __root.fallbackLocale.value;
updateFallbackLocale(_context, _locale.value, _fallbackLocale.value);
}
},
get availableLocales() {
return Object.keys(_messages.value).sort();
},
messages,
datetimeFormats,
numberFormats,
get modifiers() {
return _modifiers;
},
get pluralRules() {
return _pluralRules || {};
},
get isGlobal() {
return _isGlobal;
},
get missingWarn() {
return _missingWarn;
},
set missingWarn(val) {
_missingWarn = val;
_context.missingWarn = _missingWarn;
},
get fallbackWarn() {
return _fallbackWarn;
},
set fallbackWarn(val) {
_fallbackWarn = val;
_context.fallbackWarn = _fallbackWarn;
},
get fallbackRoot() {
return _fallbackRoot;
},
set fallbackRoot(val) {
_fallbackRoot = val;
},
get fallbackFormat() {
return _fallbackFormat;
},
set fallbackFormat(val) {
_fallbackFormat = val;
_context.fallbackFormat = _fallbackFormat;
},
get warnHtmlMessage() {
return _warnHtmlMessage;
},
set warnHtmlMessage(val) {
_warnHtmlMessage = val;
_context.warnHtmlMessage = val;
},
get escapeParameter() {
return _escapeParameter;
},
set escapeParameter(val) {
_escapeParameter = val;
_context.escapeParameter = val;
},
// methods
t,
d,
n,
te,
tm,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
[TransrateVNodeSymbol]: __transrateVNode,
[NumberPartsSymbol]: __numberParts,
[DatetimePartsSymbol]: __datetimeParts
};
// for vue-devtools timeline event
{
composer[EnableEmitter] = (emitter) => {
_context.__emitter = emitter;
};
composer[DisableEmitter] = () => {
_context.__emitter = undefined;
};
}
return composer;
}
/**
* Legacy
*
* This module is offered legacy vue-i18n API compatibility
*/
/**
* Convert to I18n Composer Options from VueI18n Options
*
* @internal
*/
function convertComposerOptions(options) {
const locale = isString(options.locale) ? options.locale : 'en-US';
const fallbackLocale = isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: locale;
const missing = isFunction(options.missing) ? options.missing : undefined;
const missingWarn = isBoolean(options.silentTranslationWarn) ||
isRegExp(options.silentTranslationWarn)
? !options.silentTranslationWarn
: true;
const fallbackWarn = isBoolean(options.silentFallbackWarn) ||
isRegExp(options.silentFallbackWarn)
? !options.silentFallbackWarn
: true;
const fallbackRoot = isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true;
const fallbackFormat = !!options.formatFallbackMessages;
const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {};
const pluralizationRules = options.pluralizationRules;
const postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: undefined;
const warnHtmlMessage = isString(options.warnHtmlInMessage)
? options.warnHtmlInMessage !== 'off'
: true;
const escapeParameter = !!options.escapeParameterHtml;
const inheritLocale = isBoolean(options.sync) ? options.sync : true;
if ( options.formatter) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
}
if ( options.preserveDirectiveContent) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
}
let messages = options.messages;
if (isPlainObject(options.sharedMessages)) {
const sharedMessages = options.sharedMessages;
const locales = Object.keys(sharedMessages);
messages = locales.reduce((messages, locale) => {
const message = messages[locale] || (messages[locale] = {});
Object.assign(message, sharedMessages[locale]);
return messages;
}, (messages || {}));
}
const { __i18n, __root } = options;
const datetimeFormats = options.datetimeFormats;
const numberFormats = options.numberFormats;
return {
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
missing,
missingWarn,
fallbackWarn,
fallbackRoot,
fallbackFormat,
modifiers,
pluralRules: pluralizationRules,
postTranslation,
warnHtmlMessage,
escapeParameter,
inheritLocale,
__i18n,
__root
};
}
/**
* create VueI18n interface factory
*
* @internal
*/
function createVueI18n(options = {}) {
const composer = createComposer(convertComposerOptions(options));
// defines VueI18n
const vueI18n = {
/**
* properties
*/
// id
id: composer.id,
// locale
get locale() {
return composer.locale.value;
},
set locale(val) {
composer.locale.value = val;
},
// fallbackLocale
get fallbackLocale() {
return composer.fallbackLocale.value;
},
set fallbackLocale(val) {
composer.fallbackLocale.value = val;
},
// messages
get messages() {
return composer.messages.value;
},
// datetimeFormats
get datetimeFormats() {
return composer.datetimeFormats.value;
},
// numberFormats
get numberFormats() {
return composer.numberFormats.value;
},
// availableLocales
get availableLocales() {
return composer.availableLocales;
},
// formatter
get formatter() {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
// dummy
return {
interpolate() {
return [];
}
};
},
set formatter(val) {
warn(getWarnMessage$1(8 /* NOT_SUPPORTED_FORMATTER */));
},
// missing
get missing() {
return composer.getMissingHandler();
},
set missing(handler) {
composer.setMissingHandler(handler);
},
// silentTranslationWarn
get silentTranslationWarn() {
return isBoolean(composer.missingWarn)
? !composer.missingWarn
: composer.missingWarn;
},
set silentTranslationWarn(val) {
composer.missingWarn = isBoolean(val) ? !val : val;
},
// silentFallbackWarn
get silentFallbackWarn() {
return isBoolean(composer.fallbackWarn)
? !composer.fallbackWarn
: composer.fallbackWarn;
},
set silentFallbackWarn(val) {
composer.fallbackWarn = isBoolean(val) ? !val : val;
},
// modifiers
get modifiers() {
return composer.modifiers;
},
// formatFallbackMessages
get formatFallbackMessages() {
return composer.fallbackFormat;
},
set formatFallbackMessages(val) {
composer.fallbackFormat = val;
},
// postTranslation
get postTranslation() {
return composer.getPostTranslationHandler();
},
set postTranslation(handler) {
composer.setPostTranslationHandler(handler);
},
// sync
get sync() {
return composer.inheritLocale;
},
set sync(val) {
composer.inheritLocale = val;
},
// warnInHtmlMessage
get warnHtmlInMessage() {
return composer.warnHtmlMessage ? 'warn' : 'off';
},
set warnHtmlInMessage(val) {
composer.warnHtmlMessage = val !== 'off';
},
// escapeParameterHtml
get escapeParameterHtml() {
return composer.escapeParameter;
},
set escapeParameterHtml(val) {
composer.escapeParameter = val;
},
// preserveDirectiveContent
get preserveDirectiveContent() {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
return true;
},
set preserveDirectiveContent(val) {
warn(getWarnMessage$1(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */));
},
// pluralizationRules
get pluralizationRules() {
return composer.pluralRules || {};
},
// for internal
__composer: composer,
/**
* methods
*/
// t
t(...args) {
const [arg1, arg2, arg3] = args;
const options = {};
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// tc
tc(...args) {
const [arg1, arg2, arg3] = args;
const options = { plural: 1 };
let list = null;
let named = null;
if (!isString(arg1)) {
throw createI18nError(13 /* INVALID_ARGUMENT */);
}
const key = arg1;
if (isString(arg2)) {
options.locale = arg2;
}
else if (isNumber(arg2)) {
options.plural = arg2;
}
else if (isArray(arg2)) {
list = arg2;
}
else if (isPlainObject(arg2)) {
named = arg2;
}
if (isString(arg3)) {
options.locale = arg3;
}
else if (isArray(arg3)) {
list = arg3;
}
else if (isPlainObject(arg3)) {
named = arg3;
}
return composer.t(key, list || named || {}, options);
},
// te
te(key, locale) {
return composer.te(key, locale);
},
// tm
tm(key) {
return composer.tm(key);
},
// getLocaleMessage
getLocaleMessage(locale) {
return composer.getLocaleMessage(locale);
},
// setLocaleMessage
setLocaleMessage(locale, message) {
composer.setLocaleMessage(locale, message);
},
// mergeLocaleMessasge
mergeLocaleMessage(locale, message) {
composer.mergeLocaleMessage(locale, message);
},
// d
d(...args) {
return composer.d(...args);
},
// getDateTimeFormat
getDateTimeFormat(locale) {
return composer.getDateTimeFormat(locale);
},
// setDateTimeFormat
setDateTimeFormat(locale, format) {
composer.setDateTimeFormat(locale, format);
},
// mergeDateTimeFormat
mergeDateTimeFormat(locale, format) {
composer.mergeDateTimeFormat(locale, format);
},
// n
n(...args) {
return composer.n(...args);
},
// getNumberFormat
getNumberFormat(locale) {
return composer.getNumberFormat(locale);
},
// setNumberFormat
setNumberFormat(locale, format) {
composer.setNumberFormat(locale, format);
},
// mergeNumberFormat
mergeNumberFormat(locale, format) {
composer.mergeNumberFormat(locale, format);
},
// getChoiceIndex
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getChoiceIndex(choice, choicesLength) {
warn(getWarnMessage$1(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */));
return -1;
},
// for internal
__onComponentInstanceCreated(target) {
const { componentInstanceCreatedListener } = options;
if (componentInstanceCreatedListener) {
componentInstanceCreatedListener(target, vueI18n);
}
}
};
// for vue-devtools timeline event
{
vueI18n.__enableEmitter = (emitter) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[EnableEmitter] && __composer[EnableEmitter](emitter);
};
vueI18n.__disableEmitter = () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __composer = composer;
__composer[DisableEmitter] && __composer[DisableEmitter]();
};
}
return vueI18n;
}
const baseFormatProps = {
tag: {
type: [String, Object]
},
locale: {
type: String
},
scope: {
type: String,
validator: (val) => val === 'parent' || val === 'global',
default: 'parent'
}
};
/**
* Translation Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [TranslationProps](component#translationprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Component Interpolation](../advanced/component)
*
* @example
* ```html
* <div id="app">
* <!-- ... -->
* <i18n path="term" tag="label" for="tos">
* <a :href="url" target="_blank">{{ $t('tos') }}</a>
* </i18n>
* <!-- ... -->
* </div>
* ```
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* const messages = {
* en: {
* tos: 'Term of Service',
* term: 'I accept xxx {0}.'
* },
* ja: {
* tos: '利用規約',
* term: '私は xxx の{0}に同意します。'
* }
* }
*
* const i18n = createI18n({
* locale: 'en',
* messages
* })
*
* const app = createApp({
* data: {
* url: '/term'
* }
* }).use(i18n).mount('#app')
* ```
*
* @VueI18nComponent
*/
const Translation = {
/* eslint-disable */
name: 'i18n-t',
props: {
...baseFormatProps,
keypath: {
type: String,
required: true
},
plural: {
type: [Number, String],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
validator: (val) => isNumber(val) || !isNaN(val)
}
},
/* eslint-enable */
setup(props, context) {
const { slots, attrs } = context;
const i18n = useI18n({ useScope: props.scope });
const keys = Object.keys(slots).filter(key => key !== '_');
return () => {
const options = {};
if (props.locale) {
options.locale = props.locale;
}
if (props.plural !== undefined) {
options.plural = isString(props.plural) ? +props.plural : props.plural;
}
const arg = getInterpolateArg(context, keys);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options);
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
};
function getInterpolateArg({ slots }, keys) {
if (keys.length === 1 && keys[0] === 'default') {
// default slot only
return slots.default ? slots.default() : [];
}
else {
// named slots
return keys.reduce((arg, key) => {
const slot = slots[key];
if (slot) {
arg[key] = slot();
}
return arg;
}, {});
}
}
function renderFormatter(props, context, slotKeys, partFormatter) {
const { slots, attrs } = context;
return () => {
const options = { part: true };
let orverrides = {};
if (props.locale) {
options.locale = props.locale;
}
if (isString(props.format)) {
options.key = props.format;
}
else if (isObject(props.format)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (isString(props.format.key)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.key = props.format.key;
}
// Filter out number format options only
orverrides = Object.keys(props.format).reduce((options, prop) => {
return slotKeys.includes(prop)
? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any
: options;
}, {});
}
const parts = partFormatter(...[props.value, options, orverrides]);
let children = [options.key];
if (isArray(parts)) {
children = parts.map((part, index) => {
const slot = slots[part.type];
return slot
? slot({ [part.type]: part.value, index, parts })
: [part.value];
});
}
else if (isString(parts)) {
children = [parts];
}
// prettier-ignore
return isString(props.tag)
? h(props.tag, { ...attrs }, children)
: isObject(props.tag)
? h(props.tag, { ...attrs }, children)
: h(Fragment, { ...attrs }, children);
};
}
const NUMBER_FORMAT_KEYS = [
'localeMatcher',
'style',
'unit',
'unitDisplay',
'currency',
'currencyDisplay',
'useGrouping',
'numberingSystem',
'minimumIntegerDigits',
'minimumFractionDigits',
'maximumFractionDigits',
'minimumSignificantDigits',
'maximumSignificantDigits',
'notation',
'formatMatcher'
];
/**
* Number Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/number#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.NumberForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat)
*
* @VueI18nComponent
*/
const NumberFormat = {
/* eslint-disable */
name: 'i18n-n',
props: {
...baseFormatProps,
value: {
type: Number,
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[NumberPartsSymbol](...args));
}
};
const DATETIME_FORMAT_KEYS = [
'dateStyle',
'timeStyle',
'fractionalSecondDigits',
'calendar',
'dayPeriod',
'numberingSystem',
'localeMatcher',
'timeZone',
'hour12',
'hourCycle',
'formatMatcher',
'weekday',
'era',
'year',
'month',
'day',
'hour',
'minute',
'second',
'timeZoneName'
];
/**
* Datetime Format Component
*
* @remarks
* See the following items for property about details
*
* @VueI18nSee [FormattableProps](component#formattableprops)
* @VueI18nSee [BaseFormatProps](component#baseformatprops)
* @VueI18nSee [Custom Formatting](../essentials/datetime#custom-formatting)
*
* @VueI18nDanger
* Not supported IE, due to no support `Intl.DateTimeForamt#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*
* If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat)
*
* @VueI18nComponent
*/
const DatetimeFormat = {
/* eslint-disable */
name: 'i18n-d',
props: {
...baseFormatProps,
value: {
type: [Number, Date],
required: true
},
format: {
type: [String, Object]
}
},
/* eslint-enable */
setup(props, context) {
const i18n = useI18n({ useScope: 'parent' });
return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) =>
// eslint-disable-next-line @typescript-eslint/no-explicit-any
i18n[DatetimePartsSymbol](...args));
}
};
function getComposer(i18n, instance) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
return (i18nInternal.__getInstance(instance) || i18n.global);
}
else {
const vueI18n = i18nInternal.__getInstance(instance);
return vueI18n != null
? vueI18n.__composer
: i18n.global.__composer;
}
}
function vTDirective(i18n) {
const bind = (el, { instance, value, modifiers }) => {
/* istanbul ignore if */
if (!instance || !instance.$) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const composer = getComposer(i18n, instance.$);
if ( modifiers.preserve) {
warn(getWarnMessage$1(7 /* NOT_SUPPORTED_PRESERVE */));
}
const parsedValue = parseValue(value);
el.textContent = composer.t(...makeParams(parsedValue));
};
return {
beforeMount: bind,
beforeUpdate: bind
};
}
function parseValue(value) {
if (isString(value)) {
return { path: value };
}
else if (isPlainObject(value)) {
if (!('path' in value)) {
throw createI18nError(17 /* REQUIRED_VALUE */, 'path');
}
return value;
}
else {
throw createI18nError(18 /* INVALID_VALUE */);
}
}
function makeParams(value) {
const { path, locale, args, choice, plural } = value;
const options = {};
const named = args || {};
if (isString(locale)) {
options.locale = locale;
}
if (isNumber(choice)) {
options.plural = choice;
}
if (isNumber(plural)) {
options.plural = plural;
}
return [path, named, options];
}
function apply(app, i18n, ...options) {
const pluginOptions = isPlainObject(options[0])
? options[0]
: {};
const useI18nComponentName = !!pluginOptions.useI18nComponentName;
const globalInstall = isBoolean(pluginOptions.globalInstall)
? pluginOptions.globalInstall
: true;
if ( globalInstall && useI18nComponentName) {
warn(getWarnMessage$1(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, {
name: Translation.name
}));
}
if (globalInstall) {
// install components
app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation);
app.component(NumberFormat.name, NumberFormat);
app.component(DatetimeFormat.name, DatetimeFormat);
}
// install directive
app.directive('t', vTDirective(i18n));
}
// supports compatibility for legacy vue-i18n APIs
function defineMixin(vuei18n, composer, i18n) {
return {
beforeCreate() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const options = this.$options;
if (options.i18n) {
const optionsI18n = options.i18n;
if (options.__i18n) {
optionsI18n.__i18n = options.__i18n;
}
optionsI18n.__root = composer;
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, optionsI18n);
}
else {
this.$i18n = createVueI18n(optionsI18n);
}
}
else if (options.__i18n) {
if (this === this.$root) {
this.$i18n = mergeToRoot(vuei18n, options);
}
else {
this.$i18n = createVueI18n({
__i18n: options.__i18n,
__root: composer
});
}
}
else {
// set global
this.$i18n = vuei18n;
}
vuei18n.__onComponentInstanceCreated(this.$i18n);
i18n.__setInstance(instance, this.$i18n);
// defines vue-i18n legacy APIs
this.$t = (...args) => this.$i18n.t(...args);
this.$tc = (...args) => this.$i18n.tc(...args);
this.$te = (key, locale) => this.$i18n.te(key, locale);
this.$d = (...args) => this.$i18n.d(...args);
this.$n = (...args) => this.$i18n.n(...args);
this.$tm = (key) => this.$i18n.tm(key);
},
mounted() {
/* istanbul ignore if */
{
this.$el.__INTLIFY__ = this.$i18n.__composer;
const emitter = (this.__emitter = createEmitter());
const _vueI18n = this.$i18n;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
emitter.on('*', addTimelineEvent);
}
},
beforeUnmount() {
const instance = getCurrentInstance();
/* istanbul ignore if */
if (!instance) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
/* istanbul ignore if */
{
if (this.__emitter) {
this.__emitter.off('*', addTimelineEvent);
delete this.__emitter;
}
const _vueI18n = this.$i18n;
_vueI18n.__disableEmitter && _vueI18n.__disableEmitter();
delete this.$el.__INTLIFY__;
}
delete this.$t;
delete this.$tc;
delete this.$te;
delete this.$d;
delete this.$n;
delete this.$tm;
i18n.__deleteInstance(instance);
delete this.$i18n;
}
};
}
function mergeToRoot(root, optoins) {
root.locale = optoins.locale || root.locale;
root.fallbackLocale = optoins.fallbackLocale || root.fallbackLocale;
root.missing = optoins.missing || root.missing;
root.silentTranslationWarn =
optoins.silentTranslationWarn || root.silentFallbackWarn;
root.silentFallbackWarn =
optoins.silentFallbackWarn || root.silentFallbackWarn;
root.formatFallbackMessages =
optoins.formatFallbackMessages || root.formatFallbackMessages;
root.postTranslation = optoins.postTranslation || root.postTranslation;
root.warnHtmlInMessage = optoins.warnHtmlInMessage || root.warnHtmlInMessage;
root.escapeParameterHtml =
optoins.escapeParameterHtml || root.escapeParameterHtml;
root.sync = optoins.sync || root.sync;
const messages = getLocaleMessages(root.locale, {
messages: optoins.messages,
__i18n: optoins.__i18n
});
Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale]));
if (optoins.datetimeFormats) {
Object.keys(optoins.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, optoins.datetimeFormats[locale]));
}
if (optoins.numberFormats) {
Object.keys(optoins.numberFormats).forEach(locale => root.mergeNumberFormat(locale, optoins.numberFormats[locale]));
}
return root;
}
/**
* Vue I18n factory
*
* @param options - An options, see the {@link I18nOptions}
*
* @returns {@link I18n} instance
*
* @remarks
* If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option.
*
* If you use composition API mode, you need to specify {@link ComposerOptions}.
*
* @VueI18nSee [Getting Started](../essentials/started)
* @VueI18nSee [Composition API](../advanced/composition)
*
* @example
* case: for Legacy API
* ```js
* import { createApp } from 'vue'
* import { createI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* // ...
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @example
* case: for composition API
* ```js
* import { createApp } from 'vue'
* import { createI18n, useI18n } from 'vue-i18n'
*
* // call with I18n option
* const i18n = createI18n({
* legacy: false, // you must specify 'lagacy: false' option
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
*
* const App = {
* setup() {
* // ...
* const { t } = useI18n({ ... })
* return { ... , t }
* }
* }
*
* const app = createApp(App)
*
* // install!
* app.use(i18n)
* app.mount('#app')
* ```
*
* @VueI18nGeneral
*/
function createI18n(options = {}) {
// prettier-ignore
const __legacyMode = isBoolean(options.legacy)
? options.legacy
: true;
const __globalInjection = !!options.globalInjection;
const __instances = new Map();
// prettier-ignore
const __global = __legacyMode
? createVueI18n(options)
: createComposer(options);
const symbol = makeSymbol( 'vue-i18n' );
const i18n = {
// mode
get mode() {
// prettier-ignore
return __legacyMode
? 'legacy'
: 'composition'
;
},
// install plugin
async install(app, ...options) {
{
app.__VUE_I18N__ = i18n;
}
// setup global provider
app.__VUE_I18N_SYMBOL__ = symbol;
app.provide(app.__VUE_I18N_SYMBOL__, i18n);
// global method and properties injection for Composition API
if (!__legacyMode && __globalInjection) {
injectGlobalFields(app, i18n.global);
}
// install built-in components and directive
{
apply(app, i18n, ...options);
}
// setup mixin for Legacy API
if ( __legacyMode) {
app.mixin(defineMixin(__global, __global.__composer, i18n));
}
// setup vue-devtools plugin
{
const ret = await enableDevTools(app, i18n);
if (!ret) {
throw createI18nError(19 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */);
}
const emitter = createEmitter();
if (__legacyMode) {
const _vueI18n = __global;
_vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter);
}
else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = __global;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
}
emitter.on('*', addTimelineEvent);
}
},
// global accsessor
get global() {
return __global;
},
// @internal
__instances,
// @internal
__getInstance(component) {
return __instances.get(component) || null;
},
// @internal
__setInstance(component, instance) {
__instances.set(component, instance);
},
// @internal
__deleteInstance(component) {
__instances.delete(component);
}
};
{
devtoolsRegisterI18n(i18n, VERSION);
}
return i18n;
}
/**
* Use Composition API for Vue I18n
*
* @param options - An options, see {@link UseI18nOptions}
*
* @returns {@link Composer} instance
*
* @remarks
* This function is mainly used by `setup`.
*
* If options are specified, Composer instance is created for each component and you can be localized on the component.
*
* If options are not specified, you can be localized using the global Composer.
*
* @example
* case: Component resource base localization
* ```html
* <template>
* <form>
* <label>{{ t('language') }}</label>
* <select v-model="locale">
* <option value="en">en</option>
* <option value="ja">ja</option>
* </select>
* </form>
* <p>message: {{ t('hello') }}</p>
* </template>
*
* <script>
* import { useI18n } from 'vue-i18n'
*
* export default {
* setup() {
* const { t, locale } = useI18n({
* locale: 'ja',
* messages: {
* en: { ... },
* ja: { ... }
* }
* })
* // Something to do ...
*
* return { ..., t, locale }
* }
* }
* </script>
* ```
*
* @VueI18nComposition
*/
function useI18n(options = {}) {
const instance = getCurrentInstance();
if (instance == null) {
throw createI18nError(14 /* MUST_BE_CALL_SETUP_TOP */);
}
if (!instance.appContext.app.__VUE_I18N_SYMBOL__) {
throw createI18nError(15 /* NOT_INSLALLED */);
}
const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__);
/* istanbul ignore if */
if (!i18n) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
// prettier-ignore
const global = i18n.mode === 'composition'
? i18n.global
: i18n.global.__composer;
// prettier-ignore
const scope = isEmptyObject(options)
? ('__i18n' in instance.type)
? 'local'
: 'global'
: !options.useScope
? 'local'
: options.useScope;
if (scope === 'global') {
let messages = isObject(options.messages) ? options.messages : {};
if ('__i18nGlobal' in instance.type) {
messages = getLocaleMessages(global.locale.value, {
messages,
__i18n: instance.type.__i18nGlobal
});
}
// merge locale messages
const locales = Object.keys(messages);
if (locales.length) {
locales.forEach(locale => {
global.mergeLocaleMessage(locale, messages[locale]);
});
}
// merge datetime formats
if (isObject(options.datetimeFormats)) {
const locales = Object.keys(options.datetimeFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]);
});
}
}
// merge number formats
if (isObject(options.numberFormats)) {
const locales = Object.keys(options.numberFormats);
if (locales.length) {
locales.forEach(locale => {
global.mergeNumberFormat(locale, options.numberFormats[locale]);
});
}
}
return global;
}
if (scope === 'parent') {
let composer = getComposer$1(i18n, instance);
if (composer == null) {
{
warn(getWarnMessage$1(12 /* NOT_FOUND_PARENT_SCOPE */));
}
composer = global;
}
return composer;
}
// scope 'local' case
if (i18n.mode === 'legacy') {
throw createI18nError(16 /* NOT_AVAILABLE_IN_LEGACY_MODE */);
}
const i18nInternal = i18n;
let composer = i18nInternal.__getInstance(instance);
if (composer == null) {
const type = instance.type;
const composerOptions = {
...options
};
if (type.__i18n) {
composerOptions.__i18n = type.__i18n;
}
if (global) {
composerOptions.__root = global;
}
composer = createComposer(composerOptions);
setupLifeCycle(i18nInternal, instance, composer);
i18nInternal.__setInstance(instance, composer);
}
return composer;
}
function getComposer$1(i18n, target) {
let composer = null;
const root = target.root;
let current = target.parent;
while (current != null) {
const i18nInternal = i18n;
if (i18n.mode === 'composition') {
composer = i18nInternal.__getInstance(current);
}
else {
const vueI18n = i18nInternal.__getInstance(current);
if (vueI18n != null) {
composer = vueI18n
.__composer;
}
}
if (composer != null) {
break;
}
if (root === current) {
break;
}
current = current.parent;
}
return composer;
}
function setupLifeCycle(i18n, target, composer) {
let emitter = null;
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (
target.vnode.el) {
target.vnode.el.__INTLIFY__ = composer;
emitter = createEmitter();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[EnableEmitter] && _composer[EnableEmitter](emitter);
emitter.on('*', addTimelineEvent);
}
}, target);
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (
target.vnode.el &&
target.vnode.el.__INTLIFY__) {
emitter && emitter.off('*', addTimelineEvent);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer;
_composer[DisableEmitter] && _composer[DisableEmitter]();
delete target.vnode.el.__INTLIFY__;
}
i18n.__deleteInstance(target);
}, target);
}
const globalExportProps = [
'locale',
'fallbackLocale',
'availableLocales'
];
const globalExportMethods = ['t', 'd', 'n', 'tm'];
function injectGlobalFields(app, composer) {
const i18n = Object.create(null);
globalExportProps.forEach(prop => {
const desc = Object.getOwnPropertyDescriptor(composer, prop);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
const wrap = isRef(desc.value) // check computed props
? {
get() {
return desc.value.value;
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
set(val) {
desc.value.value = val;
}
}
: {
get() {
return desc.get && desc.get();
}
};
Object.defineProperty(i18n, prop, wrap);
});
app.config.globalProperties.$i18n = i18n;
globalExportMethods.forEach(method => {
const desc = Object.getOwnPropertyDescriptor(composer, method);
if (!desc) {
throw createI18nError(20 /* UNEXPECTED_ERROR */);
}
Object.defineProperty(app.config.globalProperties, `$${method}`, desc);
});
}
// register message compiler at vue-i18n
registerMessageCompiler(compileToFunction);
initDev();
export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
| cdnjs/cdnjs | ajax/libs/vue-i18n/9.0.0-beta.13/vue-i18n.esm-browser.js | JavaScript | mit | 168,066 |
export default {
name: 'selfie-card',
type: 'text',
render() {
return '[ :) ]';
}
};
| atonse/mobiledoc-kit | demo/app/mobiledoc-cards/text/selfie.js | JavaScript | mit | 97 |
/* global describe, it */
var assert = require('assert')
var constantCase = require('./')
describe('constant case', function () {
it('should upper case a single word', function () {
assert.equal(constantCase('test'), 'TEST')
assert.equal(constantCase('TEST'), 'TEST')
})
it('should constant case regular sentence cased strings', function () {
assert.equal(constantCase('test string'), 'TEST_STRING')
assert.equal(constantCase('Test String'), 'TEST_STRING')
})
it('should constant case non-alphanumeric separators', function () {
assert.equal(constantCase('dot.case'), 'DOT_CASE')
assert.equal(constantCase('path/case'), 'PATH_CASE')
})
it('should constant case pascal cased strings', function () {
assert.equal(constantCase('TestString'), 'TEST_STRING')
})
it('should support locales', function () {
assert.equal(constantCase('myString', 'tr'), 'MY_STRİNG')
})
})
| blakeembrey/constant-case | test.js | JavaScript | mit | 922 |
(function($){
$.fn.onImagesLoaded = function(_cb,_ca) {
return this.each(function() {
var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this),
_cont = this,
i = 0,
_loading=function() {
if( typeof _cb === 'function') _cb(_cont);
},
_done=function() {
if( typeof _ca === 'function' ) _ca(_cont);
};
if( $imgs.length ) {
$imgs.each(function() {
var _img = this;
_loading();
$(_img).load(function(){
_done();
});
});
}
});
}
})(jQuery) | flashycud/timestack | static/js/lib.js | JavaScript | mit | 614 |
// Generated from ./Select.g4 by ANTLR 4.5
// jshint ignore: start
var antlr4 = require('../../index');
var serializedATN = ["\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd",
"\2\17\177\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t",
"\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3",
"\2\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3",
"\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3",
"\n\5\nD\n\n\3\13\3\13\3\13\3\f\5\fJ\n\f\3\f\6\fM\n\f\r\f\16\fN\3\f\7",
"\fR\n\f\f\f\16\fU\13\f\3\f\7\fX\n\f\f\f\16\f[\13\f\3\f\3\f\3\f\3\f\3",
"\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\7\fl\n\f\f\f\16\fo\13\f\3",
"\f\5\fr\n\f\3\r\6\ru\n\r\r\r\16\rv\3\16\6\16z\n\16\r\16\16\16{\3\16",
"\3\16\3m\2\17\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31",
"\16\33\17\3\2\7\4\2--//\3\2\62;\3\2\60\60\5\2C\\aac|\5\2\13\f\17\17",
"\"\"\u008d\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2",
"\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2",
"\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35\3\2\2\2\5$\3\2\2\2\7&\3",
"\2\2\2\t(\3\2\2\2\13*\3\2\2\2\r/\3\2\2\2\17\63\3\2\2\2\21\66\3\2\2\2",
"\23C\3\2\2\2\25E\3\2\2\2\27q\3\2\2\2\31t\3\2\2\2\33y\3\2\2\2\35\36\7",
"u\2\2\36\37\7g\2\2\37 \7n\2\2 !\7g\2\2!\"\7e\2\2\"#\7v\2\2#\4\3\2\2",
"\2$%\7.\2\2%\6\3\2\2\2&\'\7*\2\2\'\b\3\2\2\2()\7+\2\2)\n\3\2\2\2*+\7",
"h\2\2+,\7t\2\2,-\7q\2\2-.\7o\2\2.\f\3\2\2\2/\60\7c\2\2\60\61\7p\2\2",
"\61\62\7f\2\2\62\16\3\2\2\2\63\64\7q\2\2\64\65\7t\2\2\65\20\3\2\2\2",
"\66\67\7y\2\2\678\7j\2\289\7g\2\29:\7t\2\2:;\7g\2\2;\22\3\2\2\2<D\7",
">\2\2=>\7>\2\2>D\7?\2\2?D\7@\2\2@A\7@\2\2AD\7?\2\2BD\7?\2\2C<\3\2\2",
"\2C=\3\2\2\2C?\3\2\2\2C@\3\2\2\2CB\3\2\2\2D\24\3\2\2\2EF\7k\2\2FG\7",
"p\2\2G\26\3\2\2\2HJ\t\2\2\2IH\3\2\2\2IJ\3\2\2\2JL\3\2\2\2KM\t\3\2\2",
"LK\3\2\2\2MN\3\2\2\2NL\3\2\2\2NO\3\2\2\2OS\3\2\2\2PR\t\4\2\2QP\3\2\2",
"\2RU\3\2\2\2SQ\3\2\2\2ST\3\2\2\2TY\3\2\2\2US\3\2\2\2VX\t\3\2\2WV\3\2",
"\2\2X[\3\2\2\2YW\3\2\2\2YZ\3\2\2\2Zr\3\2\2\2[Y\3\2\2\2\\]\7v\2\2]^\7",
"t\2\2^_\7w\2\2_r\7g\2\2`a\7h\2\2ab\7c\2\2bc\7n\2\2cd\7u\2\2dr\7g\2\2",
"ef\7p\2\2fg\7w\2\2gh\7n\2\2hr\7n\2\2im\7)\2\2jl\13\2\2\2kj\3\2\2\2l",
"o\3\2\2\2mn\3\2\2\2mk\3\2\2\2np\3\2\2\2om\3\2\2\2pr\7)\2\2qI\3\2\2\2",
"q\\\3\2\2\2q`\3\2\2\2qe\3\2\2\2qi\3\2\2\2r\30\3\2\2\2su\t\5\2\2ts\3",
"\2\2\2uv\3\2\2\2vt\3\2\2\2vw\3\2\2\2w\32\3\2\2\2xz\t\6\2\2yx\3\2\2\2",
"z{\3\2\2\2{y\3\2\2\2{|\3\2\2\2|}\3\2\2\2}~\b\16\2\2~\34\3\2\2\2\f\2",
"CINSYmqv{\3\b\2\2"].join("");
var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);
var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });
function SelectLexer(input) {
antlr4.Lexer.call(this, input);
this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache());
return this;
}
SelectLexer.prototype = Object.create(antlr4.Lexer.prototype);
SelectLexer.prototype.constructor = SelectLexer;
SelectLexer.EOF = antlr4.Token.EOF;
SelectLexer.T__0 = 1;
SelectLexer.T__1 = 2;
SelectLexer.T__2 = 3;
SelectLexer.T__3 = 4;
SelectLexer.T__4 = 5;
SelectLexer.T__5 = 6;
SelectLexer.T__6 = 7;
SelectLexer.T__7 = 8;
SelectLexer.OPERATOR = 9;
SelectLexer.ARRAYOPERATOR = 10;
SelectLexer.CONSTANT = 11;
SelectLexer.FIELD = 12;
SelectLexer.WS = 13;
SelectLexer.modeNames = [ "DEFAULT_MODE" ];
SelectLexer.literalNames = [ 'null', "'select'", "','", "'('", "')'", "'from'",
"'and'", "'or'", "'where'", 'null', "'in'" ];
SelectLexer.symbolicNames = [ 'null', 'null', 'null', 'null', 'null', 'null',
'null', 'null', 'null', "OPERATOR", "ARRAYOPERATOR",
"CONSTANT", "FIELD", "WS" ];
SelectLexer.ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5",
"T__6", "T__7", "OPERATOR", "ARRAYOPERATOR", "CONSTANT",
"FIELD", "WS" ];
SelectLexer.grammarFileName = "Select.g4";
exports.SelectLexer = SelectLexer;
| bvellacott/papu-force-adapter | lib/antlr4/parsers/select/SelectLexer.js | JavaScript | mit | 4,185 |
import styled from 'styled-components';
const Wrapper = styled.div`
width: 100%;
height: 100%;
display: block;
align-items: space-between;
`;
export default Wrapper;
| andyfrith/weather.goodapplemedia.com | app/containers/ForecastListItem/Wrapper.js | JavaScript | mit | 176 |
module.exports={
setup(context, cb){
//context.sigslot.signalAt('* * * * * *', 'sayHello')
cb()
},
sep(msg,next){
console.log(msg); return next()
},
route(req, next){
switch(req.method){
case 'POST': return next()
case 'GET': this.setOutput(this.time)
default: return next(null, this.sigslot.abort())
}
},
help(next){
next(this.error(404, `api ${this.api} is not supported yet`))
},
sayNow(next){
console.log(Date.now())
next()
}
}
| ldarren/pico-api | test/util.js | JavaScript | mit | 464 |
/***********************************************
* MIT License
*
* Copyright (c) 2016 珠峰课堂,Ramroll
* 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.
*
*/
export * from "./ZButton"
export * from "./BButton"
export * from "./navbar/ZNavbar"
export * from "./tabbar/Tabbar"
export * from "./tabbar/TabbarItem"
export * from "./ZBottomButton"
export * from "./NetworkError"
export * from "./CourseCardBig"
export * from "./CourseCardSmall"
export * from "./ZInput"
export * from "./ZSwitch"
export * from "./ZVCode"
export * from "./ZImgCode"
export * from "./NavBar"
export * from "./HomeMenuView"
export * from "./HomeMenuItem"
export * from "./HomeGridView"
export * from "./HomeGridItem"
export * from "./QrImage"
| njxiaohan/TransPal | app/domain/component/index.js | JavaScript | mit | 1,752 |
goog.provide('ngeo.CreatefeatureController');
goog.provide('ngeo.createfeatureDirective');
goog.require('ngeo');
goog.require('ngeo.EventHelper');
/** @suppress {extraRequire} */
goog.require('ngeo.filters');
goog.require('ngeo.interaction.MeasureArea');
goog.require('ngeo.interaction.MeasureLength');
goog.require('ol.Feature');
goog.require('ol.geom.GeometryType');
goog.require('ol.interaction.Draw');
goog.require('ol.style.Style');
/**
* A directive used to draw vector features of a single geometry type using
* either a 'draw' or 'measure' interaction. Once a feature is finished being
* drawn, it is added to a collection of features.
*
* The geometry types supported are:
* - Point
* - LineString
* - Polygon
*
* Example:
*
* <a
* href
* translate
* ngeo-btn
* ngeo-createfeature
* ngeo-createfeature-active="ctrl.createPointActive"
* ngeo-createfeature-features="ctrl.features"
* ngeo-createfeature-geom-type="ctrl.pointGeomType"
* ngeo-createfeature-map="::ctrl.map"
* class="btn btn-default ngeo-createfeature-point"
* ng-class="{active: ctrl.createPointActive}"
* ng-model="ctrl.createPointActive">
* </a>
*
* @htmlAttribute {boolean} ngeo-createfeature-active Whether the directive is
* active or not.
* @htmlAttribute {ol.Collection} ngeo-createfeature-features The collection of
* features where to add those created by this directive.
* @htmlAttribute {string} ngeo-createfeature-geom-type Determines the type
* of geometry this directive should draw.
* @htmlAttribute {ol.Map} ngeo-createfeature-map The map.
* @return {angular.Directive} The directive specs.
* @ngInject
* @ngdoc directive
* @ngname ngeoCreatefeature
*/
ngeo.createfeatureDirective = function() {
return {
controller: 'ngeoCreatefeatureController as cfCtrl',
bindToController: true,
scope: {
'active': '=ngeoCreatefeatureActive',
'features': '=ngeoCreatefeatureFeatures',
'geomType': '=ngeoCreatefeatureGeomType',
'map': '=ngeoCreatefeatureMap'
}
};
};
ngeo.module.directive('ngeoCreatefeature', ngeo.createfeatureDirective);
/**
* @param {gettext} gettext Gettext service.
* @param {angular.$compile} $compile Angular compile service.
* @param {angular.$filter} $filter Angular filter
* @param {!angular.Scope} $scope Scope.
* @param {angular.$timeout} $timeout Angular timeout service.
* @param {ngeo.EventHelper} ngeoEventHelper Ngeo event helper service
* @constructor
* @struct
* @ngInject
* @ngdoc controller
* @ngname ngeoCreatefeatureController
*/
ngeo.CreatefeatureController = function(gettext, $compile, $filter, $scope,
$timeout, ngeoEventHelper) {
/**
* @type {boolean}
* @export
*/
this.active = this.active === true;
/**
* @type {ol.Collection.<ol.Feature>|ol.source.Vector}
* @export
*/
this.features;
/**
* @type {string}
* @export
*/
this.geomType;
/**
* @type {ol.Map}
* @export
*/
this.map;
/**
* @type {angular.$timeout}
* @private
*/
this.timeout_ = $timeout;
/**
* @type {ngeo.EventHelper}
* @private
*/
this.ngeoEventHelper_ = ngeoEventHelper;
// Create the draw or measure interaction depending on the geometry type
var interaction;
var helpMsg;
var contMsg;
if (this.geomType === ngeo.GeometryType.POINT ||
this.geomType === ngeo.GeometryType.MULTI_POINT
) {
interaction = new ol.interaction.Draw({
type: ol.geom.GeometryType.POINT
});
} else if (this.geomType === ngeo.GeometryType.LINE_STRING ||
this.geomType === ngeo.GeometryType.MULTI_LINE_STRING
) {
helpMsg = gettext('Click to start drawing length');
contMsg = gettext(
'Click to continue drawing<br/>' +
'Double-click or click last point to finish'
);
interaction = new ngeo.interaction.MeasureLength(
$filter('ngeoUnitPrefix'),
{
style: new ol.style.Style(),
startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0],
continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0]
}
);
} else if (this.geomType === ngeo.GeometryType.POLYGON ||
this.geomType === ngeo.GeometryType.MULTI_POLYGON
) {
helpMsg = gettext('Click to start drawing area');
contMsg = gettext(
'Click to continue drawing<br/>' +
'Double-click or click starting point to finish'
);
interaction = new ngeo.interaction.MeasureArea(
$filter('ngeoUnitPrefix'),
{
style: new ol.style.Style(),
startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0],
continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0]
}
);
}
goog.asserts.assert(interaction);
interaction.setActive(this.active);
this.map.addInteraction(interaction);
/**
* The draw or measure interaction responsible of drawing the vector feature.
* The actual type depends on the geometry type.
* @type {ol.interaction.Interaction}
* @private
*/
this.interaction_ = interaction;
// == Event listeners ==
$scope.$watch(
function() {
return this.active;
}.bind(this),
function(newVal) {
this.interaction_.setActive(newVal);
}.bind(this)
);
var uid = ol.getUid(this);
if (interaction instanceof ol.interaction.Draw) {
this.ngeoEventHelper_.addListenerKey(
uid,
ol.events.listen(
interaction,
ol.interaction.Draw.EventType.DRAWEND,
this.handleDrawEnd_,
this
),
true
);
} else if (interaction instanceof ngeo.interaction.MeasureLength ||
interaction instanceof ngeo.interaction.MeasureArea) {
this.ngeoEventHelper_.addListenerKey(
uid,
ol.events.listen(
interaction,
ngeo.MeasureEventType.MEASUREEND,
this.handleDrawEnd_,
this
),
true
);
}
$scope.$on('$destroy', this.handleDestroy_.bind(this));
};
/**
* Called when a feature is finished being drawn. Add the feature to the
* collection.
* @param {ol.interaction.Draw.Event|ngeo.MeasureEvent} event Event.
* @export
*/
ngeo.CreatefeatureController.prototype.handleDrawEnd_ = function(event) {
var feature = new ol.Feature(event.feature.getGeometry());
if (this.features instanceof ol.Collection) {
this.features.push(feature);
} else {
this.features.addFeature(feature);
}
};
/**
* Cleanup event listeners and remove the interaction from the map.
* @private
*/
ngeo.CreatefeatureController.prototype.handleDestroy_ = function() {
this.timeout_(function() {
var uid = ol.getUid(this);
this.ngeoEventHelper_.clearListenerKey(uid);
this.interaction_.setActive(false);
this.map.removeInteraction(this.interaction_);
}.bind(this), 0);
};
ngeo.module.controller(
'ngeoCreatefeatureController', ngeo.CreatefeatureController);
| ger-benjamin/ngeo | src/directives/createfeature.js | JavaScript | mit | 6,955 |
Mini.define('layerTemplate', function(){
var $detail = $('#t-detail').html()
return {
detail: _.template($detail)
}
});
Mini.define('serviceLayer', [
'layerTemplate'
], function(layerTemplate){
return {
ctn: function(e) {
layer.open({
title: '箱动态列表',
type: 1,
skin: 'layui-layer-rim my-layer-skin', //加上边框
area: ['480px', 'auto'], //宽高
content: layerTemplate.detail(e.data)
})
}
}
}) | hoozi/hyd2 | js/site/components/serviceLayer.js | JavaScript | mit | 559 |
/**
* @author Richard Davey <[email protected]>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Internal function to process the separation of a physics body from a tile.
*
* @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationX
* @since 3.0.0
*
* @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
* @param {number} x - The x separation amount.
*/
var ProcessTileSeparationX = function (body, x)
{
if (x < 0)
{
body.blocked.left = true;
}
else if (x > 0)
{
body.blocked.right = true;
}
body.position.x -= x;
if (body.bounce.x === 0)
{
body.velocity.x = 0;
}
else
{
body.velocity.x = -body.velocity.x * body.bounce.x;
}
};
module.exports = ProcessTileSeparationX;
| rblopes/phaser | src/physics/arcade/tilemap/ProcessTileSeparationX.js | JavaScript | mit | 901 |
export function mergeUsers({ props, state, uuid }) {
if (props.response.result.users && props.response.result.users.length !== 0) {
let orderKey = 1
for (const user of props.response.result.users) {
user.orderKey = orderKey
const usersInState = state.get('admin.users')
const uidInState = Object.keys(usersInState).filter((uid) => {
return usersInState[uid].email === user.email
})[0]
if (uidInState) {
state.merge(`admin.users.${uidInState}`, user)
} else {
state.set(`admin.users.${uuid()}`, user)
}
orderKey++
}
} else {
return { noUsersFound: true }
}
}
export function getNextPage({ props, state }) {
let nextPage = 1
switch (props.nextPage) {
case 'previous':
nextPage = parseInt(state.get('admin.currentPage')) - 1
break
case 'next':
nextPage = parseInt(state.get('admin.currentPage')) + 1
break
case 'last':
nextPage = state.get('admin.pages')
break
default:
if (typeof props.nextPage === 'number') {
nextPage = Math.floor(props.nextPage)
}
}
return { nextPage }
}
| yacoma/auth-boilerplate | client/app/modules/admin/actions.js | JavaScript | mit | 1,148 |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { customElement, html, LitElement, property, } from "lit-element";
import { fireEvent } from "./util/fire-event";
import { getMouseTouchLocation } from "./util/get-mouse-touch-location";
import { getTouchIdentifier } from "./util/get-touch-identifier";
import { matchesSelectorAndParentsTo } from "./util/match-selector";
let LitDraggable = class LitDraggable extends LitElement {
constructor() {
super(...arguments);
this.disabled = false;
this._dragging = false;
}
firstUpdated() {
this.addEventListener("mousedown", this._dragStart.bind(this), {
capture: true,
passive: false,
});
this.addEventListener("touchstart", this._dragStart.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("mousemove", this._drag.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchmove", this._drag.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("mouseup", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchcancel", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchend", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
}
render() {
return html `<slot></slot>`;
}
_dragStart(ev) {
if ((ev.type.startsWith("mouse") && ev.button !== 0) ||
this.disabled) {
return;
}
console.log(ev);
if (this.handle &&
!matchesSelectorAndParentsTo(ev.currentTarget, this.handle, this.offsetParent)) {
return;
}
ev.preventDefault();
ev.stopPropagation();
if (ev.type === "touchstart") {
this._touchIdentifier = getTouchIdentifier(ev);
}
const pos = getMouseTouchLocation(ev, this._touchIdentifier);
if (!pos) {
return;
}
this.startX = pos.x;
this.startY = pos.y;
this._dragging = true;
fireEvent(this, "dragStart", {
startX: this.startX,
startY: this.startY,
});
}
_drag(ev) {
if (!this._dragging || this.disabled) {
return;
}
ev.preventDefault();
ev.stopPropagation();
const pos = getMouseTouchLocation(ev, this._touchIdentifier);
if (!pos) {
return;
}
let deltaX = pos.x - this.startX;
let deltaY = pos.y - this.startY;
if (this.grid) {
deltaX = Math.round(deltaX / this.grid[0]) * this.grid[0];
deltaY = Math.round(deltaY / this.grid[1]) * this.grid[1];
}
if (!deltaX && !deltaY) {
return;
}
fireEvent(this, "dragging", {
deltaX,
deltaY,
});
}
_dragEnd(ev) {
if (!this._dragging || this.disabled) {
return;
}
ev.preventDefault();
ev.stopPropagation();
this._touchIdentifier = undefined;
this._dragging = false;
fireEvent(this, "dragEnd");
}
};
__decorate([
property({ type: Array })
], LitDraggable.prototype, "grid", void 0);
__decorate([
property({ type: Boolean, reflect: true })
], LitDraggable.prototype, "disabled", void 0);
__decorate([
property()
], LitDraggable.prototype, "handle", void 0);
LitDraggable = __decorate([
customElement("lit-draggable")
], LitDraggable);
export { LitDraggable };
//# sourceMappingURL=lit-draggable.js.map | cdnjs/cdnjs | ajax/libs/lit-grid-layout/1.1.4/lit-draggable.js | JavaScript | mit | 4,479 |
'use strict';
var Lab = require('lab'),
Hapi = require('hapi'),
Plugin = require('../../../lib/plugins/sugendran');
var describe = Lab.experiment;
var it = Lab.test;
var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
describe('sugendran', function() {
var server = new Hapi.Server();
it('Plugin successfully loads', function(done) {
server.pack.register(Plugin, function(err) {
expect(err).to.not.exist;
done();
});
});
it('Plugin registers routes', function(done) {
var table = server.table();
expect(table).to.have.length(1);
expect(table[0].path).to.equal('/sugendran');
done();
});
it('Plugin route responses', function(done) {
var table = server.table();
expect(table).to.have.length(1);
expect(table[0].path).to.equal('/sugendran');
var request = {
method: 'GET',
url: '/sugendran'
};
server.inject(request, function(res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal('don\'t worry, be hapi!');
done();
});
});
});
| nvcexploder/hapi-lxjs | test/plugins/sugendran/index.js | JavaScript | mit | 1,090 |
import app from 'flarum/forum/app';
import { extend } from 'flarum/common/extend';
import DiscussionControls from 'flarum/forum/utils/DiscussionControls';
import DiscussionPage from 'flarum/forum/components/DiscussionPage';
import Button from 'flarum/common/components/Button';
export default function addStickyControl() {
extend(DiscussionControls, 'moderationControls', function (items, discussion) {
if (discussion.canSticky()) {
items.add(
'sticky',
Button.component(
{
icon: 'fas fa-thumbtack',
onclick: this.stickyAction.bind(discussion),
},
app.translator.trans(
discussion.isSticky()
? 'flarum-sticky.forum.discussion_controls.unsticky_button'
: 'flarum-sticky.forum.discussion_controls.sticky_button'
)
)
);
}
});
DiscussionControls.stickyAction = function () {
this.save({ isSticky: !this.isSticky() }).then(() => {
if (app.current.matches(DiscussionPage)) {
app.current.get('stream').update();
}
m.redraw();
});
};
}
| flarum/sticky | js/src/forum/addStickyControl.js | JavaScript | mit | 1,121 |
'use strict'
import assert from 'assert'
import { btoa } from 'Base64'
import decode from 'jwt-decode'
import token from './data/token'
import tokenTimezone from './data/token-timezone'
import ls from 'local-storage'
import bluebird from 'bluebird'
import sinon from 'sinon'
const setTokenExp = (timestamp) => {
// hacky adjustment of expiration of the token
const decoded = decode(token)
decoded.exp = timestamp / 1000
const [head, , sig] = token.split('.')
return `${head}.${btoa(JSON.stringify(decoded))}.${sig}`
}
describe('Token Store', () => {
const localStorageKey = 'coolKey'
let updatedToken
beforeEach(() => {
// HACK around https://github.com/auth0/jwt-decode/issues/5
global.window = global
// HACK around cookie monster returning undefined when document isn't there
global.document = {}
})
beforeEach(() => {
updatedToken = setTokenExp(Date.now() + 1000)
})
afterEach(() => {
delete global.window
delete global.document
ls.remove(localStorageKey)
})
it('should set user after no token is present', () => {
const tokenStore = require('../src')()
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
tokenStore.setToken(token)
})
it('should get the token out of local storage', () => {
ls.set(localStorageKey, token)
const tokenStore = require('../src')({localStorageKey})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
})
it('should catch an exception token is not present in local storage', () => {
ls.set(localStorageKey, undefined)
const tokenStore = require('../src')({localStorageKey})
tokenStore.on('Token received', assert.fail)
tokenStore.init()
})
it('if no token call refresh & set token', done => {
const tokenStore = require('../src')({refresh: () =>
bluebird.resolve(updatedToken)
})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
done()
})
tokenStore.init()
})
it('if token is expired, call refresh with expired token', done => {
ls.set(localStorageKey, token)
require('../src')({
localStorageKey,
refresh: (t) => {
assert.equal(t, token)
done()
return bluebird.resolve(updatedToken)
}
}).init()
})
it('if token is expired, call refresh & set token', done => {
ls.set(localStorageKey, token)
const tokenStore = require('../src')({
localStorageKey,
refresh: () =>
bluebird.resolve(updatedToken)
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
if (++callCount === 2) { done() }
})
tokenStore.init()
})
it('if token valid, leave as is', () => {
ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000))
const tokenStore = require('../src')({
localStorageKey,
refresh: () => assert.fail('should not be called')
})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
})
it('if token to expire soon, refresh after interval', done => {
ls.set(localStorageKey, updatedToken)
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(updatedToken),
refreshInterval: 1000
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
if (++callCount === 2) { done() }
})
tokenStore.init()
})
describe('with fake timers', () => {
let clock
beforeEach(() => {
clock = sinon.useFakeTimers()
})
afterEach(() => {
clock.restore()
})
it('doesn\'t refresh if still outside the expiry window', () => {
ls.set(localStorageKey, updatedToken)
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(updatedToken),
expiryWindow: 1,
refreshInterval: 10
})
const spy = sinon.spy()
tokenStore.on('Token received', spy)
tokenStore.init()
clock.tick(11)
assert.equal(spy.callCount, 1)
})
})
it('refreshes the token and sets it', done => {
ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000))
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(tokenTimezone)
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
callCount++
if (callCount === 1) {
assert(!user.timezone)
} else if (callCount === 2) {
assert.equal(user.timezone, 'UTC')
done()
} else {
assert.fail('shouldn\'t be called more than twice')
}
})
tokenStore.init()
tokenStore.refreshToken()
})
describe('sad path', () => {
it('should not blow up when cookie is not present', () => {
let tokenStore
assert.doesNotThrow(() => tokenStore = require('../src')())
assert.doesNotThrow(() => tokenStore.init())
})
it('should not blow up when cookie is invalid', () => {
const token = 'g4rBaG3'
require('cookie-monster').set('XSRF-TOKEN', token)
let tokenStore
assert.doesNotThrow(() => tokenStore = require('../src')())
assert.doesNotThrow(() => tokenStore.init())
})
})
describe('default cookie key', () => {
let tokenFromStore
let user
beforeEach(() => {
require('cookie-monster').set('XSRF-TOKEN', token)
const tokenStore = require('../src')()
tokenStore.on('Token received', (t, u) => {
tokenFromStore = t
user = u
})
tokenStore.init()
})
it('should get the XSRF-TOKEN and return it', () => {
assert.equal(tokenFromStore, token)
})
it('should return user', () => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
})
describe('override cookie key', () => {
let tokenFromStore
beforeEach(() => {
require('cookie-monster').set('NOT-XSRF-TOKEN', token)
const tokenStore = require('../src')({ cookie: 'NOT-XSRF-TOKEN' })
tokenStore.on('Token received', (t) => {
tokenFromStore = t
})
tokenStore.init()
})
it('should get the NOT-XSRF-TOKEN and return it', () => {
assert.equal(tokenFromStore, token)
})
})
describe('terminate', () => {
let cookieMonster
beforeEach(() => {
cookieMonster = require('cookie-monster')
cookieMonster.set('XSRF-TOKEN', token)
})
it('should set token to undefined on explicit termination', done => {
let callCount = 0
const tokenStore = require('../src')({
refresh: (t) => {
if (callCount === 0) {
cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'})
assert.equal(t, token)
}
if (callCount === 1) {
assert.equal(t, undefined)
}
callCount++
return bluebird.resolve(t)
}
})
tokenStore.init()
tokenStore.terminate()
tokenStore.refreshToken()
done()
})
it('should not set token to undefined when no explicit termination', done => {
let callCount = 0
const tokenStore = require('../src')({
refresh: (t) => {
if (!t) {
return bluebird.resolve()
}
if (callCount === 0) {
cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'})
assert.equal(t, token)
}
if (callCount === 1) {
assert.equal(t, token)
}
callCount++
return bluebird.resolve(t)
}
})
tokenStore.init()
tokenStore.refreshToken()
done()
})
})
})
| lanetix/react-jwt-store | test/index.js | JavaScript | mit | 8,273 |
'use strict';
module.exports = function(grunt) {
require('jit-grunt')(grunt, {
});
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
grunt.initConfig({});
// Automatically inject Bower components into the app
grunt.config.set('wiredep', {
target: {
src: 'src/client/index.html',
ignorePath: '',
exclude: []
}
});
}; | mcortesi/artviz | Gruntfile.js | JavaScript | mit | 408 |
const angular = require('angular');
require('angular-ui-router');
require('bootstrap');
require('bootstrap/dist/css/bootstrap.css');
require('./config');
require('./services');
require('./filters');
require('./layout');
require('./list');
require('./detail');
require('./watchlist');
window.app = angular.module('app', [
'ui.router',
'app.config',
'app.filters',
'app.services',
'app.layout',
'app.list',
'app.watchlist',
'app.detail'
]);
| SCThijsse/angularjs-single-page | app/index.js | JavaScript | mit | 457 |
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const ExtraWatchWebpackPlugin = require('extra-watch-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VERSION = require('./package.json').version;
class VersionFilePlugin {
apply() {
fs.writeFileSync(
path.resolve(__dirname, 'lib/mol-plugin/version.js'),
`export var PLUGIN_VERSION = '${VERSION}';\nexport var PLUGIN_VERSION_DATE = new Date(typeof __MOLSTAR_DEBUG_TIMESTAMP__ !== 'undefined' ? __MOLSTAR_DEBUG_TIMESTAMP__ : ${new Date().valueOf()});`);
}
}
const sharedConfig = {
module: {
rules: [
{
test: /\.(html|ico)$/,
use: [{
loader: 'file-loader',
options: { name: '[name].[ext]' }
}]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: false } },
{ loader: 'sass-loader', options: { sourceMap: false } },
]
}
]
},
plugins: [
new ExtraWatchWebpackPlugin({
files: [
'./lib/**/*.scss',
'./lib/**/*.html'
],
}),
new webpack.DefinePlugin({
'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
'__MOLSTAR_DEBUG_TIMESTAMP__': webpack.DefinePlugin.runtimeValue(() => `${new Date().valueOf()}`, true)
}),
new MiniCssExtractPlugin({ filename: 'molstar.css' }),
new VersionFilePlugin(),
],
resolve: {
modules: [
'node_modules',
path.resolve(__dirname, 'lib/')
],
fallback: {
fs: false,
crypto: require.resolve('crypto-browserify'),
path: require.resolve('path-browserify'),
stream: require.resolve('stream-browserify'),
}
},
watchOptions: {
aggregateTimeout: 750
}
};
function createEntry(src, outFolder, outFilename, isNode) {
return {
target: isNode ? 'node' : void 0,
entry: path.resolve(__dirname, `lib/${src}.js`),
output: { filename: `${outFilename}.js`, path: path.resolve(__dirname, `build/${outFolder}`) },
...sharedConfig
};
}
function createEntryPoint(name, dir, out, library) {
return {
entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
output: { filename: `${library || name}.js`, path: path.resolve(__dirname, `build/${out}`), library: library || out, libraryTarget: 'umd' },
...sharedConfig
};
}
function createNodeEntryPoint(name, dir, out) {
return {
target: 'node',
entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
externals: {
argparse: 'require("argparse")',
'node-fetch': 'require("node-fetch")',
'util.promisify': 'require("util.promisify")',
xhr2: 'require("xhr2")',
},
...sharedConfig
};
}
function createApp(name, library) { return createEntryPoint('index', `apps/${name}`, name, library); }
function createExample(name) { return createEntry(`examples/${name}/index`, `examples/${name}`, 'index'); }
function createBrowserTest(name) { return createEntryPoint(name, 'tests/browser', 'tests'); }
function createNodeApp(name) { return createNodeEntryPoint('index', `apps/${name}`, name); }
module.exports = {
createApp,
createEntry,
createExample,
createBrowserTest,
createNodeEntryPoint,
createNodeApp
};
| molstar/molstar | webpack.config.common.js | JavaScript | mit | 3,792 |
{
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var contentTable = new WeakMap();
var templateContentsOwnerTable = new WeakMap();
function getTemplateContentsOwner(doc) {
if (!doc.defaultView) return doc;
var d = templateContentsOwnerTable.get(doc);
if (!d) {
d = doc.implementation.createHTMLDocument("");
while (d.lastChild) {
d.removeChild(d.lastChild);
}
templateContentsOwnerTable.set(doc, d);
}
return d;
}
function extractContent(templateElement) {
var doc = getTemplateContentsOwner(templateElement.ownerDocument);
var df = unwrap(doc.createDocumentFragment());
var child;
while ((child = templateElement.firstChild)) {
df.appendChild(child);
}
return df;
}
var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
function HTMLTemplateElement(node) {
HTMLElement.call(this, node);
if (!OriginalHTMLTemplateElement) {
var content = extractContent(node);
contentTable.set(this, wrap(content));
}
}
HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTemplateElement.prototype, {
constructor: HTMLTemplateElement,
get content() {
if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content);
return contentTable.get(this);
}
});
if (OriginalHTMLTemplateElement)
registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement);
scope.wrappers.HTMLTemplateElement = HTMLTemplateElement;
}
| stas-vilchik/bdd-ml | data/6744.js | JavaScript | mit | 1,705 |
import React from 'react';
import moment from 'moment';
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import isInclusivelyAfterDay from '../src/utils/isInclusivelyAfterDay';
import isSameDay from '../src/utils/isSameDay';
import SingleDatePickerWrapper from '../examples/SingleDatePickerWrapper';
const datesList = [
moment(),
moment().add(1, 'days'),
moment().add(3, 'days'),
moment().add(9, 'days'),
moment().add(10, 'days'),
moment().add(11, 'days'),
moment().add(12, 'days'),
moment().add(13, 'days'),
];
storiesOf('SDP - Day Props', module)
.add('default', withInfo()(() => (
<SingleDatePickerWrapper autoFocus />
)))
.add('allows all days, including past days', withInfo()(() => (
<SingleDatePickerWrapper
isOutsideRange={() => false}
autoFocus
/>
)))
.add('allows next two weeks only', withInfo()(() => (
<SingleDatePickerWrapper
isOutsideRange={day =>
!isInclusivelyAfterDay(day, moment()) ||
isInclusivelyAfterDay(day, moment().add(2, 'weeks'))
}
autoFocus
/>
)))
.add('with some blocked dates', withInfo()(() => (
<SingleDatePickerWrapper
isDayBlocked={day1 => datesList.some(day2 => isSameDay(day1, day2))}
autoFocus
/>
)))
.add('with some highlighted dates', withInfo()(() => (
<SingleDatePickerWrapper
isDayHighlighted={day1 => datesList.some(day2 => isSameDay(day1, day2))}
autoFocus
/>
)))
.add('blocks fridays', withInfo()(() => (
<SingleDatePickerWrapper
isDayBlocked={day => moment.weekdays(day.weekday()) === 'Friday'}
autoFocus
/>
)))
.add('with custom daily details', withInfo()(() => (
<SingleDatePickerWrapper
numberOfMonths={1}
renderDayContents={day => day.format('ddd')}
autoFocus
/>
)));
| airbnb/react-dates | stories/SingleDatePicker_day.js | JavaScript | mit | 1,865 |
window.onload = () => {
const root = new THREERoot({
fov: 60
});
root.renderer.setClearColor(0x222222);
root.camera.position.set(0, 0, 100);
let light = new THREE.DirectionalLight(0xffffff);
root.add(light);
light = new THREE.DirectionalLight(0xffffff);
light.position.z = 1;
root.add(light);
// mesh / skeleton based on https://threejs.org/docs/scenes/bones-browser.html
const segmentHeight = 8;
const segmentCount = 4;
const height = segmentHeight * segmentCount;
const halfHeight = height * 0.5;
const sizing = {
segmentHeight,
segmentCount,
height,
halfHeight
};
const bones = createBones(sizing);
const geometry = createGeometry(sizing);
const mesh = createMesh(geometry, bones);
const skeletonHelper = new THREE.SkeletonHelper(mesh);
root.add(skeletonHelper);
root.add(mesh);
let time = 0;
root.addUpdateCallback(() => {
time += (1/60);
mesh.material.uniforms.time.value = time % 1;
bones.forEach(bone => {
bone.rotation.z = Math.sin(time) * 0.25;
})
});
};
function createBones(sizing) {
const bones = [];
let prevBone = new THREE.Bone();
bones.push(prevBone);
prevBone.position.y = -sizing.halfHeight;
for (let i = 0; i < sizing.segmentCount; i++) {
const bone = new THREE.Bone();
bone.position.y = sizing.segmentHeight;
bones.push(bone);
prevBone.add(bone);
prevBone = bone;
}
return bones;
}
function createGeometry(sizing) {
let baseGeometry = new THREE.CylinderGeometry(
5, // radiusTop
5, // radiusBottom
sizing.height, // height
8, // radiusSegments
sizing.segmentCount * 4, // heightSegments
true // openEnded
);
baseGeometry = new THREE.Geometry().fromBufferGeometry(baseGeometry);
for (let i = 0; i < baseGeometry.vertices.length; i++) {
const vertex = baseGeometry.vertices[i];
const y = (vertex.y + sizing.halfHeight);
const skinIndex = Math.floor(y / sizing.segmentHeight);
const skinWeight = (y % sizing.segmentHeight) / sizing.segmentHeight;
// skinIndices = indices of up to 4 bones for the vertex to be influenced by
baseGeometry.skinIndices.push(new THREE.Vector4(skinIndex, skinIndex + 1, 0, 0));
// skinWeights = weights for each of the bones referenced by index above (between 0 and 1)
baseGeometry.skinWeights.push(new THREE.Vector4(1 - skinWeight, skinWeight, 0, 0));
}
// create a prefab for each vertex
const prefab = new THREE.TetrahedronGeometry(1);
const prefabCount = baseGeometry.vertices.length;
const geometry = new BAS.PrefabBufferGeometry(prefab, prefabCount);
// position (copy vertex position)
geometry.createAttribute('aPosition', 3, function(data, i) {
baseGeometry.vertices[i].toArray(data);
});
// skin indices, copy from geometry, based on vertex
geometry.createAttribute('skinIndex', 4, (data, i) => {
baseGeometry.skinIndices[i].toArray(data);
});
// skin weights, copy from geometry, based on vertex
geometry.createAttribute('skinWeight', 4, (data, i) => {
baseGeometry.skinWeights[i].toArray(data);
});
// rotation (this is completely arbitrary)
const axis = new THREE.Vector3();
geometry.createAttribute('aAxisAngle', 4, function(data, i) {
BAS.Utils.randomAxis(axis);
axis.toArray(data);
data[3] = Math.PI * 2;
});
return geometry;
}
function createMesh(geometry, bones) {
const material = new BAS.StandardAnimationMaterial({
skinning: true,
side: THREE.DoubleSide,
flatShading: true,
uniforms: {
time: {value: 0},
},
vertexParameters: `
uniform float time;
attribute vec3 aPosition;
attribute vec4 aAxisAngle;
`,
vertexFunctions: [
BAS.ShaderChunk.quaternion_rotation
],
vertexPosition: `
vec4 q = quatFromAxisAngle(aAxisAngle.xyz, aAxisAngle.w * time);
transformed = rotateVector(q, transformed);
transformed += aPosition;
`
});
const mesh = new THREE.SkinnedMesh(geometry, material);
const skeleton = new THREE.Skeleton(bones);
mesh.add(bones[0]);
mesh.bind(skeleton);
return mesh;
}
| zadvorsky/three.bas | examples/skinning_prefabs/main.js | JavaScript | mit | 4,231 |
define(function () {
return [
{"id": 10000, "val": 50.0599, "time": 1415891398900}, {"id": 20001, "val": 50.4109, "time": 1415891398903},
{"id": 30002, "val": 50.4229, "time": 1415891398906}, {"id": 40003, "val": 50.1401, "time": 1415891398909},
{"id": 50004, "val": 50.1459, "time": 1415891398911}, {"id": 60005, "val": 50.5555, "time": 1415891398916},
{"id": 70006, "val": 50.5947, "time": 1415891398923}, {"id": 80007, "val": 50.7543, "time": 1415891398930},
{"id": 90008, "val": 50.3839, "time": 1415891398932}, {"id": 100009, "val": 50.2778, "time": 1415891399491},
{"id": 110010, "val": 51.0419, "time": 1415891399495}, {"id": 120011, "val": 50.1882, "time": 1415891399498},
{"id": 130012, "val": 50.2117, "time": 1415891399500}, {"id": 140013, "val": 51.0445, "time": 1415891399503},
{"id": 150014, "val": 50.2197, "time": 1415891399506}, {"id": 160015, "val": 50.3786, "time": 1415891399508},
{"id": 170016, "val": 50.2214, "time": 1415891399513}, {"id": 180017, "val": 50.9234, "time": 1415891399524},
{"id": 190018, "val": 50.8945, "time": 1415891399530}, {"id": 200019, "val": 50.666, "time": 1415891400040},
{"id": 210020, "val": 50.405, "time": 1415891400044}, {"id": 220021, "val": 50.8956, "time": 1415891400046},
{"id": 230022, "val": 50.7253, "time": 1415891400049}, {"id": 240023, "val": 50.4591, "time": 1415891400051},
{"id": 250024, "val": 50.4498, "time": 1415891400054}, {"id": 260025, "val": 50.4777, "time": 1415891400056},
{"id": 270026, "val": 50.3059, "time": 1415891400059}, {"id": 280027, "val": 50.2074, "time": 1415891400067},
{"id": 290028, "val": 50.8433, "time": 1415891400074}, {"id": 300029, "val": 50.4162, "time": 1415891400584},
{"id": 310030, "val": 50.3363, "time": 1415891400589}, {"id": 320031, "val": 50.1961, "time": 1415891400592},
{"id": 330032, "val": 50.3535, "time": 1415891400595}, {"id": 340033, "val": 51.1318, "time": 1415891400598},
{"id": 350034, "val": 50.6912, "time": 1415891400600}, {"id": 360035, "val": 50.9208, "time": 1415891400603},
{"id": 370036, "val": 50.2145, "time": 1415891400608}, {"id": 380037, "val": 50.2154, "time": 1415891400616},
{"id": 390038, "val": 50.5988, "time": 1415891400624}, {"id": 400039, "val": 50.3584, "time": 1415891401135},
{"id": 410040, "val": 50.8205, "time": 1415891401140}, {"id": 420041, "val": 50.1177, "time": 1415891401143},
{"id": 430042, "val": 50.7813, "time": 1415891401146}, {"id": 440043, "val": 50.581, "time": 1415891401149},
{"id": 450044, "val": 50.6686, "time": 1415891401151}, {"id": 460045, "val": 49.8954, "time": 1415891401154},
{"id": 470046, "val": 49.9395, "time": 1415891401158}, {"id": 480047, "val": 50.3333, "time": 1415891401165},
{"id": 490048, "val": 50.8558, "time": 1415891401173}, {"id": 500049, "val": 50.5067, "time": 1415891401702},
{"id": 510050, "val": 51.25, "time": 1415891401706}, {"id": 520051, "val": 50.5817, "time": 1415891401709},
{"id": 530052, "val": 50.4937, "time": 1415891401711}, {"id": 540053, "val": 49.7284, "time": 1415891401715},
{"id": 550054, "val": 50.7721, "time": 1415891401717}, {"id": 560055, "val": 50.6962, "time": 1415891401720},
{"id": 570056, "val": 50.0773, "time": 1415891401726}, {"id": 580057, "val": 50.6731, "time": 1415891401735},
{"id": 590058, "val": 51.0415, "time": 1415891401737}, {"id": 600059, "val": 50.7093, "time": 1415891402230},
{"id": 610060, "val": 50.4527, "time": 1415891402235}, {"id": 620061, "val": 50.3383, "time": 1415891402238},
{"id": 630062, "val": 50.7638, "time": 1415891402241}, {"id": 640063, "val": 50.6515, "time": 1415891402245},
{"id": 650064, "val": 50.5733, "time": 1415891402247}, {"id": 660065, "val": 50.7228, "time": 1415891402249},
{"id": 670066, "val": 50.5312, "time": 1415891402254}, {"id": 680067, "val": 50.2971, "time": 1415891402261},
{"id": 690068, "val": 50.6341, "time": 1415891402271}, {"id": 700069, "val": 50.5817, "time": 1415891402796},
{"id": 710070, "val": 49.6206, "time": 1415891402801}, {"id": 720071, "val": 50.8691, "time": 1415891402804},
{"id": 730072, "val": 50.6361, "time": 1415891402806}, {"id": 740073, "val": 50.7695, "time": 1415891402810},
{"id": 750074, "val": 50.8501, "time": 1415891402812}, {"id": 760075, "val": 49.9246, "time": 1415891402814},
{"id": 770076, "val": 50.2664, "time": 1415891402819}, {"id": 780077, "val": 50.2065, "time": 1415891402829},
{"id": 790078, "val": 50.7383, "time": 1415891402831}, {"id": 800079, "val": 50.197, "time": 1415891403313},
{"id": 810080, "val": 49.7911, "time": 1415891403317}, {"id": 820081, "val": 50.4539, "time": 1415891403319},
{"id": 830082, "val": 50.2237, "time": 1415891403323}, {"id": 840083, "val": 50.3422, "time": 1415891403326},
{"id": 850084, "val": 50.5485, "time": 1415891403329}, {"id": 860085, "val": 50.3845, "time": 1415891403332},
{"id": 870086, "val": 50.5188, "time": 1415891403336}, {"id": 880087, "val": 50.9958, "time": 1415891403345},
{"id": 890088, "val": 50.4718, "time": 1415891403353}, {"id": 900089, "val": 50.1148, "time": 1415891403859},
{"id": 910090, "val": 49.9445, "time": 1415891403862}, {"id": 920091, "val": 50.6528, "time": 1415891403865},
{"id": 930092, "val": 50.897, "time": 1415891403868}, {"id": 940093, "val": 50.5441, "time": 1415891403871},
{"id": 950094, "val": 50.6114, "time": 1415891403873}, {"id": 960095, "val": 50.636, "time": 1415891403877},
{"id": 970096, "val": 50.5411, "time": 1415891403881}, {"id": 980097, "val": 50.2351, "time": 1415891403891},
{"id": 990098, "val": 50.6699, "time": 1415891403893},
{"id": 990098, "val": 50.544490455509546, "time": 1415891403893}
]
}) | gunins/stonewall | examples/application/src/chartData.js | JavaScript | mit | 5,943 |
import test from 'ava';
import snapshot from '../../helpers/snapshot';
import Vue from 'vue/dist/vue.common.js';
import u from '../../../src/lib/components/u/index.vue';
import commonTest from '../../common/unit';
const testOptions = {
test,
Vue,
snapshot,
component : window.morning._origin.Form.extend(u),
name : 'u',
attrs : ``,
uiid : 2,
delVmEl : false,
_baseTestHookCustomMount : false
};
commonTest.componentBase(testOptions);
| Morning-UI/morning-ui | test/unit/components/u.js | JavaScript | mit | 586 |
/*Création des cookies*/
$(document).ready(function () {
CreateCookies();
$('input:not([type="submit"])').each(function () {
$(this).val('');
});
});
/*Ajout des vols dans la recherche*/
function addResultVols(toAppend, compagnie, code, provenance, destination, imgSrc, date, heure, ArrDep, imgArrDep,data_vols,typeAlert,statut) {
var dateTd = (date === null) ? '' : '<td>' + date + '</td>';
var trString = '<tr class="'+ArrDep+'" active="OK" data-codevol="'+code+'" data-typevols="result">'+
'<td class="imgArrDep"><img src="'+imgArrDep+'"/></td>'+
'<td class="logoCompagny"><img src="'+imgSrc+'"/></td>'+
'<td class="numVol">'+code+'</td>'+
'<td>'+provenance+'</td>'+
'<td>'+destination+'</td>'+
dateTd+
'<td>'+heure+'</td>'+
'<td>'+statut+'</td>'+
'<td class="ToggleTd"><input type="checkbox" name="Alert" class="Alert'+typeAlert+' toggleCheckBox" data-vols="'+data_vols+'"/></td>'+
'</tr>';
var tr = $.parseHTML(trString);
toAppend.append(tr);
}
/*Ajout message -> Aucun Vol*/
function addNoVol(toAppend) {
var trString = '<tr class="NoResultVol">' +
'<td colspan="9" style="text-align:center;">Aucun vol ne correspond à la provenance et à la destination soumise ou à la date soumise </td>' +
'</tr>';
var tr = $.parseHTML(trString);
toAppend.append(tr);
}
/*Création des cookies*/
function CreateCookies() {
Cookies.set('provenance', '');
Cookies.set('destination', '');
Cookies.set('dateVol', '');
}
/*Vérifier si les cookies existent*/
function CookiesExists() {
return Cookies.get('provenance') !== '' && Cookies.get('destination') !== '' && Cookies.get('dateVol') !== '';
}
/*Véfier si les cookies contiennent les données de la précédente recherche*/
function IsSetCookies(prov, dest, date) {
return Cookies.get('provenance') == prov && Cookies.get('destination') == dest && Cookies.get('dateVol') == date;
}
/*Set Cookie*/
function SetCookies(prov, dest, date) {
Cookies.set('provenance', prov);
Cookies.set('destination', dest);
Cookies.set('dateVol', date);
}
/*Nettoyage précédent résultat*/
function NettoyageResult(trs,envoiOk) {
trs.remove();
if(envoiOk.hasClass("displayButton"))
envoiOk.removeClass("displayButton");
if(!envoiOk.hasClass('noDisplayButton'))
envoiOk.addClass('noDisplayButton');
}
/*Select -> set à défaut*/
function DefaultSelect(heureVol, textArriveeDepart, selectName) {
var selected = $('select[name="'+selectName+'"] option:selected');
if(selected.attr('id') != "default"){
selected.removeAttr("selected");
$('select[name="' + selectName + '"]').selectpicker('val', $('select[name="' + selectName +'"] #default').text());
}
heureVol.text('Heure');
textArriveeDepart.text($('select[name="' + selectName +'"] #default').text());
}
/* Message Erreur Invalide */
function MessageErreurInvalide(message, checkValid, messageText) {
if (!checkValid) {
var messageErreur = message.find('span[itemprop="3"]');
messageErreur.find('mark').text(messageText);
AfficheMessageGenerique2(message.find('span[itemprop="1"]'), 'noDisplayGenerique2');
AfficheMessageGenerique2(message.find('span[itemprop="2"]'), 'noDisplayGenerique2');
AfficheMessageGenerique(message, "displayGenerique");
AfficheMessageGenerique2(messageErreur, "displayGenerique2");
}
}
/* Recherche des vols */
$("#zoneRecherche").submit(function (event) {
event.preventDefault();
var provenance = $('select[name="ProvSearch"] option:selected');
var destination = $('select[name="DestSearch"] option:selected');
var dateVol;
/*Récupération dateVol*/
$("#dateVolRecherche input").each(function () {
if ($(this).hasClass('displayGenerique2')) {
dateVol = $(this).val();
return;
}
})
var message = $('#MessageErreurProvDest');
var provSuccess = $('select[name="ProvSearch"]').siblings('button').hasClass('success');
var destSuccess = $('select[name="DestSearch"]').siblings('button').hasClass('success');
dateVol = dateVol.replace(/[/]/g, '-');
if (!MessageErreurRecherche(provenance.val(), message, 'provenance') || !MessageErreurRecherche(destination.val(), message, 'destination') || !MessageErreurRecherche(dateVol, message, 'jour du vol'))
return;
AfficheMessageGenerique2(message, 'noDisplayGenerique2');
if(!CompareProvDest(provenance.val(),destination.val()))
return;
AfficheMessageGenerique2(message, 'noDisplayGenerique2');
if (provSuccess && destSuccess) {
$("#ResultatVol").modal("show");
let urlRechercheVol = urlApi+"/RechercheVols/" + provenance.val() + "/" + destination.val() + "/" + dateVol;
/*Lancement de la recherche*/
if (!CookiesExists() || !IsSetCookies(provenance.val(), destination.val(), dateVol)) {
/*Enregistrement des valeurs de la recherche*/
SetCookies(provenance.val(), destination.val(),dateVol);
/*Nettoyage précédente recherche*/
NettoyageResult($("#RechercheVol tr"), $(".EnvoiOkRechercheVol"));
DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol");
/*Appel API*/
$.getJSON(urlRechercheVol, {})
.done(function (data) {
if (Object.keys(data).indexOf("message") == -1) {
DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol");
Object.keys(data).forEach(function (key) {
var ArrDep = (Object.keys(data[key]).indexOf("Arr") !== -1) ? "Arrivée" : "Départ";
addResultVols(
$("#RechercheVol"),
data[key].Compagnie,
data[key].CodeVol,
data[key].Provenance,
data[key].Destination,
data[key].Img,
data[key].Date,
(ArrDep == "Arrivée") ? data[key].Arr : data[key].Dep,
ArrDep,
data[key].imgArrDep,
"Search",
'RechercheVol',
data[key].Statut
);
});
/*Contrôle fenetre modal*/
$(".AlertRechercheVol").each(function () {
var EnvoiOk = $(".EnvoiOkRechercheVol");
$(this).change(function () {
CheckButtonCheckBox(EnvoiOk, $(this));
ControleCheckBox(EnvoiOk, 'RechercheVol');
});
});
/*Paramétrage Bootstrap Toggle Checkbox*/
$('.toggleCheckBox[data-vols="Search"]').bootstrapToggle({
on: 'Suivi',
off: 'Non Suivi',
onstyle: "success",
size: "small",
height: 60,
width: 85
});
}
else {
addNoVol($("#RechercheVol"));
return;
}
});
}
}
else {
MessageErreurInvalide(message, provSuccess, 'provenance invalide');
MessageErreurInvalide(message, destSuccess, 'destination invalide');
return;
}
});
| aimanwakidou/SiteAeroport | js/RechercheVol.js | JavaScript | mit | 7,968 |
/*
*
* ProjectList constants
*
*/
// export const DEFAULT_ACTION = 'app/ProjectList/DEFAULT_ACTION';
export const GET_PROJECTS_OWNED_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED';
export const GET_PROJECTS_OWNED_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_SUCCESS';
export const GET_PROJECTS_OWNED_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_ERROR';
export const GET_PROJECTS_ACCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS';
export const GET_PROJECTS_ACCESS_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_SUCCESS';
export const GET_PROJECTS_ACCESS_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_ERROR';
| VeloCloud/website-ui | app/containers/ProjectList/constants.js | JavaScript | mit | 642 |
/**! Qoopido.nucleus 3.1.9 | http://nucleus.qoopido.com | (c) 2020 Dirk Lueth */
!function(e){"use strict";provide(["/demand/pledge"],(function(A){var t=A.defer(),d=e.createElement("img");return d.onload=function(){1===d.width&&1===d.height?t.resolve():t.reject(),delete d.onload},d.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",t.pledge}))}(document);
//# sourceMappingURL=datauri.js.map
| cdnjs/cdnjs | ajax/libs/qoopido.nucleus/3.1.9/support/test/capability/datauri.js | JavaScript | mit | 432 |
import core from 'core-js';
var originStorage = new Map();
function ensureType(value){
if(value instanceof Origin){
return value;
}
return new Origin(value);
}
/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*
* @class Origin
* @constructor
* @param {string} moduleId The origin module id.
* @param {string} moduleMember The name of the export in the origin module.
*/
export class Origin {
constructor(moduleId, moduleMember){
this.moduleId = moduleId;
this.moduleMember = moduleMember;
}
/**
* Get the Origin annotation for the specified function.
*
* @method get
* @static
* @param {Function} fn The function to inspect for Origin metadata.
* @return {Origin} Returns the Origin metadata.
*/
static get(fn){
var origin = originStorage.get(fn);
if(origin !== undefined){
return origin;
}
if(typeof fn.origin === 'function'){
originStorage.set(fn, origin = ensureType(fn.origin()));
} else if(fn.origin !== undefined){
originStorage.set(fn, origin = ensureType(fn.origin));
}
return origin;
}
/**
* Set the Origin annotation for the specified function.
*
* @method set
* @static
* @param {Function} fn The function to set the Origin metadata on.
* @param {origin} fn The Origin metadata to store on the function.
* @return {Origin} Returns the Origin metadata.
*/
static set(fn, origin){
if(Origin.get(fn) === undefined){
originStorage.set(fn, origin);
}
}
}
| behzad88/aurelia-ts-port | aurelia-latest/metadata/origin.js | JavaScript | mit | 1,546 |
var breadcrumbs=[['-1',"",""],['2',"SOLUTION-WIDE PROPERTIES Reference","topic_0000000000000C16.html"],['2977',"Tlece.Recruitment.Services.Company Namespace","topic_0000000000000A83.html"],['2978',"CompanyService Class","topic_0000000000000A84.html"],['2991',"Methods","topic_0000000000000A84_methods--.html"],['3066',"TerminateStaff Method","topic_0000000000000AAC.html"]]; | asiboro/asiboro.github.io | vsdoc/toc--/topic_0000000000000AAC.html.js | JavaScript | mit | 374 |
/*global require module*/
var q = require('q');
var async = require('async');
var constants = require('./_constants');
var Logger = require('./logger');
var CompiledNode = require('./compiled-node');
var EvaluatedNode = require('./evaluated-node');
var _8a2a4f008c464f9b81b3b5f4e75772c5 = {
evaluateValue: function(mapper, logger, parent, name, instanceNode, requiredOnly) {
var evaluated = new EvaluatedNode(this);
evaluated.content = this.value;
return q().then(function () {
return evaluated;
});
},
evaluateObject: function(mapper, logger, parent, name, instanceNode, requiredOnly) {
var self = this;
var defer = q.defer();
var hasMissingNode = false;
var evaluated = new EvaluatedNode(this);
evaluated.children = (this.children instanceof Array) ? [] : {};
evaluated.content = (this.children instanceof Array) ? [] : {};
async.each(
Object.keys(self.children),
function (key, done) {
self.children[key].evaluate(mapper, logger, evaluated, key, instanceNode).then(function (child) {
evaluated.children[key] = child;
evaluated.content[key] = child.content;
hasMissingNode = hasMissingNode || child.isMissing;
})
.finally(function () {
done();
})
},
function (err) {
if (hasMissingNode) {
evaluated.content = null;
evaluated.isMissing = (self.isRequired);
}
defer.resolve(evaluated);
}
);
return defer.promise
}
};
module.exports = Module;
/*------------------------------------------------------------------------------
A module contains 0, 1 or more properties
A property contains 0 or 1 selector and 0 or 1 module
------------------------------------------------------------------------------*/
function Module(source) {
var helper = _8a2a4f008c464f9b81b3b5f4e75772c5;
function getSource(mapper, logger) {
function _getSource(source) {
if (source) {
if (typeof(source) === 'function') {
return _getSource(source(mapper, logger));
}
if (typeof(source.getSource) === 'function') {
return _getSource(source.getSource(mapper, logger));
}
}
return source;
}
return _getSource(source);
}
function validate(mapper, instanceNode, logger) {
return q().then(function () {
return getSourceModule(mapper, module);
})
.then(function (module) {
if (module === undefined) {
return true;
}
else if (module === null) {
return true;
}
else if (typeof(module.validate) === 'function') {
return module.validate(mapper, instanceNode);
}
else {
return true;
}
});
}
function __compile(parent, source, name) {
var compiled = new CompiledNode(null, null, parent, name);
if (source !== undefined && source !== null) {
var content = source.content;
if (content === undefined) {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
else if (content === null) {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
else if (content.$isModule) {
compiled = content._compile(parent, name);
}
else if (content[constants.interface.compile]) {
compiled = content[constants.interface.compile]._compile(parent, name);
}
else if (typeof(content) === 'object') {
compiled._evaluate = helper.evaluateObject;
compiled.children = (content instanceof Array) ? [] : {};
compiled.newContent();
var keys = Object.keys(content);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var child = __compile(compiled, {content: content[key]}, key);
compiled.children[key] = child;
compiled.content[key] = child.content;
}
}
else {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
}
return compiled;
}
function _compile(parent, name) {
var logger = parent.logger;
var containingModule = parent.mapper && parent.mapper.containingModule;
var mapper = parent.mapper && parent.mapper.newChild(logger, containingModule);
var source = getSource(mapper, module);
return __compile(parent, source, name);
}
function compile(mapper, logger) {
var compiled = new CompiledNode(mapper, logger);
return _compile(compiled, '');
}
return {
$isModule: true,
logger: null,
getSource: function (mapper, logger) {
return getSource(mapper, logger);
},
validate: function (mapper, instanceNode, logger) {
return validate.call(this, mapper, instanceNode, logger || this.logger);
},
_compile: function (parent, name) {
return _compile(parent, name);
},
compile: function (mapper, logger) {
return compile(mapper, logger || this.logger).content;
},
evaluate: function (mapper, instanceNode, logger) {
var api = this.compile(mapper, logger);
api._ = instanceNode;
return api._;
},
setLogger: function (val) {
this.logger = val;
return this;
}
};
}
| cellanda/flexapi-core-js | lib/module.js | JavaScript | mit | 6,246 |
//= require jquery3
//= require popper
//= require bootstrap
//= require turbolinks
//= require_tree . | mrysav/familiar | app/assets/javascripts/application.js | JavaScript | mit | 102 |
#!/usr/bin/env node
const
fs = require('mz/fs'),
path = require('path'),
Promise = require('bluebird'),
mongoose = require('mongoose'),
uuid = require('uuid4')
const config = require('../config/api_options.json')
const MongoUtil = require('../dist/server/lib/mongo-util').default
const Order = require('../dist/server/models/order').default
const Ticket = require('../dist/server/models/ticket').default
mongoose.Promise = Promise
mongoose.connect(config.mongodb.dburl, { useMongoClient: true })
mongoose.model('Order', Order)
mongoose.model('Ticket', Ticket)
fs.readFile(path.join(__dirname, '..', 'booth.csv')).then(async data => {
const entries = data.toString().split('\n').map(line => {
const parts = line.split(',')
return { firstname: parts[0], lastname: parts[1], email: parts[2] }
})
for (let entry of entries) {
const orderobj = {
uuid: uuid(),
email: entry.email.trim(),
firstname: entry.firstname || ' ',
lastname: entry.lastname || ' ',
ticket_category: 'booth'
}
const order = await MongoUtil.model('Order').create(orderobj)
const ticket = await MongoUtil.model('Ticket').create({
uuid: uuid(),
firstname: entry.firstname || ' ',
lastname: entry.lastname || ' ',
category: 'booth',
type: 'festival',
order_uuid: order.uuid,
issued: new Date(),
price: {
amount: 0.0,
currency: 'eur'
}
})
const od = await MongoUtil.model('Order').findOne({ uuid: order.uuid }).populate('tickets')
await od.authorizeTicket()
console.log(order.uuid, ticket.uuid)
}
}).then(() => {
process.exit(0)
}).catch(err => {
throw err
})
| dasantonym/nano-ticketron-xl | bin/import-booth.js | JavaScript | mit | 1,688 |
// Currently unused, but don't want to delete it since
// it might be useful later.
//SmartRoutes.ComboBoxViewModel = function(data) {
// // Private:
// var comboboxChoices = ko.observableArray();
// var comboboxSelection = ko.observable();
// (function Init() {
// if (data && Array.isArray(data)) {
// $.each(data, function(key, value) {
// comboboxChoices.push(value);
// });
// }
// })();
// return {
// // Public:
// selectedItem: comboboxSelection,
// choices: comboboxChoices
// };
//}; | SmartRoutes/SmartRoutes | SmartRoutes/Scripts/ViewModels/ComboBoxViewModel.js | JavaScript | mit | 595 |
const TEXT_NODE = 3;
import { clearSelection } from 'content-kit-editor/utils/selection-utils';
import { walkDOMUntil } from 'content-kit-editor/utils/dom-utils';
import KEY_CODES from 'content-kit-editor/utils/keycodes';
import isPhantom from './is-phantom';
function selectRange(startNode, startOffset, endNode, endOffset) {
clearSelection();
const range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
const selection = window.getSelection();
selection.addRange(range);
}
function selectText(startText,
startContainingElement,
endText=startText,
endContainingElement=startContainingElement) {
const findTextNode = (text) => {
return (el) => el.nodeType === TEXT_NODE && el.textContent.indexOf(text) !== -1;
};
const startTextNode = walkDOMUntil(startContainingElement, findTextNode(startText));
const endTextNode = walkDOMUntil(endContainingElement, findTextNode(endText));
if (!startTextNode) {
throw new Error(`Could not find a starting textNode containing "${startText}"`);
}
if (!endTextNode) {
throw new Error(`Could not find an ending textNode containing "${endText}"`);
}
const startOffset = startTextNode.textContent.indexOf(startText),
endOffset = endTextNode.textContent.indexOf(endText) + endText.length;
selectRange(startTextNode, startOffset, endTextNode, endOffset);
}
function moveCursorTo(node, offset=0, endNode=node, endOffset=offset) {
selectRange(node, offset, endNode, endOffset);
}
function triggerEvent(node, eventType) {
if (!node) { throw new Error(`Attempted to trigger event "${eventType}" on undefined node`); }
let clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
return node.dispatchEvent(clickEvent);
}
function createKeyEvent(eventType, keyCode) {
let oEvent = document.createEvent('KeyboardEvent');
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode);
} else if (oEvent.initKeyEvent) {
oEvent.initKeyEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode);
}
// Hack for Chrome to force keyCode/which value
try {
Object.defineProperty(oEvent, 'keyCode', {get: function() { return keyCode; }});
Object.defineProperty(oEvent, 'which', {get: function() { return keyCode; }});
} catch(e) {
// FIXME
// PhantomJS/webkit will throw an error "ERROR: Attempting to change access mechanism for an unconfigurable property"
// see https://bugs.webkit.org/show_bug.cgi?id=36423
}
if (oEvent.keyCode !== keyCode || oEvent.which !== keyCode) {
throw new Error(`Failed to create key event with keyCode ${keyCode}. \`keyCode\`: ${oEvent.keyCode}, \`which\`: ${oEvent.which}`);
}
return oEvent;
}
function triggerKeyEvent(node, eventType, keyCode=KEY_CODES.ENTER) {
let oEvent = createKeyEvent(eventType, keyCode);
return node.dispatchEvent(oEvent);
}
function _buildDOM(tagName, attributes={}, children=[]) {
const el = document.createElement(tagName);
Object.keys(attributes).forEach(k => el.setAttribute(k, attributes[k]));
children.forEach(child => el.appendChild(child));
return el;
}
_buildDOM.text = (string) => {
return document.createTextNode(string);
};
/**
* Usage:
* makeDOM(t =>
* t('div', attributes={}, children=[
* t('b', {}, [
* t.text('I am a bold text node')
* ])
* ])
* );
*/
function makeDOM(tree) {
return tree(_buildDOM);
}
function getSelectedText() {
const selection = window.getSelection();
if (selection.rangeCount === 0) {
return null;
} else if (selection.rangeCount > 1) {
// FIXME?
throw new Error('Unable to get selected text for multiple ranges');
} else {
const {
anchorNode, anchorOffset,
focusNode, focusOffset
} = selection;
if (anchorNode !== focusNode) {
// FIXME
throw new Error('Unable to get selected text when multiple nodes are selected');
} else {
return anchorNode.textContent.slice(anchorOffset, focusOffset);
}
}
}
// returns the node and the offset that the cursor is on
function getCursorPosition() {
const selection = window.getSelection();
return {
node: selection.anchorNode,
offset: selection.anchorOffset
};
}
function triggerDelete(editor) {
if (isPhantom()) {
// simulate deletion for phantomjs
let event = { preventDefault() {} };
editor.handleDeletion(event);
} else {
triggerKeyEvent(document, 'keydown', KEY_CODES.DELETE);
}
}
function triggerEnter(editor) {
if (isPhantom()) {
// simulate event when testing with phantom
let event = { preventDefault() {} };
editor.handleNewline(event);
} else {
triggerKeyEvent(document, 'keydown', KEY_CODES.ENTER);
}
}
function insertText(string) {
document.execCommand('insertText', false, string);
}
const DOMHelper = {
moveCursorTo,
selectText,
clearSelection,
triggerEvent,
triggerKeyEvent,
makeDOM,
KEY_CODES,
getCursorPosition,
getSelectedText,
triggerDelete,
triggerEnter,
insertText
};
export { triggerEvent };
export default DOMHelper;
| toddself/content-kit-editor | tests/helpers/dom.js | JavaScript | mit | 5,235 |
beforeEach(function () {
jasmine.Clock.useMock();
jasmine.Clock.reset();
$.fx.off = true;
if ($('.fake_dom').length) {
$('.fake_dom').empty();
}
this.addMatchers(new CustomMatchers());
});
afterEach(function () {
$.fx.off = false;
});
function printNode(node, depth, renderer) {
renderer = renderer || _.identity;
if (node === null) { return ''; }
if (depth === 0) { return node.data ? renderer(node.data) + '@' + node.level.toString() : ''; }
return '(' + ([printNode(node.left, depth - 1, renderer), printNode(node, 0, renderer), printNode(node.right, depth - 1, renderer)].join('-')) + ')';
}
function printStack(stack) {
return _.map(stack, function(node){ return node.data; });
}
jasmine.fixture = function () {
if (!$('.fake_dom').length) {
$("body", document).prepend($('<div></div>').attr("style", "position: fixed; left: 100%").addClass('fake_dom'));
}
return $('.fake_dom');
};
function _helper_isObject(arg) {
return arg != null && typeof(arg) == 'object';
}
function _helper_isArray(arg) {
return _helper_isObject(arg) && Object.prototype.toString.apply(arg) == '[object Array]';
}
function decodeParams(string_or_object) {
if(typeof string_or_object !== 'string') {
return string_or_object;
}
var keyValuePairs = string_or_object.replace(/\+/g, "%20").split("&");
var hash = {};
$(keyValuePairs).each(function () {
var equalSplit = this.split("=");
var key = decodeURIComponent(equalSplit[0]);
if (hash[key] == null) {
hash[key] = decodeURIComponent(equalSplit[1]);
} else if (jQuery.isArray(hash[key])) {
hash[key].push(decodeURIComponent(equalSplit[1]));
} else {
hash[key] = [hash[key]];
hash[key].push(decodeURIComponent(equalSplit[1]));
}
});
return hash;
}
CustomMatchers = function() {};
CustomMatchers.prototype = {
toBeEmpty: function() {
this.message = function() {
return 'Expected ' + jasmine.pp(this.actual) + (this.isNot ? ' not' : '') + ' to be empty';
};
if (this.actual instanceof jQuery) {
return this.actual.size() == 0
} else if (_helper_isArray(this.actual)) {
return this.actual.length == 0;
} else if (_helper_isObject(this.actual)) {
// any property means not empty
for(var property in this.actual) {
return false;
}
return true;
}
return false;
},
toHaveAjaxData: function(expected) {
this.message = function() {
return 'Expected ' + jasmine.pp(decodeParams(this.actual)) + (this.isNot ? ' not' : '') + ' to match ' + jasmine.pp(expected);
}
return this.env.equals_(decodeParams(this.actual), expected);
}
};
| ohrite/view_zoo | spec/javascripts/helpers/spec_helper.js | JavaScript | mit | 2,675 |
var path = require('path');
module.exports = {
entry: {
entry:path.join(__dirname, 'src', 'entry.js'),
toggle:path.join(__dirname, 'src', 'toggle.js'),
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/static/',
filename: '[name].js'
},
module: {
loaders: [{
test: /\.js(x)?$/,
loader: 'babel'
}, {
test: /.css$/,
loader: 'style-loader!css-loader'
},{
test : /\.(json|ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
loader : 'file-loader',
query:{
name:'[name]-[md5:hash:8].[ext]'
}
}]
}
} | wyvernnot/react-datatables-example | webpack.config.js | JavaScript | mit | 599 |
import merge from 'webpack-merge';
import chalk from 'chalk';
import pkgInfo from './package.json';
import BabiliPlugin from 'babili-webpack-plugin';
import WebpackShellPlugin from '@slightlytyler/webpack-shell-plugin';
import webpackConfigBase from './webpack.config.base';
const webpackConfigProd = {
plugins: [
new BabiliPlugin({}),
new WebpackShellPlugin({
onBuildStart: [], // need to bump version first before files copied etc
onBuildExit: ['bash scripts/clean-production.sh']})
]
};
export default merge(webpackConfigBase, webpackConfigProd);
| mikeerickson/cd-messenger | webpack.config.prod.js | JavaScript | mit | 584 |
/**
* This file is where you define your application routes and controllers.
*
* Start by including the middleware you want to run for every request;
* you can attach middleware to the pre('routes') and pre('render') events.
*
* For simplicity, the default setup for route controllers is for each to be
* in its own file, and we import all the files in the /routes/views directory.
*
* Each of these files is a route controller, and is responsible for all the
* processing that needs to happen for the route (e.g. loading data, handling
* form submissions, rendering the view template, etc).
*
* Bind each route pattern your application should respond to in the function
* that is exported from this module, following the examples below.
*
* See the Express application routing documentation for more information:
* http://expressjs.com/api.html#app.VERB
*/
var keystone = require('keystone');
var middleware = require('./middleware');
var importRoutes = keystone.importer(__dirname);
var sitemap = require('keystone-express-sitemap');
var https = require('https');
// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views')
};
// Setup Route Bindings
exports = module.exports = function(app) {
// Views
app.get('/', routes.views.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/buy/:category?', routes.views.buy);
app.get('/buy/post/:post', routes.views.post);
app.get('/sell/:category?', routes.views.sell);
app.get('/sell/post/:post', routes.views.post);
app.get('/testimonial/:category?', routes.views.testimonial);
app.get('/testimonial/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
//app.get('/listing/:category?', routes.views.listing);
app.get('/listing2', routes.views.listing2);
//app.get('/listing/post/:post', routes.views.post);
app.all('/search2', routes.views.search2);
app.get('/mls', routes.views.mls);
app.all('/contact', routes.views.contact);
app.all('/coverage', routes.views.coverage);
app.all('/legal', routes.views.legal);
app.all('/location', routes.views.location);
app.get('/sitemap.xml', function(req, res) {
sitemap.create(keystone, req, res);
});
// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
// app.get('/protected', middleware.requireUser, routes.views.protected);
};
| briviere/keystone-realestate-template | routes/index.js | JavaScript | mit | 2,560 |
/**
* @license Copyright (c) {{year}}, {{author}} All Rights Reserved.
* Available via MIT license.
*/
/**
* A client {{page}} {{request}} handler.
*/
define([ 'framework/request/base_request_handler',
'../{{request}}_request',
'framework/core/deferred/deferred',
'domain/request/{{page}}/{{requestServer}}_request' ],
function(BaseRequestHandler,
{{toPascal request}}Request,
Deferred,
{{toPascal requestServer}}Request)
{
var {{toPascal request}}Handler = BaseRequestHandler.create({{toPascal request}}Request);
// @override
{{toPascal request}}Handler.prototype.execute = function(requestContext, request, response)
{
// TODO: Add in the handler method.
return Deferred.resolvedPromise(requestContext);
// OR
/*
var _this = this,
remoteRequest = new {{toPascal requestServer}}Request(request);
this._dispatcher.trigger('message', [ 'Doing Something', request.getSomething() ]);
return this._remoteRequest(requestContext, remoteRequest).then(function(remoteResponse)
{
_this._dispatcher.trigger('message', [ 'Something Done', request.getSomething() ]);
return Deferred.resolvedPromise(requestContext);
});
*/
};
return {{toPascal request}}Handler;
}); | DragonDTG/vex | lib/generator/request/public/static/scripts/pages/page/handler/request_handler.js | JavaScript | mit | 1,223 |
// A cross-browser javascript shim for html5 audio
(function(audiojs, audiojsInstance, container) {
// Use the path to the audio.js file to create relative paths to the swf and player graphics
// Remember that some systems (e.g. ruby on rails) append strings like '?1301478336' to asset paths
var path = (function() {
var re = new RegExp('audio(\.min)?\.js.*'),
scripts = document.getElementsByTagName('script');
for (var i = 0, ii = scripts.length; i < ii; i++) {
var path = scripts[i].getAttribute('src');
if(re.test(path)) return path.replace(re, '');
}
})();
// ##The audiojs interface
// This is the global object which provides an interface for creating new `audiojs` instances.
// It also stores all of the construction helper methods and variables.
container[audiojs] = {
instanceCount: 0,
instances: {},
// The markup for the swf. It is injected into the page if there is not support for the `<audio>` element. The `$n`s are placeholders.
// `$1` The name of the flash movie
// `$2` The path to the swf
// `$3` Cache invalidation
flashSource: '\
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="$1" width="1" height="1" name="$1" style="position: absolute; left: -1px;"> \
<param name="movie" value="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3"> \
<param name="allowscriptaccess" value="always"> \
<embed name="$1" src="$2?playerInstance='+audiojs+'.instances[\'$1\']&datetime=$3" width="1" height="1" allowscriptaccess="always"> \
</object>',
// ### The main settings object
// Where all the default settings are stored. Each of these variables and methods can be overwritten by the user-provided `options` object.
settings: {
autoplay: false,
loop: false,
preload: false,
imageLocation: path + 'player-graphics.gif',
swfLocation: path + 'audiojs.swf',
useFlash: (function() {
var a = document.createElement('audio');
return !(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
})(),
hasFlash: (function() {
if (navigator.plugins && navigator.plugins.length && navigator.plugins['Shockwave Flash']) {
return true;
} else if (navigator.mimeTypes && navigator.mimeTypes.length) {
var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
return mimeType && mimeType.enabledPlugin;
} else {
try {
var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
return true;
} catch (e) {}
}
return false;
})(),
// The default markup and classes for creating the player:
createPlayer: {
markup: '\
<div class="play-pause"> \
<p class="play"></p> \
<p class="pause"></p> \
<p class="loading"></p> \
<p class="error"></p> \
</div> \
<div class="scrubber"> \
<div class="progress"></div> \
<div class="loaded"></div> \
</div> \
<div class="time"> \
<em class="played">00:00</em>/<strong class="duration">00:00</strong> \
</div> \
<div class="error-message"></div>',
playPauseClass: 'play-pause',
scrubberClass: 'scrubber',
progressClass: 'progress',
loaderClass: 'loaded',
timeClass: 'time',
durationClass: 'duration',
playedClass: 'played',
errorMessageClass: 'error-message',
playingClass: 'playing',
loadingClass: 'loading',
errorClass: 'error'
},
// The css used by the default player. This is is dynamically injected into a `<style>` tag in the top of the head.
css: '\
.audiojs audio { position: absolute; left: -1px; } \
.audiojs { width: 460px; height: 36px; background: #404040; overflow: hidden; font-family: monospace; font-size: 12px; \
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #444), color-stop(0.5, #555), color-stop(0.51, #444), color-stop(1, #444)); \
background-image: -moz-linear-gradient(center top, #444 0%, #555 50%, #444 51%, #444 100%); \
-webkit-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); -moz-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); \
-o-box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); box-shadow: 1px 1px 8px rgba(0, 0, 0, 0.3); } \
.audiojs .play-pause { width: 25px; height: 40px; padding: 4px 6px; margin: 0px; float: left; overflow: hidden; border-right: 1px solid #000; } \
.audiojs p { display: none; width: 25px; height: 40px; margin: 0px; cursor: pointer; } \
.audiojs .play { display: block; } \
.audiojs .scrubber { position: relative; float: left; width: 280px; background: #5a5a5a; height: 14px; margin: 10px; border-top: 1px solid #3f3f3f; border-left: 0px; border-bottom: 0px; overflow: hidden; } \
.audiojs .progress { position: absolute; top: 0px; left: 0px; height: 14px; width: 0px; background: #ccc; z-index: 1; \
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #ccc), color-stop(0.5, #ddd), color-stop(0.51, #ccc), color-stop(1, #ccc)); \
background-image: -moz-linear-gradient(center top, #ccc 0%, #ddd 50%, #ccc 51%, #ccc 100%); } \
.audiojs .loaded { position: absolute; top: 0px; left: 0px; height: 14px; width: 0px; background: #000; \
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #222), color-stop(0.5, #333), color-stop(0.51, #222), color-stop(1, #222)); \
background-image: -moz-linear-gradient(center top, #222 0%, #333 50%, #222 51%, #222 100%); } \
.audiojs .time { float: left; height: 36px; line-height: 36px; margin: 0px 0px 0px 6px; padding: 0px 6px 0px 12px; border-left: 1px solid #000; color: #ddd; text-shadow: 1px 1px 0px rgba(0, 0, 0, 0.5); } \
.audiojs .time em { padding: 0px 2px 0px 0px; color: #f9f9f9; font-style: normal; } \
.audiojs .time strong { padding: 0px 0px 0px 2px; font-weight: normal; } \
.audiojs .error-message { float: left; display: none; margin: 0px 10px; height: 36px; width: 400px; overflow: hidden; line-height: 36px; white-space: nowrap; color: #fff; \
text-overflow: ellipsis; -o-text-overflow: ellipsis; -icab-text-overflow: ellipsis; -khtml-text-overflow: ellipsis; -moz-text-overflow: ellipsis; -webkit-text-overflow: ellipsis; } \
.audiojs .error-message a { color: #eee; text-decoration: none; padding-bottom: 1px; border-bottom: 1px solid #999; white-space: wrap; } \
\
.audiojs .play { background: url("$1") -2px -1px no-repeat; } \
.audiojs .loading { background: url("$1") -2px -31px no-repeat; } \
.audiojs .error { background: url("$1") -2px -61px no-repeat; } \
.audiojs .pause { background: url("$1") -2px -91px no-repeat; } \
\
.playing .play, .playing .loading, .playing .error { display: none; } \
.playing .pause { display: block; } \
\
.loading .play, .loading .pause, .loading .error { display: none; } \
.loading .loading { display: block; } \
\
.error .time, .error .play, .error .pause, .error .scrubber, .error .loading { display: none; } \
.error .error { display: block; } \
.error .play-pause p { cursor: auto; } \
.error .error-message { display: block; }',
// The default event callbacks:
trackEnded: function(e) {},
flashError: function() {
var player = this.settings.createPlayer,
errorMessage = getByClass(player.errorMessageClass, this.wrapper),
html = 'Missing <a href="http://get.adobe.com/flashplayer/">flash player</a> plugin.';
if (this.mp3) html += ' <a href="'+this.mp3+'">Download audio file</a>.';
container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass);
container[audiojs].helpers.addClass(this.wrapper, player.errorClass);
errorMessage.innerHTML = html;
},
loadError: function(e) {
var player = this.settings.createPlayer,
errorMessage = getByClass(player.errorMessageClass, this.wrapper);
container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass);
container[audiojs].helpers.addClass(this.wrapper, player.errorClass);
errorMessage.innerHTML = 'Error loading: "'+this.mp3+'"';
},
init: function() {
var player = this.settings.createPlayer;
container[audiojs].helpers.addClass(this.wrapper, player.loadingClass);
},
loadStarted: function() {
var player = this.settings.createPlayer,
duration = getByClass(player.durationClass, this.wrapper),
m = Math.floor(this.duration / 60),
s = Math.floor(this.duration % 60);
container[audiojs].helpers.removeClass(this.wrapper, player.loadingClass);
duration.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s);
},
loadProgress: function(percent) {
var player = this.settings.createPlayer,
scrubber = getByClass(player.scrubberClass, this.wrapper),
loaded = getByClass(player.loaderClass, this.wrapper);
loaded.style.width = (scrubber.offsetWidth * percent) + 'px';
},
playPause: function() {
if (this.playing) this.settings.play();
else this.settings.pause();
},
play: function() {
var player = this.settings.createPlayer;
container[audiojs].helpers.addClass(this.wrapper, player.playingClass);
},
pause: function() {
var player = this.settings.createPlayer;
container[audiojs].helpers.removeClass(this.wrapper, player.playingClass);
},
updatePlayhead: function(percent) {
var player = this.settings.createPlayer,
scrubber = getByClass(player.scrubberClass, this.wrapper),
progress = getByClass(player.progressClass, this.wrapper);
progress.style.width = (scrubber.offsetWidth * percent) + 'px';
var played = getByClass(player.playedClass, this.wrapper),
p = this.duration * percent,
m = Math.floor(p / 60),
s = Math.floor(p % 60);
played.innerHTML = ((m<10?'0':'')+m+':'+(s<10?'0':'')+s);
}
},
// ### Contructor functions
// `create()`
// Used to create a single `audiojs` instance.
// If an array is passed then it calls back to `createAll()`.
// Otherwise, it creates a single instance and returns it.
create: function(element, options) {
var options = options || {}
if (element.length) {
return this.createAll(options, element);
} else {
return this.newInstance(element, options);
}
},
// `createAll()`
// Creates multiple `audiojs` instances.
// If `elements` is `null`, then automatically find any `<audio>` tags on the page and create `audiojs` instances for them.
createAll: function(options, elements) {
var audioElements = elements || document.getElementsByTagName('audio'),
instances = []
options = options || {};
for (var i = 0, ii = audioElements.length; i < ii; i++) {
instances.push(this.newInstance(audioElements[i], options));
}
return instances;
},
// ### Creating and returning a new instance
// This goes through all the steps required to build out a usable `audiojs` instance.
newInstance: function(element, options) {
var element = element,
s = this.helpers.clone(this.settings),
id = 'audiojs'+this.instanceCount,
wrapperId = 'audiojs_wrapper'+this.instanceCount,
instanceCount = this.instanceCount++;
// Check for `autoplay`, `loop` and `preload` attributes and write them into the settings.
if (element.getAttribute('autoplay') != null) s.autoplay = true;
if (element.getAttribute('loop') != null) s.loop = true;
if (element.getAttribute('preload') == 'none') s.preload = false;
// Merge the default settings with the user-defined `options`.
if (options) this.helpers.merge(s, options);
// Inject the player html if required.
if (s.createPlayer.markup) element = this.createPlayer(element, s.createPlayer, wrapperId);
else element.parentNode.setAttribute('id', wrapperId);
// Return a new `audiojs` instance.
var audio = new container[audiojsInstance](element, s);
// If css has been passed in, dynamically inject it into the `<head>`.
if (s.css) this.helpers.injectCss(audio, s.css);
// If `<audio>` or mp3 playback isn't supported, insert the swf & attach the required events for it.
if (s.useFlash && s.hasFlash) {
this.injectFlash(audio, id);
this.attachFlashEvents(audio.wrapper, audio);
} else if (s.useFlash && !s.hasFlash) {
this.settings.flashError.apply(audio);
}
// Attach event callbacks to the new audiojs instance.
if (!s.useFlash || (s.useFlash && s.hasFlash)) this.attachEvents(audio.wrapper, audio);
// Store the newly-created `audiojs` instance.
this.instances[id] = audio;
return audio;
},
// ### Helper methods for constructing a working player
// Inject a wrapping div and the markup for the html player.
createPlayer: function(element, player, id) {
var wrapper = document.createElement('div'),
newElement = element.cloneNode(true);
wrapper.setAttribute('class', 'audiojs');
wrapper.setAttribute('className', 'audiojs');
wrapper.setAttribute('id', id);
// Fix IE's broken implementation of `innerHTML` & `cloneNode` for HTML5 elements.
if (newElement.outerHTML && !document.createElement('audio').canPlayType) {
newElement = this.helpers.cloneHtml5Node(element);
wrapper.innerHTML = player.markup;
wrapper.appendChild(newElement);
element.outerHTML = wrapper.outerHTML;
wrapper = document.getElementById(id);
} else {
wrapper.appendChild(newElement);
wrapper.innerHTML = wrapper.innerHTML + player.markup;
element.parentNode.replaceChild(wrapper, element);
}
return wrapper.getElementsByTagName('audio')[0];
},
// Attaches useful event callbacks to an `audiojs` instance.
attachEvents: function(wrapper, audio) {
if (!audio.settings.createPlayer) return;
var player = audio.settings.createPlayer,
playPause = getByClass(player.playPauseClass, wrapper),
scrubber = getByClass(player.scrubberClass, wrapper),
leftPos = function(elem) {
var curleft = 0;
if (elem.offsetParent) {
do { curleft += elem.offsetLeft; } while (elem = elem.offsetParent);
}
return curleft;
};
container[audiojs].events.addListener(playPause, 'click', function(e) {
audio.playPause.apply(audio);
});
container[audiojs].events.addListener(scrubber, 'click', function(e) {
var relativeLeft = e.clientX - leftPos(this);
audio.skipTo(relativeLeft / scrubber.offsetWidth);
});
// _If flash is being used, then the following handlers don't need to be registered._
if (audio.settings.useFlash) return;
// Start tracking the load progress of the track.
container[audiojs].events.trackLoadProgress(audio);
container[audiojs].events.addListener(audio.element, 'timeupdate', function(e) {
audio.updatePlayhead.apply(audio);
});
container[audiojs].events.addListener(audio.element, 'ended', function(e) {
audio.trackEnded.apply(audio);
});
container[audiojs].events.addListener(audio.source, 'error', function(e) {
// on error, cancel any load timers that are running.
clearInterval(audio.readyTimer);
clearInterval(audio.loadTimer);
audio.settings.loadError.apply(audio);
});
},
// Flash requires a slightly different API to the `<audio>` element, so this method is used to overwrite the standard event handlers.
attachFlashEvents: function(element, audio) {
audio['swfReady'] = false;
audio['load'] = function(mp3) {
// If the swf isn't ready yet then just set `audio.mp3`. `init()` will load it in once the swf is ready.
audio.mp3 = mp3;
if (audio.swfReady) audio.element.load(mp3);
}
audio['loadProgress'] = function(percent, duration) {
audio.loadedPercent = percent;
audio.duration = duration;
audio.settings.loadStarted.apply(audio);
audio.settings.loadProgress.apply(audio, [percent]);
}
audio['skipTo'] = function(percent) {
if (percent > audio.loadedPercent) return;
audio.updatePlayhead.call(audio, [percent])
audio.element.skipTo(percent);
}
audio['updatePlayhead'] = function(percent) {
audio.settings.updatePlayhead.apply(audio, [percent]);
}
audio['play'] = function() {
// If the audio hasn't started preloading, then start it now.
// Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away.
if (!audio.settings.preload) {
audio.settings.preload = true;
audio.element.init(audio.mp3);
}
audio.playing = true;
// IE doesn't allow a method named `play()` to be exposed through `ExternalInterface`, so lets go with `pplay()`.
// <http://dev.nuclearrooster.com/2008/07/27/externalinterfaceaddcallback-can-cause-ie-js-errors-with-certain-keyworkds/>
audio.element.pplay();
audio.settings.play.apply(audio);
}
audio['pause'] = function() {
audio.playing = false;
// Use `ppause()` for consistency with `pplay()`, even though it isn't really required.
audio.element.ppause();
audio.settings.pause.apply(audio);
}
audio['setVolume'] = function(v) {
audio.element.setVolume(v);
}
audio['loadStarted'] = function() {
// Load the mp3 specified by the audio element into the swf.
audio.swfReady = true;
if (audio.settings.preload) audio.element.init(audio.mp3);
if (audio.settings.autoplay) audio.play.apply(audio);
}
},
// ### Injecting an swf from a string
// Build up the swf source by replacing the `$keys` and then inject the markup into the page.
injectFlash: function(audio, id) {
var flashSource = this.flashSource.replace(/\$1/g, id);
flashSource = flashSource.replace(/\$2/g, audio.settings.swfLocation);
// `(+new Date)` ensures the swf is not pulled out of cache. The fixes an issue with Firefox running multiple players on the same page.
flashSource = flashSource.replace(/\$3/g, (+new Date + Math.random()));
// Inject the player markup using a more verbose `innerHTML` insertion technique that works with IE.
var html = audio.wrapper.innerHTML,
div = document.createElement('div');
div.innerHTML = flashSource + html;
audio.wrapper.innerHTML = div.innerHTML;
audio.element = this.helpers.getSwf(id);
},
// ## Helper functions
helpers: {
// **Merge two objects, with `obj2` overwriting `obj1`**
// The merge is shallow, but that's all that is required for our purposes.
merge: function(obj1, obj2) {
for (attr in obj2) {
if (obj1.hasOwnProperty(attr) || obj2.hasOwnProperty(attr)) {
obj1[attr] = obj2[attr];
}
}
},
// **Clone a javascript object (recursively)**
clone: function(obj){
if (obj == null || typeof(obj) !== 'object') return obj;
var temp = new obj.constructor();
for (var key in obj) temp[key] = arguments.callee(obj[key]);
return temp;
},
// **Adding/removing classnames from elements**
addClass: function(element, className) {
var re = new RegExp('(\\s|^)'+className+'(\\s|$)');
if (re.test(element.className)) return;
element.className += ' ' + className;
},
removeClass: function(element, className) {
var re = new RegExp('(\\s|^)'+className+'(\\s|$)');
element.className = element.className.replace(re,' ');
},
// **Dynamic CSS injection**
// Takes a string of css, inserts it into a `<style>`, then injects it in at the very top of the `<head>`. This ensures any user-defined styles will take precedence.
injectCss: function(audio, string) {
// If an `audiojs` `<style>` tag already exists, then append to it rather than creating a whole new `<style>`.
var prepend = '',
styles = document.getElementsByTagName('style'),
css = string.replace(/\$1/g, audio.settings.imageLocation);
for (var i = 0, ii = styles.length; i < ii; i++) {
var title = styles[i].getAttribute('title');
if (title && ~title.indexOf('audiojs')) {
style = styles[i];
if (style.innerHTML === css) return;
prepend = style.innerHTML;
break;
}
};
var head = document.getElementsByTagName('head')[0],
firstchild = head.firstChild,
style = document.createElement('style');
if (!head) return;
style.setAttribute('type', 'text/css');
style.setAttribute('title', 'audiojs');
if (style.styleSheet) style.styleSheet.cssText = prepend + css;
else style.appendChild(document.createTextNode(prepend + css));
if (firstchild) head.insertBefore(style, firstchild);
else head.appendChild(styleElement);
},
// **Handle all the IE6+7 requirements for cloning `<audio>` nodes**
// Create a html5-safe document fragment by injecting an `<audio>` element into the document fragment.
cloneHtml5Node: function(audioTag) {
var fragment = document.createDocumentFragment(),
doc = fragment.createElement ? fragment : document;
doc.createElement('audio');
var div = doc.createElement('div');
fragment.appendChild(div);
div.innerHTML = audioTag.outerHTML;
return div.firstChild;
},
// **Cross-browser `<object>` / `<embed>` element selection**
getSwf: function(name) {
var swf = document[name] || window[name];
return swf.length > 1 ? swf[swf.length - 1] : swf;
}
},
// ## Event-handling
events: {
memoryLeaking: false,
listeners: [],
// **A simple cross-browser event handler abstraction**
addListener: function(element, eventName, func) {
// For modern browsers use the standard DOM-compliant `addEventListener`.
if (element.addEventListener) {
element.addEventListener(eventName, func, false);
// For older versions of Internet Explorer, use `attachEvent`.
// Also provide a fix for scoping `this` to the calling element and register each listener so the containing elements can be purged on page unload.
} else if (element.attachEvent) {
this.listeners.push(element);
if (!this.memoryLeaking) {
window.attachEvent('onunload', function() {
if(this.listeners) {
for (var i = 0, ii = this.listeners.length; i < ii; i++) {
container[audiojs].events.purge(this.listeners[i]);
}
}
});
this.memoryLeaking = true;
}
element.attachEvent('on' + eventName, function() {
func.call(element, window.event);
});
}
},
trackLoadProgress: function(audio) {
// If `preload` has been set to `none`, then we don't want to start loading the track yet.
if (!audio.settings.preload) return;
var readyTimer,
loadTimer,
audio = audio,
ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent);
// Use timers here rather than the official `progress` event, as Chrome has issues calling `progress` when loading mp3 files from cache.
readyTimer = setInterval(function() {
if (audio.element.readyState > -1) {
// iOS doesn't start preloading the mp3 until the user interacts manually, so this stops the loader being displayed prematurely.
if (!ios) audio.init.apply(audio);
}
if (audio.element.readyState > 1) {
if (audio.settings.autoplay) audio.play.apply(audio);
clearInterval(readyTimer);
// Once we have data, start tracking the load progress.
loadTimer = setInterval(function() {
audio.loadProgress.apply(audio);
if (audio.loadedPercent >= 1) clearInterval(loadTimer);
});
}
}, 10);
audio.readyTimer = readyTimer;
audio.loadTimer = loadTimer;
},
// **Douglas Crockford's IE6 memory leak fix**
// <http://javascript.crockford.com/memory/leak.html>
// This is used to release the memory leak created by the circular references created when fixing `this` scoping for IE. It is called on page unload.
purge: function(d) {
var a = d.attributes, i;
if (a) {
for (i = 0; i < a.length; i += 1) {
if (typeof d[a[i].name] === 'function') d[a[i].name] = null;
}
}
a = d.childNodes;
if (a) {
for (i = 0; i < a.length; i += 1) purge(d.childNodes[i]);
}
},
// **DOMready function**
// As seen here: <https://github.com/dperini/ContentLoaded/>.
ready: (function() { return function(fn) {
var win = window, done = false, top = true,
doc = win.document, root = doc.documentElement,
add = doc.addEventListener ? 'addEventListener' : 'attachEvent',
rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent',
pre = doc.addEventListener ? '' : 'on',
init = function(e) {
if (e.type == 'readystatechange' && doc.readyState != 'complete') return;
(e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
},
poll = function() {
try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == 'complete') fn.call(win, 'lazy');
else {
if (doc.createEventObject && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
doc[add](pre + 'DOMContentLoaded', init, false);
doc[add](pre + 'readystatechange', init, false);
win[add](pre + 'load', init, false);
}
}
})()
}
}
// ## The audiojs class
// We create one of these per `<audio>` and then push them into `audiojs['instances']`.
container[audiojsInstance] = function(element, settings) {
// Each audio instance returns an object which contains an API back into the `<audio>` element.
this.element = element;
this.wrapper = element.parentNode;
this.source = element.getElementsByTagName('source')[0] || element;
// First check the `<audio>` element directly for a src and if one is not found, look for a `<source>` element.
this.mp3 = (function(element) {
var source = element.getElementsByTagName('source')[0];
return element.getAttribute('src') || (source ? source.getAttribute('src') : null);
})(element);
this.settings = settings;
this.loadStartedCalled = false;
this.loadedPercent = 0;
this.duration = 1;
this.playing = false;
}
container[audiojsInstance].prototype = {
// API access events:
// Each of these do what they need do and then call the matching methods defined in the settings object.
updatePlayhead: function() {
var percent = this.element.currentTime / this.duration;
this.settings.updatePlayhead.apply(this, [percent]);
},
skipTo: function(percent) {
if (percent > this.loadedPercent) return;
this.element.currentTime = this.duration * percent;
this.updatePlayhead();
},
load: function(mp3) {
this.loadStartedCalled = false;
this.source.setAttribute('src', mp3);
// The now outdated `load()` method is required for Safari 4
this.element.load();
this.mp3 = mp3;
container[audiojs].events.trackLoadProgress(this);
},
loadError: function() {
this.settings.loadError.apply(this);
},
init: function() {
this.settings.init.apply(this);
},
loadStarted: function() {
// Wait until `element.duration` exists before setting up the audio player.
if (!this.element.duration) return false;
this.duration = this.element.duration;
this.updatePlayhead();
this.settings.loadStarted.apply(this);
},
loadProgress: function() {
if (this.element.buffered != null && this.element.buffered.length) {
// Ensure `loadStarted()` is only called once.
if (!this.loadStartedCalled) {
this.loadStartedCalled = this.loadStarted();
}
var durationLoaded = this.element.buffered.end(this.element.buffered.length - 1);
this.loadedPercent = durationLoaded / this.duration;
this.settings.loadProgress.apply(this, [this.loadedPercent]);
}
},
playPause: function() {
if (this.playing) this.pause();
else this.play();
},
play: function() {
var ios = (/(ipod|iphone|ipad)/i).test(navigator.userAgent);
// On iOS this interaction will trigger loading the mp3, so run `init()`.
if (ios && this.element.readyState == 0) this.init.apply(this);
// If the audio hasn't started preloading, then start it now.
// Then set `preload` to `true`, so that any tracks loaded in subsequently are loaded straight away.
if (!this.settings.preload) {
this.settings.preload = true;
this.element.setAttribute('preload', 'auto');
container[audiojs].events.trackLoadProgress(this);
}
this.playing = true;
this.element.play();
this.settings.play.apply(this);
},
pause: function() {
this.playing = false;
this.element.pause();
this.settings.pause.apply(this);
},
setVolume: function(v) {
this.element.volume = v;
},
trackEnded: function(e) {
this.skipTo.apply(this, [0]);
if (!this.settings.loop) this.pause.apply(this);
this.settings.trackEnded.apply(this);
}
}
// **getElementsByClassName**
// Having to rely on `getElementsByTagName` is pretty inflexible internally, so a modified version of Dustin Diaz's `getElementsByClassName` has been included.
// This version cleans things up and prefers the native DOM method if it's available.
var getByClass = function(searchClass, node) {
var matches = [];
node = node || document;
if (node.getElementsByClassName) {
matches = node.getElementsByClassName(searchClass);
} else {
var i, l,
els = node.getElementsByTagName("*"),
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, l = els.length; i < l; i++) {
if (pattern.test(els[i].className)) {
matches.push(els[i]);
}
}
}
return matches.length > 1 ? matches : matches[0];
};
// The global variable names are passed in here and can be changed if they conflict with anything else.
})('audiojs', 'audiojsInstance', this); | OdeArmasSR/scsofficials.com | public/js/lib/audio.js | JavaScript | mit | 31,933 |
/*
* Cloud Foundry API module
* Service connection module helper
*/
var app = require("./properties");
function ServiceClient () { }
exports.ServiceClient = ServiceClient;
ServiceClient.prototype.create = function () {
if (!this.type) return false;
var svcNames = app.serviceNamesOfType[this.type];
if (!svcNames) return false;
if (svcNames.length !== 1) {
throw new Error("Expected 1 service of " + this.type + " type, " +
"but found " + svcNames.length + ". " +
"Consider using createFromSvc(name) instead.");
}
var args = Array.prototype.slice.call(arguments);
args.unshift(svcNames[0]);
return this.createFromSvc.apply(this, args);
};
ServiceClient.prototype.createFromSvc = function (name) {
var handler = this._create;
if (!handler) return false;
var props = app.serviceProps[name];
if (!props) return false;
switch (arguments.length) {
case 2: return handler.call(this, props, arguments[1]);
case 3: return handler.call(this, props, arguments[1], arguments[2]);
default: return handler.call(this, props);
}
}; | chinshr/foundry-node | node_modules/cf-autoconfig/node_modules/cf-runtime/lib/service.js | JavaScript | mit | 1,115 |
import {combineReducers} from 'redux';
import postValuesReducer from './post_values';
import ListReducer from './list_reducer';
import ForeignListReducer from './foreign_list_reducer';
import FuelReducer from './fuel_reducer';
import {reducer as formReducer} from 'redux-form';
const rootReducer = combineReducers({
postValues: postValuesReducer,
routePoints: ListReducer,
routeForeignPoints: ForeignListReducer,
fuel: FuelReducer,
form: formReducer
});
export default rootReducer;
| nadzins/riepas-react-redux | src/reducers/index.js | JavaScript | mit | 504 |
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var angular2_1 = require("angular2/angular2");
var GdgHeader = (function () {
function GdgHeader() {
}
GdgHeader = __decorate([
angular2_1.Component({
selector: "gdg-header",
properties: ["title"]
}),
angular2_1.View({
templateUrl: "./app/components/header/header.html"
}),
__metadata('design:paramtypes', [])
], GdgHeader);
return GdgHeader;
})();
exports.GdgHeader = GdgHeader;
| GDGAracaju/gdg.ninjas | src/app/components/header/header.js | JavaScript | mit | 1,252 |
/*(function() {
'use strict';
angular.module('myApp', []).controller('VideoListController', function($http, $log) {
var ctrl = this;
ctrl.query = 'Rick Astley';
ctrl.search = function() {
return $http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&type=video&q=' + ctrl.query + '&key=AIzaSyD4YJITOWdfQdFbcxHc6TgeCKmVS9yRuQ8')
.then(function(res) {
$log.info(res.data.items);
ctrl.videos = res.data.items.map(function (v) {
var snip = v.snippet;
return {
title: snip.title,
description: snip.description,
thumb: snip.thumbnails.medium.url,
link: 'https://www.youtube.com/watch?v=' + v.id.videoId
};
});
});
}
ctrl.search();
});
})();*/ | rasmusvhansen/angularjs-foundation-course | exercises/03Controllers/app2.js | JavaScript | mit | 884 |
import React, { PropTypes } from 'react';
import CSSModules from 'react-css-modules';
// Styles
import styles from './index.scss';
const propTypes = {
crises: PropTypes.array.isRequired,
};
const CrisisArchiveList = ({ crises }) => (
<div styleName='CrisisArchiveList'>
<h1>
All Crises
</h1>
<ul>
{crises.map((crisis, i) => {
const crisisStatusText = crisis.status === 'ARC' ?
'archived' :
'active';
return (
<li
styleName={crisisStatusText}
key={i}
>
<div styleName='header'>
{crisis.title}
</div>
<div styleName='body'>
<span>{crisis.incidents.length} incidents</span>
{crisis.description &&
<div styleName='description'>
Description: {crisis.description}
</div>
}
</div>
<div styleName='footer'>
<span styleName='tag'>
{crisis.status === 'ARC' ?
<i className='ion-ios-box-outline' /> :
<i className='ion-ios-pulse' />
}
{crisisStatusText}
</span>
</div>
</li>
);
})}
</ul>
</div>
);
CrisisArchiveList.propTypes = propTypes;
export default CSSModules(CrisisArchiveList, styles);
| Temzasse/ntu-crysis | client/components/crisis/CrisisArchiveList/index.js | JavaScript | mit | 1,416 |
/**
* @ag-grid-community/core - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v25.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/** Provides sync access to async component. Date component can be lazy created - this class encapsulates
* this by keeping value locally until DateComp has loaded, then passing DateComp the value. */
var DateCompWrapper = /** @class */ (function () {
function DateCompWrapper(context, userComponentFactory, dateComponentParams, eParent) {
var _this = this;
this.alive = true;
this.context = context;
userComponentFactory.newDateComponent(dateComponentParams).then(function (dateComp) {
// because async, check the filter still exists after component comes back
if (!_this.alive) {
context.destroyBean(dateComp);
return;
}
_this.dateComp = dateComp;
eParent.appendChild(dateComp.getGui());
if (dateComp.afterGuiAttached) {
dateComp.afterGuiAttached();
}
if (_this.tempValue) {
dateComp.setDate(_this.tempValue);
}
});
}
DateCompWrapper.prototype.destroy = function () {
this.alive = false;
this.dateComp = this.context.destroyBean(this.dateComp);
};
DateCompWrapper.prototype.getDate = function () {
return this.dateComp ? this.dateComp.getDate() : this.tempValue;
};
DateCompWrapper.prototype.setDate = function (value) {
if (this.dateComp) {
this.dateComp.setDate(value);
}
else {
this.tempValue = value;
}
};
DateCompWrapper.prototype.setInputPlaceholder = function (placeholder) {
if (this.dateComp && this.dateComp.setInputPlaceholder) {
this.dateComp.setInputPlaceholder(placeholder);
}
};
DateCompWrapper.prototype.setInputAriaLabel = function (label) {
if (this.dateComp && this.dateComp.setInputAriaLabel) {
this.dateComp.setInputAriaLabel(label);
}
};
DateCompWrapper.prototype.afterGuiAttached = function (params) {
if (this.dateComp && typeof this.dateComp.afterGuiAttached === 'function') {
this.dateComp.afterGuiAttached(params);
}
};
return DateCompWrapper;
}());
exports.DateCompWrapper = DateCompWrapper;
//# sourceMappingURL=dateCompWrapper.js.map
| ceolter/angular-grid | community-modules/core/dist/cjs/filter/provided/date/dateCompWrapper.js | JavaScript | mit | 2,578 |
'use strict';
import './index.html';
import 'babel-core/polyfill';
import PIXI from 'pixi.js';
import TWEEN from 'tween.js';
import Renderer from './Renderer/Renderer';
import App from './displayobjects/App/App.js';
var renderer = new Renderer();
var stage = new PIXI.Stage(0x333333);
var app = new App(1920, 1080);
function animate() {
renderer.render(stage);
window.requestAnimationFrame(animate);
TWEEN.update();
}
document.body.appendChild(renderer.view);
stage.addChild(app);
animate();
| edwinwebb/dashboard-playground | app/app.js | JavaScript | mit | 506 |
/**
* @author mrdoob / http://mrdoob.com/
* @author *kile / http://kile.stravaganza.org/
* @author philogb / http://blog.thejit.org/
* @author mikael emtinger / http://gomo.se/
* @author egraether / http://egraether.com/
* @author WestLangley / http://github.com/WestLangley
*/
THREE.Vector3 = function ( x, y, z ) {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
};
THREE.Vector3.prototype = {
constructor: THREE.Vector3,
set: function ( x, y, z ) {
this.x = x;
this.y = y;
this.z = z;
return this;
},
setX: function ( x ) {
this.x = x;
return this;
},
setY: function ( y ) {
this.y = y;
return this;
},
setZ: function ( z ) {
this.z = z;
return this;
},
setComponent: function ( index, value ) {
switch ( index ) {
case 0: this.x = value; break;
case 1: this.y = value; break;
case 2: this.z = value; break;
default: throw new Error( 'index is out of range: ' + index );
}
},
getComponent: function ( index ) {
switch ( index ) {
case 0: return this.x;
case 1: return this.y;
case 2: return this.z;
default: throw new Error( 'index is out of range: ' + index );
}
},
copy: function ( v ) {
this.x = v.x;
this.y = v.y;
this.z = v.z;
return this;
},
add: function ( v, w ) {
this.x += v.x;
this.y += v.y;
this.z += v.z;
return this;
},
addScalar: function ( s ) {
this.x += s;
this.y += s;
this.z += s;
return this;
},
addVectors: function ( a, b ) {
this.x = a.x + b.x;
this.y = a.y + b.y;
this.z = a.z + b.z;
return this;
},
sub: function ( v, w ) {
this.x -= v.x;
this.y -= v.y;
this.z -= v.z;
return this;
},
subScalar: function ( s ) {
this.x -= s;
this.y -= s;
this.z -= s;
return this;
},
subVectors: function ( a, b ) {
this.x = a.x - b.x;
this.y = a.y - b.y;
this.z = a.z - b.z;
return this;
},
multiply: function ( v, w ) {
if ( w !== undefined ) {
THREE.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
return this.multiplyVectors( v, w );
}
this.x *= v.x;
this.y *= v.y;
this.z *= v.z;
return this;
},
multiplyScalar: function ( scalar ) {
this.x *= scalar;
this.y *= scalar;
this.z *= scalar;
return this;
},
multiplyVectors: function ( a, b ) {
this.x = a.x * b.x;
this.y = a.y * b.y;
this.z = a.z * b.z;
return this;
},
applyEuler: function () {
var quaternion;
return function ( euler ) {
if ( euler instanceof THREE.Euler === false ) {
THREE.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
}
if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
this.applyQuaternion( quaternion.setFromEuler( euler ) );
return this;
};
}(),
applyAxisAngle: function () {
var quaternion;
return function ( axis, angle ) {
if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
return this;
};
}(),
applyMatrix3: function ( m ) {
var x = this.x;
var y = this.y;
var z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
return this;
},
applyMatrix4: function ( m ) {
// input: THREE.Matrix4 affine matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
return this;
},
applyProjection: function ( m ) {
// input: THREE.Matrix4 projection matrix
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
return this;
},
applyQuaternion: function ( q ) {
var x = this.x;
var y = this.y;
var z = this.z;
var qx = q.x;
var qy = q.y;
var qz = q.z;
var qw = q.w;
// calculate quat * vector
var ix = qw * x + qy * z - qz * y;
var iy = qw * y + qz * x - qx * z;
var iz = qw * z + qx * y - qy * x;
var iw = - qx * x - qy * y - qz * z;
// calculate result * inverse quat
this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
return this;
},
project: function () {
var matrix;
return function ( camera ) {
if ( matrix === undefined ) matrix = new THREE.Matrix4();
matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
return this.applyProjection( matrix );
};
}(),
unproject: function () {
var matrix;
return function ( camera ) {
if ( matrix === undefined ) matrix = new THREE.Matrix4();
matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
return this.applyProjection( matrix );
};
}(),
transformDirection: function ( m ) {
// input: THREE.Matrix4 affine matrix
// vector interpreted as a direction
var x = this.x, y = this.y, z = this.z;
var e = m.elements;
this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
this.normalize();
return this;
},
divide: function ( v ) {
this.x /= v.x;
this.y /= v.y;
this.z /= v.z;
return this;
},
divideScalar: function ( scalar ) {
if ( scalar !== 0 ) {
var invScalar = 1 / scalar;
this.x *= invScalar;
this.y *= invScalar;
this.z *= invScalar;
} else {
this.x = 0;
this.y = 0;
this.z = 0;
}
return this;
},
min: function ( v ) {
if ( this.x > v.x ) {
this.x = v.x;
}
if ( this.y > v.y ) {
this.y = v.y;
}
if ( this.z > v.z ) {
this.z = v.z;
}
return this;
},
max: function ( v ) {
if ( this.x < v.x ) {
this.x = v.x;
}
if ( this.y < v.y ) {
this.y = v.y;
}
if ( this.z < v.z ) {
this.z = v.z;
}
return this;
},
clamp: function ( min, max ) {
// This function assumes min < max, if this assumption isn't true it will not operate correctly
if ( this.x < min.x ) {
this.x = min.x;
} else if ( this.x > max.x ) {
this.x = max.x;
}
if ( this.y < min.y ) {
this.y = min.y;
} else if ( this.y > max.y ) {
this.y = max.y;
}
if ( this.z < min.z ) {
this.z = min.z;
} else if ( this.z > max.z ) {
this.z = max.z;
}
return this;
},
clampScalar: ( function () {
var min, max;
return function ( minVal, maxVal ) {
if ( min === undefined ) {
min = new THREE.Vector3();
max = new THREE.Vector3();
}
min.set( minVal, minVal, minVal );
max.set( maxVal, maxVal, maxVal );
return this.clamp( min, max );
};
} )(),
floor: function () {
this.x = Math.floor( this.x );
this.y = Math.floor( this.y );
this.z = Math.floor( this.z );
return this;
},
ceil: function () {
this.x = Math.ceil( this.x );
this.y = Math.ceil( this.y );
this.z = Math.ceil( this.z );
return this;
},
round: function () {
this.x = Math.round( this.x );
this.y = Math.round( this.y );
this.z = Math.round( this.z );
return this;
},
roundToZero: function () {
this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
return this;
},
negate: function () {
this.x = - this.x;
this.y = - this.y;
this.z = - this.z;
return this;
},
dot: function ( v ) {
return this.x * v.x + this.y * v.y + this.z * v.z;
},
lengthSq: function () {
return this.x * this.x + this.y * this.y + this.z * this.z;
},
length: function () {
return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
},
lengthManhattan: function () {
return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
},
normalize: function () {
return this.divideScalar( this.length() );
},
setLength: function ( l ) {
var oldLength = this.length();
if ( oldLength !== 0 && l !== oldLength ) {
this.multiplyScalar( l / oldLength );
}
return this;
},
lerp: function ( v, alpha ) {
this.x += ( v.x - this.x ) * alpha;
this.y += ( v.y - this.y ) * alpha;
this.z += ( v.z - this.z ) * alpha;
return this;
},
lerpVectors: function ( v1, v2, alpha ) {
this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
return this;
},
cross: function ( v, w ) {
if ( w !== undefined ) {
THREE.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
return this.crossVectors( v, w );
}
var x = this.x, y = this.y, z = this.z;
this.x = y * v.z - z * v.y;
this.y = z * v.x - x * v.z;
this.z = x * v.y - y * v.x;
return this;
},
crossVectors: function ( a, b ) {
var ax = a.x, ay = a.y, az = a.z;
var bx = b.x, by = b.y, bz = b.z;
this.x = ay * bz - az * by;
this.y = az * bx - ax * bz;
this.z = ax * by - ay * bx;
return this;
},
projectOnVector: function () {
var v1, dot;
return function ( vector ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
v1.copy( vector ).normalize();
dot = this.dot( v1 );
return this.copy( v1 ).multiplyScalar( dot );
};
}(),
projectOnPlane: function () {
var v1;
return function ( planeNormal ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
v1.copy( this ).projectOnVector( planeNormal );
return this.sub( v1 );
}
}(),
reflect: function () {
// reflect incident vector off plane orthogonal to normal
// normal is assumed to have unit length
var v1;
return function ( normal ) {
if ( v1 === undefined ) v1 = new THREE.Vector3();
return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
}
}(),
angleTo: function ( v ) {
var theta = this.dot( v ) / ( this.length() * v.length() );
// clamp, to handle numerical problems
return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
},
distanceTo: function ( v ) {
return Math.sqrt( this.distanceToSquared( v ) );
},
distanceToSquared: function ( v ) {
var dx = this.x - v.x;
var dy = this.y - v.y;
var dz = this.z - v.z;
return dx * dx + dy * dy + dz * dz;
},
setEulerFromRotationMatrix: function ( m, order ) {
THREE.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
},
setEulerFromQuaternion: function ( q, order ) {
THREE.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
},
getPositionFromMatrix: function ( m ) {
THREE.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
return this.setFromMatrixPosition( m );
},
getScaleFromMatrix: function ( m ) {
THREE.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
return this.setFromMatrixScale( m );
},
getColumnFromMatrix: function ( index, matrix ) {
THREE.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
return this.setFromMatrixColumn( index, matrix );
},
setFromMatrixPosition: function ( m ) {
this.x = m.elements[ 12 ];
this.y = m.elements[ 13 ];
this.z = m.elements[ 14 ];
return this;
},
setFromMatrixScale: function ( m ) {
var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
this.x = sx;
this.y = sy;
this.z = sz;
return this;
},
setFromMatrixColumn: function ( index, matrix ) {
var offset = index * 4;
var me = matrix.elements;
this.x = me[ offset ];
this.y = me[ offset + 1 ];
this.z = me[ offset + 2 ];
return this;
},
equals: function ( v ) {
return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
},
fromArray: function ( array, offset ) {
if ( offset === undefined ) offset = 0;
this.x = array[ offset ];
this.y = array[ offset + 1 ];
this.z = array[ offset + 2 ];
return this;
},
toArray: function ( array, offset ) {
if ( array === undefined ) array = [];
if ( offset === undefined ) offset = 0;
array[ offset ] = this.x;
array[ offset + 1 ] = this.y;
array[ offset + 2 ] = this.z;
return array;
},
fromAttribute: function ( attribute, index, offset ) {
if ( offset === undefined ) offset = 0;
index = index * attribute.itemSize + offset;
this.x = attribute.array[ index ];
this.y = attribute.array[ index + 1 ];
this.z = attribute.array[ index + 2 ];
return this;
},
clone: function () {
return new THREE.Vector3( this.x, this.y, this.z );
}
};
| strandedcity/makeItZoom | src/threejs_files/Vector3.js | JavaScript | mit | 13,436 |
/*! Select2 4.1.0-beta.0 | https://github.com/select2/select2/blob/master/LICENSE.md */
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var n=jQuery.fn.select2.amd;n.define("select2/i18n/fa",[],function(){return{errorLoading:function(){return"امکان بارگذاری نتایج وجود ندارد."},inputTooLong:function(n){return"لطفاً "+(n.input.length-n.maximum)+" کاراکتر را حذف نمایید"},inputTooShort:function(n){return"لطفاً تعداد "+(n.minimum-n.input.length)+" کاراکتر یا بیشتر وارد نمایید"},loadingMore:function(){return"در حال بارگذاری نتایج بیشتر..."},maximumSelected:function(n){return"شما تنها میتوانید "+n.maximum+" آیتم را انتخاب نمایید"},noResults:function(){return"هیچ نتیجهای یافت نشد"},searching:function(){return"در حال جستجو..."},removeAllItems:function(){return"همه موارد را حذف کنید"}}}),n.define,n.require}(); | cdnjs/cdnjs | ajax/libs/select2/4.1.0-beta.0/js/i18n/fa.js | JavaScript | mit | 1,029 |
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.Dropbox = {}));
}(this, (function (exports) { 'use strict';
// Auto-generated by Stone, do not modify.
var routes = {};
/**
* Sets a user's profile photo.
* @function Dropbox#accountSetProfilePhoto
* @arg {AccountSetProfilePhotoArg} arg - The request parameters.
* @returns {Promise.<AccountSetProfilePhotoResult, Error.<AccountSetProfilePhotoError>>}
*/
routes.accountSetProfilePhoto = function (arg) {
return this.request('account/set_profile_photo', arg, 'user', 'api', 'rpc');
};
/**
* Creates an OAuth 2.0 access token from the supplied OAuth 1.0 access token.
* @function Dropbox#authTokenFromOauth1
* @arg {AuthTokenFromOAuth1Arg} arg - The request parameters.
* @returns {Promise.<AuthTokenFromOAuth1Result, Error.<AuthTokenFromOAuth1Error>>}
*/
routes.authTokenFromOauth1 = function (arg) {
return this.request('auth/token/from_oauth1', arg, 'app', 'api', 'rpc');
};
/**
* Disables the access token used to authenticate the call.
* @function Dropbox#authTokenRevoke
* @arg {void} arg - The request parameters.
* @returns {Promise.<void, Error.<void>>}
*/
routes.authTokenRevoke = function (arg) {
return this.request('auth/token/revoke', arg, 'user', 'api', 'rpc');
};
/**
* This endpoint performs App Authentication, validating the supplied app key
* and secret, and returns the supplied string, to allow you to test your code
* and connection to the Dropbox API. It has no other effect. If you receive an
* HTTP 200 response with the supplied query, it indicates at least part of the
* Dropbox API infrastructure is working and that the app key and secret valid.
* @function Dropbox#checkApp
* @arg {CheckEchoArg} arg - The request parameters.
* @returns {Promise.<CheckEchoResult, Error.<void>>}
*/
routes.checkApp = function (arg) {
return this.request('check/app', arg, 'app', 'api', 'rpc');
};
/**
* This endpoint performs User Authentication, validating the supplied access
* token, and returns the supplied string, to allow you to test your code and
* connection to the Dropbox API. It has no other effect. If you receive an HTTP
* 200 response with the supplied query, it indicates at least part of the
* Dropbox API infrastructure is working and that the access token is valid.
* @function Dropbox#checkUser
* @arg {CheckEchoArg} arg - The request parameters.
* @returns {Promise.<CheckEchoResult, Error.<void>>}
*/
routes.checkUser = function (arg) {
return this.request('check/user', arg, 'user', 'api', 'rpc');
};
/**
* Fetch the binary content of the requested document. This route requires Cloud
* Docs auth. Please make a request to cloud_docs/authorize and supply that
* token in the Authorization header.
* @function Dropbox#cloudDocsGetContent
* @arg {CloudDocsGetContentArg} arg - The request parameters.
* @returns {Promise.<void, Error.<CloudDocsCloudDocsAccessError>>}
*/
routes.cloudDocsGetContent = function (arg) {
return this.request('cloud_docs/get_content', arg, 'user', 'content', 'download');
};
/**
* Fetches metadata associated with a Cloud Doc and user. This route requires
* Cloud Docs auth. Please make a request to cloud_docs/authorize and supply
* that token in the Authorization header.
* @function Dropbox#cloudDocsGetMetadata
* @arg {CloudDocsGetMetadataArg} arg - The request parameters.
* @returns {Promise.<CloudDocsGetMetadataResult, Error.<CloudDocsGetMetadataError>>}
*/
routes.cloudDocsGetMetadata = function (arg) {
return this.request('cloud_docs/get_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Lock a Cloud Doc. This route requires Cloud Docs auth. Please make a request
* to cloud_docs/authorize and supply that token in the Authorization header.
* @function Dropbox#cloudDocsLock
* @arg {CloudDocsLockArg} arg - The request parameters.
* @returns {Promise.<CloudDocsLockResult, Error.<CloudDocsLockingError>>}
*/
routes.cloudDocsLock = function (arg) {
return this.request('cloud_docs/lock', arg, 'user', 'api', 'rpc');
};
/**
* Update the title of a Cloud Doc. This route requires Cloud Docs auth. Please
* make a request to cloud_docs/authorize and supply that token in the
* Authorization header.
* @function Dropbox#cloudDocsRename
* @arg {CloudDocsRenameArg} arg - The request parameters.
* @returns {Promise.<CloudDocsRenameResult, Error.<CloudDocsRenameError>>}
*/
routes.cloudDocsRename = function (arg) {
return this.request('cloud_docs/rename', arg, 'user', 'api', 'rpc');
};
/**
* Unlock a Cloud Doc. This route requires Cloud Docs auth. Please make a
* request to cloud_docs/authorize and supply that token in the Authorization
* header.
* @function Dropbox#cloudDocsUnlock
* @arg {CloudDocsUnlockArg} arg - The request parameters.
* @returns {Promise.<CloudDocsUnlockResult, Error.<CloudDocsLockingError>>}
*/
routes.cloudDocsUnlock = function (arg) {
return this.request('cloud_docs/unlock', arg, 'user', 'api', 'rpc');
};
/**
* Update the contents of a Cloud Doc. This should be called for files with a
* max size of 150MB. This route requires Cloud Docs auth. Please make a request
* to cloud_docs/authorize and supply that token in the Authorization header.
* @function Dropbox#cloudDocsUpdateContent
* @arg {CloudDocsUpdateContentArg} arg - The request parameters.
* @returns {Promise.<CloudDocsUpdateContentResult, Error.<CloudDocsUpdateContentError>>}
*/
routes.cloudDocsUpdateContent = function (arg) {
return this.request('cloud_docs/update_content', arg, 'user', 'content', 'upload');
};
/**
* Removes all manually added contacts. You'll still keep contacts who are on
* your team or who you imported. New contacts will be added when you share.
* @function Dropbox#contactsDeleteManualContacts
* @arg {void} arg - The request parameters.
* @returns {Promise.<void, Error.<void>>}
*/
routes.contactsDeleteManualContacts = function (arg) {
return this.request('contacts/delete_manual_contacts', arg, 'user', 'api', 'rpc');
};
/**
* Removes manually added contacts from the given list.
* @function Dropbox#contactsDeleteManualContactsBatch
* @arg {ContactsDeleteManualContactsArg} arg - The request parameters.
* @returns {Promise.<void, Error.<ContactsDeleteManualContactsError>>}
*/
routes.contactsDeleteManualContactsBatch = function (arg) {
return this.request('contacts/delete_manual_contacts_batch', arg, 'user', 'api', 'rpc');
};
/**
* Add property groups to a Dropbox file. See templates/add_for_user or
* templates/add_for_team to create new templates.
* @function Dropbox#filePropertiesPropertiesAdd
* @arg {FilePropertiesAddPropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesAddPropertiesError>>}
*/
routes.filePropertiesPropertiesAdd = function (arg) {
return this.request('file_properties/properties/add', arg, 'user', 'api', 'rpc');
};
/**
* Overwrite property groups associated with a file. This endpoint should be
* used instead of properties/update when property groups are being updated via
* a "snapshot" instead of via a "delta". In other words, this endpoint will
* delete all omitted fields from a property group, whereas properties/update
* will only delete fields that are explicitly marked for deletion.
* @function Dropbox#filePropertiesPropertiesOverwrite
* @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesInvalidPropertyGroupError>>}
*/
routes.filePropertiesPropertiesOverwrite = function (arg) {
return this.request('file_properties/properties/overwrite', arg, 'user', 'api', 'rpc');
};
/**
* Permanently removes the specified property group from the file. To remove
* specific property field key value pairs, see properties/update. To update a
* template, see templates/update_for_user or templates/update_for_team. To
* remove a template, see templates/remove_for_user or
* templates/remove_for_team.
* @function Dropbox#filePropertiesPropertiesRemove
* @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesRemovePropertiesError>>}
*/
routes.filePropertiesPropertiesRemove = function (arg) {
return this.request('file_properties/properties/remove', arg, 'user', 'api', 'rpc');
};
/**
* Search across property templates for particular property field values.
* @function Dropbox#filePropertiesPropertiesSearch
* @arg {FilePropertiesPropertiesSearchArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesPropertiesSearchResult, Error.<FilePropertiesPropertiesSearchError>>}
*/
routes.filePropertiesPropertiesSearch = function (arg) {
return this.request('file_properties/properties/search', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from properties/search, use this to paginate
* through all search results.
* @function Dropbox#filePropertiesPropertiesSearchContinue
* @arg {FilePropertiesPropertiesSearchContinueArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesPropertiesSearchResult, Error.<FilePropertiesPropertiesSearchContinueError>>}
*/
routes.filePropertiesPropertiesSearchContinue = function (arg) {
return this.request('file_properties/properties/search/continue', arg, 'user', 'api', 'rpc');
};
/**
* Add, update or remove properties associated with the supplied file and
* templates. This endpoint should be used instead of properties/overwrite when
* property groups are being updated via a "delta" instead of via a "snapshot" .
* In other words, this endpoint will not delete any omitted fields from a
* property group, whereas properties/overwrite will delete any fields that are
* omitted from a property group.
* @function Dropbox#filePropertiesPropertiesUpdate
* @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesUpdatePropertiesError>>}
*/
routes.filePropertiesPropertiesUpdate = function (arg) {
return this.request('file_properties/properties/update', arg, 'user', 'api', 'rpc');
};
/**
* Add a template associated with a team. See properties/add to add properties
* to a file or folder. Note: this endpoint will create team-owned templates.
* @function Dropbox#filePropertiesTemplatesAddForTeam
* @arg {FilePropertiesAddTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes.filePropertiesTemplatesAddForTeam = function (arg) {
return this.request('file_properties/templates/add_for_team', arg, 'team', 'api', 'rpc');
};
/**
* Add a template associated with a user. See properties/add to add properties
* to a file. This endpoint can't be called on a team member or admin's behalf.
* @function Dropbox#filePropertiesTemplatesAddForUser
* @arg {FilePropertiesAddTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes.filePropertiesTemplatesAddForUser = function (arg) {
return this.request('file_properties/templates/add_for_user', arg, 'user', 'api', 'rpc');
};
/**
* Get the schema for a specified template.
* @function Dropbox#filePropertiesTemplatesGetForTeam
* @arg {FilePropertiesGetTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesGetForTeam = function (arg) {
return this.request('file_properties/templates/get_for_team', arg, 'team', 'api', 'rpc');
};
/**
* Get the schema for a specified template. This endpoint can't be called on a
* team member or admin's behalf.
* @function Dropbox#filePropertiesTemplatesGetForUser
* @arg {FilePropertiesGetTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesGetForUser = function (arg) {
return this.request('file_properties/templates/get_for_user', arg, 'user', 'api', 'rpc');
};
/**
* Get the template identifiers for a team. To get the schema of each template
* use templates/get_for_team.
* @function Dropbox#filePropertiesTemplatesListForTeam
* @arg {void} arg - The request parameters.
* @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesListForTeam = function (arg) {
return this.request('file_properties/templates/list_for_team', arg, 'team', 'api', 'rpc');
};
/**
* Get the template identifiers for a team. To get the schema of each template
* use templates/get_for_user. This endpoint can't be called on a team member or
* admin's behalf.
* @function Dropbox#filePropertiesTemplatesListForUser
* @arg {void} arg - The request parameters.
* @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesListForUser = function (arg) {
return this.request('file_properties/templates/list_for_user', arg, 'user', 'api', 'rpc');
};
/**
* Permanently removes the specified template created from
* templates/add_for_user. All properties associated with the template will also
* be removed. This action cannot be undone.
* @function Dropbox#filePropertiesTemplatesRemoveForTeam
* @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesRemoveForTeam = function (arg) {
return this.request('file_properties/templates/remove_for_team', arg, 'team', 'api', 'rpc');
};
/**
* Permanently removes the specified template created from
* templates/add_for_user. All properties associated with the template will also
* be removed. This action cannot be undone.
* @function Dropbox#filePropertiesTemplatesRemoveForUser
* @arg {FilePropertiesRemoveTemplateArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesTemplateError>>}
*/
routes.filePropertiesTemplatesRemoveForUser = function (arg) {
return this.request('file_properties/templates/remove_for_user', arg, 'user', 'api', 'rpc');
};
/**
* Update a template associated with a team. This route can update the template
* name, the template description and add optional properties to templates.
* @function Dropbox#filePropertiesTemplatesUpdateForTeam
* @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes.filePropertiesTemplatesUpdateForTeam = function (arg) {
return this.request('file_properties/templates/update_for_team', arg, 'team', 'api', 'rpc');
};
/**
* Update a template associated with a user. This route can update the template
* name, the template description and add optional properties to templates. This
* endpoint can't be called on a team member or admin's behalf.
* @function Dropbox#filePropertiesTemplatesUpdateForUser
* @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes.filePropertiesTemplatesUpdateForUser = function (arg) {
return this.request('file_properties/templates/update_for_user', arg, 'user', 'api', 'rpc');
};
/**
* Returns the total number of file requests owned by this user. Includes both
* open and closed file requests.
* @function Dropbox#fileRequestsCount
* @arg {void} arg - The request parameters.
* @returns {Promise.<FileRequestsCountFileRequestsResult, Error.<FileRequestsCountFileRequestsError>>}
*/
routes.fileRequestsCount = function (arg) {
return this.request('file_requests/count', arg, 'user', 'api', 'rpc');
};
/**
* Creates a file request for this user.
* @function Dropbox#fileRequestsCreate
* @arg {FileRequestsCreateFileRequestArgs} arg - The request parameters.
* @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsCreateFileRequestError>>}
*/
routes.fileRequestsCreate = function (arg) {
return this.request('file_requests/create', arg, 'user', 'api', 'rpc');
};
/**
* Delete a batch of closed file requests.
* @function Dropbox#fileRequestsDelete
* @arg {FileRequestsDeleteFileRequestArgs} arg - The request parameters.
* @returns {Promise.<FileRequestsDeleteFileRequestsResult, Error.<FileRequestsDeleteFileRequestError>>}
*/
routes.fileRequestsDelete = function (arg) {
return this.request('file_requests/delete', arg, 'user', 'api', 'rpc');
};
/**
* Delete all closed file requests owned by this user.
* @function Dropbox#fileRequestsDeleteAllClosed
* @arg {void} arg - The request parameters.
* @returns {Promise.<FileRequestsDeleteAllClosedFileRequestsResult, Error.<FileRequestsDeleteAllClosedFileRequestsError>>}
*/
routes.fileRequestsDeleteAllClosed = function (arg) {
return this.request('file_requests/delete_all_closed', arg, 'user', 'api', 'rpc');
};
/**
* Returns the specified file request.
* @function Dropbox#fileRequestsGet
* @arg {FileRequestsGetFileRequestArgs} arg - The request parameters.
* @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsGetFileRequestError>>}
*/
routes.fileRequestsGet = function (arg) {
return this.request('file_requests/get', arg, 'user', 'api', 'rpc');
};
/**
* Returns a list of file requests owned by this user. For apps with the app
* folder permission, this will only return file requests with destinations in
* the app folder.
* @function Dropbox#fileRequestsListV2
* @arg {FileRequestsListFileRequestsArg} arg - The request parameters.
* @returns {Promise.<FileRequestsListFileRequestsV2Result, Error.<FileRequestsListFileRequestsError>>}
*/
routes.fileRequestsListV2 = function (arg) {
return this.request('file_requests/list_v2', arg, 'user', 'api', 'rpc');
};
/**
* Returns a list of file requests owned by this user. For apps with the app
* folder permission, this will only return file requests with destinations in
* the app folder.
* @function Dropbox#fileRequestsList
* @arg {void} arg - The request parameters.
* @returns {Promise.<FileRequestsListFileRequestsResult, Error.<FileRequestsListFileRequestsError>>}
*/
routes.fileRequestsList = function (arg) {
return this.request('file_requests/list', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_v2, use this to paginate through
* all file requests. The cursor must come from a previous call to list_v2 or
* list/continue.
* @function Dropbox#fileRequestsListContinue
* @arg {FileRequestsListFileRequestsContinueArg} arg - The request parameters.
* @returns {Promise.<FileRequestsListFileRequestsV2Result, Error.<FileRequestsListFileRequestsContinueError>>}
*/
routes.fileRequestsListContinue = function (arg) {
return this.request('file_requests/list/continue', arg, 'user', 'api', 'rpc');
};
/**
* Update a file request.
* @function Dropbox#fileRequestsUpdate
* @arg {FileRequestsUpdateFileRequestArgs} arg - The request parameters.
* @returns {Promise.<FileRequestsFileRequest, Error.<FileRequestsUpdateFileRequestError>>}
*/
routes.fileRequestsUpdate = function (arg) {
return this.request('file_requests/update', arg, 'user', 'api', 'rpc');
};
/**
* Returns the metadata for a file or folder. This is an alpha endpoint
* compatible with the properties API. Note: Metadata for the root folder is
* unsupported.
* @function Dropbox#filesAlphaGetMetadata
* @deprecated
* @arg {FilesAlphaGetMetadataArg} arg - The request parameters.
* @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesAlphaGetMetadataError>>}
*/
routes.filesAlphaGetMetadata = function (arg) {
return this.request('files/alpha/get_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Create a new file with the contents provided in the request. Note that this
* endpoint is part of the properties API alpha and is slightly different from
* upload. Do not use this to upload a file larger than 150 MB. Instead, create
* an upload session with upload_session/start.
* @function Dropbox#filesAlphaUpload
* @deprecated
* @arg {FilesCommitInfoWithProperties} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesUploadErrorWithProperties>>}
*/
routes.filesAlphaUpload = function (arg) {
return this.request('files/alpha/upload', arg, 'user', 'content', 'upload');
};
/**
* Copy a file or folder to a different location in the user's Dropbox. If the
* source path is a folder all its contents will be copied.
* @function Dropbox#filesCopyV2
* @arg {FilesRelocationArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationResult, Error.<FilesRelocationError>>}
*/
routes.filesCopyV2 = function (arg) {
return this.request('files/copy_v2', arg, 'user', 'api', 'rpc');
};
/**
* Copy a file or folder to a different location in the user's Dropbox. If the
* source path is a folder all its contents will be copied.
* @function Dropbox#filesCopy
* @deprecated
* @arg {FilesRelocationArg} arg - The request parameters.
* @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesRelocationError>>}
*/
routes.filesCopy = function (arg) {
return this.request('files/copy', arg, 'user', 'api', 'rpc');
};
/**
* Copy multiple files or folders to different locations at once in the user's
* Dropbox. This route will replace copy_batch. The main difference is this
* route will return status for each entry, while copy_batch raises failure if
* any entry fails. This route will either finish synchronously, or return a job
* ID and do the async copy job in background. Please use copy_batch/check_v2 to
* check the job status.
* @function Dropbox#filesCopyBatchV2
* @arg {Object} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchV2Launch, Error.<void>>}
*/
routes.filesCopyBatchV2 = function (arg) {
return this.request('files/copy_batch_v2', arg, 'user', 'api', 'rpc');
};
/**
* Copy multiple files or folders to different locations at once in the user's
* Dropbox. If RelocationBatchArg.allow_shared_folder is false, this route is
* atomic. If one entry fails, the whole transaction will abort. If
* RelocationBatchArg.allow_shared_folder is true, atomicity is not guaranteed,
* but it allows you to copy the contents of shared folders to new locations.
* This route will return job ID immediately and do the async copy job in
* background. Please use copy_batch/check to check the job status.
* @function Dropbox#filesCopyBatch
* @deprecated
* @arg {FilesRelocationBatchArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchLaunch, Error.<void>>}
*/
routes.filesCopyBatch = function (arg) {
return this.request('files/copy_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for copy_batch_v2. It returns list
* of results for each entry.
* @function Dropbox#filesCopyBatchCheckV2
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchV2JobStatus, Error.<AsyncPollError>>}
*/
routes.filesCopyBatchCheckV2 = function (arg) {
return this.request('files/copy_batch/check_v2', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for copy_batch. If success, it
* returns list of results for each entry.
* @function Dropbox#filesCopyBatchCheck
* @deprecated
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchJobStatus, Error.<AsyncPollError>>}
*/
routes.filesCopyBatchCheck = function (arg) {
return this.request('files/copy_batch/check', arg, 'user', 'api', 'rpc');
};
/**
* Get a copy reference to a file or folder. This reference string can be used
* to save that file or folder to another user's Dropbox by passing it to
* copy_reference/save.
* @function Dropbox#filesCopyReferenceGet
* @arg {FilesGetCopyReferenceArg} arg - The request parameters.
* @returns {Promise.<FilesGetCopyReferenceResult, Error.<FilesGetCopyReferenceError>>}
*/
routes.filesCopyReferenceGet = function (arg) {
return this.request('files/copy_reference/get', arg, 'user', 'api', 'rpc');
};
/**
* Save a copy reference returned by copy_reference/get to the user's Dropbox.
* @function Dropbox#filesCopyReferenceSave
* @arg {FilesSaveCopyReferenceArg} arg - The request parameters.
* @returns {Promise.<FilesSaveCopyReferenceResult, Error.<FilesSaveCopyReferenceError>>}
*/
routes.filesCopyReferenceSave = function (arg) {
return this.request('files/copy_reference/save', arg, 'user', 'api', 'rpc');
};
/**
* Create a folder at a given path.
* @function Dropbox#filesCreateFolderV2
* @arg {FilesCreateFolderArg} arg - The request parameters.
* @returns {Promise.<FilesCreateFolderResult, Error.<FilesCreateFolderError>>}
*/
routes.filesCreateFolderV2 = function (arg) {
return this.request('files/create_folder_v2', arg, 'user', 'api', 'rpc');
};
/**
* Create a folder at a given path.
* @function Dropbox#filesCreateFolder
* @deprecated
* @arg {FilesCreateFolderArg} arg - The request parameters.
* @returns {Promise.<FilesFolderMetadata, Error.<FilesCreateFolderError>>}
*/
routes.filesCreateFolder = function (arg) {
return this.request('files/create_folder', arg, 'user', 'api', 'rpc');
};
/**
* Create multiple folders at once. This route is asynchronous for large
* batches, which returns a job ID immediately and runs the create folder batch
* asynchronously. Otherwise, creates the folders and returns the result
* synchronously for smaller inputs. You can force asynchronous behaviour by
* using the CreateFolderBatchArg.force_async flag. Use
* create_folder_batch/check to check the job status.
* @function Dropbox#filesCreateFolderBatch
* @arg {FilesCreateFolderBatchArg} arg - The request parameters.
* @returns {Promise.<FilesCreateFolderBatchLaunch, Error.<void>>}
*/
routes.filesCreateFolderBatch = function (arg) {
return this.request('files/create_folder_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for create_folder_batch. If
* success, it returns list of result for each entry.
* @function Dropbox#filesCreateFolderBatchCheck
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesCreateFolderBatchJobStatus, Error.<AsyncPollError>>}
*/
routes.filesCreateFolderBatchCheck = function (arg) {
return this.request('files/create_folder_batch/check', arg, 'user', 'api', 'rpc');
};
/**
* Delete the file or folder at a given path. If the path is a folder, all its
* contents will be deleted too. A successful response indicates that the file
* or folder was deleted. The returned metadata will be the corresponding
* FileMetadata or FolderMetadata for the item at time of deletion, and not a
* DeletedMetadata object.
* @function Dropbox#filesDeleteV2
* @arg {FilesDeleteArg} arg - The request parameters.
* @returns {Promise.<FilesDeleteResult, Error.<FilesDeleteError>>}
*/
routes.filesDeleteV2 = function (arg) {
return this.request('files/delete_v2', arg, 'user', 'api', 'rpc');
};
/**
* Delete the file or folder at a given path. If the path is a folder, all its
* contents will be deleted too. A successful response indicates that the file
* or folder was deleted. The returned metadata will be the corresponding
* FileMetadata or FolderMetadata for the item at time of deletion, and not a
* DeletedMetadata object.
* @function Dropbox#filesDelete
* @deprecated
* @arg {FilesDeleteArg} arg - The request parameters.
* @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesDeleteError>>}
*/
routes.filesDelete = function (arg) {
return this.request('files/delete', arg, 'user', 'api', 'rpc');
};
/**
* Delete multiple files/folders at once. This route is asynchronous, which
* returns a job ID immediately and runs the delete batch asynchronously. Use
* delete_batch/check to check the job status.
* @function Dropbox#filesDeleteBatch
* @arg {FilesDeleteBatchArg} arg - The request parameters.
* @returns {Promise.<FilesDeleteBatchLaunch, Error.<void>>}
*/
routes.filesDeleteBatch = function (arg) {
return this.request('files/delete_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for delete_batch. If success, it
* returns list of result for each entry.
* @function Dropbox#filesDeleteBatchCheck
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesDeleteBatchJobStatus, Error.<AsyncPollError>>}
*/
routes.filesDeleteBatchCheck = function (arg) {
return this.request('files/delete_batch/check', arg, 'user', 'api', 'rpc');
};
/**
* Download a file from a user's Dropbox.
* @function Dropbox#filesDownload
* @arg {FilesDownloadArg} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesDownloadError>>}
*/
routes.filesDownload = function (arg) {
return this.request('files/download', arg, 'user', 'content', 'download');
};
/**
* Download a folder from the user's Dropbox, as a zip file. The folder must be
* less than 20 GB in size and have fewer than 10,000 total files. The input
* cannot be a single file. Any single file must be less than 4GB in size.
* @function Dropbox#filesDownloadZip
* @arg {FilesDownloadZipArg} arg - The request parameters.
* @returns {Promise.<FilesDownloadZipResult, Error.<FilesDownloadZipError>>}
*/
routes.filesDownloadZip = function (arg) {
return this.request('files/download_zip', arg, 'user', 'content', 'download');
};
/**
* Export a file from a user's Dropbox. This route only supports exporting files
* that cannot be downloaded directly and whose ExportResult.file_metadata has
* ExportInfo.export_as populated.
* @function Dropbox#filesExport
* @arg {FilesExportArg} arg - The request parameters.
* @returns {Promise.<FilesExportResult, Error.<FilesExportError>>}
*/
routes.filesExport = function (arg) {
return this.request('files/export', arg, 'user', 'content', 'download');
};
/**
* Return the lock metadata for the given list of paths.
* @function Dropbox#filesGetFileLockBatch
* @arg {FilesLockFileBatchArg} arg - The request parameters.
* @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>}
*/
routes.filesGetFileLockBatch = function (arg) {
return this.request('files/get_file_lock_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the metadata for a file or folder. Note: Metadata for the root folder
* is unsupported.
* @function Dropbox#filesGetMetadata
* @arg {FilesGetMetadataArg} arg - The request parameters.
* @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesGetMetadataError>>}
*/
routes.filesGetMetadata = function (arg) {
return this.request('files/get_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Get a preview for a file. Currently, PDF previews are generated for files
* with the following extensions: .ai, .doc, .docm, .docx, .eps, .gdoc,
* .gslides, .odp, .odt, .pps, .ppsm, .ppsx, .ppt, .pptm, .pptx, .rtf. HTML
* previews are generated for files with the following extensions: .csv, .ods,
* .xls, .xlsm, .gsheet, .xlsx. Other formats will return an unsupported
* extension error.
* @function Dropbox#filesGetPreview
* @arg {FilesPreviewArg} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesPreviewError>>}
*/
routes.filesGetPreview = function (arg) {
return this.request('files/get_preview', arg, 'user', 'content', 'download');
};
/**
* Get a temporary link to stream content of a file. This link will expire in
* four hours and afterwards you will get 410 Gone. This URL should not be used
* to display content directly in the browser. The Content-Type of the link is
* determined automatically by the file's mime type.
* @function Dropbox#filesGetTemporaryLink
* @arg {FilesGetTemporaryLinkArg} arg - The request parameters.
* @returns {Promise.<FilesGetTemporaryLinkResult, Error.<FilesGetTemporaryLinkError>>}
*/
routes.filesGetTemporaryLink = function (arg) {
return this.request('files/get_temporary_link', arg, 'user', 'api', 'rpc');
};
/**
* Get a one-time use temporary upload link to upload a file to a Dropbox
* location. This endpoint acts as a delayed upload. The returned temporary
* upload link may be used to make a POST request with the data to be uploaded.
* The upload will then be perfomed with the CommitInfo previously provided to
* get_temporary_upload_link but evaluated only upon consumption. Hence, errors
* stemming from invalid CommitInfo with respect to the state of the user's
* Dropbox will only be communicated at consumption time. Additionally, these
* errors are surfaced as generic HTTP 409 Conflict responses, potentially
* hiding issue details. The maximum temporary upload link duration is 4 hours.
* Upon consumption or expiration, a new link will have to be generated.
* Multiple links may exist for a specific upload path at any given time. The
* POST request on the temporary upload link must have its Content-Type set to
* "application/octet-stream". Example temporary upload link consumption
* request: curl -X POST
* https://dl.dropboxusercontent.com/apitul/1/bNi2uIYF51cVBND --header
* "Content-Type: application/octet-stream" --data-binary @local_file.txt A
* successful temporary upload link consumption request returns the content hash
* of the uploaded data in JSON format. Example succesful temporary upload link
* consumption response: {"content-hash":
* "599d71033d700ac892a0e48fa61b125d2f5994"} An unsuccessful temporary upload
* link consumption request returns any of the following status codes: HTTP 400
* Bad Request: Content-Type is not one of application/octet-stream and
* text/plain or request is invalid. HTTP 409 Conflict: The temporary upload
* link does not exist or is currently unavailable, the upload failed, or
* another error happened. HTTP 410 Gone: The temporary upload link is expired
* or consumed. Example unsuccessful temporary upload link consumption
* response: Temporary upload link has been recently consumed.
* @function Dropbox#filesGetTemporaryUploadLink
* @arg {FilesGetTemporaryUploadLinkArg} arg - The request parameters.
* @returns {Promise.<FilesGetTemporaryUploadLinkResult, Error.<void>>}
*/
routes.filesGetTemporaryUploadLink = function (arg) {
return this.request('files/get_temporary_upload_link', arg, 'user', 'api', 'rpc');
};
/**
* Get a thumbnail for an image. This method currently supports files with the
* following file extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos
* that are larger than 20MB in size won't be converted to a thumbnail.
* @function Dropbox#filesGetThumbnail
* @arg {FilesThumbnailArg} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesThumbnailError>>}
*/
routes.filesGetThumbnail = function (arg) {
return this.request('files/get_thumbnail', arg, 'user', 'content', 'download');
};
/**
* Get a thumbnail for a file.
* @function Dropbox#filesGetThumbnailV2
* @arg {FilesThumbnailV2Arg} arg - The request parameters.
* @returns {Promise.<FilesPreviewResult, Error.<FilesThumbnailV2Error>>}
*/
routes.filesGetThumbnailV2 = function (arg) {
return this.request('files/get_thumbnail_v2', arg, 'app, user', 'content', 'download');
};
/**
* Get thumbnails for a list of images. We allow up to 25 thumbnails in a single
* batch. This method currently supports files with the following file
* extensions: jpg, jpeg, png, tiff, tif, gif and bmp. Photos that are larger
* than 20MB in size won't be converted to a thumbnail.
* @function Dropbox#filesGetThumbnailBatch
* @arg {FilesGetThumbnailBatchArg} arg - The request parameters.
* @returns {Promise.<FilesGetThumbnailBatchResult, Error.<FilesGetThumbnailBatchError>>}
*/
routes.filesGetThumbnailBatch = function (arg) {
return this.request('files/get_thumbnail_batch', arg, 'user', 'content', 'rpc');
};
/**
* Starts returning the contents of a folder. If the result's
* ListFolderResult.has_more field is true, call list_folder/continue with the
* returned ListFolderResult.cursor to retrieve more entries. If you're using
* ListFolderArg.recursive set to true to keep a local cache of the contents of
* a Dropbox account, iterate through each entry in order and process them as
* follows to keep your local state in sync: For each FileMetadata, store the
* new entry at the given path in your local state. If the required parent
* folders don't exist yet, create them. If there's already something else at
* the given path, replace it and remove all its children. For each
* FolderMetadata, store the new entry at the given path in your local state. If
* the required parent folders don't exist yet, create them. If there's already
* something else at the given path, replace it but leave the children as they
* are. Check the new entry's FolderSharingInfo.read_only and set all its
* children's read-only statuses to match. For each DeletedMetadata, if your
* local state has something at the given path, remove it and all its children.
* If there's nothing at the given path, ignore this entry. Note:
* auth.RateLimitError may be returned if multiple list_folder or
* list_folder/continue calls with same parameters are made simultaneously by
* same API app for same user. If your app implements retry logic, please hold
* off the retry until the previous request finishes.
* @function Dropbox#filesListFolder
* @arg {FilesListFolderArg} arg - The request parameters.
* @returns {Promise.<FilesListFolderResult, Error.<FilesListFolderError>>}
*/
routes.filesListFolder = function (arg) {
return this.request('files/list_folder', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_folder, use this to paginate
* through all files and retrieve updates to the folder, following the same
* rules as documented for list_folder.
* @function Dropbox#filesListFolderContinue
* @arg {FilesListFolderContinueArg} arg - The request parameters.
* @returns {Promise.<FilesListFolderResult, Error.<FilesListFolderContinueError>>}
*/
routes.filesListFolderContinue = function (arg) {
return this.request('files/list_folder/continue', arg, 'user', 'api', 'rpc');
};
/**
* A way to quickly get a cursor for the folder's state. Unlike list_folder,
* list_folder/get_latest_cursor doesn't return any entries. This endpoint is
* for app which only needs to know about new files and modifications and
* doesn't need to know about files that already exist in Dropbox.
* @function Dropbox#filesListFolderGetLatestCursor
* @arg {FilesListFolderArg} arg - The request parameters.
* @returns {Promise.<FilesListFolderGetLatestCursorResult, Error.<FilesListFolderError>>}
*/
routes.filesListFolderGetLatestCursor = function (arg) {
return this.request('files/list_folder/get_latest_cursor', arg, 'user', 'api', 'rpc');
};
/**
* A longpoll endpoint to wait for changes on an account. In conjunction with
* list_folder/continue, this call gives you a low-latency way to monitor an
* account for file changes. The connection will block until there are changes
* available or a timeout occurs. This endpoint is useful mostly for client-side
* apps. If you're looking for server-side notifications, check out our webhooks
* documentation https://www.dropbox.com/developers/reference/webhooks.
* @function Dropbox#filesListFolderLongpoll
* @arg {FilesListFolderLongpollArg} arg - The request parameters.
* @returns {Promise.<FilesListFolderLongpollResult, Error.<FilesListFolderLongpollError>>}
*/
routes.filesListFolderLongpoll = function (arg) {
return this.request('files/list_folder/longpoll', arg, 'noauth', 'notify', 'rpc');
};
/**
* Returns revisions for files based on a file path or a file id. The file path
* or file id is identified from the latest file entry at the given file path or
* id. This end point allows your app to query either by file path or file id by
* setting the mode parameter appropriately. In the ListRevisionsMode.path
* (default) mode, all revisions at the same file path as the latest file entry
* are returned. If revisions with the same file id are desired, then mode must
* be set to ListRevisionsMode.id. The ListRevisionsMode.id mode is useful to
* retrieve revisions for a given file across moves or renames.
* @function Dropbox#filesListRevisions
* @arg {FilesListRevisionsArg} arg - The request parameters.
* @returns {Promise.<FilesListRevisionsResult, Error.<FilesListRevisionsError>>}
*/
routes.filesListRevisions = function (arg) {
return this.request('files/list_revisions', arg, 'user', 'api', 'rpc');
};
/**
* Lock the files at the given paths. A locked file will be writable only by the
* lock holder. A successful response indicates that the file has been locked.
* Returns a list of the locked file paths and their metadata after this
* operation.
* @function Dropbox#filesLockFileBatch
* @arg {FilesLockFileBatchArg} arg - The request parameters.
* @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>}
*/
routes.filesLockFileBatch = function (arg) {
return this.request('files/lock_file_batch', arg, 'user', 'api', 'rpc');
};
/**
* Move a file or folder to a different location in the user's Dropbox. If the
* source path is a folder all its contents will be moved. Note that we do not
* currently support case-only renaming.
* @function Dropbox#filesMoveV2
* @arg {FilesRelocationArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationResult, Error.<FilesRelocationError>>}
*/
routes.filesMoveV2 = function (arg) {
return this.request('files/move_v2', arg, 'user', 'api', 'rpc');
};
/**
* Move a file or folder to a different location in the user's Dropbox. If the
* source path is a folder all its contents will be moved.
* @function Dropbox#filesMove
* @deprecated
* @arg {FilesRelocationArg} arg - The request parameters.
* @returns {Promise.<(FilesFileMetadata|FilesFolderMetadata|FilesDeletedMetadata), Error.<FilesRelocationError>>}
*/
routes.filesMove = function (arg) {
return this.request('files/move', arg, 'user', 'api', 'rpc');
};
/**
* Move multiple files or folders to different locations at once in the user's
* Dropbox. Note that we do not currently support case-only renaming. This route
* will replace move_batch. The main difference is this route will return status
* for each entry, while move_batch raises failure if any entry fails. This
* route will either finish synchronously, or return a job ID and do the async
* move job in background. Please use move_batch/check_v2 to check the job
* status.
* @function Dropbox#filesMoveBatchV2
* @arg {FilesMoveBatchArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchV2Launch, Error.<void>>}
*/
routes.filesMoveBatchV2 = function (arg) {
return this.request('files/move_batch_v2', arg, 'user', 'api', 'rpc');
};
/**
* Move multiple files or folders to different locations at once in the user's
* Dropbox. This route will return job ID immediately and do the async moving
* job in background. Please use move_batch/check to check the job status.
* @function Dropbox#filesMoveBatch
* @deprecated
* @arg {FilesRelocationBatchArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchLaunch, Error.<void>>}
*/
routes.filesMoveBatch = function (arg) {
return this.request('files/move_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for move_batch_v2. It returns list
* of results for each entry.
* @function Dropbox#filesMoveBatchCheckV2
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchV2JobStatus, Error.<AsyncPollError>>}
*/
routes.filesMoveBatchCheckV2 = function (arg) {
return this.request('files/move_batch/check_v2', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for move_batch. If success, it
* returns list of results for each entry.
* @function Dropbox#filesMoveBatchCheck
* @deprecated
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesRelocationBatchJobStatus, Error.<AsyncPollError>>}
*/
routes.filesMoveBatchCheck = function (arg) {
return this.request('files/move_batch/check', arg, 'user', 'api', 'rpc');
};
/**
* Permanently delete the file or folder at a given path (see
* https://www.dropbox.com/en/help/40). Note: This endpoint is only available
* for Dropbox Business apps.
* @function Dropbox#filesPermanentlyDelete
* @arg {FilesDeleteArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilesDeleteError>>}
*/
routes.filesPermanentlyDelete = function (arg) {
return this.request('files/permanently_delete', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesAdd
* @deprecated
* @arg {FilePropertiesAddPropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesAddPropertiesError>>}
*/
routes.filesPropertiesAdd = function (arg) {
return this.request('files/properties/add', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesOverwrite
* @deprecated
* @arg {FilePropertiesOverwritePropertyGroupArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesInvalidPropertyGroupError>>}
*/
routes.filesPropertiesOverwrite = function (arg) {
return this.request('files/properties/overwrite', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesRemove
* @deprecated
* @arg {FilePropertiesRemovePropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesRemovePropertiesError>>}
*/
routes.filesPropertiesRemove = function (arg) {
return this.request('files/properties/remove', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesTemplateGet
* @deprecated
* @arg {FilePropertiesGetTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filesPropertiesTemplateGet = function (arg) {
return this.request('files/properties/template/get', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesTemplateList
* @deprecated
* @arg {void} arg - The request parameters.
* @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes.filesPropertiesTemplateList = function (arg) {
return this.request('files/properties/template/list', arg, 'user', 'api', 'rpc');
};
/**
* @function Dropbox#filesPropertiesUpdate
* @deprecated
* @arg {FilePropertiesUpdatePropertiesArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilePropertiesUpdatePropertiesError>>}
*/
routes.filesPropertiesUpdate = function (arg) {
return this.request('files/properties/update', arg, 'user', 'api', 'rpc');
};
/**
* Restore a specific revision of a file to the given path.
* @function Dropbox#filesRestore
* @arg {FilesRestoreArg} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesRestoreError>>}
*/
routes.filesRestore = function (arg) {
return this.request('files/restore', arg, 'user', 'api', 'rpc');
};
/**
* Save the data from a specified URL into a file in user's Dropbox. Note that
* the transfer from the URL must complete within 5 minutes, or the operation
* will time out and the job will fail. If the given path already exists, the
* file will be renamed to avoid the conflict (e.g. myfile (1).txt).
* @function Dropbox#filesSaveUrl
* @arg {FilesSaveUrlArg} arg - The request parameters.
* @returns {Promise.<FilesSaveUrlResult, Error.<FilesSaveUrlError>>}
*/
routes.filesSaveUrl = function (arg) {
return this.request('files/save_url', arg, 'user', 'api', 'rpc');
};
/**
* Check the status of a save_url job.
* @function Dropbox#filesSaveUrlCheckJobStatus
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesSaveUrlJobStatus, Error.<AsyncPollError>>}
*/
routes.filesSaveUrlCheckJobStatus = function (arg) {
return this.request('files/save_url/check_job_status', arg, 'user', 'api', 'rpc');
};
/**
* Searches for files and folders. Note: Recent changes may not immediately be
* reflected in search results due to a short delay in indexing.
* @function Dropbox#filesSearch
* @deprecated
* @arg {FilesSearchArg} arg - The request parameters.
* @returns {Promise.<FilesSearchResult, Error.<FilesSearchError>>}
*/
routes.filesSearch = function (arg) {
return this.request('files/search', arg, 'user', 'api', 'rpc');
};
/**
* Searches for files and folders. Note: search_v2 along with search/continue_v2
* can only be used to retrieve a maximum of 10,000 matches. Recent changes may
* not immediately be reflected in search results due to a short delay in
* indexing. Duplicate results may be returned across pages. Some results may
* not be returned.
* @function Dropbox#filesSearchV2
* @arg {FilesSearchV2Arg} arg - The request parameters.
* @returns {Promise.<FilesSearchV2Result, Error.<FilesSearchError>>}
*/
routes.filesSearchV2 = function (arg) {
return this.request('files/search_v2', arg, 'user', 'api', 'rpc');
};
/**
* Fetches the next page of search results returned from search_v2. Note:
* search_v2 along with search/continue_v2 can only be used to retrieve a
* maximum of 10,000 matches. Recent changes may not immediately be reflected in
* search results due to a short delay in indexing. Duplicate results may be
* returned across pages. Some results may not be returned.
* @function Dropbox#filesSearchContinueV2
* @arg {FilesSearchV2ContinueArg} arg - The request parameters.
* @returns {Promise.<FilesSearchV2Result, Error.<FilesSearchError>>}
*/
routes.filesSearchContinueV2 = function (arg) {
return this.request('files/search/continue_v2', arg, 'user', 'api', 'rpc');
};
/**
* Unlock the files at the given paths. A locked file can only be unlocked by
* the lock holder or, if a business account, a team admin. A successful
* response indicates that the file has been unlocked. Returns a list of the
* unlocked file paths and their metadata after this operation.
* @function Dropbox#filesUnlockFileBatch
* @arg {FilesUnlockFileBatchArg} arg - The request parameters.
* @returns {Promise.<FilesLockFileBatchResult, Error.<FilesLockFileError>>}
*/
routes.filesUnlockFileBatch = function (arg) {
return this.request('files/unlock_file_batch', arg, 'user', 'api', 'rpc');
};
/**
* Create a new file with the contents provided in the request. Do not use this
* to upload a file larger than 150 MB. Instead, create an upload session with
* upload_session/start. Calls to this endpoint will count as data transport
* calls for any Dropbox Business teams with a limit on the number of data
* transport calls allowed per month. For more information, see the Data
* transport limit page
* https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUpload
* @arg {FilesCommitInfo} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesUploadError>>}
*/
routes.filesUpload = function (arg) {
return this.request('files/upload', arg, 'user', 'content', 'upload');
};
/**
* Append more data to an upload session. When the parameter close is set, this
* call will close the session. A single request should not upload more than 150
* MB. The maximum size of a file one can upload to an upload session is 350 GB.
* Calls to this endpoint will count as data transport calls for any Dropbox
* Business teams with a limit on the number of data transport calls allowed per
* month. For more information, see the Data transport limit page
* https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUploadSessionAppendV2
* @arg {FilesUploadSessionAppendArg} arg - The request parameters.
* @returns {Promise.<void, Error.<FilesUploadSessionLookupError>>}
*/
routes.filesUploadSessionAppendV2 = function (arg) {
return this.request('files/upload_session/append_v2', arg, 'user', 'content', 'upload');
};
/**
* Append more data to an upload session. A single request should not upload
* more than 150 MB. The maximum size of a file one can upload to an upload
* session is 350 GB. Calls to this endpoint will count as data transport calls
* for any Dropbox Business teams with a limit on the number of data transport
* calls allowed per month. For more information, see the Data transport limit
* page https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUploadSessionAppend
* @deprecated
* @arg {FilesUploadSessionCursor} arg - The request parameters.
* @returns {Promise.<void, Error.<FilesUploadSessionLookupError>>}
*/
routes.filesUploadSessionAppend = function (arg) {
return this.request('files/upload_session/append', arg, 'user', 'content', 'upload');
};
/**
* Finish an upload session and save the uploaded data to the given file path. A
* single request should not upload more than 150 MB. The maximum size of a file
* one can upload to an upload session is 350 GB. Calls to this endpoint will
* count as data transport calls for any Dropbox Business teams with a limit on
* the number of data transport calls allowed per month. For more information,
* see the Data transport limit page
* https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUploadSessionFinish
* @arg {FilesUploadSessionFinishArg} arg - The request parameters.
* @returns {Promise.<FilesFileMetadata, Error.<FilesUploadSessionFinishError>>}
*/
routes.filesUploadSessionFinish = function (arg) {
return this.request('files/upload_session/finish', arg, 'user', 'content', 'upload');
};
/**
* This route helps you commit many files at once into a user's Dropbox. Use
* upload_session/start and upload_session/append_v2 to upload file contents. We
* recommend uploading many files in parallel to increase throughput. Once the
* file contents have been uploaded, rather than calling upload_session/finish,
* use this route to finish all your upload sessions in a single request.
* UploadSessionStartArg.close or UploadSessionAppendArg.close needs to be true
* for the last upload_session/start or upload_session/append_v2 call. The
* maximum size of a file one can upload to an upload session is 350 GB. This
* route will return a job_id immediately and do the async commit job in
* background. Use upload_session/finish_batch/check to check the job status.
* For the same account, this route should be executed serially. That means you
* should not start the next job before current job finishes. We allow up to
* 1000 entries in a single request. Calls to this endpoint will count as data
* transport calls for any Dropbox Business teams with a limit on the number of
* data transport calls allowed per month. For more information, see the Data
* transport limit page
* https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUploadSessionFinishBatch
* @arg {FilesUploadSessionFinishBatchArg} arg - The request parameters.
* @returns {Promise.<FilesUploadSessionFinishBatchLaunch, Error.<void>>}
*/
routes.filesUploadSessionFinishBatch = function (arg) {
return this.request('files/upload_session/finish_batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for upload_session/finish_batch. If
* success, it returns list of result for each entry.
* @function Dropbox#filesUploadSessionFinishBatchCheck
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<FilesUploadSessionFinishBatchJobStatus, Error.<AsyncPollError>>}
*/
routes.filesUploadSessionFinishBatchCheck = function (arg) {
return this.request('files/upload_session/finish_batch/check', arg, 'user', 'api', 'rpc');
};
/**
* Upload sessions allow you to upload a single file in one or more requests,
* for example where the size of the file is greater than 150 MB. This call
* starts a new upload session with the given data. You can then use
* upload_session/append_v2 to add more data and upload_session/finish to save
* all the data to a file in Dropbox. A single request should not upload more
* than 150 MB. The maximum size of a file one can upload to an upload session
* is 350 GB. An upload session can be used for a maximum of 48 hours.
* Attempting to use an UploadSessionStartResult.session_id with
* upload_session/append_v2 or upload_session/finish more than 48 hours after
* its creation will return a UploadSessionLookupError.not_found. Calls to this
* endpoint will count as data transport calls for any Dropbox Business teams
* with a limit on the number of data transport calls allowed per month. For
* more information, see the Data transport limit page
* https://www.dropbox.com/developers/reference/data-transport-limit.
* @function Dropbox#filesUploadSessionStart
* @arg {FilesUploadSessionStartArg} arg - The request parameters.
* @returns {Promise.<FilesUploadSessionStartResult, Error.<void>>}
*/
routes.filesUploadSessionStart = function (arg) {
return this.request('files/upload_session/start', arg, 'user', 'content', 'upload');
};
/**
* Marks the given Paper doc as archived. This action can be performed or undone
* by anyone with edit permissions to the doc. Note that this endpoint will
* continue to work for content created by users on the older version of Paper.
* To check which version of Paper a user is on, use /users/features/get_values.
* If the paper_as_files feature is enabled, then the user is running the new
* version of Paper. This endpoint will be retired in September 2020. Refer to
* the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* more information.
* @function Dropbox#paperDocsArchive
* @deprecated
* @arg {PaperRefPaperDoc} arg - The request parameters.
* @returns {Promise.<void, Error.<PaperDocLookupError>>}
*/
routes.paperDocsArchive = function (arg) {
return this.request('paper/docs/archive', arg, 'user', 'api', 'rpc');
};
/**
* Creates a new Paper doc with the provided content. Note that this endpoint
* will continue to work for content created by users on the older version of
* Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. This endpoint will be retired
* in September 2020. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* more information.
* @function Dropbox#paperDocsCreate
* @deprecated
* @arg {PaperPaperDocCreateArgs} arg - The request parameters.
* @returns {Promise.<PaperPaperDocCreateUpdateResult, Error.<PaperPaperDocCreateError>>}
*/
routes.paperDocsCreate = function (arg) {
return this.request('paper/docs/create', arg, 'user', 'api', 'upload');
};
/**
* Exports and downloads Paper doc either as HTML or markdown. Note that this
* endpoint will continue to work for content created by users on the older
* version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperDocsDownload
* @deprecated
* @arg {PaperPaperDocExport} arg - The request parameters.
* @returns {Promise.<PaperPaperDocExportResult, Error.<PaperDocLookupError>>}
*/
routes.paperDocsDownload = function (arg) {
return this.request('paper/docs/download', arg, 'user', 'api', 'download');
};
/**
* Lists the users who are explicitly invited to the Paper folder in which the
* Paper doc is contained. For private folders all users (including owner)
* shared on the folder are listed and for team folders all non-team users
* shared on the folder are returned. Note that this endpoint will continue to
* work for content created by users on the older version of Paper. To check
* which version of Paper a user is on, use /users/features/get_values. If the
* paper_as_files feature is enabled, then the user is running the new version
* of Paper. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsFolderUsersList
* @deprecated
* @arg {PaperListUsersOnFolderArgs} arg - The request parameters.
* @returns {Promise.<PaperListUsersOnFolderResponse, Error.<PaperDocLookupError>>}
*/
routes.paperDocsFolderUsersList = function (arg) {
return this.request('paper/docs/folder_users/list', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from docs/folder_users/list, use this to
* paginate through all users on the Paper folder. Note that this endpoint will
* continue to work for content created by users on the older version of Paper.
* To check which version of Paper a user is on, use /users/features/get_values.
* If the paper_as_files feature is enabled, then the user is running the new
* version of Paper. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsFolderUsersListContinue
* @deprecated
* @arg {PaperListUsersOnFolderContinueArgs} arg - The request parameters.
* @returns {Promise.<PaperListUsersOnFolderResponse, Error.<PaperListUsersCursorError>>}
*/
routes.paperDocsFolderUsersListContinue = function (arg) {
return this.request('paper/docs/folder_users/list/continue', arg, 'user', 'api', 'rpc');
};
/**
* Retrieves folder information for the given Paper doc. This includes: -
* folder sharing policy; permissions for subfolders are set by the top-level
* folder. - full 'filepath', i.e. the list of folders (both folderId and
* folderName) from the root folder to the folder directly containing the
* Paper doc. If the Paper doc is not in any folder (aka unfiled) the response
* will be empty. Note that this endpoint will continue to work for content
* created by users on the older version of Paper. To check which version of
* Paper a user is on, use /users/features/get_values. If the paper_as_files
* feature is enabled, then the user is running the new version of Paper. Refer
* to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsGetFolderInfo
* @deprecated
* @arg {PaperRefPaperDoc} arg - The request parameters.
* @returns {Promise.<PaperFoldersContainingPaperDoc, Error.<PaperDocLookupError>>}
*/
routes.paperDocsGetFolderInfo = function (arg) {
return this.request('paper/docs/get_folder_info', arg, 'user', 'api', 'rpc');
};
/**
* Return the list of all Paper docs according to the argument specifications.
* To iterate over through the full pagination, pass the cursor to
* docs/list/continue. Note that this endpoint will continue to work for content
* created by users on the older version of Paper. To check which version of
* Paper a user is on, use /users/features/get_values. If the paper_as_files
* feature is enabled, then the user is running the new version of Paper. Refer
* to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsList
* @deprecated
* @arg {PaperListPaperDocsArgs} arg - The request parameters.
* @returns {Promise.<PaperListPaperDocsResponse, Error.<void>>}
*/
routes.paperDocsList = function (arg) {
return this.request('paper/docs/list', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from docs/list, use this to paginate through
* all Paper doc. Note that this endpoint will continue to work for content
* created by users on the older version of Paper. To check which version of
* Paper a user is on, use /users/features/get_values. If the paper_as_files
* feature is enabled, then the user is running the new version of Paper. Refer
* to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsListContinue
* @deprecated
* @arg {PaperListPaperDocsContinueArgs} arg - The request parameters.
* @returns {Promise.<PaperListPaperDocsResponse, Error.<PaperListDocsCursorError>>}
*/
routes.paperDocsListContinue = function (arg) {
return this.request('paper/docs/list/continue', arg, 'user', 'api', 'rpc');
};
/**
* Permanently deletes the given Paper doc. This operation is final as the doc
* cannot be recovered. This action can be performed only by the doc owner. Note
* that this endpoint will continue to work for content created by users on the
* older version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperDocsPermanentlyDelete
* @deprecated
* @arg {PaperRefPaperDoc} arg - The request parameters.
* @returns {Promise.<void, Error.<PaperDocLookupError>>}
*/
routes.paperDocsPermanentlyDelete = function (arg) {
return this.request('paper/docs/permanently_delete', arg, 'user', 'api', 'rpc');
};
/**
* Gets the default sharing policy for the given Paper doc. Note that this
* endpoint will continue to work for content created by users on the older
* version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperDocsSharingPolicyGet
* @deprecated
* @arg {PaperRefPaperDoc} arg - The request parameters.
* @returns {Promise.<PaperSharingPolicy, Error.<PaperDocLookupError>>}
*/
routes.paperDocsSharingPolicyGet = function (arg) {
return this.request('paper/docs/sharing_policy/get', arg, 'user', 'api', 'rpc');
};
/**
* Sets the default sharing policy for the given Paper doc. The default
* 'team_sharing_policy' can be changed only by teams, omit this field for
* personal accounts. The 'public_sharing_policy' policy can't be set to the
* value 'disabled' because this setting can be changed only via the team admin
* console. Note that this endpoint will continue to work for content created by
* users on the older version of Paper. To check which version of Paper a user
* is on, use /users/features/get_values. If the paper_as_files feature is
* enabled, then the user is running the new version of Paper. Refer to the
* Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsSharingPolicySet
* @deprecated
* @arg {PaperPaperDocSharingPolicy} arg - The request parameters.
* @returns {Promise.<void, Error.<PaperDocLookupError>>}
*/
routes.paperDocsSharingPolicySet = function (arg) {
return this.request('paper/docs/sharing_policy/set', arg, 'user', 'api', 'rpc');
};
/**
* Updates an existing Paper doc with the provided content. Note that this
* endpoint will continue to work for content created by users on the older
* version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. This endpoint will be retired
* in September 2020. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* more information.
* @function Dropbox#paperDocsUpdate
* @deprecated
* @arg {PaperPaperDocUpdateArgs} arg - The request parameters.
* @returns {Promise.<PaperPaperDocCreateUpdateResult, Error.<PaperPaperDocUpdateError>>}
*/
routes.paperDocsUpdate = function (arg) {
return this.request('paper/docs/update', arg, 'user', 'api', 'upload');
};
/**
* Allows an owner or editor to add users to a Paper doc or change their
* permissions using their email address or Dropbox account ID. The doc owner's
* permissions cannot be changed. Note that this endpoint will continue to work
* for content created by users on the older version of Paper. To check which
* version of Paper a user is on, use /users/features/get_values. If the
* paper_as_files feature is enabled, then the user is running the new version
* of Paper. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsUsersAdd
* @deprecated
* @arg {PaperAddPaperDocUser} arg - The request parameters.
* @returns {Promise.<Array.<PaperAddPaperDocUserMemberResult>, Error.<PaperDocLookupError>>}
*/
routes.paperDocsUsersAdd = function (arg) {
return this.request('paper/docs/users/add', arg, 'user', 'api', 'rpc');
};
/**
* Lists all users who visited the Paper doc or users with explicit access. This
* call excludes users who have been removed. The list is sorted by the date of
* the visit or the share date. The list will include both users, the explicitly
* shared ones as well as those who came in using the Paper url link. Note that
* this endpoint will continue to work for content created by users on the older
* version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperDocsUsersList
* @deprecated
* @arg {PaperListUsersOnPaperDocArgs} arg - The request parameters.
* @returns {Promise.<PaperListUsersOnPaperDocResponse, Error.<PaperDocLookupError>>}
*/
routes.paperDocsUsersList = function (arg) {
return this.request('paper/docs/users/list', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from docs/users/list, use this to paginate
* through all users on the Paper doc. Note that this endpoint will continue to
* work for content created by users on the older version of Paper. To check
* which version of Paper a user is on, use /users/features/get_values. If the
* paper_as_files feature is enabled, then the user is running the new version
* of Paper. Refer to the Paper Migration Guide
* https://www.dropbox.com/lp/developers/reference/paper-migration-guide for
* migration information.
* @function Dropbox#paperDocsUsersListContinue
* @deprecated
* @arg {PaperListUsersOnPaperDocContinueArgs} arg - The request parameters.
* @returns {Promise.<PaperListUsersOnPaperDocResponse, Error.<PaperListUsersCursorError>>}
*/
routes.paperDocsUsersListContinue = function (arg) {
return this.request('paper/docs/users/list/continue', arg, 'user', 'api', 'rpc');
};
/**
* Allows an owner or editor to remove users from a Paper doc using their email
* address or Dropbox account ID. The doc owner cannot be removed. Note that
* this endpoint will continue to work for content created by users on the older
* version of Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperDocsUsersRemove
* @deprecated
* @arg {PaperRemovePaperDocUser} arg - The request parameters.
* @returns {Promise.<void, Error.<PaperDocLookupError>>}
*/
routes.paperDocsUsersRemove = function (arg) {
return this.request('paper/docs/users/remove', arg, 'user', 'api', 'rpc');
};
/**
* Create a new Paper folder with the provided info. Note that this endpoint
* will continue to work for content created by users on the older version of
* Paper. To check which version of Paper a user is on, use
* /users/features/get_values. If the paper_as_files feature is enabled, then
* the user is running the new version of Paper. Refer to the Paper Migration
* Guide https://www.dropbox.com/lp/developers/reference/paper-migration-guide
* for migration information.
* @function Dropbox#paperFoldersCreate
* @deprecated
* @arg {PaperPaperFolderCreateArg} arg - The request parameters.
* @returns {Promise.<PaperPaperFolderCreateResult, Error.<PaperPaperFolderCreateError>>}
*/
routes.paperFoldersCreate = function (arg) {
return this.request('paper/folders/create', arg, 'user', 'api', 'rpc');
};
/**
* Adds specified members to a file.
* @function Dropbox#sharingAddFileMember
* @arg {SharingAddFileMemberArgs} arg - The request parameters.
* @returns {Promise.<Array.<SharingFileMemberActionResult>, Error.<SharingAddFileMemberError>>}
*/
routes.sharingAddFileMember = function (arg) {
return this.request('sharing/add_file_member', arg, 'user', 'api', 'rpc');
};
/**
* Allows an owner or editor (if the ACL update policy allows) of a shared
* folder to add another member. For the new member to get access to all the
* functionality for this folder, you will need to call mount_folder on their
* behalf.
* @function Dropbox#sharingAddFolderMember
* @arg {SharingAddFolderMemberArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingAddFolderMemberError>>}
*/
routes.sharingAddFolderMember = function (arg) {
return this.request('sharing/add_folder_member', arg, 'user', 'api', 'rpc');
};
/**
* Identical to update_file_member but with less information returned.
* @function Dropbox#sharingChangeFileMemberAccess
* @deprecated
* @arg {SharingChangeFileMemberAccessArgs} arg - The request parameters.
* @returns {Promise.<SharingFileMemberActionResult, Error.<SharingFileMemberActionError>>}
*/
routes.sharingChangeFileMemberAccess = function (arg) {
return this.request('sharing/change_file_member_access', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job.
* @function Dropbox#sharingCheckJobStatus
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<SharingJobStatus, Error.<AsyncPollError>>}
*/
routes.sharingCheckJobStatus = function (arg) {
return this.request('sharing/check_job_status', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for sharing a folder.
* @function Dropbox#sharingCheckRemoveMemberJobStatus
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<SharingRemoveMemberJobStatus, Error.<AsyncPollError>>}
*/
routes.sharingCheckRemoveMemberJobStatus = function (arg) {
return this.request('sharing/check_remove_member_job_status', arg, 'user', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for sharing a folder.
* @function Dropbox#sharingCheckShareJobStatus
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<SharingShareFolderJobStatus, Error.<AsyncPollError>>}
*/
routes.sharingCheckShareJobStatus = function (arg) {
return this.request('sharing/check_share_job_status', arg, 'user', 'api', 'rpc');
};
/**
* Create a shared link. If a shared link already exists for the given path,
* that link is returned. Note that in the returned PathLinkMetadata, the
* PathLinkMetadata.url field is the shortened URL if
* CreateSharedLinkArg.short_url argument is set to true. Previously, it was
* technically possible to break a shared link by moving or renaming the
* corresponding file or folder. In the future, this will no longer be the case,
* so your app shouldn't rely on this behavior. Instead, if your app needs to
* revoke a shared link, use revoke_shared_link.
* @function Dropbox#sharingCreateSharedLink
* @deprecated
* @arg {SharingCreateSharedLinkArg} arg - The request parameters.
* @returns {Promise.<SharingPathLinkMetadata, Error.<SharingCreateSharedLinkError>>}
*/
routes.sharingCreateSharedLink = function (arg) {
return this.request('sharing/create_shared_link', arg, 'user', 'api', 'rpc');
};
/**
* Create a shared link with custom settings. If no settings are given then the
* default visibility is RequestedVisibility.public (The resolved visibility,
* though, may depend on other aspects such as team and shared folder settings).
* @function Dropbox#sharingCreateSharedLinkWithSettings
* @arg {SharingCreateSharedLinkWithSettingsArg} arg - The request parameters.
* @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingCreateSharedLinkWithSettingsError>>}
*/
routes.sharingCreateSharedLinkWithSettings = function (arg) {
return this.request('sharing/create_shared_link_with_settings', arg, 'user', 'api', 'rpc');
};
/**
* Returns shared file metadata.
* @function Dropbox#sharingGetFileMetadata
* @arg {SharingGetFileMetadataArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFileMetadata, Error.<SharingGetFileMetadataError>>}
*/
routes.sharingGetFileMetadata = function (arg) {
return this.request('sharing/get_file_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Returns shared file metadata.
* @function Dropbox#sharingGetFileMetadataBatch
* @arg {SharingGetFileMetadataBatchArg} arg - The request parameters.
* @returns {Promise.<Array.<SharingGetFileMetadataBatchResult>, Error.<SharingSharingUserError>>}
*/
routes.sharingGetFileMetadataBatch = function (arg) {
return this.request('sharing/get_file_metadata/batch', arg, 'user', 'api', 'rpc');
};
/**
* Returns shared folder metadata by its folder ID.
* @function Dropbox#sharingGetFolderMetadata
* @arg {SharingGetMetadataArgs} arg - The request parameters.
* @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingSharedFolderAccessError>>}
*/
routes.sharingGetFolderMetadata = function (arg) {
return this.request('sharing/get_folder_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Download the shared link's file from a user's Dropbox.
* @function Dropbox#sharingGetSharedLinkFile
* @arg {Object} arg - The request parameters.
* @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingGetSharedLinkFileError>>}
*/
routes.sharingGetSharedLinkFile = function (arg) {
return this.request('sharing/get_shared_link_file', arg, 'user', 'content', 'download');
};
/**
* Get the shared link's metadata.
* @function Dropbox#sharingGetSharedLinkMetadata
* @arg {SharingGetSharedLinkMetadataArg} arg - The request parameters.
* @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingSharedLinkError>>}
*/
routes.sharingGetSharedLinkMetadata = function (arg) {
return this.request('sharing/get_shared_link_metadata', arg, 'user', 'api', 'rpc');
};
/**
* Returns a list of LinkMetadata objects for this user, including collection
* links. If no path is given, returns a list of all shared links for the
* current user, including collection links, up to a maximum of 1000 links. If a
* non-empty path is given, returns a list of all shared links that allow access
* to the given path. Collection links are never returned in this case. Note
* that the url field in the response is never the shortened URL.
* @function Dropbox#sharingGetSharedLinks
* @deprecated
* @arg {SharingGetSharedLinksArg} arg - The request parameters.
* @returns {Promise.<SharingGetSharedLinksResult, Error.<SharingGetSharedLinksError>>}
*/
routes.sharingGetSharedLinks = function (arg) {
return this.request('sharing/get_shared_links', arg, 'user', 'api', 'rpc');
};
/**
* Use to obtain the members who have been invited to a file, both inherited and
* uninherited members.
* @function Dropbox#sharingListFileMembers
* @arg {SharingListFileMembersArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFileMembers, Error.<SharingListFileMembersError>>}
*/
routes.sharingListFileMembers = function (arg) {
return this.request('sharing/list_file_members', arg, 'user', 'api', 'rpc');
};
/**
* Get members of multiple files at once. The arguments to this route are more
* limited, and the limit on query result size per file is more strict. To
* customize the results more, use the individual file endpoint. Inherited users
* and groups are not included in the result, and permissions are not returned
* for this endpoint.
* @function Dropbox#sharingListFileMembersBatch
* @arg {SharingListFileMembersBatchArg} arg - The request parameters.
* @returns {Promise.<Array.<SharingListFileMembersBatchResult>, Error.<SharingSharingUserError>>}
*/
routes.sharingListFileMembersBatch = function (arg) {
return this.request('sharing/list_file_members/batch', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_file_members or
* list_file_members/batch, use this to paginate through all shared file
* members.
* @function Dropbox#sharingListFileMembersContinue
* @arg {SharingListFileMembersContinueArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFileMembers, Error.<SharingListFileMembersContinueError>>}
*/
routes.sharingListFileMembersContinue = function (arg) {
return this.request('sharing/list_file_members/continue', arg, 'user', 'api', 'rpc');
};
/**
* Returns shared folder membership by its folder ID.
* @function Dropbox#sharingListFolderMembers
* @arg {SharingListFolderMembersArgs} arg - The request parameters.
* @returns {Promise.<SharingSharedFolderMembers, Error.<SharingSharedFolderAccessError>>}
*/
routes.sharingListFolderMembers = function (arg) {
return this.request('sharing/list_folder_members', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_folder_members, use this to
* paginate through all shared folder members.
* @function Dropbox#sharingListFolderMembersContinue
* @arg {SharingListFolderMembersContinueArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFolderMembers, Error.<SharingListFolderMembersContinueError>>}
*/
routes.sharingListFolderMembersContinue = function (arg) {
return this.request('sharing/list_folder_members/continue', arg, 'user', 'api', 'rpc');
};
/**
* Return the list of all shared folders the current user has access to.
* @function Dropbox#sharingListFolders
* @arg {SharingListFoldersArgs} arg - The request parameters.
* @returns {Promise.<SharingListFoldersResult, Error.<void>>}
*/
routes.sharingListFolders = function (arg) {
return this.request('sharing/list_folders', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_folders, use this to paginate
* through all shared folders. The cursor must come from a previous call to
* list_folders or list_folders/continue.
* @function Dropbox#sharingListFoldersContinue
* @arg {SharingListFoldersContinueArg} arg - The request parameters.
* @returns {Promise.<SharingListFoldersResult, Error.<SharingListFoldersContinueError>>}
*/
routes.sharingListFoldersContinue = function (arg) {
return this.request('sharing/list_folders/continue', arg, 'user', 'api', 'rpc');
};
/**
* Return the list of all shared folders the current user can mount or unmount.
* @function Dropbox#sharingListMountableFolders
* @arg {SharingListFoldersArgs} arg - The request parameters.
* @returns {Promise.<SharingListFoldersResult, Error.<void>>}
*/
routes.sharingListMountableFolders = function (arg) {
return this.request('sharing/list_mountable_folders', arg, 'user', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from list_mountable_folders, use this to
* paginate through all mountable shared folders. The cursor must come from a
* previous call to list_mountable_folders or list_mountable_folders/continue.
* @function Dropbox#sharingListMountableFoldersContinue
* @arg {SharingListFoldersContinueArg} arg - The request parameters.
* @returns {Promise.<SharingListFoldersResult, Error.<SharingListFoldersContinueError>>}
*/
routes.sharingListMountableFoldersContinue = function (arg) {
return this.request('sharing/list_mountable_folders/continue', arg, 'user', 'api', 'rpc');
};
/**
* Returns a list of all files shared with current user. Does not include files
* the user has received via shared folders, and does not include unclaimed
* invitations.
* @function Dropbox#sharingListReceivedFiles
* @arg {SharingListFilesArg} arg - The request parameters.
* @returns {Promise.<SharingListFilesResult, Error.<SharingSharingUserError>>}
*/
routes.sharingListReceivedFiles = function (arg) {
return this.request('sharing/list_received_files', arg, 'user', 'api', 'rpc');
};
/**
* Get more results with a cursor from list_received_files.
* @function Dropbox#sharingListReceivedFilesContinue
* @arg {SharingListFilesContinueArg} arg - The request parameters.
* @returns {Promise.<SharingListFilesResult, Error.<SharingListFilesContinueError>>}
*/
routes.sharingListReceivedFilesContinue = function (arg) {
return this.request('sharing/list_received_files/continue', arg, 'user', 'api', 'rpc');
};
/**
* List shared links of this user. If no path is given, returns a list of all
* shared links for the current user. If a non-empty path is given, returns a
* list of all shared links that allow access to the given path - direct links
* to the given path and links to parent folders of the given path. Links to
* parent folders can be suppressed by setting direct_only to true.
* @function Dropbox#sharingListSharedLinks
* @arg {SharingListSharedLinksArg} arg - The request parameters.
* @returns {Promise.<SharingListSharedLinksResult, Error.<SharingListSharedLinksError>>}
*/
routes.sharingListSharedLinks = function (arg) {
return this.request('sharing/list_shared_links', arg, 'user', 'api', 'rpc');
};
/**
* Modify the shared link's settings. If the requested visibility conflict with
* the shared links policy of the team or the shared folder (in case the linked
* file is part of a shared folder) then the LinkPermissions.resolved_visibility
* of the returned SharedLinkMetadata will reflect the actual visibility of the
* shared link and the LinkPermissions.requested_visibility will reflect the
* requested visibility.
* @function Dropbox#sharingModifySharedLinkSettings
* @arg {SharingModifySharedLinkSettingsArgs} arg - The request parameters.
* @returns {Promise.<(SharingFileLinkMetadata|SharingFolderLinkMetadata|SharingSharedLinkMetadata), Error.<SharingModifySharedLinkSettingsError>>}
*/
routes.sharingModifySharedLinkSettings = function (arg) {
return this.request('sharing/modify_shared_link_settings', arg, 'user', 'api', 'rpc');
};
/**
* The current user mounts the designated folder. Mount a shared folder for a
* user after they have been added as a member. Once mounted, the shared folder
* will appear in their Dropbox.
* @function Dropbox#sharingMountFolder
* @arg {SharingMountFolderArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingMountFolderError>>}
*/
routes.sharingMountFolder = function (arg) {
return this.request('sharing/mount_folder', arg, 'user', 'api', 'rpc');
};
/**
* The current user relinquishes their membership in the designated file. Note
* that the current user may still have inherited access to this file through
* the parent folder.
* @function Dropbox#sharingRelinquishFileMembership
* @arg {SharingRelinquishFileMembershipArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingRelinquishFileMembershipError>>}
*/
routes.sharingRelinquishFileMembership = function (arg) {
return this.request('sharing/relinquish_file_membership', arg, 'user', 'api', 'rpc');
};
/**
* The current user relinquishes their membership in the designated shared
* folder and will no longer have access to the folder. A folder owner cannot
* relinquish membership in their own folder. This will run synchronously if
* leave_a_copy is false, and asynchronously if leave_a_copy is true.
* @function Dropbox#sharingRelinquishFolderMembership
* @arg {SharingRelinquishFolderMembershipArg} arg - The request parameters.
* @returns {Promise.<AsyncLaunchEmptyResult, Error.<SharingRelinquishFolderMembershipError>>}
*/
routes.sharingRelinquishFolderMembership = function (arg) {
return this.request('sharing/relinquish_folder_membership', arg, 'user', 'api', 'rpc');
};
/**
* Identical to remove_file_member_2 but with less information returned.
* @function Dropbox#sharingRemoveFileMember
* @deprecated
* @arg {SharingRemoveFileMemberArg} arg - The request parameters.
* @returns {Promise.<SharingFileMemberActionIndividualResult, Error.<SharingRemoveFileMemberError>>}
*/
routes.sharingRemoveFileMember = function (arg) {
return this.request('sharing/remove_file_member', arg, 'user', 'api', 'rpc');
};
/**
* Removes a specified member from the file.
* @function Dropbox#sharingRemoveFileMember2
* @arg {SharingRemoveFileMemberArg} arg - The request parameters.
* @returns {Promise.<SharingFileMemberRemoveActionResult, Error.<SharingRemoveFileMemberError>>}
*/
routes.sharingRemoveFileMember2 = function (arg) {
return this.request('sharing/remove_file_member_2', arg, 'user', 'api', 'rpc');
};
/**
* Allows an owner or editor (if the ACL update policy allows) of a shared
* folder to remove another member.
* @function Dropbox#sharingRemoveFolderMember
* @arg {SharingRemoveFolderMemberArg} arg - The request parameters.
* @returns {Promise.<AsyncLaunchResultBase, Error.<SharingRemoveFolderMemberError>>}
*/
routes.sharingRemoveFolderMember = function (arg) {
return this.request('sharing/remove_folder_member', arg, 'user', 'api', 'rpc');
};
/**
* Revoke a shared link. Note that even after revoking a shared link to a file,
* the file may be accessible if there are shared links leading to any of the
* file parent folders. To list all shared links that enable access to a
* specific file, you can use the list_shared_links with the file as the
* ListSharedLinksArg.path argument.
* @function Dropbox#sharingRevokeSharedLink
* @arg {SharingRevokeSharedLinkArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingRevokeSharedLinkError>>}
*/
routes.sharingRevokeSharedLink = function (arg) {
return this.request('sharing/revoke_shared_link', arg, 'user', 'api', 'rpc');
};
/**
* Change the inheritance policy of an existing Shared Folder. Only permitted
* for shared folders in a shared team root. If a ShareFolderLaunch.async_job_id
* is returned, you'll need to call check_share_job_status until the action
* completes to get the metadata for the folder.
* @function Dropbox#sharingSetAccessInheritance
* @arg {SharingSetAccessInheritanceArg} arg - The request parameters.
* @returns {Promise.<SharingShareFolderLaunch, Error.<SharingSetAccessInheritanceError>>}
*/
routes.sharingSetAccessInheritance = function (arg) {
return this.request('sharing/set_access_inheritance', arg, 'user', 'api', 'rpc');
};
/**
* Share a folder with collaborators. Most sharing will be completed
* synchronously. Large folders will be completed asynchronously. To make
* testing the async case repeatable, set `ShareFolderArg.force_async`. If a
* ShareFolderLaunch.async_job_id is returned, you'll need to call
* check_share_job_status until the action completes to get the metadata for the
* folder.
* @function Dropbox#sharingShareFolder
* @arg {SharingShareFolderArg} arg - The request parameters.
* @returns {Promise.<SharingShareFolderLaunch, Error.<SharingShareFolderError>>}
*/
routes.sharingShareFolder = function (arg) {
return this.request('sharing/share_folder', arg, 'user', 'api', 'rpc');
};
/**
* Transfer ownership of a shared folder to a member of the shared folder. User
* must have AccessLevel.owner access to the shared folder to perform a
* transfer.
* @function Dropbox#sharingTransferFolder
* @arg {SharingTransferFolderArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingTransferFolderError>>}
*/
routes.sharingTransferFolder = function (arg) {
return this.request('sharing/transfer_folder', arg, 'user', 'api', 'rpc');
};
/**
* The current user unmounts the designated folder. They can re-mount the folder
* at a later time using mount_folder.
* @function Dropbox#sharingUnmountFolder
* @arg {SharingUnmountFolderArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingUnmountFolderError>>}
*/
routes.sharingUnmountFolder = function (arg) {
return this.request('sharing/unmount_folder', arg, 'user', 'api', 'rpc');
};
/**
* Remove all members from this file. Does not remove inherited members.
* @function Dropbox#sharingUnshareFile
* @arg {SharingUnshareFileArg} arg - The request parameters.
* @returns {Promise.<void, Error.<SharingUnshareFileError>>}
*/
routes.sharingUnshareFile = function (arg) {
return this.request('sharing/unshare_file', arg, 'user', 'api', 'rpc');
};
/**
* Allows a shared folder owner to unshare the folder. You'll need to call
* check_job_status to determine if the action has completed successfully.
* @function Dropbox#sharingUnshareFolder
* @arg {SharingUnshareFolderArg} arg - The request parameters.
* @returns {Promise.<AsyncLaunchEmptyResult, Error.<SharingUnshareFolderError>>}
*/
routes.sharingUnshareFolder = function (arg) {
return this.request('sharing/unshare_folder', arg, 'user', 'api', 'rpc');
};
/**
* Changes a member's access on a shared file.
* @function Dropbox#sharingUpdateFileMember
* @arg {SharingUpdateFileMemberArgs} arg - The request parameters.
* @returns {Promise.<SharingMemberAccessLevelResult, Error.<SharingFileMemberActionError>>}
*/
routes.sharingUpdateFileMember = function (arg) {
return this.request('sharing/update_file_member', arg, 'user', 'api', 'rpc');
};
/**
* Allows an owner or editor of a shared folder to update another member's
* permissions.
* @function Dropbox#sharingUpdateFolderMember
* @arg {SharingUpdateFolderMemberArg} arg - The request parameters.
* @returns {Promise.<SharingMemberAccessLevelResult, Error.<SharingUpdateFolderMemberError>>}
*/
routes.sharingUpdateFolderMember = function (arg) {
return this.request('sharing/update_folder_member', arg, 'user', 'api', 'rpc');
};
/**
* Update the sharing policies for a shared folder. User must have
* AccessLevel.owner access to the shared folder to update its policies.
* @function Dropbox#sharingUpdateFolderPolicy
* @arg {SharingUpdateFolderPolicyArg} arg - The request parameters.
* @returns {Promise.<SharingSharedFolderMetadata, Error.<SharingUpdateFolderPolicyError>>}
*/
routes.sharingUpdateFolderPolicy = function (arg) {
return this.request('sharing/update_folder_policy', arg, 'user', 'api', 'rpc');
};
/**
* Retrieves team events. If the result's GetTeamEventsResult.has_more field is
* true, call get_events/continue with the returned cursor to retrieve more
* entries. If end_time is not specified in your request, you may use the
* returned cursor to poll get_events/continue for new events. Many attributes
* note 'may be missing due to historical data gap'. Note that the
* file_operations category and & analogous paper events are not available on
* all Dropbox Business plans /business/plans-comparison. Use
* features/get_values
* /developers/documentation/http/teams#team-features-get_values to check for
* this feature. Permission : Team Auditing.
* @function Dropbox#teamLogGetEvents
* @arg {TeamLogGetTeamEventsArg} arg - The request parameters.
* @returns {Promise.<TeamLogGetTeamEventsResult, Error.<TeamLogGetTeamEventsError>>}
*/
routes.teamLogGetEvents = function (arg) {
return this.request('team_log/get_events', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from get_events, use this to paginate
* through all events. Permission : Team Auditing.
* @function Dropbox#teamLogGetEventsContinue
* @arg {TeamLogGetTeamEventsContinueArg} arg - The request parameters.
* @returns {Promise.<TeamLogGetTeamEventsResult, Error.<TeamLogGetTeamEventsContinueError>>}
*/
routes.teamLogGetEventsContinue = function (arg) {
return this.request('team_log/get_events/continue', arg, 'team', 'api', 'rpc');
};
/**
* Get a list of feature values that may be configured for the current account.
* @function Dropbox#usersFeaturesGetValues
* @arg {UsersUserFeaturesGetValuesBatchArg} arg - The request parameters.
* @returns {Promise.<UsersUserFeaturesGetValuesBatchResult, Error.<UsersUserFeaturesGetValuesBatchError>>}
*/
routes.usersFeaturesGetValues = function (arg) {
return this.request('users/features/get_values', arg, 'user', 'api', 'rpc');
};
/**
* Get information about a user's account.
* @function Dropbox#usersGetAccount
* @arg {UsersGetAccountArg} arg - The request parameters.
* @returns {Promise.<UsersBasicAccount, Error.<UsersGetAccountError>>}
*/
routes.usersGetAccount = function (arg) {
return this.request('users/get_account', arg, 'user', 'api', 'rpc');
};
/**
* Get information about multiple user accounts. At most 300 accounts may be
* queried per request.
* @function Dropbox#usersGetAccountBatch
* @arg {UsersGetAccountBatchArg} arg - The request parameters.
* @returns {Promise.<Object, Error.<UsersGetAccountBatchError>>}
*/
routes.usersGetAccountBatch = function (arg) {
return this.request('users/get_account_batch', arg, 'user', 'api', 'rpc');
};
/**
* Get information about the current user's account.
* @function Dropbox#usersGetCurrentAccount
* @arg {void} arg - The request parameters.
* @returns {Promise.<UsersFullAccount, Error.<void>>}
*/
routes.usersGetCurrentAccount = function (arg) {
return this.request('users/get_current_account', arg, 'user', 'api', 'rpc');
};
/**
* Get the space usage information for the current user's account.
* @function Dropbox#usersGetSpaceUsage
* @arg {void} arg - The request parameters.
* @returns {Promise.<UsersSpaceUsage, Error.<void>>}
*/
routes.usersGetSpaceUsage = function (arg) {
return this.request('users/get_space_usage', arg, 'user', 'api', 'rpc');
};
var RPC = 'rpc';
var UPLOAD = 'upload';
var DOWNLOAD = 'download';
function getSafeUnicode(c) {
var unicode = ('000' + c.charCodeAt(0).toString(16)).slice(-4);
return '\\u' + unicode;
}
/* global WorkerGlobalScope */
function isWindowOrWorker() {
return typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope || typeof module === 'undefined' || typeof window !== 'undefined';
}
function getBaseURL(host) {
return 'https://' + host + '.dropboxapi.com/2/';
}
// source https://www.dropboxforum.com/t5/API-support/HTTP-header-quot-Dropbox-API-Arg-quot-could-not-decode-input-as/m-p/173823/highlight/true#M6786
function httpHeaderSafeJson(args) {
return JSON.stringify(args).replace(/[\u007f-\uffff]/g, getSafeUnicode);
}
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var possibleConstructorReturn = function (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;
};
var slicedToArray = function () {
function sliceIterator(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"]) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
return function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else if (Symbol.iterator in Object(arr)) {
return sliceIterator(arr, i);
} else {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
};
}();
function getDataFromConsumer(res) {
if (!res.ok) {
return res.text();
}
return isWindowOrWorker() ? res.blob() : res.buffer();
}
function responseHandler(res, data) {
if (!res.ok) {
// eslint-disable-next-line no-throw-literal
throw {
error: data,
response: res,
status: res.status
};
}
var result = JSON.parse(res.headers.get('dropbox-api-result'));
if (isWindowOrWorker()) {
result.fileBlob = data;
} else {
result.fileBinary = data;
}
return result;
}
function downloadRequest(fetch) {
return function downloadRequestWithFetch(path, args, auth, host, client, options) {
return client.checkAndRefreshAccessToken().then(function () {
if (auth !== 'user') {
throw new Error('Unexpected auth type: ' + auth);
}
var fetchOptions = {
method: 'POST',
headers: {
Authorization: 'Bearer ' + client.getAccessToken(),
'Dropbox-API-Arg': httpHeaderSafeJson(args)
}
};
if (options) {
if (options.selectUser) {
fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser;
}
if (options.selectAdmin) {
fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin;
}
if (options.pathRoot) {
fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot;
}
}
return fetchOptions;
}).then(function (fetchOptions) {
return fetch(getBaseURL(host) + path, fetchOptions);
}).then(function (res) {
return getDataFromConsumer(res).then(function (data) {
return [res, data];
});
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
res = _ref2[0],
data = _ref2[1];
return responseHandler(res, data);
});
};
}
function parseBodyToType(res) {
var clone = res.clone();
return new Promise(function (resolve) {
res.json().then(function (data) {
return resolve(data);
}).catch(function () {
return clone.text().then(function (data) {
return resolve(data);
});
});
}).then(function (data) {
return [res, data];
});
}
function uploadRequest(fetch) {
return function uploadRequestWithFetch(path, args, auth, host, client, options) {
return client.checkAndRefreshAccessToken().then(function () {
if (auth !== 'user') {
throw new Error('Unexpected auth type: ' + auth);
}
var contents = args.contents;
delete args.contents;
var fetchOptions = {
body: contents,
method: 'POST',
headers: {
Authorization: 'Bearer ' + client.getAccessToken(),
'Content-Type': 'application/octet-stream',
'Dropbox-API-Arg': httpHeaderSafeJson(args)
}
};
if (options) {
if (options.selectUser) {
fetchOptions.headers['Dropbox-API-Select-User'] = options.selectUser;
}
if (options.selectAdmin) {
fetchOptions.headers['Dropbox-API-Select-Admin'] = options.selectAdmin;
}
if (options.pathRoot) {
fetchOptions.headers['Dropbox-API-Path-Root'] = options.pathRoot;
}
}
return fetchOptions;
}).then(function (fetchOptions) {
return fetch(getBaseURL(host) + path, fetchOptions);
}).then(function (res) {
return parseBodyToType(res);
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
res = _ref2[0],
data = _ref2[1];
// maintaining existing API for error codes not equal to 200 range
if (!res.ok) {
// eslint-disable-next-line no-throw-literal
throw {
error: data,
response: res,
status: res.status
};
}
return data;
});
};
}
var global$1 = (typeof global !== "undefined" ? global :
typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window : {});
var lookup = [];
var revLookup = [];
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;
var inited = false;
function init () {
inited = true;
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
revLookup['-'.charCodeAt(0)] = 62;
revLookup['_'.charCodeAt(0)] = 63;
}
function toByteArray (b64) {
if (!inited) {
init();
}
var i, j, l, tmp, placeHolders, arr;
var len = b64.length;
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;
// base64 is 4/3 + up to two characters of the original data
arr = new Arr(len * 3 / 4 - placeHolders);
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len;
var L = 0;
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];
arr[L++] = (tmp >> 16) & 0xFF;
arr[L++] = (tmp >> 8) & 0xFF;
arr[L++] = tmp & 0xFF;
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);
arr[L++] = tmp & 0xFF;
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);
arr[L++] = (tmp >> 8) & 0xFF;
arr[L++] = tmp & 0xFF;
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);
output.push(tripletToBase64(tmp));
}
return output.join('')
}
function fromByteArray (uint8) {
if (!inited) {
init();
}
var tmp;
var len = uint8.length;
var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes
var output = '';
var parts = [];
var maxChunkLength = 16383; // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1];
output += lookup[tmp >> 2];
output += lookup[(tmp << 4) & 0x3F];
output += '==';
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);
output += lookup[tmp >> 10];
output += lookup[(tmp >> 4) & 0x3F];
output += lookup[(tmp << 2) & 0x3F];
output += '=';
}
parts.push(output);
return parts.join('')
}
function read (buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? (nBytes - 1) : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & ((1 << (-nBits)) - 1);
s >>= (-nBits);
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1);
e >>= (-nBits);
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias;
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
function write (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);
var i = isLE ? 0 : (nBytes - 1);
var d = isLE ? 1 : -1;
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) {
value += rt / c;
} else {
value += rt * Math.pow(2, 1 - eBias);
}
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128;
}
var toString = {}.toString;
var isArray = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
var INSPECT_MAX_BYTES = 50;
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined
? global$1.TYPED_ARRAY_SUPPORT
: true;
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length);
that.__proto__ = Buffer.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length);
}
that.length = length;
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192; // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype;
return arr
};
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
};
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype;
Buffer.__proto__ = Uint8Array;
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size);
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
};
function allocUnsafe (that, size) {
assertSize(size);
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0;
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
};
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
};
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8';
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0;
that = createBuffer(that, length);
var actual = that.write(string, encoding);
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual);
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0;
that = createBuffer(that, length);
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255;
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength; // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array);
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset);
} else {
array = new Uint8Array(array, byteOffset, length);
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array;
that.__proto__ = Buffer.prototype;
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array);
}
return that
}
function fromObject (that, obj) {
if (internalIsBuffer(obj)) {
var len = checked(obj.length) | 0;
that = createBuffer(that, len);
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len);
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
Buffer.isBuffer = isBuffer;
function internalIsBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!internalIsBuffer(a) || !internalIsBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
};
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
};
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i;
if (length === undefined) {
length = 0;
for (i = 0; i < list.length; ++i) {
length += list[i].length;
}
}
var buffer = Buffer.allocUnsafe(length);
var pos = 0;
for (i = 0; i < list.length; ++i) {
var buf = list[i];
if (!internalIsBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos);
pos += buf.length;
}
return buffer
};
function byteLength (string, encoding) {
if (internalIsBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string;
}
var len = string.length;
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
}
Buffer.byteLength = byteLength;
function slowToString (encoding, start, end) {
var loweredCase = false;
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0;
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length;
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0;
start >>>= 0;
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8';
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase();
loweredCase = true;
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true;
function swap (b, n, m) {
var i = b[n];
b[n] = b[m];
b[m] = i;
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length;
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1);
}
return this
};
Buffer.prototype.swap32 = function swap32 () {
var len = this.length;
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3);
swap(this, i + 1, i + 2);
}
return this
};
Buffer.prototype.swap64 = function swap64 () {
var len = this.length;
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7);
swap(this, i + 1, i + 6);
swap(this, i + 2, i + 5);
swap(this, i + 3, i + 4);
}
return this
};
Buffer.prototype.toString = function toString () {
var length = this.length | 0;
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
};
Buffer.prototype.equals = function equals (b) {
if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
};
Buffer.prototype.inspect = function inspect () {
var str = '';
var max = INSPECT_MAX_BYTES;
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');
if (this.length > max) str += ' ... ';
}
return '<Buffer ' + str + '>'
};
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!internalIsBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0;
}
if (end === undefined) {
end = target ? target.length : 0;
}
if (thisStart === undefined) {
thisStart = 0;
}
if (thisEnd === undefined) {
thisEnd = this.length;
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0;
end >>>= 0;
thisStart >>>= 0;
thisEnd >>>= 0;
if (this === target) return 0
var x = thisEnd - thisStart;
var y = end - start;
var len = Math.min(x, y);
var thisCopy = this.slice(thisStart, thisEnd);
var targetCopy = target.slice(start, end);
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i];
y = targetCopy[i];
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
};
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset;
byteOffset = 0;
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff;
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000;
}
byteOffset = +byteOffset; // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1);
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1;
} else if (byteOffset < 0) {
if (dir) byteOffset = 0;
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding);
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (internalIsBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF; // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1;
var arrLength = arr.length;
var valLength = val.length;
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase();
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2;
arrLength /= 2;
valLength /= 2;
byteOffset /= 2;
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i;
if (dir) {
var foundIndex = -1;
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i;
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex;
foundIndex = -1;
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
for (i = byteOffset; i >= 0; i--) {
var found = true;
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false;
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
};
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
};
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
};
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0;
var remaining = buf.length - offset;
if (!length) {
length = remaining;
} else {
length = Number(length);
if (length > remaining) {
length = remaining;
}
}
// must be an even number of digits
var strLen = string.length;
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2;
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16);
if (isNaN(parsed)) return i
buf[offset + i] = parsed;
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8';
length = this.length;
offset = 0;
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset;
length = this.length;
offset = 0;
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0;
if (isFinite(length)) {
length = length | 0;
if (encoding === undefined) encoding = 'utf8';
} else {
encoding = length;
length = undefined;
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset;
if (length === undefined || length > remaining) length = remaining;
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8';
var loweredCase = false;
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase();
loweredCase = true;
}
}
};
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
};
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return fromByteArray(buf)
} else {
return fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end);
var res = [];
var i = start;
while (i < end) {
var firstByte = buf[i];
var codePoint = null;
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1;
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint;
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte;
}
break
case 2:
secondByte = buf[i + 1];
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint;
}
}
break
case 3:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint;
}
}
break
case 4:
secondByte = buf[i + 1];
thirdByte = buf[i + 2];
fourthByte = buf[i + 3];
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint;
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD;
bytesPerSequence = 1;
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000;
res.push(codePoint >>> 10 & 0x3FF | 0xD800);
codePoint = 0xDC00 | codePoint & 0x3FF;
}
res.push(codePoint);
i += bytesPerSequence;
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000;
function decodeCodePointsArray (codePoints) {
var len = codePoints.length;
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = '';
var i = 0;
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
);
}
return res
}
function asciiSlice (buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F);
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = '';
end = Math.min(buf.length, end);
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i]);
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length;
if (!start || start < 0) start = 0;
if (!end || end < 0 || end > len) end = len;
var out = '';
for (var i = start; i < end; ++i) {
out += toHex(buf[i]);
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end);
var res = '';
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length;
start = ~~start;
end = end === undefined ? len : ~~end;
if (start < 0) {
start += len;
if (start < 0) start = 0;
} else if (start > len) {
start = len;
}
if (end < 0) {
end += len;
if (end < 0) end = 0;
} else if (end > len) {
end = len;
}
if (end < start) end = start;
var newBuf;
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end);
newBuf.__proto__ = Buffer.prototype;
} else {
var sliceLen = end - start;
newBuf = new Buffer(sliceLen, undefined);
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start];
}
}
return newBuf
};
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
return val
};
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
checkOffset(offset, byteLength, this.length);
}
var val = this[offset + --byteLength];
var mul = 1;
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul;
}
return val
};
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
return this[offset]
};
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return this[offset] | (this[offset + 1] << 8)
};
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
return (this[offset] << 8) | this[offset + 1]
};
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
};
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
};
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var val = this[offset];
var mul = 1;
var i = 0;
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val
};
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) checkOffset(offset, byteLength, this.length);
var i = byteLength;
var mul = 1;
var val = this[offset + --i];
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul;
}
mul *= 0x80;
if (val >= mul) val -= Math.pow(2, 8 * byteLength);
return val
};
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length);
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
};
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset] | (this[offset + 1] << 8);
return (val & 0x8000) ? val | 0xFFFF0000 : val
};
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length);
var val = this[offset + 1] | (this[offset] << 8);
return (val & 0x8000) ? val | 0xFFFF0000 : val
};
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
};
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
};
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return read(this, offset, true, 23, 4)
};
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length);
return read(this, offset, false, 23, 4)
};
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return read(this, offset, true, 52, 8)
};
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length);
return read(this, offset, false, 52, 8)
};
function checkInt (buf, value, offset, ext, max, min) {
if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var mul = 1;
var i = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF;
}
return offset + byteLength
};
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
byteLength = byteLength | 0;
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1;
checkInt(this, value, offset, byteLength, maxBytes, 0);
}
var i = byteLength - 1;
var mul = 1;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF;
}
return offset + byteLength
};
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
this[offset] = (value & 0xff);
return offset + 1
};
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8;
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2
};
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8);
this[offset + 1] = (value & 0xff);
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2
};
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1;
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24);
this[offset + 2] = (value >>> 16);
this[offset + 1] = (value >>> 8);
this[offset] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4
};
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24);
this[offset + 1] = (value >>> 16);
this[offset + 2] = (value >>> 8);
this[offset + 3] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4
};
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = 0;
var mul = 1;
var sub = 0;
this[offset] = value & 0xFF;
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1;
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
}
return offset + byteLength
};
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1);
checkInt(this, value, offset, byteLength, limit - 1, -limit);
}
var i = byteLength - 1;
var mul = 1;
var sub = 0;
this[offset + i] = value & 0xFF;
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1;
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
}
return offset + byteLength
};
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);
if (value < 0) value = 0xff + value + 1;
this[offset] = (value & 0xff);
return offset + 1
};
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
} else {
objectWriteUInt16(this, value, offset, true);
}
return offset + 2
};
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8);
this[offset + 1] = (value & 0xff);
} else {
objectWriteUInt16(this, value, offset, false);
}
return offset + 2
};
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff);
this[offset + 1] = (value >>> 8);
this[offset + 2] = (value >>> 16);
this[offset + 3] = (value >>> 24);
} else {
objectWriteUInt32(this, value, offset, true);
}
return offset + 4
};
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value;
offset = offset | 0;
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
if (value < 0) value = 0xffffffff + value + 1;
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24);
this[offset + 1] = (value >>> 16);
this[offset + 2] = (value >>> 8);
this[offset + 3] = (value & 0xff);
} else {
objectWriteUInt32(this, value, offset, false);
}
return offset + 4
};
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4);
}
write(buf, value, offset, littleEndian, 23, 4);
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
};
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
};
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8);
}
write(buf, value, offset, littleEndian, 52, 8);
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
};
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
};
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0;
if (!end && end !== 0) end = this.length;
if (targetStart >= target.length) targetStart = target.length;
if (!targetStart) targetStart = 0;
if (end > 0 && end < start) end = start;
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length;
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start;
}
var len = end - start;
var i;
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start];
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start];
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
);
}
return len
};
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start;
start = 0;
end = this.length;
} else if (typeof end === 'string') {
encoding = end;
end = this.length;
}
if (val.length === 1) {
var code = val.charCodeAt(0);
if (code < 256) {
val = code;
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255;
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0;
end = end === undefined ? this.length : end >>> 0;
if (!val) val = 0;
var i;
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val;
}
} else {
var bytes = internalIsBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString());
var len = bytes.length;
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len];
}
}
return this
};
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g;
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '');
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '=';
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity;
var codePoint;
var length = string.length;
var leadSurrogate = null;
var bytes = [];
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i);
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
continue
}
// valid lead
leadSurrogate = codePoint;
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
leadSurrogate = codePoint;
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
}
leadSurrogate = null;
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint);
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
);
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
);
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
);
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF);
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo;
var byteArray = [];
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i);
hi = c >> 8;
lo = c % 256;
byteArray.push(lo);
byteArray.push(hi);
}
return byteArray
}
function base64ToBytes (str) {
return toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i];
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
function isBuffer(obj) {
return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))
}
function isFastBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
}
function parseBodyToType$1(res) {
if (res.headers.get('Content-Type') === 'application/json') {
return res.json().then(function (data) {
return [res, data];
});
}
return res.text().then(function (data) {
return [res, data];
});
}
function rpcRequest(fetch) {
return function rpcRequestWithFetch(path, body, auth, host, client, options) {
return client.checkAndRefreshAccessToken().then(function () {
var fetchOptions = {
method: 'POST',
body: body ? JSON.stringify(body) : null
};
var headers = {};
if (body) {
headers['Content-Type'] = 'application/json';
}
var authHeader = '';
switch (auth) {
case 'app':
if (!options.clientId || !options.clientSecret) {
throw new Error('A client id and secret is required for this function');
}
authHeader = new Buffer(options.clientId + ':' + options.clientSecret).toString('base64');
headers.Authorization = 'Basic ' + authHeader;
break;
case 'team':
case 'user':
headers.Authorization = 'Bearer ' + client.getAccessToken();
break;
case 'noauth':
break;
default:
throw new Error('Unhandled auth type: ' + auth);
}
if (options) {
if (options.selectUser) {
headers['Dropbox-API-Select-User'] = options.selectUser;
}
if (options.selectAdmin) {
headers['Dropbox-API-Select-Admin'] = options.selectAdmin;
}
if (options.pathRoot) {
headers['Dropbox-API-Path-Root'] = options.pathRoot;
}
}
fetchOptions.headers = headers;
return fetchOptions;
}).then(function (fetchOptions) {
return fetch(getBaseURL(host) + path, fetchOptions);
}).then(function (res) {
return parseBodyToType$1(res);
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
res = _ref2[0],
data = _ref2[1];
// maintaining existing API for error codes not equal to 200 range
if (!res.ok) {
// eslint-disable-next-line no-throw-literal
throw {
error: data,
response: res,
status: res.status
};
}
return data;
});
};
}
var crypto = void 0;
try {
crypto = require('crypto'); // eslint-disable-line global-require
} catch (Exception) {
crypto = window.crypto;
}
// Expiration is 300 seconds but needs to be in milliseconds for Date object
var TokenExpirationBuffer = 300 * 1000;
var PKCELength = 128;
var TokenAccessTypes = ['legacy', 'offline', 'online'];
var GrantTypes = ['code', 'token'];
var IncludeGrantedScopes = ['none', 'user', 'team'];
var BaseAuthorizeUrl = 'https://www.dropbox.com/oauth2/authorize';
var BaseTokenUrl = 'https://api.dropboxapi.com/oauth2/token';
/* eslint-disable */
// Polyfill object.assign for legacy browsers
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
if (typeof Object.assign !== 'function') {
(function () {
Object.assign = function (target) {
var output;
var index;
var source;
var nextKey;
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
output = Object(target);
for (index = 1; index < arguments.length; index++) {
source = arguments[index];
if (source !== undefined && source !== null) {
for (nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
// Polyfill Array.includes for legacy browsers
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value: function value(searchElement, fromIndex) {
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
// 1. Let O be ? ToObject(this value).
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If len is 0, return false.
if (len === 0) {
return false;
}
// 4. Let n be ? ToInteger(fromIndex).
// (If fromIndex is undefined, this step produces the value 0.)
var n = fromIndex | 0;
// 5. If n ≥ 0, then
// a. Let k be n.
// 6. Else n < 0,
// a. Let k be len + n.
// b. If k < 0, let k be 0.
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);
}
// 7. Repeat, while k < len
while (k < len) {
// a. Let elementK be the result of ? Get(O, ! ToString(k)).
// b. If SameValueZero(searchElement, elementK) is true, return true.
if (sameValueZero(o[k], searchElement)) {
return true;
}
// c. Increase k by 1.
k++;
}
// 8. Return false
return false;
}
});
}
/* eslint-enable */
/**
* @private
* @class DropboxBase
* @classdesc The main Dropbox SDK class. This contains the methods that are
* shared between Dropbox and DropboxTeam classes. It is marked as private so
* that it doesn't show up in the docs because it is never used directly.
* @arg {Object} options
* @arg {Function} [options.fetch] - fetch library for making requests.
* @arg {String} [options.accessToken] - An access token for making authenticated
* requests.
* @arg {String} [options.clientId] - The client id for your app. Used to create
* authentication URL.
* @arg {String} [options.clientSecret] - The client secret for your app.
* @arg {Number} [options.selectUser] - User that the team access token would like
* to act as.
* @arg {String} [options.selectAdmin] - Team admin that the team access token would like
* to act as.
* @arg {String} [options.pathRoot] - root pass to access other namespaces
* Use to access team folders for example
*/
function parseBodyToType$2(res) {
var clone = res.clone();
return new Promise(function (resolve) {
res.json().then(function (data) {
return resolve(data);
}).catch(function () {
return clone.text().then(function (data) {
return resolve(data);
});
});
}).then(function (data) {
return [res, data];
});
}
/**
*
* @param expiresIn
*/
function getTokenExpiresAt(expiresIn) {
return new Date(Date.now() + expiresIn * 1000);
}
var DropboxBase = function () {
function DropboxBase(options) {
classCallCheck(this, DropboxBase);
options = options || {};
this.accessToken = options.accessToken;
this.accessTokenExpiresAt = options.accessTokenExpiresAt;
this.refreshToken = options.refreshToken;
this.clientId = options.clientId;
this.clientSecret = options.clientSecret;
this.selectUser = options.selectUser;
this.selectAdmin = options.selectAdmin;
this.fetch = options.fetch || fetch;
this.pathRoot = options.pathRoot;
if (!options.fetch) {
console.warn('Global fetch is deprecated and will be unsupported in a future version. Please pass fetch function as option when instantiating dropbox instance: new Dropbox({fetch})');
} // eslint-disable-line no-console
}
/**
* Set the access token used to authenticate requests to the API.
* @arg {String} accessToken - An access token
* @returns {undefined}
*/
createClass(DropboxBase, [{
key: 'setAccessToken',
value: function setAccessToken(accessToken) {
this.accessToken = accessToken;
}
/**
* Get the access token
* @returns {String} Access token
*/
}, {
key: 'getAccessToken',
value: function getAccessToken() {
return this.accessToken;
}
/**
* Set the client id, which is used to help gain an access token.
* @arg {String} clientId - Your apps client id
* @returns {undefined}
*/
}, {
key: 'setClientId',
value: function setClientId(clientId) {
this.clientId = clientId;
}
/**
* Get the client id
* @returns {String} Client id
*/
}, {
key: 'getClientId',
value: function getClientId() {
return this.clientId;
}
/**
* Set the client secret
* @arg {String} clientSecret - Your app's client secret
* @returns {undefined}
*/
}, {
key: 'setClientSecret',
value: function setClientSecret(clientSecret) {
this.clientSecret = clientSecret;
}
/**
* Get the client secret
* @returns {String} Client secret
*/
}, {
key: 'getClientSecret',
value: function getClientSecret() {
return this.clientSecret;
}
/**
* Gets the refresh token
* @returns {String} Refresh token
*/
}, {
key: 'getRefreshToken',
value: function getRefreshToken() {
return this.refreshToken;
}
/**
* Sets the refresh token
* @param refreshToken - A refresh token
*/
}, {
key: 'setRefreshToken',
value: function setRefreshToken(refreshToken) {
this.refreshToken = refreshToken;
}
/**
* Gets the access token's expiration date
* @returns {Date} date of token expiration
*/
}, {
key: 'getAccessTokenExpiresAt',
value: function getAccessTokenExpiresAt() {
return this.accessTokenExpiresAt;
}
/**
* Sets the access token's expiration date
* @param accessTokenExpiresAt - new expiration date
*/
}, {
key: 'setAccessTokenExpiresAt',
value: function setAccessTokenExpiresAt(accessTokenExpiresAt) {
this.accessTokenExpiresAt = accessTokenExpiresAt;
}
}, {
key: 'generatePKCECodes',
value: function generatePKCECodes() {
var codeVerifier = crypto.randomBytes(PKCELength);
codeVerifier = codeVerifier.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '').substr(0, 128);
this.codeVerifier = codeVerifier;
var encoder = new TextEncoder();
var codeData = encoder.encode(codeVerifier);
var codeChallenge = crypto.createHash('sha256').update(codeData).digest();
codeChallenge = codeChallenge.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
this.codeChallenge = codeChallenge;
}
/**
* Get a URL that can be used to authenticate users for the Dropbox API.
* @arg {String} redirectUri - A URL to redirect the user to after
* authenticating. This must be added to your app through the admin interface.
* @arg {String} [state] - State that will be returned in the redirect URL to help
* prevent cross site scripting attacks.
* @arg {String} [authType] - auth type, defaults to 'token', other option is 'code'
* @arg {String} [tokenAccessType] - type of token to request. From the following:
* legacy - creates one long-lived token with no expiration
* online - create one short-lived token with an expiration
* offline - create one short-lived token with an expiration with a refresh token
* @arg {Array<String>>} [scope] - scopes to request for the grant
* @arg {String} [includeGrantedScopes] - whether or not to include previously granted scopes.
* From the following:
* user - include user scopes in the grant
* team - include team scopes in the grant
* Note: if this user has never linked the app, include_granted_scopes must be None
* @arg {boolean} [usePKCE] - Whether or not to use Sha256 based PKCE. PKCE should be only use on
* client apps which doesn't call your server. It is less secure than non-PKCE flow but
* can be used if you are unable to safely retrieve your app secret
* @returns {String} Url to send user to for Dropbox API authentication
*/
}, {
key: 'getAuthenticationUrl',
value: function getAuthenticationUrl(redirectUri, state) {
var authType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'token';
var tokenAccessType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'legacy';
var scope = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null;
var includeGrantedScopes = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 'none';
var usePKCE = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false;
var clientId = this.getClientId();
var baseUrl = BaseAuthorizeUrl;
if (!clientId) {
throw new Error('A client id is required. You can set the client id using .setClientId().');
}
if (authType !== 'code' && !redirectUri) {
throw new Error('A redirect uri is required.');
}
if (!GrantTypes.includes(authType)) {
throw new Error('Authorization type must be code or token');
}
if (!TokenAccessTypes.includes(tokenAccessType)) {
throw new Error('Token Access Type must be legacy, offline, or online');
}
if (scope && !(scope instanceof Array)) {
throw new Error('Scope must be an array of strings');
}
if (!IncludeGrantedScopes.includes(includeGrantedScopes)) {
throw new Error('includeGrantedScopes must be none, user, or team');
}
var authUrl = void 0;
if (authType === 'code') {
authUrl = baseUrl + '?response_type=code&client_id=' + clientId;
} else {
authUrl = baseUrl + '?response_type=token&client_id=' + clientId;
}
if (redirectUri) {
authUrl += '&redirect_uri=' + redirectUri;
}
if (state) {
authUrl += '&state=' + state;
}
if (tokenAccessType !== 'legacy') {
authUrl += '&token_access_type=' + tokenAccessType;
}
if (scope) {
authUrl += '&scope=' + scope.join(' ');
}
if (includeGrantedScopes !== 'none') {
authUrl += '&include_granted_scopes=' + includeGrantedScopes;
}
if (usePKCE) {
this.generatePKCECodes();
authUrl += '&code_challenge_method=S256';
authUrl += '&code_challenge=' + this.codeChallenge;
}
return authUrl;
}
/**
* Get an OAuth2 access token from an OAuth2 Code.
* @arg {String} redirectUri - A URL to redirect the user to after
* authenticating. This must be added to your app through the admin interface.
* @arg {String} code - An OAuth2 code.
*/
}, {
key: 'getAccessTokenFromCode',
value: function getAccessTokenFromCode(redirectUri, code) {
var clientId = this.getClientId();
var clientSecret = this.getClientSecret();
if (!clientId) {
throw new Error('A client id is required. You can set the client id using .setClientId().');
}
var path = BaseTokenUrl;
path += '?grant_type=authorization_code';
path += '&code=' + code;
path += '&client_id=' + clientId;
if (clientSecret) {
path += '&client_secret=' + clientSecret;
} else {
if (!this.codeChallenge) {
throw new Error('You must use PKCE when generating the authorization URL to not include a client secret');
}
path += '&code_verifier=' + this.codeVerifier;
}
if (redirectUri) {
path += '&redirect_uri=' + redirectUri;
}
var fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
return this.fetch(path, fetchOptions).then(function (res) {
return parseBodyToType$2(res);
}).then(function (_ref) {
var _ref2 = slicedToArray(_ref, 2),
res = _ref2[0],
data = _ref2[1];
// maintaining existing API for error codes not equal to 200 range
if (!res.ok) {
// eslint-disable-next-line no-throw-literal
throw {
error: data,
response: res,
status: res.status
};
}
if (data.refresh_token) {
return {
accessToken: data.access_token,
refreshToken: data.refresh_token,
accessTokenExpiresAt: getTokenExpiresAt(data.expires_in)
};
}
return data.access_token;
});
}
/**
* Checks if a token is needed, can be refreshed and if the token is expired.
* If so, attempts to refresh access token
* @returns {Promise<*>}
*/
}, {
key: 'checkAndRefreshAccessToken',
value: function checkAndRefreshAccessToken() {
var canRefresh = this.getRefreshToken() && this.getClientId();
var needsRefresh = this.getAccessTokenExpiresAt() && new Date(Date.now() + TokenExpirationBuffer) >= this.getAccessTokenExpiresAt();
var needsToken = !this.getAccessToken();
if ((needsRefresh || needsToken) && canRefresh) {
return this.refreshAccessToken();
}
return Promise.resolve();
}
/**
* Refreshes the access token using the refresh token, if available
* @arg {List} scope - a subset of scopes from the original
* refresh to acquire with an access token
* @returns {Promise<*>}
*/
}, {
key: 'refreshAccessToken',
value: function refreshAccessToken() {
var _this = this;
var scope = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
var refreshUrl = BaseTokenUrl;
var clientId = this.getClientId();
var clientSecret = this.getClientSecret();
if (!clientId) {
throw new Error('A client id is required. You can set the client id using .setClientId().');
}
if (scope && !(scope instanceof Array)) {
throw new Error('Scope must be an array of strings');
}
var headers = {};
headers['Content-Type'] = 'application/json';
refreshUrl += '?grant_type=refresh_token&refresh_token=' + this.getRefreshToken();
refreshUrl += '&client_id=' + clientId;
if (clientSecret) {
refreshUrl += '&client_secret=' + clientSecret;
}
if (scope) {
refreshUrl += '&scope=' + scope.join(' ');
}
var fetchOptions = {
method: 'POST'
};
fetchOptions.headers = headers;
return this.fetch(refreshUrl, fetchOptions).then(function (res) {
return parseBodyToType$2(res);
}).then(function (_ref3) {
var _ref4 = slicedToArray(_ref3, 2),
res = _ref4[0],
data = _ref4[1];
// maintaining existing API for error codes not equal to 200 range
if (!res.ok) {
// eslint-disable-next-line no-throw-literal
throw {
error: data,
response: res,
status: res.status
};
}
_this.setAccessToken(data.access_token);
_this.setAccessTokenExpiresAt(getTokenExpiresAt(data.expires_in));
});
}
/**
* Called when the authentication succeed
* @callback successCallback
* @param {string} access_token The application's access token
*/
/**
* Called when the authentication failed.
* @callback errorCallback
*/
/**
* An authentication process that works with cordova applications.
* @param {successCallback} successCallback
* @param {errorCallback} errorCallback
*/
}, {
key: 'authenticateWithCordova',
value: function authenticateWithCordova(successCallback, errorCallback) {
var redirectUrl = 'https://www.dropbox.com/1/oauth2/redirect_receiver';
var url = this.getAuthenticationUrl(redirectUrl);
var removed = false;
var browser = window.open(url, '_blank');
function onLoadError(event) {
if (event.code !== -999) {
// Workaround to fix wrong behavior on cordova-plugin-inappbrowser
// Try to avoid a browser crash on browser.close().
window.setTimeout(function () {
browser.close();
}, 10);
errorCallback();
}
}
function onLoadStop(event) {
var errorLabel = '&error=';
var errorIndex = event.url.indexOf(errorLabel);
if (errorIndex > -1) {
// Try to avoid a browser crash on browser.close().
window.setTimeout(function () {
browser.close();
}, 10);
errorCallback();
} else {
var tokenLabel = '#access_token=';
var tokenIndex = event.url.indexOf(tokenLabel);
var tokenTypeIndex = event.url.indexOf('&token_type=');
if (tokenIndex > -1) {
tokenIndex += tokenLabel.length;
// Try to avoid a browser crash on browser.close().
window.setTimeout(function () {
browser.close();
}, 10);
var accessToken = event.url.substring(tokenIndex, tokenTypeIndex);
successCallback(accessToken);
}
}
}
function onExit() {
if (removed) {
return;
}
browser.removeEventListener('loaderror', onLoadError);
browser.removeEventListener('loadstop', onLoadStop);
browser.removeEventListener('exit', onExit);
removed = true;
}
browser.addEventListener('loaderror', onLoadError);
browser.addEventListener('loadstop', onLoadStop);
browser.addEventListener('exit', onExit);
}
}, {
key: 'request',
value: function request(path, args, auth, host, style) {
var request = null;
switch (style) {
case RPC:
request = this.getRpcRequest();
break;
case DOWNLOAD:
request = this.getDownloadRequest();
break;
case UPLOAD:
request = this.getUploadRequest();
break;
default:
throw new Error('Invalid request style: ' + style);
}
var options = {
selectUser: this.selectUser,
selectAdmin: this.selectAdmin,
clientId: this.getClientId(),
clientSecret: this.getClientSecret(),
pathRoot: this.pathRoot
};
return request(path, args, auth, host, this, options);
}
}, {
key: 'setRpcRequest',
value: function setRpcRequest(newRpcRequest) {
this.rpcRequest = newRpcRequest;
}
}, {
key: 'getRpcRequest',
value: function getRpcRequest() {
if (this.rpcRequest === undefined) {
this.rpcRequest = rpcRequest(this.fetch);
}
return this.rpcRequest;
}
}, {
key: 'setDownloadRequest',
value: function setDownloadRequest(newDownloadRequest) {
this.downloadRequest = newDownloadRequest;
}
}, {
key: 'getDownloadRequest',
value: function getDownloadRequest() {
if (this.downloadRequest === undefined) {
this.downloadRequest = downloadRequest(this.fetch);
}
return this.downloadRequest;
}
}, {
key: 'setUploadRequest',
value: function setUploadRequest(newUploadRequest) {
this.uploadRequest = newUploadRequest;
}
}, {
key: 'getUploadRequest',
value: function getUploadRequest() {
if (this.uploadRequest === undefined) {
this.uploadRequest = uploadRequest(this.fetch);
}
return this.uploadRequest;
}
}]);
return DropboxBase;
}();
/**
* @class Dropbox
* @extends DropboxBase
* @classdesc The Dropbox SDK class that provides methods to read, write and
* create files or folders in a user's Dropbox.
* @arg {Object} options
* @arg {Function} [options.fetch] - fetch library for making requests.
* @arg {String} [options.accessToken] - An access token for making authenticated
* requests.
* @arg {String} [options.clientId] - The client id for your app. Used to create
* authentication URL.
* @arg {String} [options.selectUser] - Select user is only used by DropboxTeam.
* It specifies which user the team access token should be acting as.
* @arg {String} [options.pathRoot] - root pass to access other namespaces
* Use to access team folders for example
* @arg {String} [options.refreshToken] - A refresh token for retrieving access tokens
* @arg {Date} [options.AccessTokenExpiresAt] - Date of the current access token's
* expiration (if available)
*/
var Dropbox = function (_DropboxBase) {
inherits(Dropbox, _DropboxBase);
function Dropbox(options) {
classCallCheck(this, Dropbox);
var _this = possibleConstructorReturn(this, (Dropbox.__proto__ || Object.getPrototypeOf(Dropbox)).call(this, options));
Object.assign(_this, routes);
return _this;
}
createClass(Dropbox, [{
key: 'filesGetSharedLinkFile',
value: function filesGetSharedLinkFile(arg) {
return this.request('sharing/get_shared_link_file', arg, 'api', 'download');
}
}]);
return Dropbox;
}(DropboxBase);
var dropbox = /*#__PURE__*/Object.freeze({
__proto__: null,
Dropbox: Dropbox
});
// Auto-generated by Stone, do not modify.
var routes$1 = {};
/**
* List all device sessions of a team's member.
* @function DropboxTeam#teamDevicesListMemberDevices
* @arg {TeamListMemberDevicesArg} arg - The request parameters.
* @returns {Promise.<TeamListMemberDevicesResult, Error.<TeamListMemberDevicesError>>}
*/
routes$1.teamDevicesListMemberDevices = function (arg) {
return this.request('team/devices/list_member_devices', arg, 'team', 'api', 'rpc');
};
/**
* List all device sessions of a team. Permission : Team member file access.
* @function DropboxTeam#teamDevicesListMembersDevices
* @arg {TeamListMembersDevicesArg} arg - The request parameters.
* @returns {Promise.<TeamListMembersDevicesResult, Error.<TeamListMembersDevicesError>>}
*/
routes$1.teamDevicesListMembersDevices = function (arg) {
return this.request('team/devices/list_members_devices', arg, 'team', 'api', 'rpc');
};
/**
* List all device sessions of a team. Permission : Team member file access.
* @function DropboxTeam#teamDevicesListTeamDevices
* @deprecated
* @arg {TeamListTeamDevicesArg} arg - The request parameters.
* @returns {Promise.<TeamListTeamDevicesResult, Error.<TeamListTeamDevicesError>>}
*/
routes$1.teamDevicesListTeamDevices = function (arg) {
return this.request('team/devices/list_team_devices', arg, 'team', 'api', 'rpc');
};
/**
* Revoke a device session of a team's member.
* @function DropboxTeam#teamDevicesRevokeDeviceSession
* @arg {TeamRevokeDeviceSessionArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamRevokeDeviceSessionError>>}
*/
routes$1.teamDevicesRevokeDeviceSession = function (arg) {
return this.request('team/devices/revoke_device_session', arg, 'team', 'api', 'rpc');
};
/**
* Revoke a list of device sessions of team members.
* @function DropboxTeam#teamDevicesRevokeDeviceSessionBatch
* @arg {TeamRevokeDeviceSessionBatchArg} arg - The request parameters.
* @returns {Promise.<TeamRevokeDeviceSessionBatchResult, Error.<TeamRevokeDeviceSessionBatchError>>}
*/
routes$1.teamDevicesRevokeDeviceSessionBatch = function (arg) {
return this.request('team/devices/revoke_device_session_batch', arg, 'team', 'api', 'rpc');
};
/**
* Get the values for one or more featues. This route allows you to check your
* account's capability for what feature you can access or what value you have
* for certain features. Permission : Team information.
* @function DropboxTeam#teamFeaturesGetValues
* @arg {TeamFeaturesGetValuesBatchArg} arg - The request parameters.
* @returns {Promise.<TeamFeaturesGetValuesBatchResult, Error.<TeamFeaturesGetValuesBatchError>>}
*/
routes$1.teamFeaturesGetValues = function (arg) {
return this.request('team/features/get_values', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves information about a team.
* @function DropboxTeam#teamGetInfo
* @arg {void} arg - The request parameters.
* @returns {Promise.<TeamTeamGetInfoResult, Error.<void>>}
*/
routes$1.teamGetInfo = function (arg) {
return this.request('team/get_info', arg, 'team', 'api', 'rpc');
};
/**
* Creates a new, empty group, with a requested name. Permission : Team member
* management.
* @function DropboxTeam#teamGroupsCreate
* @arg {TeamGroupCreateArg} arg - The request parameters.
* @returns {Promise.<TeamGroupFullInfo, Error.<TeamGroupCreateError>>}
*/
routes$1.teamGroupsCreate = function (arg) {
return this.request('team/groups/create', arg, 'team', 'api', 'rpc');
};
/**
* Deletes a group. The group is deleted immediately. However the revoking of
* group-owned resources may take additional time. Use the groups/job_status/get
* to determine whether this process has completed. Permission : Team member
* management.
* @function DropboxTeam#teamGroupsDelete
* @arg {TeamGroupSelector} arg - The request parameters.
* @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamGroupDeleteError>>}
*/
routes$1.teamGroupsDelete = function (arg) {
return this.request('team/groups/delete', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves information about one or more groups. Note that the optional field
* GroupFullInfo.members is not returned for system-managed groups. Permission :
* Team Information.
* @function DropboxTeam#teamGroupsGetInfo
* @arg {TeamGroupsSelector} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamGroupsGetInfoError>>}
*/
routes$1.teamGroupsGetInfo = function (arg) {
return this.request('team/groups/get_info', arg, 'team', 'api', 'rpc');
};
/**
* Once an async_job_id is returned from groups/delete, groups/members/add , or
* groups/members/remove use this method to poll the status of granting/revoking
* group members' access to group-owned resources. Permission : Team member
* management.
* @function DropboxTeam#teamGroupsJobStatusGet
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<AsyncPollEmptyResult, Error.<TeamGroupsPollError>>}
*/
routes$1.teamGroupsJobStatusGet = function (arg) {
return this.request('team/groups/job_status/get', arg, 'team', 'api', 'rpc');
};
/**
* Lists groups on a team. Permission : Team Information.
* @function DropboxTeam#teamGroupsList
* @arg {TeamGroupsListArg} arg - The request parameters.
* @returns {Promise.<TeamGroupsListResult, Error.<void>>}
*/
routes$1.teamGroupsList = function (arg) {
return this.request('team/groups/list', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from groups/list, use this to paginate
* through all groups. Permission : Team Information.
* @function DropboxTeam#teamGroupsListContinue
* @arg {TeamGroupsListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamGroupsListResult, Error.<TeamGroupsListContinueError>>}
*/
routes$1.teamGroupsListContinue = function (arg) {
return this.request('team/groups/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Adds members to a group. The members are added immediately. However the
* granting of group-owned resources may take additional time. Use the
* groups/job_status/get to determine whether this process has completed.
* Permission : Team member management.
* @function DropboxTeam#teamGroupsMembersAdd
* @arg {TeamGroupMembersAddArg} arg - The request parameters.
* @returns {Promise.<TeamGroupMembersChangeResult, Error.<TeamGroupMembersAddError>>}
*/
routes$1.teamGroupsMembersAdd = function (arg) {
return this.request('team/groups/members/add', arg, 'team', 'api', 'rpc');
};
/**
* Lists members of a group. Permission : Team Information.
* @function DropboxTeam#teamGroupsMembersList
* @arg {TeamGroupsMembersListArg} arg - The request parameters.
* @returns {Promise.<TeamGroupsMembersListResult, Error.<TeamGroupSelectorError>>}
*/
routes$1.teamGroupsMembersList = function (arg) {
return this.request('team/groups/members/list', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from groups/members/list, use this to
* paginate through all members of the group. Permission : Team information.
* @function DropboxTeam#teamGroupsMembersListContinue
* @arg {TeamGroupsMembersListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamGroupsMembersListResult, Error.<TeamGroupsMembersListContinueError>>}
*/
routes$1.teamGroupsMembersListContinue = function (arg) {
return this.request('team/groups/members/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Removes members from a group. The members are removed immediately. However
* the revoking of group-owned resources may take additional time. Use the
* groups/job_status/get to determine whether this process has completed. This
* method permits removing the only owner of a group, even in cases where this
* is not possible via the web client. Permission : Team member management.
* @function DropboxTeam#teamGroupsMembersRemove
* @arg {TeamGroupMembersRemoveArg} arg - The request parameters.
* @returns {Promise.<TeamGroupMembersChangeResult, Error.<TeamGroupMembersRemoveError>>}
*/
routes$1.teamGroupsMembersRemove = function (arg) {
return this.request('team/groups/members/remove', arg, 'team', 'api', 'rpc');
};
/**
* Sets a member's access type in a group. Permission : Team member management.
* @function DropboxTeam#teamGroupsMembersSetAccessType
* @arg {TeamGroupMembersSetAccessTypeArg} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamGroupMemberSetAccessTypeError>>}
*/
routes$1.teamGroupsMembersSetAccessType = function (arg) {
return this.request('team/groups/members/set_access_type', arg, 'team', 'api', 'rpc');
};
/**
* Updates a group's name and/or external ID. Permission : Team member
* management.
* @function DropboxTeam#teamGroupsUpdate
* @arg {TeamGroupUpdateArgs} arg - The request parameters.
* @returns {Promise.<TeamGroupFullInfo, Error.<TeamGroupUpdateError>>}
*/
routes$1.teamGroupsUpdate = function (arg) {
return this.request('team/groups/update', arg, 'team', 'api', 'rpc');
};
/**
* Creates new legal hold policy. Permission : Team member file access.
* @function DropboxTeam#teamLegalHoldsCreatePolicy
* @arg {TeamLegalHoldsPolicyCreateArg} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamLegalHoldsPolicyCreateError>>}
*/
routes$1.teamLegalHoldsCreatePolicy = function (arg) {
return this.request('team/legal_holds/create_policy', arg, 'team', 'api', 'rpc');
};
/**
* Gets a legal hold by Id. Permission : Team member file access.
* @function DropboxTeam#teamLegalHoldsGetPolicy
* @arg {TeamLegalHoldsGetPolicyArg} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamLegalHoldsGetPolicyError>>}
*/
routes$1.teamLegalHoldsGetPolicy = function (arg) {
return this.request('team/legal_holds/get_policy', arg, 'team', 'api', 'rpc');
};
/**
* @function DropboxTeam#teamLegalHoldsListHeldRevisions
* @arg {TeamLegalHoldsListHeldRevisionsArg} arg - The request parameters.
* @returns {Promise.<TeamLegalHoldsListHeldRevisionResult, Error.<TeamLegalHoldsListHeldRevisionsError>>}
*/
routes$1.teamLegalHoldsListHeldRevisions = function (arg) {
return this.request('team/legal_holds/list_held_revisions', arg, 'team', 'api', 'rpc');
};
/**
* @function DropboxTeam#teamLegalHoldsListHeldRevisionsContinue
* @arg {TeamLegalHoldsListHeldRevisionsContinueArg} arg - The request parameters.
* @returns {Promise.<TeamLegalHoldsListHeldRevisionResult, Error.<TeamLegalHoldsListHeldRevisionsError>>}
*/
routes$1.teamLegalHoldsListHeldRevisionsContinue = function (arg) {
return this.request('team/legal_holds/list_held_revisions_continue', arg, 'team', 'api', 'rpc');
};
/**
* Lists legal holds on a team. Permission : Team member file access.
* @function DropboxTeam#teamLegalHoldsListPolicies
* @arg {TeamLegalHoldsListPoliciesArg} arg - The request parameters.
* @returns {Promise.<TeamLegalHoldsListPoliciesResult, Error.<TeamLegalHoldsListPoliciesError>>}
*/
routes$1.teamLegalHoldsListPolicies = function (arg) {
return this.request('team/legal_holds/list_policies', arg, 'team', 'api', 'rpc');
};
/**
* Releases a legal hold by Id. Permission : Team member file access.
* @function DropboxTeam#teamLegalHoldsReleasePolicy
* @arg {TeamLegalHoldsPolicyReleaseArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamLegalHoldsPolicyReleaseError>>}
*/
routes$1.teamLegalHoldsReleasePolicy = function (arg) {
return this.request('team/legal_holds/release_policy', arg, 'team', 'api', 'rpc');
};
/**
* Updates a legal hold. Permission : Team member file access.
* @function DropboxTeam#teamLegalHoldsUpdatePolicy
* @arg {TeamLegalHoldsPolicyUpdateArg} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamLegalHoldsPolicyUpdateError>>}
*/
routes$1.teamLegalHoldsUpdatePolicy = function (arg) {
return this.request('team/legal_holds/update_policy', arg, 'team', 'api', 'rpc');
};
/**
* List all linked applications of the team member. Note, this endpoint does not
* list any team-linked applications.
* @function DropboxTeam#teamLinkedAppsListMemberLinkedApps
* @arg {TeamListMemberAppsArg} arg - The request parameters.
* @returns {Promise.<TeamListMemberAppsResult, Error.<TeamListMemberAppsError>>}
*/
routes$1.teamLinkedAppsListMemberLinkedApps = function (arg) {
return this.request('team/linked_apps/list_member_linked_apps', arg, 'team', 'api', 'rpc');
};
/**
* List all applications linked to the team members' accounts. Note, this
* endpoint does not list any team-linked applications.
* @function DropboxTeam#teamLinkedAppsListMembersLinkedApps
* @arg {TeamListMembersAppsArg} arg - The request parameters.
* @returns {Promise.<TeamListMembersAppsResult, Error.<TeamListMembersAppsError>>}
*/
routes$1.teamLinkedAppsListMembersLinkedApps = function (arg) {
return this.request('team/linked_apps/list_members_linked_apps', arg, 'team', 'api', 'rpc');
};
/**
* List all applications linked to the team members' accounts. Note, this
* endpoint doesn't list any team-linked applications.
* @function DropboxTeam#teamLinkedAppsListTeamLinkedApps
* @deprecated
* @arg {TeamListTeamAppsArg} arg - The request parameters.
* @returns {Promise.<TeamListTeamAppsResult, Error.<TeamListTeamAppsError>>}
*/
routes$1.teamLinkedAppsListTeamLinkedApps = function (arg) {
return this.request('team/linked_apps/list_team_linked_apps', arg, 'team', 'api', 'rpc');
};
/**
* Revoke a linked application of the team member.
* @function DropboxTeam#teamLinkedAppsRevokeLinkedApp
* @arg {TeamRevokeLinkedApiAppArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamRevokeLinkedAppError>>}
*/
routes$1.teamLinkedAppsRevokeLinkedApp = function (arg) {
return this.request('team/linked_apps/revoke_linked_app', arg, 'team', 'api', 'rpc');
};
/**
* Revoke a list of linked applications of the team members.
* @function DropboxTeam#teamLinkedAppsRevokeLinkedAppBatch
* @arg {TeamRevokeLinkedApiAppBatchArg} arg - The request parameters.
* @returns {Promise.<TeamRevokeLinkedAppBatchResult, Error.<TeamRevokeLinkedAppBatchError>>}
*/
routes$1.teamLinkedAppsRevokeLinkedAppBatch = function (arg) {
return this.request('team/linked_apps/revoke_linked_app_batch', arg, 'team', 'api', 'rpc');
};
/**
* Add users to member space limits excluded users list.
* @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersAdd
* @arg {TeamExcludedUsersUpdateArg} arg - The request parameters.
* @returns {Promise.<TeamExcludedUsersUpdateResult, Error.<TeamExcludedUsersUpdateError>>}
*/
routes$1.teamMemberSpaceLimitsExcludedUsersAdd = function (arg) {
return this.request('team/member_space_limits/excluded_users/add', arg, 'team', 'api', 'rpc');
};
/**
* List member space limits excluded users.
* @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersList
* @arg {TeamExcludedUsersListArg} arg - The request parameters.
* @returns {Promise.<TeamExcludedUsersListResult, Error.<TeamExcludedUsersListError>>}
*/
routes$1.teamMemberSpaceLimitsExcludedUsersList = function (arg) {
return this.request('team/member_space_limits/excluded_users/list', arg, 'team', 'api', 'rpc');
};
/**
* Continue listing member space limits excluded users.
* @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersListContinue
* @arg {TeamExcludedUsersListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamExcludedUsersListResult, Error.<TeamExcludedUsersListContinueError>>}
*/
routes$1.teamMemberSpaceLimitsExcludedUsersListContinue = function (arg) {
return this.request('team/member_space_limits/excluded_users/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Remove users from member space limits excluded users list.
* @function DropboxTeam#teamMemberSpaceLimitsExcludedUsersRemove
* @arg {TeamExcludedUsersUpdateArg} arg - The request parameters.
* @returns {Promise.<TeamExcludedUsersUpdateResult, Error.<TeamExcludedUsersUpdateError>>}
*/
routes$1.teamMemberSpaceLimitsExcludedUsersRemove = function (arg) {
return this.request('team/member_space_limits/excluded_users/remove', arg, 'team', 'api', 'rpc');
};
/**
* Get users custom quota. Returns none as the custom quota if none was set. A
* maximum of 1000 members can be specified in a single call.
* @function DropboxTeam#teamMemberSpaceLimitsGetCustomQuota
* @arg {TeamCustomQuotaUsersArg} arg - The request parameters.
* @returns {Promise.<Array.<TeamCustomQuotaResult>, Error.<TeamCustomQuotaError>>}
*/
routes$1.teamMemberSpaceLimitsGetCustomQuota = function (arg) {
return this.request('team/member_space_limits/get_custom_quota', arg, 'team', 'api', 'rpc');
};
/**
* Remove users custom quota. A maximum of 1000 members can be specified in a
* single call.
* @function DropboxTeam#teamMemberSpaceLimitsRemoveCustomQuota
* @arg {TeamCustomQuotaUsersArg} arg - The request parameters.
* @returns {Promise.<Array.<TeamRemoveCustomQuotaResult>, Error.<TeamCustomQuotaError>>}
*/
routes$1.teamMemberSpaceLimitsRemoveCustomQuota = function (arg) {
return this.request('team/member_space_limits/remove_custom_quota', arg, 'team', 'api', 'rpc');
};
/**
* Set users custom quota. Custom quota has to be at least 15GB. A maximum of
* 1000 members can be specified in a single call.
* @function DropboxTeam#teamMemberSpaceLimitsSetCustomQuota
* @arg {TeamSetCustomQuotaArg} arg - The request parameters.
* @returns {Promise.<Array.<TeamCustomQuotaResult>, Error.<TeamSetCustomQuotaError>>}
*/
routes$1.teamMemberSpaceLimitsSetCustomQuota = function (arg) {
return this.request('team/member_space_limits/set_custom_quota', arg, 'team', 'api', 'rpc');
};
/**
* Adds members to a team. Permission : Team member management A maximum of 20
* members can be specified in a single call. If no Dropbox account exists with
* the email address specified, a new Dropbox account will be created with the
* given email address, and that account will be invited to the team. If a
* personal Dropbox account exists with the email address specified in the call,
* this call will create a placeholder Dropbox account for the user on the team
* and send an email inviting the user to migrate their existing personal
* account onto the team. Team member management apps are required to set an
* initial given_name and surname for a user to use in the team invitation and
* for 'Perform as team member' actions taken on the user before they become
* 'active'.
* @function DropboxTeam#teamMembersAdd
* @arg {TeamMembersAddArg} arg - The request parameters.
* @returns {Promise.<TeamMembersAddLaunch, Error.<void>>}
*/
routes$1.teamMembersAdd = function (arg) {
return this.request('team/members/add', arg, 'team', 'api', 'rpc');
};
/**
* Once an async_job_id is returned from members/add , use this to poll the
* status of the asynchronous request. Permission : Team member management.
* @function DropboxTeam#teamMembersAddJobStatusGet
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<TeamMembersAddJobStatus, Error.<AsyncPollError>>}
*/
routes$1.teamMembersAddJobStatusGet = function (arg) {
return this.request('team/members/add/job_status/get', arg, 'team', 'api', 'rpc');
};
/**
* Deletes a team member's profile photo. Permission : Team member management.
* @function DropboxTeam#teamMembersDeleteProfilePhoto
* @arg {TeamMembersDeleteProfilePhotoArg} arg - The request parameters.
* @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersDeleteProfilePhotoError>>}
*/
routes$1.teamMembersDeleteProfilePhoto = function (arg) {
return this.request('team/members/delete_profile_photo', arg, 'team', 'api', 'rpc');
};
/**
* Returns information about multiple team members. Permission : Team
* information This endpoint will return MembersGetInfoItem.id_not_found, for
* IDs (or emails) that cannot be matched to a valid team member.
* @function DropboxTeam#teamMembersGetInfo
* @arg {TeamMembersGetInfoArgs} arg - The request parameters.
* @returns {Promise.<Object, Error.<TeamMembersGetInfoError>>}
*/
routes$1.teamMembersGetInfo = function (arg) {
return this.request('team/members/get_info', arg, 'team', 'api', 'rpc');
};
/**
* Lists members of a team. Permission : Team information.
* @function DropboxTeam#teamMembersList
* @arg {TeamMembersListArg} arg - The request parameters.
* @returns {Promise.<TeamMembersListResult, Error.<TeamMembersListError>>}
*/
routes$1.teamMembersList = function (arg) {
return this.request('team/members/list', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from members/list, use this to paginate
* through all team members. Permission : Team information.
* @function DropboxTeam#teamMembersListContinue
* @arg {TeamMembersListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamMembersListResult, Error.<TeamMembersListContinueError>>}
*/
routes$1.teamMembersListContinue = function (arg) {
return this.request('team/members/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Moves removed member's files to a different member. This endpoint initiates
* an asynchronous job. To obtain the final result of the job, the client should
* periodically poll members/move_former_member_files/job_status/check.
* Permission : Team member management.
* @function DropboxTeam#teamMembersMoveFormerMemberFiles
* @arg {TeamMembersDataTransferArg} arg - The request parameters.
* @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamMembersTransferFormerMembersFilesError>>}
*/
routes$1.teamMembersMoveFormerMemberFiles = function (arg) {
return this.request('team/members/move_former_member_files', arg, 'team', 'api', 'rpc');
};
/**
* Once an async_job_id is returned from members/move_former_member_files , use
* this to poll the status of the asynchronous request. Permission : Team member
* management.
* @function DropboxTeam#teamMembersMoveFormerMemberFilesJobStatusCheck
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<AsyncPollEmptyResult, Error.<AsyncPollError>>}
*/
routes$1.teamMembersMoveFormerMemberFilesJobStatusCheck = function (arg) {
return this.request('team/members/move_former_member_files/job_status/check', arg, 'team', 'api', 'rpc');
};
/**
* Recover a deleted member. Permission : Team member management Exactly one of
* team_member_id, email, or external_id must be provided to identify the user
* account.
* @function DropboxTeam#teamMembersRecover
* @arg {TeamMembersRecoverArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamMembersRecoverError>>}
*/
routes$1.teamMembersRecover = function (arg) {
return this.request('team/members/recover', arg, 'team', 'api', 'rpc');
};
/**
* Removes a member from a team. Permission : Team member management Exactly one
* of team_member_id, email, or external_id must be provided to identify the
* user account. Accounts can be recovered via members/recover for a 7 day
* period or until the account has been permanently deleted or transferred to
* another account (whichever comes first). Calling members/add while a user is
* still recoverable on your team will return with
* MemberAddResult.user_already_on_team. Accounts can have their files
* transferred via the admin console for a limited time, based on the version
* history length associated with the team (180 days for most teams). This
* endpoint may initiate an asynchronous job. To obtain the final result of the
* job, the client should periodically poll members/remove/job_status/get.
* @function DropboxTeam#teamMembersRemove
* @arg {TeamMembersRemoveArg} arg - The request parameters.
* @returns {Promise.<AsyncLaunchEmptyResult, Error.<TeamMembersRemoveError>>}
*/
routes$1.teamMembersRemove = function (arg) {
return this.request('team/members/remove', arg, 'team', 'api', 'rpc');
};
/**
* Once an async_job_id is returned from members/remove , use this to poll the
* status of the asynchronous request. Permission : Team member management.
* @function DropboxTeam#teamMembersRemoveJobStatusGet
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<AsyncPollEmptyResult, Error.<AsyncPollError>>}
*/
routes$1.teamMembersRemoveJobStatusGet = function (arg) {
return this.request('team/members/remove/job_status/get', arg, 'team', 'api', 'rpc');
};
/**
* Add secondary emails to users. Permission : Team member management. Emails
* that are on verified domains will be verified automatically. For each email
* address not on a verified domain a verification email will be sent.
* @function DropboxTeam#teamMembersSecondaryEmailsAdd
* @arg {TeamAddSecondaryEmailsArg} arg - The request parameters.
* @returns {Promise.<TeamAddSecondaryEmailsResult, Error.<TeamAddSecondaryEmailsError>>}
*/
routes$1.teamMembersSecondaryEmailsAdd = function (arg) {
return this.request('team/members/secondary_emails/add', arg, 'team', 'api', 'rpc');
};
/**
* Delete secondary emails from users Permission : Team member management. Users
* will be notified of deletions of verified secondary emails at both the
* secondary email and their primary email.
* @function DropboxTeam#teamMembersSecondaryEmailsDelete
* @arg {TeamDeleteSecondaryEmailsArg} arg - The request parameters.
* @returns {Promise.<TeamDeleteSecondaryEmailsResult, Error.<void>>}
*/
routes$1.teamMembersSecondaryEmailsDelete = function (arg) {
return this.request('team/members/secondary_emails/delete', arg, 'team', 'api', 'rpc');
};
/**
* Resend secondary email verification emails. Permission : Team member
* management.
* @function DropboxTeam#teamMembersSecondaryEmailsResendVerificationEmails
* @arg {TeamResendVerificationEmailArg} arg - The request parameters.
* @returns {Promise.<TeamResendVerificationEmailResult, Error.<void>>}
*/
routes$1.teamMembersSecondaryEmailsResendVerificationEmails = function (arg) {
return this.request('team/members/secondary_emails/resend_verification_emails', arg, 'team', 'api', 'rpc');
};
/**
* Sends welcome email to pending team member. Permission : Team member
* management Exactly one of team_member_id, email, or external_id must be
* provided to identify the user account. No-op if team member is not pending.
* @function DropboxTeam#teamMembersSendWelcomeEmail
* @arg {TeamUserSelectorArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamMembersSendWelcomeError>>}
*/
routes$1.teamMembersSendWelcomeEmail = function (arg) {
return this.request('team/members/send_welcome_email', arg, 'team', 'api', 'rpc');
};
/**
* Updates a team member's permissions. Permission : Team member management.
* @function DropboxTeam#teamMembersSetAdminPermissions
* @arg {TeamMembersSetPermissionsArg} arg - The request parameters.
* @returns {Promise.<TeamMembersSetPermissionsResult, Error.<TeamMembersSetPermissionsError>>}
*/
routes$1.teamMembersSetAdminPermissions = function (arg) {
return this.request('team/members/set_admin_permissions', arg, 'team', 'api', 'rpc');
};
/**
* Updates a team member's profile. Permission : Team member management.
* @function DropboxTeam#teamMembersSetProfile
* @arg {TeamMembersSetProfileArg} arg - The request parameters.
* @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersSetProfileError>>}
*/
routes$1.teamMembersSetProfile = function (arg) {
return this.request('team/members/set_profile', arg, 'team', 'api', 'rpc');
};
/**
* Updates a team member's profile photo. Permission : Team member management.
* @function DropboxTeam#teamMembersSetProfilePhoto
* @arg {TeamMembersSetProfilePhotoArg} arg - The request parameters.
* @returns {Promise.<TeamTeamMemberInfo, Error.<TeamMembersSetProfilePhotoError>>}
*/
routes$1.teamMembersSetProfilePhoto = function (arg) {
return this.request('team/members/set_profile_photo', arg, 'team', 'api', 'rpc');
};
/**
* Suspend a member from a team. Permission : Team member management Exactly one
* of team_member_id, email, or external_id must be provided to identify the
* user account.
* @function DropboxTeam#teamMembersSuspend
* @arg {TeamMembersDeactivateArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamMembersSuspendError>>}
*/
routes$1.teamMembersSuspend = function (arg) {
return this.request('team/members/suspend', arg, 'team', 'api', 'rpc');
};
/**
* Unsuspend a member from a team. Permission : Team member management Exactly
* one of team_member_id, email, or external_id must be provided to identify the
* user account.
* @function DropboxTeam#teamMembersUnsuspend
* @arg {TeamMembersUnsuspendArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamMembersUnsuspendError>>}
*/
routes$1.teamMembersUnsuspend = function (arg) {
return this.request('team/members/unsuspend', arg, 'team', 'api', 'rpc');
};
/**
* Returns a list of all team-accessible namespaces. This list includes team
* folders, shared folders containing team members, team members' home
* namespaces, and team members' app folders. Home namespaces and app folders
* are always owned by this team or members of the team, but shared folders may
* be owned by other users or other teams. Duplicates may occur in the list.
* @function DropboxTeam#teamNamespacesList
* @arg {TeamTeamNamespacesListArg} arg - The request parameters.
* @returns {Promise.<TeamTeamNamespacesListResult, Error.<TeamTeamNamespacesListError>>}
*/
routes$1.teamNamespacesList = function (arg) {
return this.request('team/namespaces/list', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from namespaces/list, use this to paginate
* through all team-accessible namespaces. Duplicates may occur in the list.
* @function DropboxTeam#teamNamespacesListContinue
* @arg {TeamTeamNamespacesListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamTeamNamespacesListResult, Error.<TeamTeamNamespacesListContinueError>>}
*/
routes$1.teamNamespacesListContinue = function (arg) {
return this.request('team/namespaces/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Permission : Team member file access.
* @function DropboxTeam#teamPropertiesTemplateAdd
* @deprecated
* @arg {FilePropertiesAddTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesAddTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes$1.teamPropertiesTemplateAdd = function (arg) {
return this.request('team/properties/template/add', arg, 'team', 'api', 'rpc');
};
/**
* Permission : Team member file access.
* @function DropboxTeam#teamPropertiesTemplateGet
* @deprecated
* @arg {FilePropertiesGetTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesGetTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes$1.teamPropertiesTemplateGet = function (arg) {
return this.request('team/properties/template/get', arg, 'team', 'api', 'rpc');
};
/**
* Permission : Team member file access.
* @function DropboxTeam#teamPropertiesTemplateList
* @deprecated
* @arg {void} arg - The request parameters.
* @returns {Promise.<FilePropertiesListTemplateResult, Error.<FilePropertiesTemplateError>>}
*/
routes$1.teamPropertiesTemplateList = function (arg) {
return this.request('team/properties/template/list', arg, 'team', 'api', 'rpc');
};
/**
* Permission : Team member file access.
* @function DropboxTeam#teamPropertiesTemplateUpdate
* @deprecated
* @arg {FilePropertiesUpdateTemplateArg} arg - The request parameters.
* @returns {Promise.<FilePropertiesUpdateTemplateResult, Error.<FilePropertiesModifyTemplateError>>}
*/
routes$1.teamPropertiesTemplateUpdate = function (arg) {
return this.request('team/properties/template/update', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves reporting data about a team's user activity.
* @function DropboxTeam#teamReportsGetActivity
* @arg {TeamDateRange} arg - The request parameters.
* @returns {Promise.<TeamGetActivityReport, Error.<TeamDateRangeError>>}
*/
routes$1.teamReportsGetActivity = function (arg) {
return this.request('team/reports/get_activity', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves reporting data about a team's linked devices.
* @function DropboxTeam#teamReportsGetDevices
* @arg {TeamDateRange} arg - The request parameters.
* @returns {Promise.<TeamGetDevicesReport, Error.<TeamDateRangeError>>}
*/
routes$1.teamReportsGetDevices = function (arg) {
return this.request('team/reports/get_devices', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves reporting data about a team's membership.
* @function DropboxTeam#teamReportsGetMembership
* @arg {TeamDateRange} arg - The request parameters.
* @returns {Promise.<TeamGetMembershipReport, Error.<TeamDateRangeError>>}
*/
routes$1.teamReportsGetMembership = function (arg) {
return this.request('team/reports/get_membership', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves reporting data about a team's storage usage.
* @function DropboxTeam#teamReportsGetStorage
* @arg {TeamDateRange} arg - The request parameters.
* @returns {Promise.<TeamGetStorageReport, Error.<TeamDateRangeError>>}
*/
routes$1.teamReportsGetStorage = function (arg) {
return this.request('team/reports/get_storage', arg, 'team', 'api', 'rpc');
};
/**
* Sets an archived team folder's status to active. Permission : Team member
* file access.
* @function DropboxTeam#teamTeamFolderActivate
* @arg {TeamTeamFolderIdArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderActivateError>>}
*/
routes$1.teamTeamFolderActivate = function (arg) {
return this.request('team/team_folder/activate', arg, 'team', 'api', 'rpc');
};
/**
* Sets an active team folder's status to archived and removes all folder and
* file members. Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderArchive
* @arg {TeamTeamFolderArchiveArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderArchiveLaunch, Error.<TeamTeamFolderArchiveError>>}
*/
routes$1.teamTeamFolderArchive = function (arg) {
return this.request('team/team_folder/archive', arg, 'team', 'api', 'rpc');
};
/**
* Returns the status of an asynchronous job for archiving a team folder.
* Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderArchiveCheck
* @arg {AsyncPollArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderArchiveJobStatus, Error.<AsyncPollError>>}
*/
routes$1.teamTeamFolderArchiveCheck = function (arg) {
return this.request('team/team_folder/archive/check', arg, 'team', 'api', 'rpc');
};
/**
* Creates a new, active, team folder with no members. Permission : Team member
* file access.
* @function DropboxTeam#teamTeamFolderCreate
* @arg {TeamTeamFolderCreateArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderCreateError>>}
*/
routes$1.teamTeamFolderCreate = function (arg) {
return this.request('team/team_folder/create', arg, 'team', 'api', 'rpc');
};
/**
* Retrieves metadata for team folders. Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderGetInfo
* @arg {TeamTeamFolderIdListArg} arg - The request parameters.
* @returns {Promise.<Array.<TeamTeamFolderGetInfoItem>, Error.<void>>}
*/
routes$1.teamTeamFolderGetInfo = function (arg) {
return this.request('team/team_folder/get_info', arg, 'team', 'api', 'rpc');
};
/**
* Lists all team folders. Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderList
* @arg {TeamTeamFolderListArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderListResult, Error.<TeamTeamFolderListError>>}
*/
routes$1.teamTeamFolderList = function (arg) {
return this.request('team/team_folder/list', arg, 'team', 'api', 'rpc');
};
/**
* Once a cursor has been retrieved from team_folder/list, use this to paginate
* through all team folders. Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderListContinue
* @arg {TeamTeamFolderListContinueArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderListResult, Error.<TeamTeamFolderListContinueError>>}
*/
routes$1.teamTeamFolderListContinue = function (arg) {
return this.request('team/team_folder/list/continue', arg, 'team', 'api', 'rpc');
};
/**
* Permanently deletes an archived team folder. Permission : Team member file
* access.
* @function DropboxTeam#teamTeamFolderPermanentlyDelete
* @arg {TeamTeamFolderIdArg} arg - The request parameters.
* @returns {Promise.<void, Error.<TeamTeamFolderPermanentlyDeleteError>>}
*/
routes$1.teamTeamFolderPermanentlyDelete = function (arg) {
return this.request('team/team_folder/permanently_delete', arg, 'team', 'api', 'rpc');
};
/**
* Changes an active team folder's name. Permission : Team member file access.
* @function DropboxTeam#teamTeamFolderRename
* @arg {TeamTeamFolderRenameArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderRenameError>>}
*/
routes$1.teamTeamFolderRename = function (arg) {
return this.request('team/team_folder/rename', arg, 'team', 'api', 'rpc');
};
/**
* Updates the sync settings on a team folder or its contents. Use of this
* endpoint requires that the team has team selective sync enabled.
* @function DropboxTeam#teamTeamFolderUpdateSyncSettings
* @arg {TeamTeamFolderUpdateSyncSettingsArg} arg - The request parameters.
* @returns {Promise.<TeamTeamFolderMetadata, Error.<TeamTeamFolderUpdateSyncSettingsError>>}
*/
routes$1.teamTeamFolderUpdateSyncSettings = function (arg) {
return this.request('team/team_folder/update_sync_settings', arg, 'team', 'api', 'rpc');
};
/**
* Returns the member profile of the admin who generated the team access token
* used to make the call.
* @function DropboxTeam#teamTokenGetAuthenticatedAdmin
* @arg {void} arg - The request parameters.
* @returns {Promise.<TeamTokenGetAuthenticatedAdminResult, Error.<TeamTokenGetAuthenticatedAdminError>>}
*/
routes$1.teamTokenGetAuthenticatedAdmin = function (arg) {
return this.request('team/token/get_authenticated_admin', arg, 'team', 'api', 'rpc');
};
/**
* @class DropboxTeam
* @extends DropboxBase
* @classdesc The Dropbox SDK class that provides access to team endpoints.
* @arg {Object} options
* @arg {String} [options.accessToken] - An access token for making authenticated
* requests.
* @arg {String} [options.clientId] - The client id for your app. Used to create
* authentication URL.
*/
var DropboxTeam = function (_DropboxBase) {
inherits(DropboxTeam, _DropboxBase);
function DropboxTeam(options) {
classCallCheck(this, DropboxTeam);
var _this = possibleConstructorReturn(this, (DropboxTeam.__proto__ || Object.getPrototypeOf(DropboxTeam)).call(this, options));
Object.assign(_this, routes$1);
return _this;
}
/**
* Returns an instance of Dropbox that can make calls to user api endpoints on
* behalf of the passed user id, using the team access token.
* @arg {String} userId - The user id to use the Dropbox class as
* @returns {Dropbox} An instance of Dropbox used to make calls to user api
* endpoints
*/
createClass(DropboxTeam, [{
key: 'actAsUser',
value: function actAsUser(userId) {
return new Dropbox({
accessToken: this.accessToken,
clientId: this.clientId,
selectUser: userId
});
}
}]);
return DropboxTeam;
}(DropboxBase);
var dropboxTeam = /*#__PURE__*/Object.freeze({
__proto__: null,
DropboxTeam: DropboxTeam
});
var dropbox$1 = ( dropbox && undefined ) || dropbox;
var dropboxTeam$1 = ( dropboxTeam && undefined ) || dropboxTeam;
var src = {
Dropbox: dropbox$1.Dropbox,
DropboxTeam: dropboxTeam$1.DropboxTeam
};
var src_1 = src.Dropbox;
var src_2 = src.DropboxTeam;
exports.Dropbox = src_1;
exports.DropboxTeam = src_2;
exports.default = src;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=Dropbox-sdk.js.map
| cdnjs/cdnjs | ajax/libs/dropbox.js/5.1.0/Dropbox-sdk.js | JavaScript | mit | 236,211 |
/*jshint eqeqeq:false, eqnull:true, devel:true */
/*global jQuery, define */
(function( factory ) {
"use strict";
if ( typeof define === "function" && define.amd ) {
// AMD. Register as an anonymous module.
define([
"jquery",
"./grid.base",
"./grid.common"
], factory );
} else {
// Browser globals
factory( jQuery );
}
}(function( $ ) {
"use strict";
//module begin
var rp_ge = {};
$.jgrid.extend({
editGridRow : function(rowid, p){
var regional = $.jgrid.getRegional(this[0], 'edit'),
currstyle = this[0].p.styleUI,
styles = $.jgrid.styleUI[currstyle].formedit,
commonstyle = $.jgrid.styleUI[currstyle].common;
p = $.extend(true, {
top : 0,
left: 0,
width: '500',
datawidth: 'auto',
height: 'auto',
dataheight: 'auto',
modal: false,
overlay : 30,
drag: true,
resize: true,
url: null,
mtype : "POST",
clearAfterAdd :true,
closeAfterEdit : false,
reloadAfterSubmit : true,
onInitializeForm: null,
beforeInitData: null,
beforeShowForm: null,
afterShowForm: null,
beforeSubmit: null,
afterSubmit: null,
onclickSubmit: null,
afterComplete: null,
onclickPgButtons : null,
afterclickPgButtons: null,
editData : {},
recreateForm : false,
jqModal : true,
closeOnEscape : false,
addedrow : "first",
topinfo : '',
bottominfo: '',
saveicon : [],
closeicon : [],
savekey: [false,13],
navkeys: [false,38,40],
checkOnSubmit : false,
checkOnUpdate : false,
processing : false,
onClose : null,
ajaxEditOptions : {},
serializeEditData : null,
viewPagerButtons : true,
overlayClass : commonstyle.overlay,
removemodal : true,
form: 'edit',
template : null,
focusField : true,
editselected : false,
html5Check : false,
buttons : []
}, regional, p || {});
rp_ge[$(this)[0].p.id] = p;
return this.each(function(){
var $t = this;
if (!$t.grid || !rowid) {return;}
$t.p.savedData = {};
var gID = $t.p.id,
frmgr = "FrmGrid_"+gID, frmtborg = "TblGrid_"+gID, frmtb = "#"+$.jgrid.jqID(frmtborg), frmtb2,
IDs = {themodal:'editmod'+gID,modalhead:'edithd'+gID,modalcontent:'editcnt'+gID, scrollelm : frmgr},
showFrm = true, maxCols = 1, maxRows=0, postdata, diff, frmoper,
templ = typeof rp_ge[$t.p.id].template === "string" && rp_ge[$t.p.id].template.length > 0,
errors =$.jgrid.getRegional(this, 'errors');
rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI';
if($.jgrid.isMobile()) {
rp_ge[$t.p.id].resize = false;
}
if (rowid === "new") {
rowid = "_empty";
frmoper = "add";
p.caption=rp_ge[$t.p.id].addCaption;
} else {
p.caption=rp_ge[$t.p.id].editCaption;
frmoper = "edit";
}
if(!p.recreateForm) {
if( $($t).data("formProp") ) {
$.extend(rp_ge[$(this)[0].p.id], $($t).data("formProp"));
}
}
var closeovrl = true;
if(p.checkOnUpdate && p.jqModal && !p.modal) {
closeovrl = false;
}
function getFormData(){
var a2 ={}, i;
$(frmtb).find(".FormElement").each(function() {
var celm = $(".customelement", this);
if (celm.length) {
var elem = celm[0], nm = $(elem).attr('name');
$.each($t.p.colModel, function(){
if(this.name === nm && this.editoptions && $.jgrid.isFunction(this.editoptions.custom_value)) {
try {
postdata[nm] = this.editoptions.custom_value.call($t, $("#"+$.jgrid.jqID(nm),frmtb),'get');
if (postdata[nm] === undefined) {throw "e1";}
} catch (e) {
if (e==="e1") {$.jgrid.info_dialog(errors.errcap,"function 'custom_value' "+rp_ge[$(this)[0]].p.msg.novalue,rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });}
else {$.jgrid.info_dialog(errors.errcap,e.message,rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });}
}
return true;
}
});
} else {
switch ($(this).get(0).type) {
case "checkbox":
if($(this).is(":checked")) {
postdata[this.name]= $(this).val();
} else {
var ofv = $(this).attr("offval");
postdata[this.name]= ofv;
}
break;
case "select-one":
postdata[this.name]= $(this).val();
break;
case "select-multiple":
postdata[this.name]= $(this).val();
postdata[this.name] = postdata[this.name] ? postdata[this.name].join(",") : "";
break;
case "radio" :
if(a2.hasOwnProperty(this.name)) {
return true;
} else {
a2[this.name] = ($(this).attr("offval") === undefined) ? "off" : $(this).attr("offval");
}
break;
default:
postdata[this.name] = $(this).val();
}
if($t.p.autoencode) {
postdata[this.name] = $.jgrid.htmlEncode(postdata[this.name]);
}
}
});
for(i in a2 ) {
if( a2.hasOwnProperty(i)) {
var val = $('input[name="'+i+'"]:checked',frmtb).val();
postdata[i] = (val !== undefined) ? val : a2[i];
if($t.p.autoencode) {
postdata[i] = $.jgrid.htmlEncode(postdata[i]);
}
}
}
return true;
}
function createData(rowid,obj,tb,maxcols){
var nm, hc,trdata, cnt=0,tmp, dc,elc, retpos=[], ind=false,
tdtmpl = "<td class='CaptionTD'></td><td class='DataTD'></td>", tmpl="", i, ffld; //*2
for (i =1; i<=maxcols;i++) {
tmpl += tdtmpl;
}
if(rowid !== '_empty') {
ind = $(obj).jqGrid("getInd",rowid);
}
$(obj.p.colModel).each( function(i) {
nm = this.name;
// hidden fields are included in the form
if(this.editrules && this.editrules.edithidden === true) {
hc = false;
} else {
hc = this.hidden === true ? true : false;
}
dc = hc ? "style='display:none'" : "";
if ( nm !== 'cb' && nm !== 'subgrid' && this.editable===true && nm !== 'rn') {
if(ind === false) {
tmp = "";
} else {
if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) {
tmp = $("td[role='gridcell']",obj.rows[ind]).eq( i ).text();
} else {
try {
tmp = $.unformat.call(obj, $("td[role='gridcell']",obj.rows[ind]).eq( i ),{rowId:rowid, colModel:this},i);
} catch (_) {
tmp = (this.edittype && this.edittype === "textarea") ? $("td[role='gridcell']",obj.rows[ind]).eq( i ).text() : $("td[role='gridcell']",obj.rows[ind]).eq( i ).html();
}
if(!tmp || tmp === " " || tmp === " " || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';}
}
}
var opt = $.extend({}, this.editoptions || {} ,{id:nm,name:nm, rowId: rowid, oper:'edit', module : 'form', checkUpdate : rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate}),
frmopt = $.extend({}, {elmprefix:'',elmsuffix:'',rowabove:false,rowcontent:''}, this.formoptions || {}),
rp = parseInt(frmopt.rowpos,10) || cnt+1,
cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10);
if(rowid === "_empty" && opt.defaultValue ) {
tmp = $.jgrid.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
}
if(!this.edittype) {
this.edittype = "text";
}
if($t.p.autoencode) {
tmp = $.jgrid.htmlDecode(tmp);
}
elc = $.jgrid.createEl.call($t,this.edittype,opt,tmp,false,$.extend({},$.jgrid.ajaxOptions,obj.p.ajaxSelectOptions || {}));
//if(tmp === "" && this.edittype == "checkbox") {tmp = $(elc).attr("offval");}
//if(tmp === "" && this.edittype == "select") {tmp = $("option:eq(0)",elc).text();}
if(this.edittype === "select") {
tmp = $(elc).val();
if($(elc).get(0).type === 'select-multiple' && tmp) {
tmp = tmp.join(",");
}
}
if(this.edittype === 'checkbox') {
if($(elc).is(":checked")) {
tmp= $(elc).val();
} else {
tmp = $(elc).attr("offval");
}
}
$(elc).addClass("FormElement");
if( $.inArray(this.edittype,
['text','textarea','password','select',
'color', 'date', 'datetime', 'datetime-local','email','month',
'number','range', 'search', 'tel', 'time', 'url','week'] ) > -1) {
$(elc).addClass( styles.inputClass );
}
ffld = true;
if(templ) {
var ftmplfld = $(frm).find("#"+nm);
if(ftmplfld.length){
ftmplfld.replaceWith( elc );
} else {
ffld = false;
}
} else {
//--------------------
trdata = $(tb).find("tr[rowpos="+rp+"]");
if(frmopt.rowabove) {
var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>");
$(tb).append(newdata);
newdata[0].rp = rp;
}
if ( trdata.length===0 ) {
if(maxcols > 1) {
trdata = $("<tr rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm);
} else {
trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","tr_"+nm);
}
$(trdata).append(tmpl);
$(tb).append(trdata);
trdata[0].rp = rp;
}
$("td",trdata[0]).eq( cp-2 ).html("<label for='"+nm+"'>"+ (frmopt.label === undefined ? obj.p.colNames[i]: frmopt.label) + "</label>");
$("td",trdata[0]).eq( cp-1 ).append(frmopt.elmprefix).append(elc).append(frmopt.elmsuffix);
if( maxcols > 1 && hc) {
$("td",trdata[0]).eq( cp-2 ).hide();
$("td",trdata[0]).eq( cp-1 ).hide();
}
//-------------------------
}
if( (rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) && ffld) {
$t.p.savedData[nm] = tmp;
}
if(this.edittype==='custom' && $.jgrid.isFunction(opt.custom_value) ) {
opt.custom_value.call($t, $("#"+nm, frmgr),'set',tmp);
}
$.jgrid.bindEv.call($t, elc, opt);
retpos[cnt] = i;
cnt++;
}
});
if( cnt > 0) {
var idrow;
if(templ) {
idrow = "<div class='FormData' style='display:none'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/>";
$(frm).append(idrow);
} else {
idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+obj.p.id+"_id' value='"+rowid+"'/></td></tr>");
idrow[0].rp = cnt+999;
$(tb).append(idrow);
}
//$(tb).append(idrow);
if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
$t.p.savedData[obj.p.id+"_id"] = rowid;
}
}
return retpos;
}
function fillData(rowid,obj,fmid){
var nm,cnt=0,tmp, fld,opt,vl,vlc;
if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
$t.p.savedData = {};
$t.p.savedData[obj.p.id+"_id"]=rowid;
}
var cm = obj.p.colModel;
if(rowid === '_empty') {
$(cm).each(function(){
nm = this.name;
opt = $.extend({}, this.editoptions || {} );
fld = $("#"+$.jgrid.jqID(nm),fmid);
if(fld && fld.length && fld[0] !== null) {
vl = "";
if(this.edittype === 'custom' && $.jgrid.isFunction(opt.custom_value)) {
opt.custom_value.call($t, $("#"+nm,fmid),'set',vl);
} else if(opt.defaultValue ) {
vl = $.jgrid.isFunction(opt.defaultValue) ? opt.defaultValue.call($t) : opt.defaultValue;
if(fld[0].type==='checkbox') {
vlc = vl.toLowerCase();
if(vlc.search(/(false|f|0|no|n|off|undefined)/i)<0 && vlc!=="") {
fld[0].checked = true;
fld[0].defaultChecked = true;
fld[0].value = vl;
} else {
fld[0].checked = false;
fld[0].defaultChecked = false;
}
} else {fld.val(vl);}
} else {
if( fld[0].type==='checkbox' ) {
fld[0].checked = false;
fld[0].defaultChecked = false;
vl = $(fld).attr("offval");
} else if (fld[0].type && fld[0].type.substr(0,6)==='select') {
fld[0].selectedIndex = 0;
} else {
fld.val(vl);
}
}
if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {
$t.p.savedData[nm] = vl;
}
}
});
$("#id_g",fmid).val(rowid);
return;
}
var tre = $(obj).jqGrid("getInd",rowid,true);
if(!tre) {return;}
$('td[role="gridcell"]',tre).each( function(i) {
nm = cm[i].name;
// hidden fields are included in the form
if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && cm[i].editable===true) {
if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) {
tmp = $(this).text();
} else {
try {
tmp = $.unformat.call(obj, $(this),{rowId:rowid, colModel:cm[i]},i);
} catch (_) {
tmp = cm[i].edittype==="textarea" ? $(this).text() : $(this).html();
}
}
if($t.p.autoencode) {tmp = $.jgrid.htmlDecode(tmp);}
if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {
$t.p.savedData[nm] = tmp;
}
nm = $.jgrid.jqID(nm);
switch (cm[i].edittype) {
case "select":
var opv = tmp.split(",");
opv = $.map(opv,function(n){return $.jgrid.trim(n);});
$("#"+nm+" option",fmid).each(function(){
if (!cm[i].editoptions.multiple && ($.jgrid.trim(tmp) === $.jgrid.trim($(this).text()) || opv[0] === $.jgrid.trim($(this).text()) || opv[0] === $.jgrid.trim($(this).val())) ){
this.selected= true;
} else if (cm[i].editoptions.multiple){
if( $.inArray($.jgrid.trim($(this).text()), opv ) > -1 || $.inArray($.jgrid.trim($(this).val()), opv ) > -1 ){
this.selected = true;
}else{
this.selected = false;
}
} else {
this.selected = false;
}
});
if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {
tmp = $("#"+nm,fmid).val();
if(cm[i].editoptions.multiple) {
tmp = tmp.join(",");
}
$t.p.savedData[nm] = tmp;
}
break;
case "checkbox":
tmp = String(tmp);
if(cm[i].editoptions && cm[i].editoptions.value) {
var cb = cm[i].editoptions.value.split(":");
if(cb[0] === tmp) {
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']({"checked":true, "defaultChecked" : true});
} else {
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']({"checked":false, "defaultChecked" : false});
}
} else {
tmp = tmp.toLowerCase();
if(tmp.search(/(false|f|0|no|n|off|undefined)/i)<0 && tmp!=="") {
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("checked",true);
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked",true); //ie
} else {
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("checked", false);
$("#"+nm, fmid)[$t.p.useProp ? 'prop': 'attr']("defaultChecked", false); //ie
}
}
if(rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate) {
if($("#"+nm, fmid).is(":checked")) {
tmp = $("#"+nm, fmid).val();
} else {
tmp = $("#"+nm, fmid).attr("offval");
}
$t.p.savedData[nm] = tmp;
}
break;
case 'custom' :
try {
if(cm[i].editoptions && $.jgrid.isFunction(cm[i].editoptions.custom_value)) {
cm[i].editoptions.custom_value.call($t, $("#"+nm, fmid),'set',tmp);
} else {throw "e1";}
} catch (e) {
if (e==="e1") {$.jgrid.info_dialog(errors.errcap,"function 'custom_value' "+rp_ge[$(this)[0]].p.msg.nodefined,$.rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });}
else {$.jgrid.info_dialog(errors.errcap,e.message,$.rp_ge[$(this)[0]].p.bClose, {styleUI : rp_ge[$(this)[0]].p.styleUI });}
}
break;
default :
if(tmp === " " || tmp === " " || (tmp.length===1 && tmp.charCodeAt(0)===160) ) {tmp='';}
$("#"+nm,fmid).val(tmp);
}
cnt++;
}
});
if(cnt>0) {
$("#id_g",frmtb).val(rowid);
if( rp_ge[$t.p.id].checkOnSubmit===true || rp_ge[$t.p.id].checkOnUpdate ) {
$t.p.savedData[obj.p.id+"_id"] = rowid;
}
}
}
function setNulls() {
$.each($t.p.colModel, function(i,n){
if(n.editoptions && n.editoptions.NullIfEmpty === true) {
if(postdata.hasOwnProperty(n.name) && postdata[n.name] === "") {
postdata[n.name] = 'null';
}
}
});
}
function postIt() {
var copydata, ret=[true,"",""], onCS = {}, opers = $t.p.prmNames, idname, oper, key, selr, i, url;
var retvals = $($t).triggerHandler("jqGridAddEditBeforeCheckValues", [postdata, $(frmgr), frmoper]);
if(retvals && typeof retvals === 'object') {postdata = retvals;}
if($.jgrid.isFunction(rp_ge[$t.p.id].beforeCheckValues)) {
retvals = rp_ge[$t.p.id].beforeCheckValues.call($t, postdata, $(frmgr),frmoper);
if(retvals && typeof retvals === 'object') {postdata = retvals;}
}
if(rp_ge[$t.p.id].html5Check) {
if( !$.jgrid.validateForm(frm[0]) ) {
return false;
}
}
for( key in postdata ){
if(postdata.hasOwnProperty(key)) {
ret = $.jgrid.checkValues.call($t,postdata[key],key);
if(ret[0] === false) {break;}
}
}
setNulls();
if(ret[0]) {
onCS = $($t).triggerHandler("jqGridAddEditClickSubmit", [rp_ge[$t.p.id], postdata, frmoper]);
if( onCS === undefined && $.jgrid.isFunction( rp_ge[$t.p.id].onclickSubmit)) {
onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata, frmoper) || {};
}
ret = $($t).triggerHandler("jqGridAddEditBeforeSubmit", [postdata, $(frmgr), frmoper]);
if(ret === undefined) {
ret = [true,"",""];
}
if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].beforeSubmit)) {
ret = rp_ge[$t.p.id].beforeSubmit.call($t,postdata,$(frmgr), frmoper);
}
}
if(ret[0] && !rp_ge[$t.p.id].processing) {
rp_ge[$t.p.id].processing = true;
$("#sData", frmtb+"_2").addClass( commonstyle.active );
url = rp_ge[$t.p.id].url || $($t).jqGrid('getGridParam','editurl');
oper = opers.oper;
idname = url === 'clientArray' ? $t.p.keyName : opers.id;
// we add to pos data array the action - the name is oper
postdata[oper] = ($.jgrid.trim(postdata[$t.p.id+"_id"]) === "_empty") ? opers.addoper : opers.editoper;
if(postdata[oper] !== opers.addoper) {
postdata[idname] = postdata[$t.p.id+"_id"];
} else {
// check to see if we have allredy this field in the form and if yes lieve it
if( postdata[idname] === undefined ) {postdata[idname] = postdata[$t.p.id+"_id"];}
}
delete postdata[$t.p.id+"_id"];
postdata = $.extend(postdata,rp_ge[$t.p.id].editData,onCS);
if($t.p.treeGrid === true) {
if(postdata[oper] === opers.addoper) {
selr = $($t).jqGrid("getGridParam", 'selrow');
var tr_par_id = $t.p.treeGridModel === 'adjacency' ? $t.p.treeReader.parent_id_field : 'parent_id';
postdata[tr_par_id] = selr;
}
for(i in $t.p.treeReader){
if($t.p.treeReader.hasOwnProperty(i)) {
var itm = $t.p.treeReader[i];
if(postdata.hasOwnProperty(itm)) {
if(postdata[oper] === opers.addoper && i === 'parent_id_field') {continue;}
delete postdata[itm];
}
}
}
}
postdata[idname] = $.jgrid.stripPref($t.p.idPrefix, postdata[idname]);
var ajaxOptions = $.extend({
url: url,
type: rp_ge[$t.p.id].mtype,
data: $.jgrid.isFunction(rp_ge[$t.p.id].serializeEditData) ? rp_ge[$t.p.id].serializeEditData.call($t,postdata) : postdata,
complete:function(data,status){
var key;
$("#sData", frmtb+"_2").removeClass( commonstyle.active );
postdata[idname] = $t.p.idPrefix + postdata[idname];
if(data.status >= 300 && data.status !== 304) {
ret[0] = false;
ret[1] = $($t).triggerHandler("jqGridAddEditErrorTextFormat", [data, frmoper]);
if ($.jgrid.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data, frmoper);
} else {
ret[1] = status + " Status: '" + data.statusText + "'. Error code: " + data.status;
}
} else {
// data is posted successful
// execute aftersubmit with the returned data from server
ret = $($t).triggerHandler("jqGridAddEditAfterSubmit", [data, postdata, frmoper]);
if(ret === undefined) {
ret = [true,"",""];
}
if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].afterSubmit) ) {
ret = rp_ge[$t.p.id].afterSubmit.call($t, data,postdata, frmoper);
}
}
if(ret[0] === false) {
$(".FormError",frmgr).html(ret[1]);
$(".FormError",frmgr).show();
} else {
if($t.p.autoencode) {
$.each(postdata,function(n,v){
postdata[n] = $.jgrid.htmlDecode(v);
});
}
//rp_ge[$t.p.id].reloadAfterSubmit = rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype != "local";
// the action is add
if(postdata[oper] === opers.addoper ) {
//id processing
// user not set the id ret[2]
if(!ret[2]) {ret[2] = $.jgrid.randId();}
if(postdata[idname] == null || postdata[idname] === ($t.p.idPrefix + "_empty") || postdata[idname] === ""){
postdata[idname] = ret[2];
} else {
ret[2] = postdata[idname];
}
if(rp_ge[$t.p.id].reloadAfterSubmit) {
$($t).trigger("reloadGrid");
} else {
if($t.p.treeGrid === true){
$($t).jqGrid("addChildNode",ret[2],selr,postdata );
} else {
$($t).jqGrid("addRowData",ret[2],postdata,p.addedrow);
}
}
if(rp_ge[$t.p.id].closeAfterAdd) {
if($t.p.treeGrid !== true){
$($t).jqGrid("setSelection",ret[2]);
}
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
} else if (rp_ge[$t.p.id].clearAfterAdd) {
fillData("_empty", $t, frmgr);
}
} else {
// the action is update
if(rp_ge[$t.p.id].reloadAfterSubmit) {
$($t).trigger("reloadGrid");
if( !rp_ge[$t.p.id].closeAfterEdit ) {setTimeout(function(){$($t).jqGrid("setSelection",postdata[idname]);},1000);}
} else {
if($t.p.treeGrid === true) {
$($t).jqGrid("setTreeRow", postdata[idname],postdata);
} else {
$($t).jqGrid("setRowData", postdata[idname],postdata);
}
}
if(rp_ge[$t.p.id].closeAfterEdit) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});}
}
if( $.jgrid.isFunction(rp_ge[$t.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data( $($t)[0], 'events' ), 'jqGridAddEditAfterComplete') ) {
copydata = data;
setTimeout(function(){
$($t).triggerHandler("jqGridAddEditAfterComplete", [copydata, postdata, $(frmgr), frmoper]);
try {
rp_ge[$t.p.id].afterComplete.call($t, copydata, postdata, $(frmgr), frmoper);
} catch(excacmp) {
//do nothing
}
copydata=null;
},500);
}
if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
$(frmgr).data("disabled",false);
if($t.p.savedData[$t.p.id+"_id"] !== "_empty"){
for(key in $t.p.savedData) {
if($t.p.savedData.hasOwnProperty(key) && postdata[key]) {
$t.p.savedData[key] = postdata[key];
}
}
}
}
}
rp_ge[$t.p.id].processing=false;
try{$(':input:visible',frmgr)[0].focus();} catch (e){}
}
}, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxEditOptions );
if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
if ($.jgrid.isFunction($t.p.dataProxy)) {
rp_ge[$t.p.id].useDataProxy = true;
} else {
ret[0]=false;ret[1] += " "+errors.nourl;
}
}
if (ret[0]) {
if (rp_ge[$t.p.id].useDataProxy) {
var dpret = $t.p.dataProxy.call($t, ajaxOptions, "set_"+$t.p.id);
if(dpret === undefined) {
dpret = [true, ""];
}
if(dpret[0] === false ) {
ret[0] = false;
ret[1] = dpret[1] || "Error deleting the selected row!" ;
} else {
if(ajaxOptions.data.oper === opers.addoper && rp_ge[$t.p.id].closeAfterAdd ) {
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
}
if(ajaxOptions.data.oper === opers.editoper && rp_ge[$t.p.id].closeAfterEdit ) {
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
}
}
} else {
if(ajaxOptions.url === "clientArray") {
rp_ge[$t.p.id].reloadAfterSubmit = false;
postdata = ajaxOptions.data;
ajaxOptions.complete({status:200, statusText:''},'');
} else {
$.ajax(ajaxOptions);
}
}
}
}
if(ret[0] === false) {
$(".FormError",frmgr).html(ret[1]);
$(".FormError",frmgr).show();
// return;
}
}
function compareData(nObj, oObj ) {
var ret = false,key;
ret = !( $.isPlainObject(nObj) && $.isPlainObject(oObj) && Object.getOwnPropertyNames(nObj).length === Object.getOwnPropertyNames(oObj).length);
if(!ret) {
for (key in oObj) {
if(oObj.hasOwnProperty(key) ) {
if(nObj.hasOwnProperty(key) ) {
if( nObj[key] !== oObj[key] ) {
ret = true;
break;
}
} else {
ret = true;
break;
}
}
}
}
return ret;
}
function checkUpdates () {
var stat = true;
$(".FormError",frmgr).hide();
if(rp_ge[$t.p.id].checkOnUpdate) {
postdata = {};
getFormData();
diff = compareData(postdata, $t.p.savedData);
if(diff) {
$(frmgr).data("disabled",true);
$(".confirm","#"+IDs.themodal).show();
stat = false;
}
}
return stat;
}
function restoreInline() {
var i;
if (rowid !== "_empty" && $t.p.savedRow !== undefined && $t.p.savedRow.length > 0 && $.jgrid.isFunction($.fn.jqGrid.restoreRow)) {
for (i=0;i<$t.p.savedRow.length;i++) {
if ($t.p.savedRow[i].id === rowid) {
$($t).jqGrid('restoreRow',rowid);
break;
}
}
}
}
function updateNav(cr, posarr){
var totr = posarr[1].length-1;
if (cr===0) {
$("#pData",frmtb2).addClass( commonstyle.disabled );
} else if( posarr[1][cr-1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr-1])).hasClass( commonstyle.disabled )) {
$("#pData",frmtb2).addClass( commonstyle.disabled );
} else {
$("#pData",frmtb2).removeClass( commonstyle.disabled );
}
if (cr===totr) {
$("#nData",frmtb2).addClass( commonstyle.disabled );
} else if( posarr[1][cr+1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr+1])).hasClass( commonstyle.disabled )) {
$("#nData",frmtb2).addClass( commonstyle.disabled );
} else {
$("#nData",frmtb2).removeClass( commonstyle.disabled );
}
}
function getCurrPos() {
var rowsInGrid = $($t).jqGrid("getDataIDs"),
selrow = $("#id_g",frmtb).val(), pos;
if($t.p.multiselect && rp_ge[$t.p.id].editselected) {
var arr = [];
for(var i=0, len = rowsInGrid.length;i<len;i++) {
if($.inArray(rowsInGrid[i],$t.p.selarrrow) !== -1) {
arr.push(rowsInGrid[i]);
}
}
pos = $.inArray(selrow,arr);
return [pos, arr];
} else {
pos = $.inArray(selrow,rowsInGrid);
}
return [pos,rowsInGrid];
}
function parseTemplate ( template ){
var tmpl ="";
if(typeof template === "string") {
tmpl = template.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?\}/g, function(m,i){
return '<span id="'+ i+ '" ></span>';
});
}
return tmpl;
}
function syncSavedData () {
if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
var a1=[], a2={};
a1 = $.map($t.p.savedData, function(v, i){
return i;
});
$(".FormElement", frm ).each(function(){
if( $.jgrid.trim(this.name) !== "" && a1.indexOf(this.name) === -1 ) {
var tv = $(this).val(), tt = $(this).get(0).type;
if( tt === 'checkbox') {
if(!$(this).is(":checked")) {
tv = $(this).attr("offval");
}
} else if(tt === 'select-multiple') {
tv = tv.join(",");
} else if(tt === 'radio') {
if(a2.hasOwnProperty(this.name)) {
return true;
} else {
a2[this.name] = ($(this).attr("offval") === undefined) ? "off" : $(this).attr("offval");
}
}
$t.p.savedData[this.name] = tv;
}
});
for(var i in a2 ) {
if( a2.hasOwnProperty(i)) {
var val = $('input[name="'+i+'"]:checked',frm).val();
$t.p.savedData[i] = (val !== undefined) ? val : a2[i];
}
}
}
}
var dh = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight+"px",
dw = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth+"px",
frm = $("<form name='FormPost' id='"+frmgr+"' class='FormGrid' onSubmit='return false;' style='width:"+dw+";height:"+dh+";'></form>").data("disabled",false),
tbl;
if(templ) {
tbl = parseTemplate( rp_ge[$(this)[0].p.id].template );
frmtb2 = frmtb;
} else {
tbl = $("<table id='"+frmtborg+"' class='EditTable ui-common-table'><tbody></tbody></table>");
frmtb2 = frmtb+"_2";
}
frmgr = "#"+ $.jgrid.jqID(frmgr);
// errors
$(frm).append("<div class='FormError " + commonstyle.error + "' style='display:none;'></div>" );
// topinfo
$(frm).append("<div class='tinfo topinfo'>"+rp_ge[$t.p.id].topinfo+"</div>");
$($t.p.colModel).each( function() {
var fmto = this.formoptions;
maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 );
maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 );
});
$(frm).append(tbl);
showFrm = $($t).triggerHandler("jqGridAddEditBeforeInitData", [frm, frmoper]);
if(showFrm === undefined) {
showFrm = true;
}
if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) {
showFrm = rp_ge[$t.p.id].beforeInitData.call($t,frm, frmoper);
}
if(showFrm === false) {return;}
restoreInline();
// set the id.
// use carefull only to change here colproperties.
// create data
createData(rowid,$t,tbl,maxCols);
// buttons at footer
var rtlb = $t.p.direction === "rtl" ? true :false,
bp = rtlb ? "nData" : "pData",
bn = rtlb ? "pData" : "nData";
var bP = "<a id='"+bp+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_prev+ "'></span></a>",
bN = "<a id='"+bn+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_next+ "'></span></a>",
bS ="<a id='sData' class='fm-button " + commonstyle.button + "'>"+p.bSubmit+"</a>",
bC ="<a id='cData' class='fm-button " + commonstyle.button + "'>"+p.bCancel+"</a>",
user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bS + bC, commonstyle ) : bS + bC );
var bt = "<table style='height:auto' class='EditTable ui-common-table' id='"+frmtborg+"_2'><tbody><tr><td colspan='2'><hr class='"+commonstyle.content+"' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+ user_buttons +"</td></tr>";
//bt += "<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+rp_ge[$t.p.id].bottominfo+"</td></tr>";
bt += "</tbody></table>";
if(maxRows > 0) {
var sd=[];
$.each($(tbl)[0].rows,function(i,r){
sd[i] = r;
});
sd.sort(function(a,b){
if(a.rp > b.rp) {return 1;}
if(a.rp < b.rp) {return -1;}
return 0;
});
$.each(sd, function(index, row) {
$('tbody',tbl).append(row);
});
}
p.gbox = "#gbox_"+$.jgrid.jqID(gID);
var cle = false;
if(p.closeOnEscape===true){
p.closeOnEscape = false;
cle = true;
}
var tms;
if(templ) {
$(frm).find("#pData").replaceWith( bP );
$(frm).find("#nData").replaceWith( bN );
$(frm).find("#sData").replaceWith( bS );
$(frm).find("#cData").replaceWith( bC );
tms = $("<div id="+frmtborg+"></div>").append(frm);
} else {
tms = $("<div></div>").append(frm).append(bt);
}
$(frm).append("<div class='binfo topinfo bottominfo'>"+rp_ge[$t.p.id].bottominfo+"</div>");
var fs = $('.ui-jqgrid').css('font-size') || '11px';
$.jgrid.createModal(IDs, tms, rp_ge[$(this)[0].p.id], "#gview_"+$.jgrid.jqID($t.p.id), $("#gbox_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size": fs});
if(rtlb) {
$("#pData, #nData",frmtb+"_2").css("float","right");
$(".EditButton",frmtb+"_2").css("text-align","left");
}
if(rp_ge[$t.p.id].topinfo) {$(".tinfo", frmgr).show();}
if(rp_ge[$t.p.id].bottominfo) {$(".binfo",frmgr).show();}
tms = null;bt=null;
$("#"+$.jgrid.jqID(IDs.themodal)).keydown( function( e ) {
var wkey = e.target;
if ($(frmgr).data("disabled")===true ) {return false;}//??
if(rp_ge[$t.p.id].savekey[0] === true && e.which === rp_ge[$t.p.id].savekey[1]) { // save
if(wkey.tagName !== "TEXTAREA") {
$("#sData", frmtb+"_2").trigger("click");
return false;
}
}
if(e.which === 27) {
if(!checkUpdates()) {return false;}
if(cle) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:p.gbox,jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});}
return false;
}
if(rp_ge[$t.p.id].navkeys[0]===true) {
if($("#id_g",frmtb).val() === "_empty") {return true;}
if(e.which === rp_ge[$t.p.id].navkeys[1]){ //up
$("#pData", frmtb2).trigger("click");
return false;
}
if(e.which === rp_ge[$t.p.id].navkeys[2]){ //down
$("#nData", frmtb2).trigger("click");
return false;
}
}
});
if(p.checkOnUpdate) {
$("a.ui-jqdialog-titlebar-close span","#"+$.jgrid.jqID(IDs.themodal)).removeClass("jqmClose");
$("a.ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.themodal)).off("click")
.click(function(){
if(!checkUpdates()) {return false;}
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
return false;
});
}
p.saveicon = $.extend([true,"left", styles.icon_save ],p.saveicon);
p.closeicon = $.extend([true,"left", styles.icon_close ],p.closeicon);
// beforeinitdata after creation of the form
if(p.saveicon[0]===true) {
$("#sData",frmtb2).addClass(p.saveicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
.append("<span class='"+commonstyle.icon_base + " " +p.saveicon[2]+"'></span>");
}
if(p.closeicon[0]===true) {
$("#cData",frmtb2).addClass(p.closeicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
.append("<span class='" + commonstyle.icon_base +" "+p.closeicon[2]+"'></span>");
}
if(rp_ge[$t.p.id].checkOnSubmit || rp_ge[$t.p.id].checkOnUpdate) {
bS ="<a id='sNew' class='fm-button "+commonstyle.button + "' style='z-index:1002'>"+p.bYes+"</a>";
bN ="<a id='nNew' class='fm-button "+commonstyle.button + "' style='z-index:1002;margin-left:5px'>"+p.bNo+"</a>";
bC ="<a id='cNew' class='fm-button "+commonstyle.button + "' style='z-index:1002;margin-left:5px;'>"+p.bExit+"</a>";
var zI = p.zIndex || 999;zI ++;
$("#"+IDs.themodal).append("<div class='"+ p.overlayClass+" jqgrid-overlay confirm' style='z-index:"+zI+";display:none;position:absolute;'> "+"</div><div class='confirm ui-jqconfirm "+commonstyle.content+"' style='z-index:"+(zI+1)+"'>"+p.saveData+"<br/><br/>"+bS+bN+bC+"</div>");
$("#sNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
postIt();
$(frmgr).data("disabled",false);
$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
return false;
});
$("#nNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
$(frmgr).data("disabled",false);
setTimeout(function(){$(":input:visible",frmgr)[0].focus();},0);
return false;
});
$("#cNew","#"+$.jgrid.jqID(IDs.themodal)).click(function(){
$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).hide();
$(frmgr).data("disabled",false);
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
return false;
});
}
// here initform
$($t).triggerHandler("jqGridAddEditInitializeForm", [$(frmgr), frmoper]);
if($.jgrid.isFunction(rp_ge[$t.p.id].onInitializeForm)) { rp_ge[$t.p.id].onInitializeForm.call($t,$(frmgr), frmoper);}
if(rowid==="_empty" || !rp_ge[$t.p.id].viewPagerButtons) {$("#pData,#nData",frmtb2).hide();} else {$("#pData,#nData",frmtb2).show();}
$($t).triggerHandler("jqGridAddEditBeforeShowForm", [$(frmgr), frmoper]);
if($.jgrid.isFunction(rp_ge[$t.p.id].beforeShowForm)) { rp_ge[$t.p.id].beforeShowForm.call($t, $(frmgr), frmoper);}
syncSavedData();
$("#"+$.jgrid.jqID(IDs.themodal)).data("onClose",rp_ge[$t.p.id].onClose);
$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{
gbox:"#gbox_"+$.jgrid.jqID(gID),
jqm:p.jqModal,
overlay: p.overlay,
modal:p.modal,
overlayClass: p.overlayClass,
focusField : p.focusField,
onHide : function(h) {
var fh = $('#editmod'+gID)[0].style.height,
fw = $('#editmod'+gID)[0].style.width,
rtlsup = $("#gbox_"+$.jgrid.jqID(gID)).attr("dir") === "rtl" ? true : false;
if(fh.indexOf("px") > -1 ) {
fh = parseFloat(fh);
}
if(fw.indexOf("px") > -1 ) {
fw = parseFloat(fw);
}
$($t).data("formProp", {
top:parseFloat($(h.w).css("top")),
left : rtlsup ? ( $("#gbox_"+$.jgrid.jqID(gID)).outerWidth() - fw - parseFloat($(h.w).css("left")) + 12 ) : parseFloat($(h.w).css("left")),
width : fw,
height : fh,
dataheight : $(frmgr).height(),
datawidth: $(frmgr).width()
});
h.w.remove();
if(h.o) {h.o.remove();}
}
});
if(!closeovrl) {
$("." + $.jgrid.jqID(p.overlayClass)).click(function(){
if(!checkUpdates()) {return false;}
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
return false;
});
}
$(".fm-button","#"+$.jgrid.jqID(IDs.themodal)).hover(
function(){$(this).addClass( commonstyle.hover );},
function(){$(this).removeClass( commonstyle.hover );}
);
$("#sData", frmtb2).click(function(){
postdata = {};
$(".FormError",frmgr).hide();
// all depend on ret array
//ret[0] - succes
//ret[1] - msg if not succes
//ret[2] - the id that will be set if reload after submit false
getFormData();
if(postdata[$t.p.id+"_id"] === "_empty") {
postIt();
} else if(p.checkOnSubmit===true ) {
diff = compareData(postdata, $t.p.savedData);
if(diff) {
$(frmgr).data("disabled",true);
$(".confirm","#"+$.jgrid.jqID(IDs.themodal)).show();
} else {
postIt();
}
} else {
postIt();
}
return false;
});
$("#cData", frmtb2).click(function(){
if(!checkUpdates()) {return false;}
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal,onClose: rp_ge[$t.p.id].onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
return false;
});
// user buttons bind
$(frmtb2).find("[data-index]").each(function(){
var index = parseInt($(this).attr('data-index'),10);
if(index >=0 ) {
if( p.buttons[index].hasOwnProperty('click')) {
$(this).on('click', function(e) {
p.buttons[index].click.call($t, $(frmgr)[0], rp_ge[$t.p.id], e);
});
}
}
});
$("#nData", frmtb2).click(function(){
if(!checkUpdates()) {return false;}
$(".FormError",frmgr).hide();
var npos = getCurrPos();
npos[0] = parseInt(npos[0],10);
if(npos[0] !== -1 && npos[1][npos[0]+1]) {
$($t).triggerHandler("jqGridAddEditClickPgButtons", ['next',$(frmgr),npos[1][npos[0]]]);
var nposret;
if($.jgrid.isFunction(p.onclickPgButtons)) {
nposret = p.onclickPgButtons.call($t, 'next',$(frmgr),npos[1][npos[0]]);
if( nposret !== undefined && nposret === false ) {return false;}
}
if( $("#"+$.jgrid.jqID(npos[1][npos[0]+1])).hasClass( commonstyle.disabled )) {return false;}
fillData(npos[1][npos[0]+1],$t,frmgr);
if(!($t.p.multiselect && rp_ge[$t.p.id].editselected)) {
$($t).jqGrid("setSelection",npos[1][npos[0]+1]);
}
$($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['next',$(frmgr),npos[1][npos[0]]]);
if($.jgrid.isFunction(p.afterclickPgButtons)) {
p.afterclickPgButtons.call($t, 'next',$(frmgr),npos[1][npos[0]+1]);
}
syncSavedData();
updateNav(npos[0]+1,npos);
}
return false;
});
$("#pData", frmtb2).click(function(){
if(!checkUpdates()) {return false;}
$(".FormError",frmgr).hide();
var ppos = getCurrPos();
if(ppos[0] !== -1 && ppos[1][ppos[0]-1]) {
$($t).triggerHandler("jqGridAddEditClickPgButtons", ['prev',$(frmgr),ppos[1][ppos[0]]]);
var pposret;
if($.jgrid.isFunction(p.onclickPgButtons)) {
pposret = p.onclickPgButtons.call($t, 'prev',$(frmgr),ppos[1][ppos[0]]);
if( pposret !== undefined && pposret === false ) {return false;}
}
if( $("#"+$.jgrid.jqID(ppos[1][ppos[0]-1])).hasClass( commonstyle.disabled )) {return false;}
fillData(ppos[1][ppos[0]-1],$t,frmgr);
if(!($t.p.multiselect && rp_ge[$t.p.id].editselected)) {
$($t).jqGrid("setSelection",ppos[1][ppos[0]-1]);
}
$($t).triggerHandler("jqGridAddEditAfterClickPgButtons", ['prev',$(frmgr),ppos[1][ppos[0]]]);
if($.jgrid.isFunction(p.afterclickPgButtons)) {
p.afterclickPgButtons.call($t, 'prev',$(frmgr),ppos[1][ppos[0]-1]);
}
syncSavedData();
updateNav(ppos[0]-1,ppos);
}
return false;
});
$($t).triggerHandler("jqGridAddEditAfterShowForm", [$(frmgr), frmoper]);
if($.jgrid.isFunction(rp_ge[$t.p.id].afterShowForm)) { rp_ge[$t.p.id].afterShowForm.call($t, $(frmgr), frmoper); }
var posInit =getCurrPos();
updateNav(posInit[0],posInit);
});
},
viewGridRow : function(rowid, p){
var regional = $.jgrid.getRegional(this[0], 'view'),
currstyle = this[0].p.styleUI,
styles = $.jgrid.styleUI[currstyle].formedit,
commonstyle = $.jgrid.styleUI[currstyle].common;
p = $.extend(true, {
top : 0,
left: 0,
width: 500,
datawidth: 'auto',
height: 'auto',
dataheight: 'auto',
modal: false,
overlay: 30,
drag: true,
resize: true,
jqModal: true,
closeOnEscape : false,
labelswidth: 'auto',
closeicon: [],
navkeys: [false,38,40],
onClose: null,
beforeShowForm : null,
beforeInitData : null,
viewPagerButtons : true,
recreateForm : false,
removemodal: true,
form: 'view',
buttons : []
}, regional, p || {});
rp_ge[$(this)[0].p.id] = p;
return this.each(function(){
var $t = this;
if (!$t.grid || !rowid) {return;}
var gID = $t.p.id,
frmgr = "ViewGrid_"+$.jgrid.jqID( gID ), frmtb = "ViewTbl_" + $.jgrid.jqID( gID ),
frmgr_id = "ViewGrid_"+gID, frmtb_id = "ViewTbl_"+gID,
IDs = {themodal:'viewmod'+gID,modalhead:'viewhd'+gID,modalcontent:'viewcnt'+gID, scrollelm : frmgr},
showFrm = true,
maxCols = 1, maxRows=0;
rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI';
if(!p.recreateForm) {
if( $($t).data("viewProp") ) {
$.extend(rp_ge[$(this)[0].p.id], $($t).data("viewProp"));
}
}
function focusaref(){ //Sfari 3 issues
if(rp_ge[$t.p.id].closeOnEscape===true || rp_ge[$t.p.id].navkeys[0]===true) {
setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).attr("tabindex", "-1").focus();},0);
}
}
function createData(rowid,obj,tb,maxcols){
var nm, hc,trdata, cnt=0,tmp, dc, retpos=[], ind=false, i,
tdtmpl = "<td class='CaptionTD form-view-label " + commonstyle.content + "' width='"+p.labelswidth+"'></td><td class='DataTD form-view-data ui-helper-reset " + commonstyle.content +"'></td>", tmpl="",
tdtmpl2 = "<td class='CaptionTD form-view-label " + commonstyle.content +"'></td><td class='DataTD form-view-data " + commonstyle.content +"'></td>",
fmtnum = ['integer','number','currency'],max1 =0, max2=0 ,maxw,setme, viewfld;
for (i=1;i<=maxcols;i++) {
tmpl += i === 1 ? tdtmpl : tdtmpl2;
}
// find max number align rigth with property formatter
$(obj.p.colModel).each( function() {
if(this.editrules && this.editrules.edithidden === true) {
hc = false;
} else {
hc = this.hidden === true ? true : false;
}
if(!hc && this.align==='right') {
if(this.formatter && $.inArray(this.formatter,fmtnum) !== -1 ) {
max1 = Math.max(max1,parseInt(this.width,10));
} else {
max2 = Math.max(max2,parseInt(this.width,10));
}
}
});
maxw = max1 !==0 ? max1 : max2 !==0 ? max2 : 0;
ind = $(obj).jqGrid("getInd",rowid);
$(obj.p.colModel).each( function(i) {
nm = this.name;
setme = false;
// hidden fields are included in the form
if(this.editrules && this.editrules.edithidden === true) {
hc = false;
} else {
hc = this.hidden === true ? true : false;
}
dc = hc ? "style='display:none'" : "";
viewfld = (typeof this.viewable !== 'boolean') ? true : this.viewable;
if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn' && viewfld) {
if(ind === false) {
tmp = "";
} else {
if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) {
tmp = $("td",obj.rows[ind]).eq( i ).text();
} else {
tmp = $("td",obj.rows[ind]).eq( i ).html();
}
}
setme = this.align === 'right' && maxw !==0 ? true : false;
var frmopt = $.extend({},{rowabove:false,rowcontent:''}, this.formoptions || {}),
rp = parseInt(frmopt.rowpos,10) || cnt+1,
cp = parseInt((parseInt(frmopt.colpos,10) || 1)*2,10);
if(frmopt.rowabove) {
var newdata = $("<tr><td class='contentinfo' colspan='"+(maxcols*2)+"'>"+frmopt.rowcontent+"</td></tr>");
$(tb).append(newdata);
newdata[0].rp = rp;
}
trdata = $(tb).find("tr[rowpos="+rp+"]");
if ( trdata.length===0 ) {
trdata = $("<tr "+dc+" rowpos='"+rp+"'></tr>").addClass("FormData").attr("id","trv_"+nm);
$(trdata).append(tmpl);
$(tb).append(trdata);
trdata[0].rp = rp;
}
$("td",trdata[0]).eq( cp-2 ).html('<b>'+ (frmopt.label === undefined ? obj.p.colNames[i]: frmopt.label)+'</b>');
$("td",trdata[0]).eq( cp-1 ).append("<span>"+tmp+"</span>").attr("id","v_"+nm);
if(setme){
$("td",trdata[0]).eq( cp-1 ).find('span').css({ 'text-align':'right',width:maxw+"px" });
}
retpos[cnt] = i;
cnt++;
}
});
if( cnt > 0) {
var idrow = $("<tr class='FormData' style='display:none'><td class='CaptionTD'></td><td colspan='"+ (maxcols*2-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+rowid+"'/></td></tr>");
idrow[0].rp = cnt+99;
$(tb).append(idrow);
}
return retpos;
}
function fillData(rowid,obj){
var nm, hc,cnt=0,tmp,trv;
trv = $(obj).jqGrid("getInd",rowid,true);
if(!trv) {return;}
$('td',trv).each( function(i) {
nm = obj.p.colModel[i].name;
// hidden fields are included in the form
if(obj.p.colModel[i].editrules && obj.p.colModel[i].editrules.edithidden === true) {
hc = false;
} else {
hc = obj.p.colModel[i].hidden === true ? true : false;
}
if ( nm !== 'cb' && nm !== 'subgrid' && nm !== 'rn') {
if(nm === obj.p.ExpandColumn && obj.p.treeGrid === true) {
tmp = $(this).text();
} else {
tmp = $(this).html();
}
nm = $.jgrid.jqID("v_"+nm);
$("#"+nm+" span","#"+frmtb).html(tmp);
if (hc) {$("#"+nm,"#"+frmtb).parents("tr").first().hide();}
cnt++;
}
});
if(cnt>0) {$("#id_g","#"+frmtb).val(rowid);}
}
function updateNav(cr,posarr){
var totr = posarr[1].length-1;
if (cr===0) {
$("#pData","#"+frmtb+"_2").addClass( commonstyle.disabled );
} else if( posarr[1][cr-1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr-1])).hasClass(commonstyle.disabled)) {
$("#pData",frmtb+"_2").addClass( commonstyle.disabled );
} else {
$("#pData","#"+frmtb+"_2").removeClass( commonstyle.disabled );
}
if (cr===totr) {
$("#nData","#"+frmtb+"_2").addClass( commonstyle.disabled );
} else if( posarr[1][cr+1] !== undefined && $("#"+$.jgrid.jqID(posarr[1][cr+1])).hasClass( commonstyle.disabled )) {
$("#nData",frmtb+"_2").addClass( commonstyle.disabled );
} else {
$("#nData","#"+frmtb+"_2").removeClass( commonstyle.disabled );
}
}
function getCurrPos() {
var rowsInGrid = $($t).jqGrid("getDataIDs"),
selrow = $("#id_g","#"+frmtb).val(), pos;
if($t.p.multiselect && rp_ge[$t.p.id].viewselected) {
var arr = [];
for(var i=0, len = rowsInGrid.length;i<len;i++) {
if($.inArray(rowsInGrid[i],$t.p.selarrrow) !== -1) {
arr.push(rowsInGrid[i]);
}
}
pos = $.inArray(selrow,arr);
return [pos, arr];
} else {
pos = $.inArray(selrow,rowsInGrid);
}
return [pos,rowsInGrid];
}
var dh = isNaN(rp_ge[$(this)[0].p.id].dataheight) ? rp_ge[$(this)[0].p.id].dataheight : rp_ge[$(this)[0].p.id].dataheight+"px",
dw = isNaN(rp_ge[$(this)[0].p.id].datawidth) ? rp_ge[$(this)[0].p.id].datawidth : rp_ge[$(this)[0].p.id].datawidth+"px",
frm = $("<form name='FormPost' id='"+frmgr_id+"' class='FormGrid' style='width:"+dw+";height:"+dh+";'></form>"),
tbl =$("<table id='"+frmtb_id+"' class='EditTable ViewTable'><tbody></tbody></table>");
$($t.p.colModel).each( function() {
var fmto = this.formoptions;
maxCols = Math.max(maxCols, fmto ? fmto.colpos || 0 : 0 );
maxRows = Math.max(maxRows, fmto ? fmto.rowpos || 0 : 0 );
});
// set the id.
$(frm).append(tbl);
showFrm = $($t).triggerHandler("jqGridViewRowBeforeInitData", [frm]);
if(showFrm === undefined) {
showFrm = true;
}
if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) {
showFrm = rp_ge[$t.p.id].beforeInitData.call($t, frm);
}
if(showFrm === false) {return;}
createData(rowid, $t, tbl, maxCols);
var rtlb = $t.p.direction === "rtl" ? true :false,
bp = rtlb ? "nData" : "pData",
bn = rtlb ? "pData" : "nData",
// buttons at footer
bP = "<a id='"+bp+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_prev+ "'></span></a>",
bN = "<a id='"+bn+"' class='fm-button " + commonstyle.button + "'><span class='" + commonstyle.icon_base + " " + styles.icon_next+ "'></span></a>",
bC ="<a id='cData' class='fm-button " + commonstyle.button + "'>"+p.bClose+"</a>",
user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bC, commonstyle ) : bC );
if(maxRows > 0) {
var sd=[];
$.each($(tbl)[0].rows,function(i,r){
sd[i] = r;
});
sd.sort(function(a,b){
if(a.rp > b.rp) {return 1;}
if(a.rp < b.rp) {return -1;}
return 0;
});
$.each(sd, function(index, row) {
$('tbody',tbl).append(row);
});
}
p.gbox = "#gbox_"+$.jgrid.jqID(gID);
var bt = $("<div></div>").append(frm).append("<table border='0' class='EditTable' id='"+frmtb+"_2'><tbody><tr id='Act_Buttons'><td class='navButton' width='"+p.labelswidth+"'>"+(rtlb ? bN+bP : bP+bN)+"</td><td class='EditButton'>"+ user_buttons+"</td></tr></tbody></table>"),
fs = $('.ui-jqgrid').css('font-size') || '11px';
$.jgrid.createModal(IDs,bt, rp_ge[$(this)[0].p.id],"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size":fs});
if(rtlb) {
$("#pData, #nData","#"+frmtb+"_2").css("float","right");
$(".EditButton","#"+frmtb+"_2").css("text-align","left");
}
if(!p.viewPagerButtons) {$("#pData, #nData","#"+frmtb+"_2").hide();}
bt = null;
$("#"+IDs.themodal).keydown( function( e ) {
if(e.which === 27) {
if(rp_ge[$t.p.id].closeOnEscape) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:p.gbox,jqm:p.jqModal, onClose: p.onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});}
return false;
}
if(p.navkeys[0]===true) {
if(e.which === p.navkeys[1]){ //up
$("#pData", "#"+frmtb+"_2").trigger("click");
return false;
}
if(e.which === p.navkeys[2]){ //down
$("#nData", "#"+frmtb+"_2").trigger("click");
return false;
}
}
});
p.closeicon = $.extend([true,"left", styles.icon_close ],p.closeicon);
if(p.closeicon[0]===true) {
$("#cData","#"+frmtb+"_2").addClass(p.closeicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
.append("<span class='" + commonstyle.icon_base+ " " +p.closeicon[2]+"'></span>");
}
$($t).triggerHandler("jqGridViewRowBeforeShowForm", [$("#"+frmgr)]);
if($.jgrid.isFunction(p.beforeShowForm)) {p.beforeShowForm.call($t,$("#"+frmgr));}
$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{
gbox:"#gbox_"+$.jgrid.jqID(gID),
jqm:p.jqModal,
overlay: p.overlay,
modal:p.modal,
onHide : function(h) {
var rtlsup = $("#gbox_"+$.jgrid.jqID(gID)).attr("dir") === "rtl" ? true : false,
fw = parseFloat($('#viewmod'+gID)[0].style.width);
$($t).data("viewProp", {
top:parseFloat($(h.w).css("top")),
left : rtlsup ? ( $("#gbox_"+$.jgrid.jqID(gID)).outerWidth() - fw - parseFloat($(h.w).css("left")) + 12 ) : parseFloat($(h.w).css("left")),
width : $(h.w).width(),
height : $(h.w).height(),
dataheight : $("#"+frmgr).height(),
datawidth: $("#"+frmgr).width()
});
h.w.remove();
if(h.o) {h.o.remove();}
}
});
$(".fm-button:not(." + commonstyle.disabled + ")","#"+frmtb+"_2").hover(
function(){$(this).addClass( commonstyle.hover );},
function(){$(this).removeClass( commonstyle.hover );}
);
focusaref();
$("#cData", "#"+frmtb+"_2").click(function(){
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: p.onClose, removemodal: rp_ge[$t.p.id].removemodal, formprop: !rp_ge[$t.p.id].recreateForm, form: rp_ge[$t.p.id].form});
return false;
});
$("#"+frmtb+"_2").find("[data-index]").each(function(){
var index = parseInt($(this).attr('data-index'),10);
if(index >=0 ) {
if( p.buttons[index].hasOwnProperty('click')) {
$(this).on('click', function(e) {
p.buttons[index].click.call($t, $("#"+frmgr_id)[0], rp_ge[$t.p.id], e);
});
}
}
});
$("#nData", "#"+frmtb+"_2").click(function(){
$("#FormError","#"+frmtb).hide();
var npos = getCurrPos();
npos[0] = parseInt(npos[0],10);
if(npos[0] !== -1 && npos[1][npos[0]+1]) {
$($t).triggerHandler("jqGridViewRowClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]]]);
if($.jgrid.isFunction(p.onclickPgButtons)) {
p.onclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]]);
}
fillData(npos[1][npos[0]+1],$t);
if(!($t.p.multiselect && rp_ge[$t.p.id].viewselected)) {
$($t).jqGrid("setSelection",npos[1][npos[0]+1]);
}
$($t).triggerHandler("jqGridViewRowAfterClickPgButtons", ['next',$("#"+frmgr),npos[1][npos[0]+1]]);
if($.jgrid.isFunction(p.afterclickPgButtons)) {
p.afterclickPgButtons.call($t,'next',$("#"+frmgr),npos[1][npos[0]+1]);
}
updateNav(npos[0]+1,npos);
}
focusaref();
return false;
});
$("#pData", "#"+frmtb+"_2").click(function(){
$("#FormError","#"+frmtb).hide();
var ppos = getCurrPos();
if(ppos[0] !== -1 && ppos[1][ppos[0]-1]) {
$($t).triggerHandler("jqGridViewRowClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]]]);
if($.jgrid.isFunction(p.onclickPgButtons)) {
p.onclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]]);
}
fillData(ppos[1][ppos[0]-1],$t);
if(!($t.p.multiselect && rp_ge[$t.p.id].viewselected)) {
$($t).jqGrid("setSelection",ppos[1][ppos[0]-1]);
}
$($t).triggerHandler("jqGridViewRowAfterClickPgButtons", ['prev',$("#"+frmgr),ppos[1][ppos[0]-1]]);
if($.jgrid.isFunction(p.afterclickPgButtons)) {
p.afterclickPgButtons.call($t,'prev',$("#"+frmgr),ppos[1][ppos[0]-1]);
}
updateNav(ppos[0]-1,ppos);
}
focusaref();
return false;
});
var posInit =getCurrPos();
updateNav(posInit[0],posInit);
});
},
delGridRow : function(rowids,p) {
var regional = $.jgrid.getRegional(this[0], 'del'),
currstyle = this[0].p.styleUI,
styles = $.jgrid.styleUI[currstyle].formedit,
commonstyle = $.jgrid.styleUI[currstyle].common;
p = $.extend(true, {
top : 0,
left: 0,
width: 240,
height: 'auto',
dataheight : 'auto',
modal: false,
overlay: 30,
drag: true,
resize: true,
url : '',
mtype : "POST",
reloadAfterSubmit: true,
beforeShowForm: null,
beforeInitData : null,
afterShowForm: null,
beforeSubmit: null,
onclickSubmit: null,
afterSubmit: null,
jqModal : true,
closeOnEscape : false,
delData: {},
delicon : [],
cancelicon : [],
onClose : null,
ajaxDelOptions : {},
processing : false,
serializeDelData : null,
useDataProxy : false
}, regional, p ||{});
rp_ge[$(this)[0].p.id] = p;
return this.each(function(){
var $t = this;
if (!$t.grid ) {return;}
if(!rowids) {return;}
var gID = $t.p.id, onCS = {},
showFrm = true,
dtbl = "DelTbl_"+$.jgrid.jqID(gID),postd, idname, opers, oper,
dtbl_id = "DelTbl_" + gID,
IDs = {themodal:'delmod'+gID,modalhead:'delhd'+gID,modalcontent:'delcnt'+gID, scrollelm: dtbl};
rp_ge[$t.p.id].styleUI = $t.p.styleUI || 'jQueryUI';
if (Array.isArray(rowids)) {rowids = rowids.join();}
if ( $("#"+$.jgrid.jqID(IDs.themodal))[0] !== undefined ) {
showFrm = $($t).triggerHandler("jqGridDelRowBeforeInitData", [$("#"+dtbl)]);
if(showFrm === undefined) {
showFrm = true;
}
if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) {
showFrm = rp_ge[$t.p.id].beforeInitData.call($t, $("#"+dtbl));
}
if(showFrm === false) {return;}
$("#DelData>td","#"+dtbl).text(rowids);
$("#DelError","#"+dtbl).hide();
if( rp_ge[$t.p.id].processing === true) {
rp_ge[$t.p.id].processing=false;
$("#dData", "#"+dtbl).removeClass( commonstyle.active );
}
$($t).triggerHandler("jqGridDelRowBeforeShowForm", [$("#"+dtbl)]);
if($.jgrid.isFunction( rp_ge[$t.p.id].beforeShowForm )) {
rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl));
}
$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal});
$($t).triggerHandler("jqGridDelRowAfterShowForm", [$("#"+dtbl)]);
if($.jgrid.isFunction( rp_ge[$t.p.id].afterShowForm )) {
rp_ge[$t.p.id].afterShowForm.call($t, $("#"+dtbl));
}
} else {
var dh = isNaN(rp_ge[$t.p.id].dataheight) ? rp_ge[$t.p.id].dataheight : rp_ge[$t.p.id].dataheight+"px",
dw = isNaN(p.datawidth) ? p.datawidth : p.datawidth+"px",
tbl = "<div id='"+dtbl_id+"' class='formdata' style='width:"+dw+";overflow:auto;position:relative;height:"+dh+";'>";
tbl += "<table class='DelTable'><tbody>";
// error data
tbl += "<tr id='DelError' style='display:none'><td class='" + commonstyle.error +"'></td></tr>";
tbl += "<tr id='DelData' style='display:none'><td >"+rowids+"</td></tr>";
tbl += "<tr><td class=\"delmsg\" style=\"white-space:pre;\">"+rp_ge[$t.p.id].msg+"</td></tr><tr><td > </td></tr>";
// buttons at footer
tbl += "</tbody></table></div>";
var bS = "<a id='dData' class='fm-button " + commonstyle.button + "'>"+p.bSubmit+"</a>",
bC = "<a id='eData' class='fm-button " + commonstyle.button + "'>"+p.bCancel+"</a>",
user_buttons = ( Array.isArray( rp_ge[$t.p.id].buttons ) ? $.jgrid.buildButtons( rp_ge[$t.p.id].buttons, bS + bC, commonstyle ) : bS + bC ),
fs = $('.ui-jqgrid').css('font-size') || '11px';
tbl += "<table class='EditTable ui-common-table' id='"+dtbl+"_2'><tbody><tr><td><hr class='" + commonstyle.content + "' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton'>"+ user_buttons +"</td></tr></tbody></table>";
p.gbox = "#gbox_"+$.jgrid.jqID(gID);
$.jgrid.createModal(IDs,tbl, rp_ge[$t.p.id] ,"#gview_"+$.jgrid.jqID($t.p.id),$("#gview_"+$.jgrid.jqID($t.p.id))[0], null, {"font-size": fs});
$(".fm-button","#"+dtbl+"_2").hover(
function(){$(this).addClass( commonstyle.hover );},
function(){$(this).removeClass( commonstyle.hover );}
);
p.delicon = $.extend([true,"left", styles.icon_del ],rp_ge[$t.p.id].delicon);
p.cancelicon = $.extend([true,"left", styles.icon_cancel ],rp_ge[$t.p.id].cancelicon);
if(p.delicon[0]===true) {
$("#dData","#"+dtbl+"_2").addClass(p.delicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
.append("<span class='" + commonstyle.icon_base + " " + p.delicon[2]+"'></span>");
}
if(p.cancelicon[0]===true) {
$("#eData","#"+dtbl+"_2").addClass(p.cancelicon[1] === "right" ? 'fm-button-icon-right' : 'fm-button-icon-left')
.append("<span class='" + commonstyle.icon_base + " " + p.cancelicon[2]+"'></span>");
}
$("#dData","#"+dtbl+"_2").click(function(){
var ret=[true,""], pk,
postdata = $("#DelData>td","#"+dtbl).text(); //the pair is name=val1,val2,...
onCS = {};
onCS = $($t).triggerHandler("jqGridDelRowClickSubmit", [rp_ge[$t.p.id], postdata]);
if(onCS === undefined && $.jgrid.isFunction( rp_ge[$t.p.id].onclickSubmit ) ) {
onCS = rp_ge[$t.p.id].onclickSubmit.call($t, rp_ge[$t.p.id], postdata) || {};
}
ret = $($t).triggerHandler("jqGridDelRowBeforeSubmit", [postdata]);
if(ret === undefined) {
ret = [true,"",""];
}
if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].beforeSubmit)) {
ret = rp_ge[$t.p.id].beforeSubmit.call($t, postdata);
}
if(ret[0] && !rp_ge[$t.p.id].processing) {
rp_ge[$t.p.id].processing = true;
opers = $t.p.prmNames;
postd = $.extend({},rp_ge[$t.p.id].delData, onCS);
oper = opers.oper;
postd[oper] = opers.deloper;
idname = opers.id;
postdata = String(postdata).split(",");
if(!postdata.length) { return false; }
for(pk in postdata) {
if(postdata.hasOwnProperty(pk)) {
postdata[pk] = $.jgrid.stripPref($t.p.idPrefix, postdata[pk]);
}
}
postd[idname] = postdata.join();
$(this).addClass( commonstyle.active );
var ajaxOptions = $.extend({
url: rp_ge[$t.p.id].url || $($t).jqGrid('getGridParam','editurl'),
type: rp_ge[$t.p.id].mtype,
data: $.jgrid.isFunction(rp_ge[$t.p.id].serializeDelData) ? rp_ge[$t.p.id].serializeDelData.call($t,postd) : postd,
complete:function(data,status){
var i;
$("#dData", "#"+dtbl+"_2").removeClass( commonstyle.active );
if(data.status >= 300 && data.status !== 304) {
ret[0] = false;
ret[1] = $($t).triggerHandler("jqGridDelRowErrorTextFormat", [data]);
if ($.jgrid.isFunction(rp_ge[$t.p.id].errorTextFormat)) {
ret[1] = rp_ge[$t.p.id].errorTextFormat.call($t, data);
}
if(ret[1] === undefined) {
ret[1] = status + " Status: '" + data.statusText + "'. Error code: " + data.status;
}
} else {
// data is posted successful
// execute aftersubmit with the returned data from server
ret = $($t).triggerHandler("jqGridDelRowAfterSubmit", [data, postd]);
if(ret === undefined) {
ret = [true,"",""];
}
if( ret[0] && $.jgrid.isFunction(rp_ge[$t.p.id].afterSubmit) ) {
ret = rp_ge[$t.p.id].afterSubmit.call($t, data, postd);
}
}
if(ret[0] === false) {
$("#DelError>td","#"+dtbl).html(ret[1]);
$("#DelError","#"+dtbl).show();
} else {
if(rp_ge[$t.p.id].reloadAfterSubmit && $t.p.datatype !== "local") {
$($t).trigger("reloadGrid");
} else {
if($t.p.treeGrid===true){
try {$($t).jqGrid("delTreeNode",$t.p.idPrefix+postdata[0]);} catch(e){}
} else {
for(i=0;i<postdata.length;i++) {
$($t).jqGrid("delRowData",$t.p.idPrefix+ postdata[i]);
}
}
$t.p.selrow = null;
$t.p.selarrrow = [];
}
if($.jgrid.isFunction(rp_ge[$t.p.id].afterComplete) || Object.prototype.hasOwnProperty.call($._data( $($t)[0], 'events' ), 'jqGridDelRowAfterComplete')) {
var copydata = data;
setTimeout(function(){
$($t).triggerHandler("jqGridDelRowAfterComplete", [copydata, postd]);
try {
rp_ge[$t.p.id].afterComplete.call($t, copydata, postd);
} catch(eacg) {
// do nothing
}
},500);
}
}
rp_ge[$t.p.id].processing=false;
if(ret[0]) {$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});}
}
}, $.jgrid.ajaxOptions, rp_ge[$t.p.id].ajaxDelOptions);
if (!ajaxOptions.url && !rp_ge[$t.p.id].useDataProxy) {
if ($.jgrid.isFunction($t.p.dataProxy)) {
rp_ge[$t.p.id].useDataProxy = true;
} else {
ret[0]=false;ret[1] += " "+$.jgrid.getRegional($t, 'errors.nourl');
}
}
if (ret[0]) {
if (rp_ge[$t.p.id].useDataProxy) {
var dpret = $t.p.dataProxy.call($t, ajaxOptions, "del_"+$t.p.id);
if(dpret === undefined) {
dpret = [true, ""];
}
if(dpret[0] === false ) {
ret[0] = false;
ret[1] = dpret[1] || "Error deleting the selected row!" ;
} else {
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:p.jqModal, onClose: rp_ge[$t.p.id].onClose});
}
}
else {
if(ajaxOptions.url === "clientArray") {
postd = ajaxOptions.data;
ajaxOptions.complete({status:200, statusText:''},'');
} else {
$.ajax(ajaxOptions);
}
}
}
}
if(ret[0] === false) {
$("#DelError>td","#"+dtbl).html(ret[1]);
$("#DelError","#"+dtbl).show();
}
return false;
});
$("#eData", "#"+dtbl+"_2").click(function(){
$.jgrid.hideModal("#"+$.jgrid.jqID(IDs.themodal),{gb:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, onClose: rp_ge[$t.p.id].onClose});
return false;
});
$("#"+dtbl+"_2").find("[data-index]").each(function(){
var index = parseInt($(this).attr('data-index'),10);
if(index >=0 ) {
if( p.buttons[index].hasOwnProperty('click')) {
$(this).on('click', function(e) {
p.buttons[index].click.call($t, $("#"+dtbl_id)[0], rp_ge[$t.p.id], e);
});
}
}
});
showFrm = $($t).triggerHandler("jqGridDelRowBeforeInitData", [$("#"+dtbl)]);
if(showFrm === undefined) {
showFrm = true;
}
if(showFrm && $.jgrid.isFunction(rp_ge[$t.p.id].beforeInitData)) {
showFrm = rp_ge[$t.p.id].beforeInitData.call($t, $("#"+dtbl));
}
if(showFrm === false) {return;}
$($t).triggerHandler("jqGridDelRowBeforeShowForm", [$("#"+dtbl)]);
if($.jgrid.isFunction( rp_ge[$t.p.id].beforeShowForm )) {
rp_ge[$t.p.id].beforeShowForm.call($t,$("#"+dtbl));
}
$.jgrid.viewModal("#"+$.jgrid.jqID(IDs.themodal),{gbox:"#gbox_"+$.jgrid.jqID(gID),jqm:rp_ge[$t.p.id].jqModal, overlay: rp_ge[$t.p.id].overlay, modal:rp_ge[$t.p.id].modal});
$($t).triggerHandler("jqGridDelRowAfterShowForm", [$("#"+dtbl)]);
if($.jgrid.isFunction( rp_ge[$t.p.id].afterShowForm )) {
rp_ge[$t.p.id].afterShowForm.call($t,$("#"+dtbl));
}
}
if(rp_ge[$t.p.id].closeOnEscape===true) {
setTimeout(function(){$(".ui-jqdialog-titlebar-close","#"+$.jgrid.jqID(IDs.modalhead)).attr("tabindex","-1").focus();},0);
}
});
},
navGrid : function (elem, p, pEdit, pAdd, pDel, pSearch, pView) {
var regional = $.jgrid.getRegional(this[0], 'nav'),
currstyle = this[0].p.styleUI,
styles = $.jgrid.styleUI[currstyle].navigator,
commonstyle = $.jgrid.styleUI[currstyle].common;
p = $.extend({
edit: true,
editicon: styles.icon_edit_nav,
add: true,
addicon: styles.icon_add_nav,
del: true,
delicon: styles.icon_del_nav,
search: true,
searchicon: styles.icon_search_nav,
refresh: true,
refreshicon: styles.icon_refresh_nav,
refreshstate: 'firstpage',
view: false,
viewicon : styles.icon_view_nav,
position : "left",
closeOnEscape : true,
beforeRefresh : null,
afterRefresh : null,
cloneToTop : false,
alertwidth : 200,
alertheight : 'auto',
alerttop: null,
alertleft: null,
alertzIndex : null,
dropmenu : false,
navButtonText : ''
}, regional, p ||{});
return this.each(function() {
if(this.p.navGrid) {return;}
var alertIDs = {themodal: 'alertmod_' + this.p.id, modalhead: 'alerthd_' + this.p.id,modalcontent: 'alertcnt_' + this.p.id},
$t = this, twd, tdw, o;
if(!$t.grid || typeof elem !== 'string') {return;}
if(!$($t).data('navGrid')) {
$($t).data('navGrid',p);
}
// speedoverhead, but usefull for future
o = $($t).data('navGrid');
if($t.p.force_regional) {
o = $.extend(o, regional);
}
if ($("#"+alertIDs.themodal)[0] === undefined) {
if(!o.alerttop && !o.alertleft) {
var pos=$.jgrid.findPos(this);
pos[0]=Math.round(pos[0]);
pos[1]=Math.round(pos[1]);
o.alertleft = pos[0] + (this.p.width/2)-parseInt(o.alertwidth,10)/2;
o.alerttop = pos[1] + (this.p.height/2)-25;
}
var fs = $('.ui-jqgrid').css('font-size') || '11px';
$.jgrid.createModal(alertIDs,
"<div>"+o.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='jqg_alrt'></span></span>",
{
gbox:"#gbox_"+$.jgrid.jqID($t.p.id),
jqModal:true,
drag:true,
resize:true,
caption:o.alertcap,
top:o.alerttop,
left:o.alertleft,
width:o.alertwidth,
height: o.alertheight,
closeOnEscape:o.closeOnEscape,
zIndex: o.alertzIndex,
styleUI: $t.p.styleUI
},
"#gview_"+$.jgrid.jqID($t.p.id),
$("#gbox_"+$.jgrid.jqID($t.p.id))[0],
true,
{"font-size": fs}
);
}
var clone = 1, i,
onHoverIn = function () {
if (!$(this).hasClass(commonstyle.disabled)) {
$(this).addClass(commonstyle.hover);
}
},
onHoverOut = function () {
$(this).removeClass(commonstyle.hover);
};
if(o.cloneToTop && $t.p.toppager) {clone = 2;}
for(i = 0; i<clone; i++) {
var tbd,
navtbl = $("<table class='ui-pg-table navtable ui-common-table'><tbody><tr></tr></tbody></table>"),
sep = "<td class='ui-pg-button " +commonstyle.disabled + "' style='width:4px;'><span class='ui-separator'></span></td>",
pgid, elemids;
if(i===0) {
pgid = elem;
if(pgid.indexOf("#") === 0 ) {
pgid = pgid.substring(1);
pgid = "#"+ $.jgrid.jqID( pgid );
}
elemids = $t.p.id;
if(pgid === $t.p.toppager) {
elemids += "_top";
clone = 1;
}
} else {
pgid = $t.p.toppager;
elemids = $t.p.id+"_top";
}
if($t.p.direction === "rtl") {
$(navtbl).attr("dir","rtl").css("float","right");
}
pAdd = pAdd || {};
if (o.add) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base +" " +o.addicon+"'></span>"+o.addtext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.addtitle || "",id : pAdd.id || "add_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
$.jgrid.setSelNavIndex( $t, this);
if ($.jgrid.isFunction( o.addfunc )) {
o.addfunc.call($t);
} else {
$($t).jqGrid("editGridRow","new",pAdd);
}
}
return false;
}).hover(onHoverIn, onHoverOut);
tbd = null;
}
pEdit = pEdit || {};
if (o.edit) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.editicon+"'></span>"+o.edittext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.edittitle || "",id: pEdit.id || "edit_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var sr = $t.p.selrow;
if (sr) {
$.jgrid.setSelNavIndex( $t, this);
if($.jgrid.isFunction( o.editfunc ) ) {
o.editfunc.call($t, sr);
} else {
$($t).jqGrid("editGridRow",sr,pEdit);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
return false;
}).hover(onHoverIn, onHoverOut);
tbd = null;
}
pView = pView || {};
if (o.view) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.viewicon+"'></span>"+o.viewtext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.viewtitle || "",id: pView.id || "view_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var sr = $t.p.selrow;
if (sr) {
$.jgrid.setSelNavIndex( $t, this);
if($.jgrid.isFunction( o.viewfunc ) ) {
o.viewfunc.call($t, sr);
} else {
$($t).jqGrid("viewGridRow",sr,pView);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
$("#jqg_alrt").focus();
}
}
return false;
}).hover(onHoverIn, onHoverOut);
tbd = null;
}
pDel = pDel || {};
if (o.del) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.delicon+"'></span>"+o.deltext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.deltitle || "",id: pDel.id || "del_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var dr;
if($t.p.multiselect) {
dr = $t.p.selarrrow;
if(dr.length===0) {dr = null;}
} else {
dr = $t.p.selrow;
}
if(dr){
$.jgrid.setSelNavIndex( $t, this);
if($.jgrid.isFunction( o.delfunc )){
o.delfunc.call($t, dr);
}else{
$($t).jqGrid("delGridRow",dr,pDel);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});$("#jqg_alrt").focus();
}
}
return false;
}).hover(onHoverIn, onHoverOut);
tbd = null;
}
if(o.add || o.edit || o.del || o.view) {$("tr",navtbl).append(sep);}
pSearch = pSearch || {};
if (o.search) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.searchicon+"'></span>"+o.searchtext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.searchtitle || "",id:pSearch.id || "search_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
$.jgrid.setSelNavIndex( $t, this);
if($.jgrid.isFunction( o.searchfunc )) {
o.searchfunc.call($t, pSearch);
} else {
$($t).jqGrid("searchGrid",pSearch);
}
}
return false;
}).hover(onHoverIn, onHoverOut);
if (pSearch.showOnLoad && pSearch.showOnLoad === true) {
$(tbd,navtbl).click();
}
tbd = null;
}
if (o.refresh) {
tbd = $("<td class='ui-pg-button "+commonstyle.cornerall+"'></td>");
$(tbd).append("<div class='ui-pg-div'><span class='"+commonstyle.icon_base+" "+o.refreshicon+"'></span>"+o.refreshtext+"</div>");
$("tr",navtbl).append(tbd);
$(tbd,navtbl)
.attr({"title":o.refreshtitle || "",id: "refresh_"+elemids})
.click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
if($.jgrid.isFunction(o.beforeRefresh)) {o.beforeRefresh.call($t);}
$t.p.search = false;
$t.p.resetsearch = true;
try {
if( o.refreshstate !== 'currentfilter') {
var gID = $t.p.id;
$t.p.postData.filters ="";
try {
$("#fbox_"+$.jgrid.jqID(gID)).jqFilter('resetFilter');
} catch(ef) {}
if($.jgrid.isFunction($t.clearToolbar)) {$t.clearToolbar.call($t,false);}
}
} catch (e) {}
switch (o.refreshstate) {
case 'firstpage':
$($t).trigger("reloadGrid", [{page:1}]);
break;
case 'current':
case 'currentfilter':
$($t).trigger("reloadGrid", [{current:true}]);
break;
}
if($.jgrid.isFunction(o.afterRefresh)) {o.afterRefresh.call($t);}
$.jgrid.setSelNavIndex( $t, this);
}
return false;
}).hover(onHoverIn, onHoverOut);
tbd = null;
}
tdw = $(".ui-jqgrid").css("font-size") || "11px";
$('body').append("<div id='testpg2' class='ui-jqgrid "+$.jgrid.styleUI[currstyle].base.entrieBox+"' style='font-size:"+tdw+";visibility:hidden;' ></div>");
twd = $(navtbl).clone().appendTo("#testpg2").width();
$("#testpg2").remove();
if($t.p._nvtd) {
if(o.dropmenu) {
navtbl = null;
$($t).jqGrid('_buildNavMenu', pgid, elemids, p, pEdit, pAdd, pDel, pSearch, pView );
} else if(twd > $t.p._nvtd[0] ) {
if($t.p.responsive) {
navtbl = null;
$($t).jqGrid('_buildNavMenu', pgid, elemids, p, pEdit, pAdd, pDel, pSearch, pView );
} else {
$(pgid+"_"+o.position,pgid).append(navtbl).width(twd);
}
$t.p._nvtd[0] = twd;
} else {
$(pgid+"_"+o.position,pgid).append(navtbl);
}
$t.p._nvtd[1] = twd;
}
$t.p.navGrid = true;
}
if($t.p.storeNavOptions) {
$t.p.navOptions = o;
$t.p.editOptions = pEdit;
$t.p.addOptions = pAdd;
$t.p.delOptions = pDel;
$t.p.searchOptions = pSearch;
$t.p.viewOptions = pView;
$t.p.navButtons =[];
}
});
},
navButtonAdd : function (elem, p) {
var currstyle = this[0].p.styleUI,
styles = $.jgrid.styleUI[currstyle].navigator;
p = $.extend({
caption : "newButton",
title: '',
buttonicon : styles.icon_newbutton_nav,
onClickButton: null,
position : "last",
cursor : 'pointer',
internal : false
}, p ||{});
return this.each(function() {
if(!this.grid || typeof elem !== 'string') {return;}
if( elem.indexOf("#") === 0 ) {
elem = elem.substring(1);
}
elem = "#" + $.jgrid.jqID(elem);
var findnav = $(".navtable",elem)[0], $t = this,
//getstyle = $.jgrid.getMethod("getStyleUI"),
disabled = $.jgrid.styleUI[currstyle].common.disabled,
hover = $.jgrid.styleUI[currstyle].common.hover,
cornerall = $.jgrid.styleUI[currstyle].common.cornerall,
iconbase = $.jgrid.styleUI[currstyle].common.icon_base;
if ($t.p.storeNavOptions && !p.internal) {
$t.p.navButtons.push([elem,p]);
}
if (findnav) {
if( p.id && $("#"+$.jgrid.jqID(p.id), findnav)[0] !== undefined ) {return;}
var tbd = $("<td></td>");
if(p.buttonicon.toString().toUpperCase() === "NONE") {
$(tbd).addClass('ui-pg-button '+cornerall).append("<div class='ui-pg-div'>"+p.caption+"</div>");
} else {
$(tbd).addClass('ui-pg-button '+cornerall).append("<div class='ui-pg-div'><span class='"+iconbase+" "+p.buttonicon+"'></span>"+p.caption+"</div>");
}
if(p.id) {$(tbd).attr("id",p.id);}
if(p.position==='first'){
if(findnav.rows[0].cells.length ===0 ) {
$("tr",findnav).append(tbd);
} else {
$("tr td",findnav).eq( 0 ).before(tbd);
}
} else {
$("tr",findnav).append(tbd);
}
$(tbd,findnav)
.attr("title",p.title || "")
.click(function(e){
if (!$(this).hasClass(disabled)) {
$.jgrid.setSelNavIndex( $t, this);
if ($.jgrid.isFunction(p.onClickButton) ) {p.onClickButton.call($t,e);}
}
return false;
})
.hover(
function () {
if (!$(this).hasClass(disabled)) {
$(this).addClass(hover);
}
},
function () {$(this).removeClass(hover);}
);
} else {
findnav = $(".dropdownmenu",elem)[0];
if (findnav) {
var id = $(findnav).val(),
eid = p.id || $.jgrid.randId(),
item = $('<li class="ui-menu-item" role="presentation"><a class="'+ cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.caption || p.title)+'</a></li>');
if(id) {
if(p.position === 'first') {
$("#"+id).prepend( item );
} else {
$("#"+id).append( item );
}
$(item).on("click", function(e){
if (!$(this).hasClass(disabled)) {
$("#"+id).hide();
if ($.jgrid.isFunction(p.onClickButton) ) {
p.onClickButton.call($t,e);
}
}
return false;
}).find("a")
.hover(
function () {
if (!$(this).hasClass(disabled)) {
$(this).addClass(hover);
}
},
function () {$(this).removeClass(hover);}
);
}
}
}
});
},
navSeparatorAdd:function (elem,p) {
var currstyle = this[0].p.styleUI,
commonstyle = $.jgrid.styleUI[currstyle].common;
p = $.extend({
sepclass : "ui-separator",
sepcontent: '',
position : "last"
}, p ||{});
return this.each(function() {
if( !this.grid) {return;}
if( typeof elem === "string" && elem.indexOf("#") !== 0) {elem = "#"+$.jgrid.jqID(elem);}
var findnav = $(".navtable",elem)[0], sep, id;
if ( this.p.storeNavOptions ) {
this.p.navButtons.push([elem,p]);
}
if(findnav) {
sep = "<td class='ui-pg-button "+ commonstyle.disabled +"' style='width:4px;'><span class='"+p.sepclass+"'></span>"+p.sepcontent+"</td>";
if (p.position === 'first') {
if (findnav.rows[0].cells.length === 0) {
$("tr", findnav).append(sep);
} else {
$("tr td", findnav).eq( 0 ).before(sep);
}
} else {
$("tr", findnav).append(sep);
}
} else {
findnav = $(".dropdownmenu",elem)[0];
sep = "<li class='ui-menu-item " +commonstyle.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>";
if(findnav) {
id = $(findnav).val();
if(id) {
if(p.position === "first") {
$("#"+id).prepend( sep );
} else {
$("#"+id).append( sep );
}
}
}
}
});
},
_buildNavMenu : function ( elem, elemids, p, pEdit, pAdd, pDel, pSearch, pView ) {
return this.each(function() {
var $t = this,
//actions = ['add','edit', 'del', 'view', 'search','refresh'],
regional = $.jgrid.getRegional($t, 'nav'),
currstyle = $t.p.styleUI,
styles = $.jgrid.styleUI[currstyle].navigator,
classes = $.jgrid.styleUI[currstyle].filter,
commonstyle = $.jgrid.styleUI[currstyle].common,
mid = "form_menu_"+$.jgrid.randId(),
bt = p.navButtonText ? p.navButtonText : regional.selectcaption || 'Actions',
act = "<button class='dropdownmenu "+commonstyle.button+"' value='"+mid+"'>" + bt +"</button>";
$(elem+"_"+p.position, elem).append( act );
var alertIDs = {themodal: 'alertmod_' + this.p.id, modalhead: 'alerthd_' + this.p.id,modalcontent: 'alertcnt_' + this.p.id},
_buildMenu = function() {
var fs = $('.ui-jqgrid').css('font-size') || '11px',
eid, itm,
str = $('<ul id="'+mid+'" class="ui-nav-menu modal-content" role="menu" tabindex="0" style="display:none;font-size:'+fs+'"></ul>');
if( p.add ) {
pAdd = pAdd || {};
eid = pAdd.id || "add_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.addtext || p.addtitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
if ($.jgrid.isFunction( p.addfunc )) {
p.addfunc.call($t);
} else {
$($t).jqGrid("editGridRow","new",pAdd);
}
$(str).hide();
}
return false;
});
$(str).append(itm);
}
if( p.edit ) {
pEdit = pEdit || {};
eid = pEdit.id || "edit_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.edittext || p.edittitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var sr = $t.p.selrow;
if (sr) {
if($.jgrid.isFunction( p.editfunc ) ) {
p.editfunc.call($t, sr);
} else {
$($t).jqGrid("editGridRow",sr,pEdit);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
$("#jqg_alrt").focus();
}
$(str).hide();
}
return false;
});
$(str).append(itm);
}
if( p.view ) {
pView = pView || {};
eid = pView.id || "view_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.viewtext || p.viewtitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var sr = $t.p.selrow;
if (sr) {
if($.jgrid.isFunction( p.editfunc ) ) {
p.viewfunc.call($t, sr);
} else {
$($t).jqGrid("viewGridRow",sr,pView);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});
$("#jqg_alrt").focus();
}
$(str).hide();
}
return false;
});
$(str).append(itm);
}
if( p.del ) {
pDel = pDel || {};
eid = pDel.id || "del_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.deltext || p.deltitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
var dr;
if($t.p.multiselect) {
dr = $t.p.selarrrow;
if(dr.length===0) {dr = null;}
} else {
dr = $t.p.selrow;
}
if(dr){
if($.jgrid.isFunction( p.delfunc )){
p.delfunc.call($t, dr);
}else{
$($t).jqGrid("delGridRow",dr,pDel);
}
} else {
$.jgrid.viewModal("#"+alertIDs.themodal,{gbox:"#gbox_"+$.jgrid.jqID($t.p.id),jqm:true});$("#jqg_alrt").focus();
}
$(str).hide();
}
return false;
});
$(str).append(itm);
}
if(p.add || p.edit || p.del || p.view) {
$(str).append("<li class='ui-menu-item " +commonstyle.disabled + "' style='width:100%' role='presentation'><hr class='ui-separator-li'></li>");
}
if( p.search ) {
pSearch = pSearch || {};
eid = pSearch.id || "search_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.searchtext || p.searchtitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
if($.jgrid.isFunction( p.searchfunc )) {
p.searchfunc.call($t, pSearch);
} else {
$($t).jqGrid("searchGrid",pSearch);
}
$(str).hide();
}
return false;
});
$(str).append(itm);
if (pSearch.showOnLoad && pSearch.showOnLoad === true) {
$( itm ).click();
}
}
if( p.refresh ) {
eid = pSearch.id || "search_"+elemids;
itm = $('<li class="ui-menu-item" role="presentation"><a class="'+ commonstyle.cornerall+' g-menu-item" tabindex="0" role="menuitem" id="'+eid+'">'+(p.refreshtext || p.refreshtitle)+'</a></li>').click(function(){
if (!$(this).hasClass( commonstyle.disabled )) {
if($.jgrid.isFunction(p.beforeRefresh)) {p.beforeRefresh.call($t);}
$t.p.search = false;
$t.p.resetsearch = true;
try {
if( p.refreshstate !== 'currentfilter') {
var gID = $t.p.id;
$t.p.postData.filters ="";
try {
$("#fbox_"+$.jgrid.jqID(gID)).jqFilter('resetFilter');
} catch(ef) {}
if($.jgrid.isFunction($t.clearToolbar)) {$t.clearToolbar.call($t,false);}
}
} catch (e) {}
switch (p.refreshstate) {
case 'firstpage':
$($t).trigger("reloadGrid", [{page:1}]);
break;
case 'current':
case 'currentfilter':
$($t).trigger("reloadGrid", [{current:true}]);
break;
}
if($.jgrid.isFunction(p.afterRefresh)) {p.afterRefresh.call($t);}
$(str).hide();
}
return false;
});
$(str).append(itm);
}
$(str).hide();
$('body').append(str);
$("#"+mid).addClass("ui-menu " + classes.menu_widget);
$("#"+mid+" > li > a").hover(
function(){ $(this).addClass(commonstyle.hover); },
function(){ $(this).removeClass(commonstyle.hover); }
);
};
_buildMenu();
$(".dropdownmenu", elem+"_"+p.position).on("click", function( e ){
var offset = $(this).offset(),
left = ( offset.left ),
top = parseInt( offset.top),
bid =$(this).val();
//if( $("#"+mid)[0] === undefined) {
//_buildMenu();
//}
$("#"+bid).show().css({"top":top - ($("#"+bid).height() +10)+"px", "left":left+"px"});
e.stopPropagation();
});
$("body").on('click', function(e){
if(!$(e.target).hasClass("dropdownmenu")) {
$("#"+mid).hide();
}
});
});
},
GridToForm : function( rowid, formid ) {
return this.each(function(){
var $t = this, i;
if (!$t.grid) {return;}
var rowdata = $($t).jqGrid("getRowData",rowid);
if (rowdata) {
for(i in rowdata) {
if(rowdata.hasOwnProperty(i)) {
if ( $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:radio") || $("[name="+$.jgrid.jqID(i)+"]",formid).is("input:checkbox")) {
$("[name="+$.jgrid.jqID(i)+"]",formid).each( function() {
if( $(this).val() == rowdata[i] ) {
$(this)[$t.p.useProp ? 'prop': 'attr']("checked",true);
} else {
$(this)[$t.p.useProp ? 'prop': 'attr']("checked", false);
}
});
} else {
// this is very slow on big table and form.
$("[name="+$.jgrid.jqID(i)+"]",formid).val(rowdata[i]);
}
}
}
}
});
},
FormToGrid : function(rowid, formid, mode, position){
return this.each(function() {
var $t = this;
if(!$t.grid) {return;}
if(!mode) {mode = 'set';}
if(!position) {position = 'first';}
var fields = $(formid).serializeArray();
var griddata = {};
$.each(fields, function(i, field){
griddata[field.name] = field.value;
});
if(mode==='add') {$($t).jqGrid("addRowData",rowid,griddata, position);}
else if(mode==='set') {$($t).jqGrid("setRowData",rowid,griddata);}
});
}
});
//module end
}));
| cdnjs/cdnjs | ajax/libs/jqgrid/5.5.4/js/grid.formedit.js | JavaScript | mit | 93,444 |
function createBrowserLocalStorageCache(options) {
const namespaceKey = `algoliasearch-client-js-${options.key}`;
// eslint-disable-next-line functional/no-let
let storage;
const getStorage = () => {
if (storage === undefined) {
storage = options.localStorage || window.localStorage;
}
return storage;
};
const getNamespace = () => {
return JSON.parse(getStorage().getItem(namespaceKey) || '{}');
};
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve(),
}) {
return Promise.resolve()
.then(() => {
const keyAsString = JSON.stringify(key);
const value = getNamespace()[keyAsString];
return Promise.all([value || defaultValue(), value !== undefined]);
})
.then(([value, exists]) => {
return Promise.all([value, exists || events.miss(value)]);
})
.then(([value]) => value);
},
set(key, value) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
// eslint-disable-next-line functional/immutable-data
namespace[JSON.stringify(key)] = value;
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
return value;
});
},
delete(key) {
return Promise.resolve().then(() => {
const namespace = getNamespace();
// eslint-disable-next-line functional/immutable-data
delete namespace[JSON.stringify(key)];
getStorage().setItem(namespaceKey, JSON.stringify(namespace));
});
},
clear() {
return Promise.resolve().then(() => {
getStorage().removeItem(namespaceKey);
});
},
};
}
// @todo Add logger on options to debug when caches go wrong.
function createFallbackableCache(options) {
const caches = [...options.caches];
const current = caches.shift(); // eslint-disable-line functional/immutable-data
if (current === undefined) {
return createNullCache();
}
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve(),
}) {
return current.get(key, defaultValue, events).catch(() => {
return createFallbackableCache({ caches }).get(key, defaultValue, events);
});
},
set(key, value) {
return current.set(key, value).catch(() => {
return createFallbackableCache({ caches }).set(key, value);
});
},
delete(key) {
return current.delete(key).catch(() => {
return createFallbackableCache({ caches }).delete(key);
});
},
clear() {
return current.clear().catch(() => {
return createFallbackableCache({ caches }).clear();
});
},
};
}
function createNullCache() {
return {
get(_key, defaultValue, events = {
miss: () => Promise.resolve(),
}) {
const value = defaultValue();
return value
.then(result => Promise.all([result, events.miss(result)]))
.then(([result]) => result);
},
set(_key, value) {
return Promise.resolve(value);
},
delete(_key) {
return Promise.resolve();
},
clear() {
return Promise.resolve();
},
};
}
function createInMemoryCache(options = { serializable: true }) {
// eslint-disable-next-line functional/no-let
let cache = {};
return {
get(key, defaultValue, events = {
miss: () => Promise.resolve(),
}) {
const keyAsString = JSON.stringify(key);
if (keyAsString in cache) {
return Promise.resolve(options.serializable ? JSON.parse(cache[keyAsString]) : cache[keyAsString]);
}
const promise = defaultValue();
const miss = (events && events.miss) || (() => Promise.resolve());
return promise.then((value) => miss(value)).then(() => promise);
},
set(key, value) {
// eslint-disable-next-line functional/immutable-data
cache[JSON.stringify(key)] = options.serializable ? JSON.stringify(value) : value;
return Promise.resolve(value);
},
delete(key) {
// eslint-disable-next-line functional/immutable-data
delete cache[JSON.stringify(key)];
return Promise.resolve();
},
clear() {
cache = {};
return Promise.resolve();
},
};
}
function createAuth(authMode, appId, apiKey) {
const credentials = {
'x-algolia-api-key': apiKey,
'x-algolia-application-id': appId,
};
return {
headers() {
return authMode === AuthMode.WithinHeaders ? credentials : {};
},
queryParameters() {
return authMode === AuthMode.WithinQueryParameters ? credentials : {};
},
};
}
// eslint-disable-next-line functional/prefer-readonly-type
function shuffle(array) {
let c = array.length - 1; // eslint-disable-line functional/no-let
// eslint-disable-next-line functional/no-loop-statement
for (c; c > 0; c--) {
const b = Math.floor(Math.random() * (c + 1));
const a = array[c];
array[c] = array[b]; // eslint-disable-line functional/immutable-data, no-param-reassign
array[b] = a; // eslint-disable-line functional/immutable-data, no-param-reassign
}
return array;
}
function addMethods(base, methods) {
if (!methods) {
return base;
}
Object.keys(methods).forEach(key => {
// eslint-disable-next-line functional/immutable-data, no-param-reassign
base[key] = methods[key](base);
});
return base;
}
function encode(format, ...args) {
// eslint-disable-next-line functional/no-let
let i = 0;
return format.replace(/%s/g, () => encodeURIComponent(args[i++]));
}
const version = '4.12.1';
const AuthMode = {
/**
* If auth credentials should be in query parameters.
*/
WithinQueryParameters: 0,
/**
* If auth credentials should be in headers.
*/
WithinHeaders: 1,
};
function createMappedRequestOptions(requestOptions, timeout) {
const options = requestOptions || {};
const data = options.data || {};
Object.keys(options).forEach(key => {
if (['timeout', 'headers', 'queryParameters', 'data', 'cacheable'].indexOf(key) === -1) {
data[key] = options[key]; // eslint-disable-line functional/immutable-data
}
});
return {
data: Object.entries(data).length > 0 ? data : undefined,
timeout: options.timeout || timeout,
headers: options.headers || {},
queryParameters: options.queryParameters || {},
cacheable: options.cacheable,
};
}
const CallEnum = {
/**
* If the host is read only.
*/
Read: 1,
/**
* If the host is write only.
*/
Write: 2,
/**
* If the host is both read and write.
*/
Any: 3,
};
const HostStatusEnum = {
Up: 1,
Down: 2,
Timeouted: 3,
};
// By default, API Clients at Algolia have expiration delay
// of 5 mins. In the JavaScript client, we have 2 mins.
const EXPIRATION_DELAY = 2 * 60 * 1000;
function createStatefulHost(host, status = HostStatusEnum.Up) {
return {
...host,
status,
lastUpdate: Date.now(),
};
}
function isStatefulHostUp(host) {
return host.status === HostStatusEnum.Up || Date.now() - host.lastUpdate > EXPIRATION_DELAY;
}
function isStatefulHostTimeouted(host) {
return (host.status === HostStatusEnum.Timeouted && Date.now() - host.lastUpdate <= EXPIRATION_DELAY);
}
function createStatelessHost(options) {
if (typeof options === 'string') {
return {
protocol: 'https',
url: options,
accept: CallEnum.Any,
};
}
return {
protocol: options.protocol || 'https',
url: options.url,
accept: options.accept || CallEnum.Any,
};
}
const MethodEnum = {
Delete: 'DELETE',
Get: 'GET',
Post: 'POST',
Put: 'PUT',
};
function createRetryableOptions(hostsCache, statelessHosts) {
return Promise.all(statelessHosts.map(statelessHost => {
return hostsCache.get(statelessHost, () => {
return Promise.resolve(createStatefulHost(statelessHost));
});
})).then(statefulHosts => {
const hostsUp = statefulHosts.filter(host => isStatefulHostUp(host));
const hostsTimeouted = statefulHosts.filter(host => isStatefulHostTimeouted(host));
/**
* Note, we put the hosts that previously timeouted on the end of the list.
*/
const hostsAvailable = [...hostsUp, ...hostsTimeouted];
const statelessHostsAvailable = hostsAvailable.length > 0
? hostsAvailable.map(host => createStatelessHost(host))
: statelessHosts;
return {
getTimeout(timeoutsCount, baseTimeout) {
/**
* Imagine that you have 4 hosts, if timeouts will increase
* on the following way: 1 (timeouted) > 4 (timeouted) > 5 (200)
*
* Note that, the very next request, we start from the previous timeout
*
* 5 (timeouted) > 6 (timeouted) > 7 ...
*
* This strategy may need to be reviewed, but is the strategy on the our
* current v3 version.
*/
const timeoutMultiplier = hostsTimeouted.length === 0 && timeoutsCount === 0
? 1
: hostsTimeouted.length + 3 + timeoutsCount;
return timeoutMultiplier * baseTimeout;
},
statelessHosts: statelessHostsAvailable,
};
});
}
const isNetworkError = ({ isTimedOut, status }) => {
return !isTimedOut && ~~status === 0;
};
const isRetryable = (response) => {
const status = response.status;
const isTimedOut = response.isTimedOut;
return (isTimedOut || isNetworkError(response) || (~~(status / 100) !== 2 && ~~(status / 100) !== 4));
};
const isSuccess = ({ status }) => {
return ~~(status / 100) === 2;
};
const retryDecision = (response, outcomes) => {
if (isRetryable(response)) {
return outcomes.onRetry(response);
}
if (isSuccess(response)) {
return outcomes.onSuccess(response);
}
return outcomes.onFail(response);
};
function retryableRequest(transporter, statelessHosts, request, requestOptions) {
const stackTrace = []; // eslint-disable-line functional/prefer-readonly-type
/**
* First we prepare the payload that do not depend from hosts.
*/
const data = serializeData(request, requestOptions);
const headers = serializeHeaders(transporter, requestOptions);
const method = request.method;
// On `GET`, the data is proxied to query parameters.
const dataQueryParameters = request.method !== MethodEnum.Get
? {}
: {
...request.data,
...requestOptions.data,
};
const queryParameters = {
'x-algolia-agent': transporter.userAgent.value,
...transporter.queryParameters,
...dataQueryParameters,
...requestOptions.queryParameters,
};
let timeoutsCount = 0; // eslint-disable-line functional/no-let
const retry = (hosts, // eslint-disable-line functional/prefer-readonly-type
getTimeout) => {
/**
* We iterate on each host, until there is no host left.
*/
const host = hosts.pop(); // eslint-disable-line functional/immutable-data
if (host === undefined) {
throw createRetryError(stackTraceWithoutCredentials(stackTrace));
}
const payload = {
data,
headers,
method,
url: serializeUrl(host, request.path, queryParameters),
connectTimeout: getTimeout(timeoutsCount, transporter.timeouts.connect),
responseTimeout: getTimeout(timeoutsCount, requestOptions.timeout),
};
/**
* The stackFrame is pushed to the stackTrace so we
* can have information about onRetry and onFailure
* decisions.
*/
const pushToStackTrace = (response) => {
const stackFrame = {
request: payload,
response,
host,
triesLeft: hosts.length,
};
// eslint-disable-next-line functional/immutable-data
stackTrace.push(stackFrame);
return stackFrame;
};
const decisions = {
onSuccess: response => deserializeSuccess(response),
onRetry(response) {
const stackFrame = pushToStackTrace(response);
/**
* If response is a timeout, we increaset the number of
* timeouts so we can increase the timeout later.
*/
if (response.isTimedOut) {
timeoutsCount++;
}
return Promise.all([
/**
* Failures are individually send the logger, allowing
* the end user to debug / store stack frames even
* when a retry error does not happen.
*/
transporter.logger.info('Retryable failure', stackFrameWithoutCredentials(stackFrame)),
/**
* We also store the state of the host in failure cases. If the host, is
* down it will remain down for the next 2 minutes. In a timeout situation,
* this host will be added end of the list of hosts on the next request.
*/
transporter.hostsCache.set(host, createStatefulHost(host, response.isTimedOut ? HostStatusEnum.Timeouted : HostStatusEnum.Down)),
]).then(() => retry(hosts, getTimeout));
},
onFail(response) {
pushToStackTrace(response);
throw deserializeFailure(response, stackTraceWithoutCredentials(stackTrace));
},
};
return transporter.requester.send(payload).then(response => {
return retryDecision(response, decisions);
});
};
/**
* Finally, for each retryable host perform request until we got a non
* retryable response. Some notes here:
*
* 1. The reverse here is applied so we can apply a `pop` later on => more performant.
* 2. We also get from the retryable options a timeout multiplier that is tailored
* for the current context.
*/
return createRetryableOptions(transporter.hostsCache, statelessHosts).then(options => {
return retry([...options.statelessHosts].reverse(), options.getTimeout);
});
}
function createTransporter(options) {
const { hostsCache, logger, requester, requestsCache, responsesCache, timeouts, userAgent, hosts, queryParameters, headers, } = options;
const transporter = {
hostsCache,
logger,
requester,
requestsCache,
responsesCache,
timeouts,
userAgent,
headers,
queryParameters,
hosts: hosts.map(host => createStatelessHost(host)),
read(request, requestOptions) {
/**
* First, we compute the user request options. Now, keep in mind,
* that using request options the user is able to modified the intire
* payload of the request. Such as headers, query parameters, and others.
*/
const mappedRequestOptions = createMappedRequestOptions(requestOptions, transporter.timeouts.read);
const createRetryableRequest = () => {
/**
* Then, we prepare a function factory that contains the construction of
* the retryable request. At this point, we may *not* perform the actual
* request. But we want to have the function factory ready.
*/
return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Read) !== 0), request, mappedRequestOptions);
};
/**
* Once we have the function factory ready, we need to determine of the
* request is "cacheable" - should be cached. Note that, once again,
* the user can force this option.
*/
const cacheable = mappedRequestOptions.cacheable !== undefined
? mappedRequestOptions.cacheable
: request.cacheable;
/**
* If is not "cacheable", we immediatly trigger the retryable request, no
* need to check cache implementations.
*/
if (cacheable !== true) {
return createRetryableRequest();
}
/**
* If the request is "cacheable", we need to first compute the key to ask
* the cache implementations if this request is on progress or if the
* response already exists on the cache.
*/
const key = {
request,
mappedRequestOptions,
transporter: {
queryParameters: transporter.queryParameters,
headers: transporter.headers,
},
};
/**
* With the computed key, we first ask the responses cache
* implemention if this request was been resolved before.
*/
return transporter.responsesCache.get(key, () => {
/**
* If the request has never resolved before, we actually ask if there
* is a current request with the same key on progress.
*/
return transporter.requestsCache.get(key, () => {
return (transporter.requestsCache
/**
* Finally, if there is no request in progress with the same key,
* this `createRetryableRequest()` will actually trigger the
* retryable request.
*/
.set(key, createRetryableRequest())
.then(response => Promise.all([transporter.requestsCache.delete(key), response]), err => Promise.all([transporter.requestsCache.delete(key), Promise.reject(err)]))
.then(([_, response]) => response));
});
}, {
/**
* Of course, once we get this response back from the server, we
* tell response cache to actually store the received response
* to be used later.
*/
miss: response => transporter.responsesCache.set(key, response),
});
},
write(request, requestOptions) {
/**
* On write requests, no cache mechanisms are applied, and we
* proxy the request immediately to the requester.
*/
return retryableRequest(transporter, transporter.hosts.filter(host => (host.accept & CallEnum.Write) !== 0), request, createMappedRequestOptions(requestOptions, transporter.timeouts.write));
},
};
return transporter;
}
function createUserAgent(version) {
const userAgent = {
value: `Algolia for JavaScript (${version})`,
add(options) {
const addedUserAgent = `; ${options.segment}${options.version !== undefined ? ` (${options.version})` : ''}`;
if (userAgent.value.indexOf(addedUserAgent) === -1) {
// eslint-disable-next-line functional/immutable-data
userAgent.value = `${userAgent.value}${addedUserAgent}`;
}
return userAgent;
},
};
return userAgent;
}
function deserializeSuccess(response) {
// eslint-disable-next-line functional/no-try-statement
try {
return JSON.parse(response.content);
}
catch (e) {
throw createDeserializationError(e.message, response);
}
}
function deserializeFailure({ content, status }, stackFrame) {
// eslint-disable-next-line functional/no-let
let message = content;
// eslint-disable-next-line functional/no-try-statement
try {
message = JSON.parse(content).message;
}
catch (e) {
// ..
}
return createApiError(message, status, stackFrame);
}
function serializeUrl(host, path, queryParameters) {
const queryParametersAsString = serializeQueryParameters(queryParameters);
// eslint-disable-next-line functional/no-let
let url = `${host.protocol}://${host.url}/${path.charAt(0) === '/' ? path.substr(1) : path}`;
if (queryParametersAsString.length) {
url += `?${queryParametersAsString}`;
}
return url;
}
function serializeQueryParameters(parameters) {
const isObjectOrArray = (value) => Object.prototype.toString.call(value) === '[object Object]' ||
Object.prototype.toString.call(value) === '[object Array]';
return Object.keys(parameters)
.map(key => encode('%s=%s', key, isObjectOrArray(parameters[key]) ? JSON.stringify(parameters[key]) : parameters[key]))
.join('&');
}
function serializeData(request, requestOptions) {
if (request.method === MethodEnum.Get ||
(request.data === undefined && requestOptions.data === undefined)) {
return undefined;
}
const data = Array.isArray(request.data)
? request.data
: { ...request.data, ...requestOptions.data };
return JSON.stringify(data);
}
function serializeHeaders(transporter, requestOptions) {
const headers = {
...transporter.headers,
...requestOptions.headers,
};
const serializedHeaders = {};
Object.keys(headers).forEach(header => {
const value = headers[header];
// @ts-ignore
// eslint-disable-next-line functional/immutable-data
serializedHeaders[header.toLowerCase()] = value;
});
return serializedHeaders;
}
function stackTraceWithoutCredentials(stackTrace) {
return stackTrace.map(stackFrame => stackFrameWithoutCredentials(stackFrame));
}
function stackFrameWithoutCredentials(stackFrame) {
const modifiedHeaders = stackFrame.request.headers['x-algolia-api-key']
? { 'x-algolia-api-key': '*****' }
: {};
return {
...stackFrame,
request: {
...stackFrame.request,
headers: {
...stackFrame.request.headers,
...modifiedHeaders,
},
},
};
}
function createApiError(message, status, transporterStackTrace) {
return {
name: 'ApiError',
message,
status,
transporterStackTrace,
};
}
function createDeserializationError(message, response) {
return {
name: 'DeserializationError',
message,
response,
};
}
function createRetryError(transporterStackTrace) {
return {
name: 'RetryError',
message: 'Unreachable hosts - your application id may be incorrect. If the error persists, contact [email protected].',
transporterStackTrace,
};
}
const createSearchClient = options => {
const appId = options.appId;
const auth = createAuth(options.authMode !== undefined ? options.authMode : AuthMode.WithinHeaders, appId, options.apiKey);
const transporter = createTransporter({
hosts: [
{ url: `${appId}-dsn.algolia.net`, accept: CallEnum.Read },
{ url: `${appId}.algolia.net`, accept: CallEnum.Write },
].concat(shuffle([
{ url: `${appId}-1.algolianet.com` },
{ url: `${appId}-2.algolianet.com` },
{ url: `${appId}-3.algolianet.com` },
])),
...options,
headers: {
...auth.headers(),
...{ 'content-type': 'application/x-www-form-urlencoded' },
...options.headers,
},
queryParameters: {
...auth.queryParameters(),
...options.queryParameters,
},
});
const base = {
transporter,
appId,
addAlgoliaAgent(segment, version) {
transporter.userAgent.add({ segment, version });
},
clearCache() {
return Promise.all([
transporter.requestsCache.clear(),
transporter.responsesCache.clear(),
]).then(() => undefined);
},
};
return addMethods(base, options.methods);
};
const customRequest = (base) => {
return (request, requestOptions) => {
if (request.method === MethodEnum.Get) {
return base.transporter.read(request, requestOptions);
}
return base.transporter.write(request, requestOptions);
};
};
const initIndex = (base) => {
return (indexName, options = {}) => {
const searchIndex = {
transporter: base.transporter,
appId: base.appId,
indexName,
};
return addMethods(searchIndex, options.methods);
};
};
const multipleQueries = (base) => {
return (queries, requestOptions) => {
const requests = queries.map(query => {
return {
...query,
params: serializeQueryParameters(query.params || {}),
};
});
return base.transporter.read({
method: MethodEnum.Post,
path: '1/indexes/*/queries',
data: {
requests,
},
cacheable: true,
}, requestOptions);
};
};
const multipleSearchForFacetValues = (base) => {
return (queries, requestOptions) => {
return Promise.all(queries.map(query => {
const { facetName, facetQuery, ...params } = query.params;
return initIndex(base)(query.indexName, {
methods: { searchForFacetValues },
}).searchForFacetValues(facetName, facetQuery, {
...requestOptions,
...params,
});
}));
};
};
const findAnswers = (base) => {
return (query, queryLanguages, requestOptions) => {
return base.transporter.read({
method: MethodEnum.Post,
path: encode('1/answers/%s/prediction', base.indexName),
data: {
query,
queryLanguages,
},
cacheable: true,
}, requestOptions);
};
};
const search = (base) => {
return (query, requestOptions) => {
return base.transporter.read({
method: MethodEnum.Post,
path: encode('1/indexes/%s/query', base.indexName),
data: {
query,
},
cacheable: true,
}, requestOptions);
};
};
const searchForFacetValues = (base) => {
return (facetName, facetQuery, requestOptions) => {
return base.transporter.read({
method: MethodEnum.Post,
path: encode('1/indexes/%s/facets/%s/query', base.indexName, facetName),
data: {
facetQuery,
},
cacheable: true,
}, requestOptions);
};
};
const LogLevelEnum = {
Debug: 1,
Info: 2,
Error: 3,
};
/* eslint no-console: 0 */
function createConsoleLogger(logLevel) {
return {
debug(message, args) {
if (LogLevelEnum.Debug >= logLevel) {
console.debug(message, args);
}
return Promise.resolve();
},
info(message, args) {
if (LogLevelEnum.Info >= logLevel) {
console.info(message, args);
}
return Promise.resolve();
},
error(message, args) {
console.error(message, args);
return Promise.resolve();
},
};
}
function createBrowserXhrRequester() {
return {
send(request) {
return new Promise((resolve) => {
const baseRequester = new XMLHttpRequest();
baseRequester.open(request.method, request.url, true);
Object.keys(request.headers).forEach(key => baseRequester.setRequestHeader(key, request.headers[key]));
const createTimeout = (timeout, content) => {
return setTimeout(() => {
baseRequester.abort();
resolve({
status: 0,
content,
isTimedOut: true,
});
}, timeout * 1000);
};
const connectTimeout = createTimeout(request.connectTimeout, 'Connection timeout');
// eslint-disable-next-line functional/no-let
let responseTimeout;
// eslint-disable-next-line functional/immutable-data
baseRequester.onreadystatechange = () => {
if (baseRequester.readyState > baseRequester.OPENED && responseTimeout === undefined) {
clearTimeout(connectTimeout);
responseTimeout = createTimeout(request.responseTimeout, 'Socket timeout');
}
};
// eslint-disable-next-line functional/immutable-data
baseRequester.onerror = () => {
// istanbul ignore next
if (baseRequester.status === 0) {
clearTimeout(connectTimeout);
clearTimeout(responseTimeout);
resolve({
content: baseRequester.responseText || 'Network request failed',
status: baseRequester.status,
isTimedOut: false,
});
}
};
// eslint-disable-next-line functional/immutable-data
baseRequester.onload = () => {
clearTimeout(connectTimeout);
clearTimeout(responseTimeout);
resolve({
content: baseRequester.responseText,
status: baseRequester.status,
isTimedOut: false,
});
};
baseRequester.send(request.data);
});
},
};
}
function algoliasearch(appId, apiKey, options) {
const commonOptions = {
appId,
apiKey,
timeouts: {
connect: 1,
read: 2,
write: 30,
},
requester: createBrowserXhrRequester(),
logger: createConsoleLogger(LogLevelEnum.Error),
responsesCache: createInMemoryCache(),
requestsCache: createInMemoryCache({ serializable: false }),
hostsCache: createFallbackableCache({
caches: [
createBrowserLocalStorageCache({ key: `${version}-${appId}` }),
createInMemoryCache(),
],
}),
userAgent: createUserAgent(version).add({
segment: 'Browser',
version: 'lite',
}),
authMode: AuthMode.WithinQueryParameters,
};
return createSearchClient({
...commonOptions,
...options,
methods: {
search: multipleQueries,
searchForFacetValues: multipleSearchForFacetValues,
multipleQueries,
multipleSearchForFacetValues,
customRequest,
initIndex: base => (indexName) => {
return initIndex(base)(indexName, {
methods: { search, searchForFacetValues, findAnswers },
});
},
},
});
}
// eslint-disable-next-line functional/immutable-data
algoliasearch.version = version;
export default algoliasearch;
| cdnjs/cdnjs | ajax/libs/algoliasearch/4.12.1/algoliasearch-lite.esm.browser.js | JavaScript | mit | 33,346 |
/*
Highcharts JS v9.1.1 (2021-06-03)
(c) 2010-2021 Highsoft AS
Author: Sebastian Domas
License: www.highcharts.com/license
*/
'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/histogram-bellcurve",["highcharts"],function(g){a(g);a.Highcharts=g;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function g(a,c,b,t){a.hasOwnProperty(c)||(a[c]=t.apply(null,b))}a=a?a._modules:{};g(a,"Mixins/DerivedSeries.js",[a["Core/Globals.js"],a["Core/Series/Series.js"],a["Core/Utilities.js"]],function(a,
c,b){var f=b.addEvent,g=b.defined;return{hasDerivedData:!0,init:function(){c.prototype.init.apply(this,arguments);this.initialised=!1;this.baseSeries=null;this.eventRemovers=[];this.addEvents()},setDerivedData:a.noop,setBaseSeries:function(){var a=this.chart,b=this.options.baseSeries;this.baseSeries=g(b)&&(a.series[b]||a.get(b))||null},addEvents:function(){var a=this;var b=f(this.chart,"afterLinkSeries",function(){a.setBaseSeries();a.baseSeries&&!a.initialised&&(a.setDerivedData(),a.addBaseSeriesEvents(),
a.initialised=!0)});this.eventRemovers.push(b)},addBaseSeriesEvents:function(){var a=this;var b=f(a.baseSeries,"updatedData",function(){a.setDerivedData()});var c=f(a.baseSeries,"destroy",function(){a.baseSeries=null;a.initialised=!1});a.eventRemovers.push(b,c)},destroy:function(){this.eventRemovers.forEach(function(a){a()});c.prototype.destroy.apply(this,arguments)}}});g(a,"Series/Histogram/HistogramSeries.js",[a["Mixins/DerivedSeries.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],
function(a,c,b){function g(a){return function(b){for(var e=1;a[e]<=b;)e++;return a[--e]}}var f=this&&this.__extends||function(){var a=function(b,e){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,b){a.__proto__=b}||function(a,b){for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e])};return a(b,e)};return function(b,e){function d(){this.constructor=b}a(b,e);b.prototype=null===e?Object.create(e):(d.prototype=e.prototype,new d)}}(),l=c.seriesTypes.column,n=b.arrayMax,p=b.arrayMin,h=b.correctFloat,
q=b.extend,r=b.isNumber,d=b.merge,u=b.objectEach,k={"square-root":function(a){return Math.ceil(Math.sqrt(a.options.data.length))},sturges:function(a){return Math.ceil(Math.log(a.options.data.length)*Math.LOG2E)},rice:function(a){return Math.ceil(2*Math.pow(a.options.data.length,1/3))}};b=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;b.userOptions=void 0;return b}f(b,a);b.prototype.binsNumber=function(){var a=this.options.binsNumber,
b=k[a]||"function"===typeof a&&a;return Math.ceil(b&&b(this.baseSeries)||(r(a)?a:k["square-root"](this.baseSeries)))};b.prototype.derivedData=function(a,b,d){var e=h(n(a)),k=h(p(a)),c=[],m={},f=[];d=this.binWidth=h(r(d)?d||1:(e-k)/b);this.options.pointRange=Math.max(d,0);for(b=k;b<e&&(this.userOptions.binWidth||h(e-b)>=d||0>=h(h(k+c.length*d)-b));b=h(b+d))c.push(b),m[b]=0;0!==m[k]&&(c.push(k),m[k]=0);var q=g(c.map(function(a){return parseFloat(a)}));a.forEach(function(a){a=h(q(a));m[a]++});u(m,function(a,
b){f.push({x:Number(b),y:a,x2:h(Number(b)+d)})});f.sort(function(a,b){return a.x-b.x});f[f.length-1].x2=e;return f};b.prototype.setDerivedData=function(){var a=this.baseSeries.yData;a.length?(a=this.derivedData(a,this.binsNumber(),this.options.binWidth),this.setData(a,!1)):this.setData([])};b.defaultOptions=d(l.defaultOptions,{binsNumber:"square-root",binWidth:void 0,pointPadding:0,groupPadding:0,grouping:!1,pointPlacement:"between",tooltip:{headerFormat:"",pointFormat:'<span style="font-size: 10px">{point.x} - {point.x2}</span><br/><span style="color:{point.color}">\u25cf</span> {series.name} <b>{point.y}</b><br/>'}});
return b}(l);q(b.prototype,{addBaseSeriesEvents:a.addBaseSeriesEvents,addEvents:a.addEvents,destroy:a.destroy,hasDerivedData:a.hasDerivedData,init:a.init,setBaseSeries:a.setBaseSeries});c.registerSeriesType("histogram",b);"";return b});g(a,"Series/Bellcurve/BellcurveSeries.js",[a["Mixins/DerivedSeries.js"],a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,c,b){var g=this&&this.__extends||function(){var a=function(b,d){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,
b){a.__proto__=b}||function(a,b){for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d])};return a(b,d)};return function(b,d){function c(){this.constructor=b}a(b,d);b.prototype=null===d?Object.create(d):(c.prototype=d.prototype,new c)}}(),f=c.seriesTypes.areaspline,l=b.correctFloat,n=b.extend,p=b.isNumber,h=b.merge;b=function(a){function b(){var b=null!==a&&a.apply(this,arguments)||this;b.data=void 0;b.options=void 0;b.points=void 0;return b}g(b,a);b.mean=function(a){var b=a.length;a=a.reduce(function(a,
b){return a+b},0);return 0<b&&a/b};b.standardDeviation=function(a,c){var d=a.length;c=p(c)?c:b.mean(a);a=a.reduce(function(a,b){b-=c;return a+b*b},0);return 1<d&&Math.sqrt(a/(d-1))};b.normalDensity=function(a,b,c){a-=b;return Math.exp(-(a*a)/(2*c*c))/(c*Math.sqrt(2*Math.PI))};b.prototype.derivedData=function(a,c){var d=this.options.intervals,f=this.options.pointsInInterval,g=a-d*c;d=d*f*2+1;f=c/f;var e=[],h;for(h=0;h<d;h++)e.push([g,b.normalDensity(g,a,c)]),g+=f;return e};b.prototype.setDerivedData=
function(){1<this.baseSeries.yData.length&&(this.setMean(),this.setStandardDeviation(),this.setData(this.derivedData(this.mean,this.standardDeviation),!1))};b.prototype.setMean=function(){this.mean=l(b.mean(this.baseSeries.yData))};b.prototype.setStandardDeviation=function(){this.standardDeviation=l(b.standardDeviation(this.baseSeries.yData,this.mean))};b.defaultOptions=h(f.defaultOptions,{intervals:3,pointsInInterval:3,marker:{enabled:!1}});return b}(f);n(b.prototype,{addBaseSeriesEvents:a.addBaseSeriesEvents,
addEvents:a.addEvents,destroy:a.destroy,init:a.init,setBaseSeries:a.setBaseSeries});c.registerSeriesType("bellcurve",b);"";return b});g(a,"masters/modules/histogram-bellcurve.src.js",[],function(){})});
//# sourceMappingURL=histogram-bellcurve.js.map | cdnjs/cdnjs | ajax/libs/highcharts/9.1.1/modules/histogram-bellcurve.js | JavaScript | mit | 6,105 |
/*!
* chartjs-plugin-annotation v1.3.1
* https://www.chartjs.org/chartjs-plugin-annotation/index
* (c) 2022 chartjs-plugin-annotation Contributors
* Released under the MIT License
*/
import { Element, defaults, Chart, Animations } from 'chart.js';
import { defined, distanceBetweenPoints, callback, isFinite, valueOrDefault, isObject, toRadians, toFont, isArray, addRoundedRectPath, toTRBLCorners, toPadding, PI, drawPoint, RAD_PER_DEG, clipArea, unclipArea } from 'chart.js/helpers';
const clickHooks = ['click', 'dblclick'];
const moveHooks = ['enter', 'leave'];
const hooks = clickHooks.concat(moveHooks);
function updateListeners(chart, state, options) {
state.listened = false;
state.moveListened = false;
hooks.forEach(hook => {
if (typeof options[hook] === 'function') {
state.listened = true;
state.listeners[hook] = options[hook];
} else if (defined(state.listeners[hook])) {
delete state.listeners[hook];
}
});
moveHooks.forEach(hook => {
if (typeof options[hook] === 'function') {
state.moveListened = true;
}
});
if (!state.listened || !state.moveListened) {
state.annotations.forEach(scope => {
if (!state.listened) {
clickHooks.forEach(hook => {
if (typeof scope[hook] === 'function') {
state.listened = true;
}
});
}
if (!state.moveListened) {
moveHooks.forEach(hook => {
if (typeof scope[hook] === 'function') {
state.listened = true;
state.moveListened = true;
}
});
}
});
}
}
function handleEvent(state, event, options) {
if (state.listened) {
switch (event.type) {
case 'mousemove':
case 'mouseout':
handleMoveEvents(state, event);
break;
case 'click':
handleClickEvents(state, event, options);
break;
}
}
}
function handleMoveEvents(state, event) {
if (!state.moveListened) {
return;
}
let element;
if (event.type === 'mousemove') {
element = getNearestItem(state.elements, event);
}
const previous = state.hovered;
state.hovered = element;
dispatchMoveEvents(state, {previous, element}, event);
}
function dispatchMoveEvents(state, elements, event) {
const {previous, element} = elements;
if (previous && previous !== element) {
dispatchEvent(previous.options.leave || state.listeners.leave, previous, event);
}
if (element && element !== previous) {
dispatchEvent(element.options.enter || state.listeners.enter, element, event);
}
}
function handleClickEvents(state, event, options) {
const listeners = state.listeners;
const element = getNearestItem(state.elements, event);
if (element) {
const elOpts = element.options;
const dblclick = elOpts.dblclick || listeners.dblclick;
const click = elOpts.click || listeners.click;
if (element.clickTimeout) {
// 2nd click before timeout, so its a double click
clearTimeout(element.clickTimeout);
delete element.clickTimeout;
dispatchEvent(dblclick, element, event);
} else if (dblclick) {
// if there is a dblclick handler, wait for dblClickSpeed ms before deciding its a click
element.clickTimeout = setTimeout(() => {
delete element.clickTimeout;
dispatchEvent(click, element, event);
}, options.dblClickSpeed);
} else {
// no double click handler, just call the click handler directly
dispatchEvent(click, element, event);
}
}
}
function dispatchEvent(handler, element, event) {
callback(handler, [element.$context, event]);
}
function getNearestItem(elements, position) {
let minDistance = Number.POSITIVE_INFINITY;
return elements
.filter((element) => element.options.display && element.inRange(position.x, position.y))
.reduce((nearestItems, element) => {
const center = element.getCenterPoint();
const distance = distanceBetweenPoints(position, center);
if (distance < minDistance) {
nearestItems = [element];
minDistance = distance;
} else if (distance === minDistance) {
// Can have multiple items at the same distance in which case we sort by size
nearestItems.push(element);
}
return nearestItems;
}, [])
.sort((a, b) => a._index - b._index)
.slice(0, 1)[0]; // return only the top item
}
function adjustScaleRange(chart, scale, annotations) {
const range = getScaleLimits(scale, annotations);
let changed = changeScaleLimit(scale, range, 'min', 'suggestedMin');
changed = changeScaleLimit(scale, range, 'max', 'suggestedMax') || changed;
if (changed && typeof scale.handleTickRangeOptions === 'function') {
scale.handleTickRangeOptions();
}
}
function verifyScaleOptions(annotations, scales) {
for (const annotation of annotations) {
verifyScaleIDs(annotation, scales);
}
}
function changeScaleLimit(scale, range, limit, suggestedLimit) {
if (isFinite(range[limit]) && !scaleLimitDefined(scale.options, limit, suggestedLimit)) {
const changed = scale[limit] !== range[limit];
scale[limit] = range[limit];
return changed;
}
}
function scaleLimitDefined(scaleOptions, limit, suggestedLimit) {
return defined(scaleOptions[limit]) || defined(scaleOptions[suggestedLimit]);
}
function verifyScaleIDs(annotation, scales) {
for (const key of ['scaleID', 'xScaleID', 'yScaleID']) {
if (annotation[key] && !scales[annotation[key]] && verifyProperties(annotation, key)) {
console.warn(`No scale found with id '${annotation[key]}' for annotation '${annotation.id}'`);
}
}
}
function verifyProperties(annotation, key) {
if (key === 'scaleID') {
return true;
}
const axis = key.charAt(0);
for (const prop of ['Min', 'Max', 'Value']) {
if (defined(annotation[axis + prop])) {
return true;
}
}
return false;
}
function getScaleLimits(scale, annotations) {
const axis = scale.axis;
const scaleID = scale.id;
const scaleIDOption = axis + 'ScaleID';
const limits = {
min: valueOrDefault(scale.min, Number.NEGATIVE_INFINITY),
max: valueOrDefault(scale.max, Number.POSITIVE_INFINITY)
};
for (const annotation of annotations) {
if (annotation.scaleID === scaleID) {
updateLimits(annotation, scale, ['value', 'endValue'], limits);
} else if (annotation[scaleIDOption] === scaleID) {
updateLimits(annotation, scale, [axis + 'Min', axis + 'Max', axis + 'Value'], limits);
}
}
return limits;
}
function updateLimits(annotation, scale, props, limits) {
for (const prop of props) {
const raw = annotation[prop];
if (defined(raw)) {
const value = scale.parse(raw);
limits.min = Math.min(limits.min, value);
limits.max = Math.max(limits.max, value);
}
}
}
const clamp = (x, from, to) => Math.min(to, Math.max(from, x));
function clampAll(obj, from, to) {
for (const key of Object.keys(obj)) {
obj[key] = clamp(obj[key], from, to);
}
return obj;
}
function inPointRange(point, center, radius, borderWidth) {
if (!point || !center || radius <= 0) {
return false;
}
const hBorderWidth = borderWidth / 2 || 0;
return (Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2)) <= Math.pow(radius + hBorderWidth, 2);
}
function inBoxRange(mouseX, mouseY, {x, y, width, height}, borderWidth) {
const hBorderWidth = borderWidth / 2 || 0;
return mouseX >= x - hBorderWidth &&
mouseX <= x + width + hBorderWidth &&
mouseY >= y - hBorderWidth &&
mouseY <= y + height + hBorderWidth;
}
function getElementCenterPoint(element, useFinalPosition) {
const {x, y} = element.getProps(['x', 'y'], useFinalPosition);
return {x, y};
}
const isOlderPart = (act, req) => req > act || (act.length > req.length && act.substr(0, req.length) === req);
function requireVersion(pkg, min, ver, strict = true) {
const parts = ver.split('.');
let i = 0;
for (const req of min.split('.')) {
const act = parts[i++];
if (parseInt(req, 10) < parseInt(act, 10)) {
break;
}
if (isOlderPart(act, req)) {
if (strict) {
throw new Error(`${pkg} v${ver} is not supported. v${min} or newer is required.`);
} else {
return false;
}
}
}
return true;
}
const isPercentString = (s) => typeof s === 'string' && s.endsWith('%');
const toPercent = (s) => clamp(parseFloat(s) / 100, 0, 1);
function getRelativePosition(size, positionOption) {
if (positionOption === 'start') {
return 0;
}
if (positionOption === 'end') {
return size;
}
if (isPercentString(positionOption)) {
return toPercent(positionOption) * size;
}
return size / 2;
}
function getSize(size, value) {
if (typeof value === 'number') {
return value;
} else if (isPercentString(value)) {
return toPercent(value) * size;
}
return size;
}
function calculateTextAlignment(size, options) {
const {x, width} = size;
const textAlign = options.textAlign;
if (textAlign === 'center') {
return x + width / 2;
} else if (textAlign === 'end' || textAlign === 'right') {
return x + width;
}
return x;
}
function toPosition(value) {
if (isObject(value)) {
return {
x: valueOrDefault(value.x, 'center'),
y: valueOrDefault(value.y, 'center'),
};
}
value = valueOrDefault(value, 'center');
return {
x: value,
y: value
};
}
function isBoundToPoint(options) {
return options && (defined(options.xValue) || defined(options.yValue));
}
const widthCache = new Map();
function isImageOrCanvas(content) {
return content instanceof Image || content instanceof HTMLCanvasElement;
}
/**
* Set the translation on the canvas if the rotation must be applied.
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {Element} element - annotation element to use for applying the translation
* @param {number} rotation - rotation (in degrees) to apply
*/
function translate(ctx, element, rotation) {
if (rotation) {
const center = element.getCenterPoint();
ctx.translate(center.x, center.y);
ctx.rotate(toRadians(rotation));
ctx.translate(-center.x, -center.y);
}
}
/**
* Apply border options to the canvas context before drawing a shape
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {Object} options - options with border configuration
* @returns {boolean} true is the border options have been applied
*/
function setBorderStyle(ctx, options) {
if (options && options.borderWidth) {
ctx.lineCap = options.borderCapStyle;
ctx.setLineDash(options.borderDash);
ctx.lineDashOffset = options.borderDashOffset;
ctx.lineJoin = options.borderJoinStyle;
ctx.lineWidth = options.borderWidth;
ctx.strokeStyle = options.borderColor;
return true;
}
}
/**
* Apply shadow options to the canvas context before drawing a shape
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {Object} options - options with shadow configuration
*/
function setShadowStyle(ctx, options) {
ctx.shadowColor = options.backgroundShadowColor;
ctx.shadowBlur = options.shadowBlur;
ctx.shadowOffsetX = options.shadowOffsetX;
ctx.shadowOffsetY = options.shadowOffsetY;
}
/**
* Measure the label size using the label options.
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {Object} options - options to configure the label
* @returns {{width: number, height: number}} the measured size of the label
*/
function measureLabelSize(ctx, options) {
const content = options.content;
if (isImageOrCanvas(content)) {
return {
width: getSize(content.width, options.width),
height: getSize(content.height, options.height)
};
}
const font = toFont(options.font);
const lines = isArray(content) ? content : [content];
const mapKey = lines.join() + font.string + (ctx._measureText ? '-spriting' : '');
if (!widthCache.has(mapKey)) {
ctx.save();
ctx.font = font.string;
const count = lines.length;
let width = 0;
for (let i = 0; i < count; i++) {
const text = lines[i];
width = Math.max(width, ctx.measureText(text).width);
}
ctx.restore();
const height = count * font.lineHeight;
widthCache.set(mapKey, {width, height});
}
return widthCache.get(mapKey);
}
/**
* Draw a box with the size and the styling options.
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {{x: number, y: number, width: number, height: number}} rect - rect to draw
* @param {Object} options - options to style the box
* @returns {undefined}
*/
function drawBox(ctx, rect, options) {
const {x, y, width, height} = rect;
ctx.save();
setShadowStyle(ctx, options);
const stroke = setBorderStyle(ctx, options);
ctx.fillStyle = options.backgroundColor;
ctx.beginPath();
addRoundedRectPath(ctx, {
x, y, w: width, h: height,
// TODO: v2 remove support for cornerRadius
radius: clampAll(toTRBLCorners(valueOrDefault(options.cornerRadius, options.borderRadius)), 0, Math.min(width, height) / 2)
});
ctx.closePath();
ctx.fill();
if (stroke) {
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
}
ctx.restore();
}
function drawLabel(ctx, rect, options) {
const content = options.content;
if (isImageOrCanvas(content)) {
ctx.drawImage(content, rect.x, rect.y, rect.width, rect.height);
return;
}
const labels = isArray(content) ? content : [content];
const font = toFont(options.font);
const lh = font.lineHeight;
const x = calculateTextAlignment(rect, options);
const y = rect.y + (lh / 2);
ctx.font = font.string;
ctx.textBaseline = 'middle';
ctx.textAlign = options.textAlign;
ctx.fillStyle = options.color;
labels.forEach((l, i) => ctx.fillText(l, x, y + (i * lh)));
}
/**
* @typedef {import('chart.js').Point} Point
*/
/**
* @param {{x: number, y: number, width: number, height: number}} rect
* @returns {Point}
*/
function getRectCenterPoint(rect) {
const {x, y, width, height} = rect;
return {
x: x + width / 2,
y: y + height / 2
};
}
/**
* Rotate a `point` relative to `center` point by `angle`
* @param {Point} point - the point to rotate
* @param {Point} center - center point for rotation
* @param {number} angle - angle for rotation, in radians
* @returns {Point} rotated point
*/
function rotated(point, center, angle) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const cx = center.x;
const cy = center.y;
return {
x: cx + cos * (point.x - cx) - sin * (point.y - cy),
y: cy + sin * (point.x - cx) + cos * (point.y - cy)
};
}
/**
* @typedef { import("chart.js").Chart } Chart
* @typedef { import("chart.js").Scale } Scale
* @typedef { import("chart.js").Point } Point
* @typedef { import('../../types/options').CoreAnnotationOptions } CoreAnnotationOptions
* @typedef { import('../../types/options').PointAnnotationOptions } PointAnnotationOptions
*/
/**
* @param {Scale} scale
* @param {number|string} value
* @param {number} fallback
* @returns {number}
*/
function scaleValue(scale, value, fallback) {
value = typeof value === 'number' ? value : scale.parse(value);
return isFinite(value) ? scale.getPixelForValue(value) : fallback;
}
/**
* @param {Scale} scale
* @param {{start: number, end: number}} options
* @returns {{start: number, end: number}}
*/
function getChartDimensionByScale(scale, options) {
if (scale) {
const min = scaleValue(scale, options.min, options.start);
const max = scaleValue(scale, options.max, options.end);
return {
start: Math.min(min, max),
end: Math.max(min, max)
};
}
return {
start: options.start,
end: options.end
};
}
/**
* @param {Chart} chart
* @param {CoreAnnotationOptions} options
* @returns {Point}
*/
function getChartPoint(chart, options) {
const {chartArea, scales} = chart;
const xScale = scales[options.xScaleID];
const yScale = scales[options.yScaleID];
let x = chartArea.width / 2;
let y = chartArea.height / 2;
if (xScale) {
x = scaleValue(xScale, options.xValue, x);
}
if (yScale) {
y = scaleValue(yScale, options.yValue, y);
}
return {x, y};
}
/**
* @param {Chart} chart
* @param {CoreAnnotationOptions} options
* @returns {{x?:number, y?: number, x2?: number, y2?: number, width?: number, height?: number}}
*/
function getChartRect(chart, options) {
const xScale = chart.scales[options.xScaleID];
const yScale = chart.scales[options.yScaleID];
let {top: y, left: x, bottom: y2, right: x2} = chart.chartArea;
if (!xScale && !yScale) {
return {};
}
const xDim = getChartDimensionByScale(xScale, {min: options.xMin, max: options.xMax, start: x, end: x2});
x = xDim.start;
x2 = xDim.end;
const yDim = getChartDimensionByScale(yScale, {min: options.yMin, max: options.yMax, start: y, end: y2});
y = yDim.start;
y2 = yDim.end;
return {
x,
y,
x2,
y2,
width: x2 - x,
height: y2 - y
};
}
/**
* @param {Chart} chart
* @param {PointAnnotationOptions} options
*/
function getChartCircle(chart, options) {
const point = getChartPoint(chart, options);
return {
x: point.x + options.xAdjust,
y: point.y + options.yAdjust,
width: options.radius * 2,
height: options.radius * 2
};
}
/**
* @param {Chart} chart
* @param {PointAnnotationOptions} options
* @returns
*/
function resolvePointPosition(chart, options) {
if (!isBoundToPoint(options)) {
const box = getChartRect(chart, options);
const point = getRectCenterPoint(box);
let radius = options.radius;
if (!radius || isNaN(radius)) {
radius = Math.min(box.width, box.height) / 2;
options.radius = radius;
}
return {
x: point.x + options.xAdjust,
y: point.y + options.yAdjust,
width: radius * 2,
height: radius * 2
};
}
return getChartCircle(chart, options);
}
class BoxAnnotation extends Element {
inRange(mouseX, mouseY, useFinalPosition) {
return inBoxRange(mouseX, mouseY, this.getProps(['x', 'y', 'width', 'height'], useFinalPosition), this.options.borderWidth);
}
getCenterPoint(useFinalPosition) {
return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition));
}
draw(ctx) {
ctx.save();
drawBox(ctx, this, this.options);
ctx.restore();
}
drawLabel(ctx) {
const {x, y, width, height, options} = this;
const {label, borderWidth} = options;
const halfBorder = borderWidth / 2;
const position = toPosition(label.position);
const padding = toPadding(label.padding);
const labelSize = measureLabelSize(ctx, label);
const labelRect = {
x: calculateX(this, labelSize, position, padding),
y: calculateY(this, labelSize, position, padding),
width: labelSize.width,
height: labelSize.height
};
ctx.save();
ctx.beginPath();
ctx.rect(x + halfBorder + padding.left, y + halfBorder + padding.top,
width - borderWidth - padding.width, height - borderWidth - padding.height);
ctx.clip();
drawLabel(ctx, labelRect, label);
ctx.restore();
}
resolveElementProperties(chart, options) {
return getChartRect(chart, options);
}
}
BoxAnnotation.id = 'boxAnnotation';
BoxAnnotation.defaults = {
adjustScaleRange: true,
backgroundShadowColor: 'transparent',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: 'miter',
borderRadius: 0,
borderShadowColor: 'transparent',
borderWidth: 1,
cornerRadius: undefined, // TODO: v2 remove support for cornerRadius
display: true,
label: {
borderWidth: undefined,
color: 'black',
content: null,
drawTime: undefined,
enabled: false,
font: {
family: undefined,
lineHeight: undefined,
size: undefined,
style: undefined,
weight: 'bold'
},
height: undefined,
padding: 6,
position: 'center',
textAlign: 'start',
xAdjust: 0,
yAdjust: 0,
width: undefined
},
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
yMax: undefined,
yMin: undefined,
yScaleID: 'y'
};
BoxAnnotation.defaultRoutes = {
borderColor: 'color',
backgroundColor: 'color'
};
BoxAnnotation.descriptors = {
label: {
_fallback: true
}
};
function calculateX(box, labelSize, position, padding) {
const {x: start, x2: end, width: size, options} = box;
const {xAdjust: adjust, borderWidth} = options.label;
return calculatePosition$1({start, end, size}, {
position: position.x,
padding: {start: padding.left, end: padding.right},
adjust, borderWidth,
size: labelSize.width
});
}
function calculateY(box, labelSize, position, padding) {
const {y: start, y2: end, height: size, options} = box;
const {yAdjust: adjust, borderWidth} = options.label;
return calculatePosition$1({start, end, size}, {
position: position.y,
padding: {start: padding.top, end: padding.bottom},
adjust, borderWidth,
size: labelSize.height
});
}
function calculatePosition$1(boxOpts, labelOpts) {
const {start, end} = boxOpts;
const {position, padding: {start: padStart, end: padEnd}, adjust, borderWidth} = labelOpts;
const availableSize = end - borderWidth - start - padStart - padEnd - labelOpts.size;
return start + borderWidth / 2 + adjust + padStart + getRelativePosition(availableSize, position);
}
const pointInLine = (p1, p2, t) => ({x: p1.x + t * (p2.x - p1.x), y: p1.y + t * (p2.y - p1.y)});
const interpolateX = (y, p1, p2) => pointInLine(p1, p2, Math.abs((y - p1.y) / (p2.y - p1.y))).x;
const interpolateY = (x, p1, p2) => pointInLine(p1, p2, Math.abs((x - p1.x) / (p2.x - p1.x))).y;
const sqr = v => v * v;
const defaultEpsilon = 0.001;
function isLineInArea({x, y, x2, y2}, {top, right, bottom, left}) {
return !(
(x < left && x2 < left) ||
(x > right && x2 > right) ||
(y < top && y2 < top) ||
(y > bottom && y2 > bottom)
);
}
function limitPointToArea({x, y}, p2, {top, right, bottom, left}) {
if (x < left) {
y = interpolateY(left, {x, y}, p2);
x = left;
}
if (x > right) {
y = interpolateY(right, {x, y}, p2);
x = right;
}
if (y < top) {
x = interpolateX(top, {x, y}, p2);
y = top;
}
if (y > bottom) {
x = interpolateX(bottom, {x, y}, p2);
y = bottom;
}
return {x, y};
}
function limitLineToArea(p1, p2, area) {
const {x, y} = limitPointToArea(p1, p2, area);
const {x: x2, y: y2} = limitPointToArea(p2, p1, area);
return {x, y, x2, y2, width: Math.abs(x2 - x), height: Math.abs(y2 - y)};
}
class LineAnnotation extends Element {
// TODO: make private in v2
intersects(x, y, epsilon = defaultEpsilon, useFinalPosition) {
// Adapted from https://stackoverflow.com/a/6853926/25507
const {x: x1, y: y1, x2, y2} = this.getProps(['x', 'y', 'x2', 'y2'], useFinalPosition);
const dx = x2 - x1;
const dy = y2 - y1;
const lenSq = sqr(dx) + sqr(dy);
const t = lenSq === 0 ? -1 : ((x - x1) * dx + (y - y1) * dy) / lenSq;
let xx, yy;
if (t < 0) {
xx = x1;
yy = y1;
} else if (t > 1) {
xx = x2;
yy = y2;
} else {
xx = x1 + t * dx;
yy = y1 + t * dy;
}
return (sqr(x - xx) + sqr(y - yy)) <= epsilon;
}
/**
* @todo make private in v2
* @param {boolean} useFinalPosition - use the element's animation target instead of current position
* @param {top, right, bottom, left} [chartArea] - optional, area of the chart
* @returns {boolean} true if the label is visible
*/
labelIsVisible(useFinalPosition, chartArea) {
const labelOpts = this.options.label;
if (!labelOpts || !labelOpts.enabled) {
return false;
}
return !chartArea || isLineInArea(this.getProps(['x', 'y', 'x2', 'y2'], useFinalPosition), chartArea);
}
// TODO: make private in v2
isOnLabel(mouseX, mouseY, useFinalPosition) {
if (!this.labelIsVisible(useFinalPosition)) {
return false;
}
const {labelX, labelY, labelWidth, labelHeight, labelRotation} = this.getProps(['labelX', 'labelY', 'labelWidth', 'labelHeight', 'labelRotation'], useFinalPosition);
const {x, y} = rotated({x: mouseX, y: mouseY}, {x: labelX, y: labelY}, -labelRotation);
const hBorderWidth = this.options.label.borderWidth / 2 || 0;
const w2 = labelWidth / 2 + hBorderWidth;
const h2 = labelHeight / 2 + hBorderWidth;
return x >= labelX - w2 - defaultEpsilon && x <= labelX + w2 + defaultEpsilon &&
y >= labelY - h2 - defaultEpsilon && y <= labelY + h2 + defaultEpsilon;
}
inRange(mouseX, mouseY, useFinalPosition) {
const epsilon = sqr(this.options.borderWidth / 2);
return this.intersects(mouseX, mouseY, epsilon, useFinalPosition) || this.isOnLabel(mouseX, mouseY, useFinalPosition);
}
getCenterPoint() {
return {
x: (this.x2 + this.x) / 2,
y: (this.y2 + this.y) / 2
};
}
draw(ctx) {
const {x, y, x2, y2, options} = this;
ctx.save();
if (!setBorderStyle(ctx, options)) {
// no border width, then line is not drawn
return ctx.restore();
}
setShadowStyle(ctx, options);
const angle = Math.atan2(y2 - y, x2 - x);
const length = Math.sqrt(Math.pow(x2 - x, 2) + Math.pow(y2 - y, 2));
const {startOpts, endOpts, startAdjust, endAdjust} = getArrowHeads(this);
ctx.translate(x, y);
ctx.rotate(angle);
ctx.beginPath();
ctx.moveTo(0 + startAdjust, 0);
ctx.lineTo(length - endAdjust, 0);
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
drawArrowHead(ctx, 0, startAdjust, startOpts);
drawArrowHead(ctx, length, -endAdjust, endOpts);
ctx.restore();
}
drawLabel(ctx, chartArea) {
if (!this.labelIsVisible(false, chartArea)) {
return;
}
const {labelX, labelY, labelWidth, labelHeight, labelRotation, labelPadding, labelTextSize, options: {label}} = this;
ctx.save();
ctx.translate(labelX, labelY);
ctx.rotate(labelRotation);
const boxRect = {
x: -(labelWidth / 2),
y: -(labelHeight / 2),
width: labelWidth,
height: labelHeight
};
drawBox(ctx, boxRect, label);
const labelTextRect = {
x: -(labelWidth / 2) + labelPadding.left + label.borderWidth / 2,
y: -(labelHeight / 2) + labelPadding.top + label.borderWidth / 2,
width: labelTextSize.width,
height: labelTextSize.height
};
drawLabel(ctx, labelTextRect, label);
ctx.restore();
}
resolveElementProperties(chart, options) {
const scale = chart.scales[options.scaleID];
let {top: y, left: x, bottom: y2, right: x2} = chart.chartArea;
let min, max;
if (scale) {
min = scaleValue(scale, options.value, NaN);
max = scaleValue(scale, options.endValue, min);
if (scale.isHorizontal()) {
x = min;
x2 = max;
} else {
y = min;
y2 = max;
}
} else {
const xScale = chart.scales[options.xScaleID];
const yScale = chart.scales[options.yScaleID];
if (xScale) {
x = scaleValue(xScale, options.xMin, x);
x2 = scaleValue(xScale, options.xMax, x2);
}
if (yScale) {
y = scaleValue(yScale, options.yMin, y);
y2 = scaleValue(yScale, options.yMax, y2);
}
}
const inside = isLineInArea({x, y, x2, y2}, chart.chartArea);
const properties = inside
? limitLineToArea({x, y}, {x: x2, y: y2}, chart.chartArea)
: {x, y, x2, y2, width: Math.abs(x2 - x), height: Math.abs(y2 - y)};
const label = options.label;
if (label && label.content) {
return loadLabelRect(properties, chart, label);
}
return properties;
}
}
LineAnnotation.id = 'lineAnnotation';
const arrowHeadsDefaults = {
backgroundColor: undefined,
backgroundShadowColor: undefined,
borderColor: undefined,
borderDash: undefined,
borderDashOffset: undefined,
borderShadowColor: undefined,
borderWidth: undefined,
enabled: undefined,
fill: undefined,
length: undefined,
shadowBlur: undefined,
shadowOffsetX: undefined,
shadowOffsetY: undefined,
width: undefined
};
LineAnnotation.defaults = {
adjustScaleRange: true,
arrowHeads: {
enabled: false,
end: Object.assign({}, arrowHeadsDefaults),
fill: false,
length: 12,
start: Object.assign({}, arrowHeadsDefaults),
width: 6
},
borderDash: [],
borderDashOffset: 0,
borderShadowColor: 'transparent',
borderWidth: 2,
display: true,
endValue: undefined,
label: {
backgroundColor: 'rgba(0,0,0,0.8)',
backgroundShadowColor: 'transparent',
borderCapStyle: 'butt',
borderColor: 'black',
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: 'miter',
borderRadius: 6,
borderShadowColor: 'transparent',
borderWidth: 0,
color: '#fff',
content: null,
cornerRadius: undefined, // TODO: v2 remove support for cornerRadius
drawTime: undefined,
enabled: false,
font: {
family: undefined,
lineHeight: undefined,
size: undefined,
style: undefined,
weight: 'bold'
},
height: undefined,
padding: 6,
position: 'center',
rotation: 0,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
textAlign: 'center',
width: undefined,
xAdjust: 0,
xPadding: undefined, // TODO: v2 remove support for xPadding
yAdjust: 0,
yPadding: undefined, // TODO: v2 remove support for yPadding
},
scaleID: undefined,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
value: undefined,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
yMax: undefined,
yMin: undefined,
yScaleID: 'y'
};
LineAnnotation.descriptors = {
arrowHeads: {
start: {
_fallback: true
},
end: {
_fallback: true
},
_fallback: true
}
};
LineAnnotation.defaultRoutes = {
borderColor: 'color'
};
function loadLabelRect(line, chart, options) {
// TODO: v2 remove support for xPadding and yPadding
const {padding: lblPadding, xPadding, yPadding, borderWidth} = options;
const padding = getPadding(lblPadding, xPadding, yPadding);
const textSize = measureLabelSize(chart.ctx, options);
const width = textSize.width + padding.width + borderWidth;
const height = textSize.height + padding.height + borderWidth;
const labelRect = calculateLabelPosition(line, options, {width, height, padding}, chart.chartArea);
line.labelX = labelRect.x;
line.labelY = labelRect.y;
line.labelWidth = labelRect.width;
line.labelHeight = labelRect.height;
line.labelRotation = labelRect.rotation;
line.labelPadding = padding;
line.labelTextSize = textSize;
return line;
}
function calculateAutoRotation(line) {
const {x, y, x2, y2} = line;
const rotation = Math.atan2(y2 - y, x2 - x);
// Flip the rotation if it goes > PI/2 or < -PI/2, so label stays upright
return rotation > PI / 2 ? rotation - PI : rotation < PI / -2 ? rotation + PI : rotation;
}
// TODO: v2 remove support for xPadding and yPadding
function getPadding(padding, xPadding, yPadding) {
let tempPadding = padding;
if (xPadding || yPadding) {
tempPadding = {x: xPadding || 6, y: yPadding || 6};
}
return toPadding(tempPadding);
}
function calculateLabelPosition(line, label, sizes, chartArea) {
const {width, height, padding} = sizes;
const {xAdjust, yAdjust} = label;
const p1 = {x: line.x, y: line.y};
const p2 = {x: line.x2, y: line.y2};
const rotation = label.rotation === 'auto' ? calculateAutoRotation(line) : toRadians(label.rotation);
const size = rotatedSize(width, height, rotation);
const t = calculateT(line, label, {labelSize: size, padding}, chartArea);
const pt = pointInLine(p1, p2, t);
const xCoordinateSizes = {size: size.w, min: chartArea.left, max: chartArea.right, padding: padding.left};
const yCoordinateSizes = {size: size.h, min: chartArea.top, max: chartArea.bottom, padding: padding.top};
return {
x: adjustLabelCoordinate(pt.x, xCoordinateSizes) + xAdjust,
y: adjustLabelCoordinate(pt.y, yCoordinateSizes) + yAdjust,
width,
height,
rotation
};
}
function rotatedSize(width, height, rotation) {
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
return {
w: Math.abs(width * cos) + Math.abs(height * sin),
h: Math.abs(width * sin) + Math.abs(height * cos)
};
}
function calculateT(line, label, sizes, chartArea) {
let t;
const space = spaceAround(line, chartArea);
if (label.position === 'start') {
t = calculateTAdjust({w: line.x2 - line.x, h: line.y2 - line.y}, sizes, label, space);
} else if (label.position === 'end') {
t = 1 - calculateTAdjust({w: line.x - line.x2, h: line.y - line.y2}, sizes, label, space);
} else {
t = getRelativePosition(1, label.position);
}
return t;
}
function calculateTAdjust(lineSize, sizes, label, space) {
const {labelSize, padding} = sizes;
const lineW = lineSize.w * space.dx;
const lineH = lineSize.h * space.dy;
const x = (lineW > 0) && ((labelSize.w / 2 + padding.left - space.x) / lineW);
const y = (lineH > 0) && ((labelSize.h / 2 + padding.top - space.y) / lineH);
return clamp(Math.max(x, y), 0, 0.25);
}
function spaceAround(line, chartArea) {
const {x, x2, y, y2} = line;
const t = Math.min(y, y2) - chartArea.top;
const l = Math.min(x, x2) - chartArea.left;
const b = chartArea.bottom - Math.max(y, y2);
const r = chartArea.right - Math.max(x, x2);
return {
x: Math.min(l, r),
y: Math.min(t, b),
dx: l <= r ? 1 : -1,
dy: t <= b ? 1 : -1
};
}
function adjustLabelCoordinate(coordinate, labelSizes) {
const {size, min, max, padding} = labelSizes;
const halfSize = size / 2;
if (size > max - min) {
// if it does not fit, display as much as possible
return (max + min) / 2;
}
if (min >= (coordinate - padding - halfSize)) {
coordinate = min + padding + halfSize;
}
if (max <= (coordinate + padding + halfSize)) {
coordinate = max - padding - halfSize;
}
return coordinate;
}
function getArrowHeads(line) {
const options = line.options;
const arrowStartOpts = options.arrowHeads && options.arrowHeads.start;
const arrowEndOpts = options.arrowHeads && options.arrowHeads.end;
return {
startOpts: arrowStartOpts,
endOpts: arrowEndOpts,
startAdjust: getLineAdjust(line, arrowStartOpts),
endAdjust: getLineAdjust(line, arrowEndOpts)
};
}
function getLineAdjust(line, arrowOpts) {
if (!arrowOpts || !arrowOpts.enabled) {
return 0;
}
const {length, width} = arrowOpts;
const adjust = line.options.borderWidth / 2;
const p1 = {x: length, y: width + adjust};
const p2 = {x: 0, y: adjust};
return Math.abs(interpolateX(0, p1, p2));
}
function drawArrowHead(ctx, offset, adjust, arrowOpts) {
if (!arrowOpts || !arrowOpts.enabled) {
return;
}
const {length, width, fill, backgroundColor, borderColor} = arrowOpts;
const arrowOffsetX = Math.abs(offset - length) + adjust;
ctx.beginPath();
setShadowStyle(ctx, arrowOpts);
setBorderStyle(ctx, arrowOpts);
ctx.moveTo(arrowOffsetX, -width);
ctx.lineTo(offset + adjust, 0);
ctx.lineTo(arrowOffsetX, width);
if (fill === true) {
ctx.fillStyle = backgroundColor || borderColor;
ctx.closePath();
ctx.fill();
ctx.shadowColor = 'transparent';
} else {
ctx.shadowColor = arrowOpts.borderShadowColor;
}
ctx.stroke();
}
class EllipseAnnotation extends Element {
inRange(mouseX, mouseY, useFinalPosition) {
return pointInEllipse({x: mouseX, y: mouseY}, this.getProps(['width', 'height'], useFinalPosition), this.options.rotation, this.options.borderWidth);
}
getCenterPoint(useFinalPosition) {
return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition));
}
draw(ctx) {
const {width, height, options} = this;
const center = this.getCenterPoint();
ctx.save();
translate(ctx, this, options.rotation);
setShadowStyle(ctx, this.options);
ctx.beginPath();
ctx.fillStyle = options.backgroundColor;
const stroke = setBorderStyle(ctx, options);
ctx.ellipse(center.x, center.y, height / 2, width / 2, PI / 2, 0, 2 * PI);
ctx.fill();
if (stroke) {
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
}
ctx.restore();
}
resolveElementProperties(chart, options) {
return getChartRect(chart, options);
}
}
EllipseAnnotation.id = 'ellipseAnnotation';
EllipseAnnotation.defaults = {
adjustScaleRange: true,
backgroundShadowColor: 'transparent',
borderDash: [],
borderDashOffset: 0,
borderShadowColor: 'transparent',
borderWidth: 1,
display: true,
rotation: 0,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
yMax: undefined,
yMin: undefined,
yScaleID: 'y'
};
EllipseAnnotation.defaultRoutes = {
borderColor: 'color',
backgroundColor: 'color'
};
function pointInEllipse(p, ellipse, rotation, borderWidth) {
const {width, height} = ellipse;
const center = ellipse.getCenterPoint(true);
const xRadius = width / 2;
const yRadius = height / 2;
if (xRadius <= 0 || yRadius <= 0) {
return false;
}
// https://stackoverflow.com/questions/7946187/point-and-ellipse-rotated-position-test-algorithm
const angle = toRadians(rotation || 0);
const hBorderWidth = borderWidth / 2 || 0;
const cosAngle = Math.cos(angle);
const sinAngle = Math.sin(angle);
const a = Math.pow(cosAngle * (p.x - center.x) + sinAngle * (p.y - center.y), 2);
const b = Math.pow(sinAngle * (p.x - center.x) - cosAngle * (p.y - center.y), 2);
return (a / Math.pow(xRadius + hBorderWidth, 2)) + (b / Math.pow(yRadius + hBorderWidth, 2)) <= 1.0001;
}
class LabelAnnotation extends Element {
inRange(mouseX, mouseY, useFinalPosition) {
return inBoxRange(mouseX, mouseY, this.getProps(['x', 'y', 'width', 'height'], useFinalPosition), this.options.borderWidth);
}
getCenterPoint(useFinalPosition) {
return getRectCenterPoint(this.getProps(['x', 'y', 'width', 'height'], useFinalPosition));
}
draw(ctx) {
if (!this.options.content) {
return;
}
const {labelX, labelY, labelWidth, labelHeight, options} = this;
drawCallout(ctx, this);
drawBox(ctx, this, options);
drawLabel(ctx, {x: labelX, y: labelY, width: labelWidth, height: labelHeight}, options);
}
// TODO: make private in v2
resolveElementProperties(chart, options) {
const point = !isBoundToPoint(options) ? getRectCenterPoint(getChartRect(chart, options)) : getChartPoint(chart, options);
const padding = toPadding(options.padding);
const labelSize = measureLabelSize(chart.ctx, options);
const boxSize = measureRect(point, labelSize, options, padding);
const hBorderWidth = options.borderWidth / 2;
const properties = {
pointX: point.x,
pointY: point.y,
...boxSize,
labelX: boxSize.x + padding.left + hBorderWidth,
labelY: boxSize.y + padding.top + hBorderWidth,
labelWidth: labelSize.width,
labelHeight: labelSize.height
};
properties.calloutPosition = options.callout.enabled && resolveCalloutPosition(properties, options.callout);
return properties;
}
}
LabelAnnotation.id = 'labelAnnotation';
LabelAnnotation.defaults = {
adjustScaleRange: true,
backgroundColor: 'transparent',
backgroundShadowColor: 'transparent',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: 'miter',
borderRadius: 0,
borderShadowColor: 'transparent',
borderWidth: 0,
callout: {
borderCapStyle: 'butt',
borderColor: undefined,
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: 'miter',
borderWidth: 1,
enabled: false,
margin: 5,
position: 'auto',
side: 5,
start: '50%',
},
color: 'black',
content: null,
display: true,
font: {
family: undefined,
lineHeight: undefined,
size: undefined,
style: undefined,
weight: undefined
},
height: undefined,
padding: 6,
position: 'center',
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
textAlign: 'center',
width: undefined,
xAdjust: 0,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
xValue: undefined,
yAdjust: 0,
yMax: undefined,
yMin: undefined,
yScaleID: 'y',
yValue: undefined
};
LabelAnnotation.defaultRoutes = {
borderColor: 'color'
};
function measureRect(point, size, options, padding) {
const width = size.width + padding.width + options.borderWidth;
const height = size.height + padding.height + options.borderWidth;
const position = toPosition(options.position);
return {
x: calculatePosition(point.x, width, options.xAdjust, position.x),
y: calculatePosition(point.y, height, options.yAdjust, position.y),
width,
height
};
}
function calculatePosition(start, size, adjust = 0, position) {
return start - getRelativePosition(size, position) + adjust;
}
function drawCallout(ctx, element) {
const {pointX, pointY, calloutPosition, options} = element;
if (!calloutPosition) {
return;
}
const callout = options.callout;
ctx.save();
ctx.beginPath();
const stroke = setBorderStyle(ctx, callout);
if (!stroke) {
return ctx.restore();
}
const {separatorStart, separatorEnd} = getCalloutSeparatorCoord(element, calloutPosition);
const {sideStart, sideEnd} = getCalloutSideCoord(element, calloutPosition, separatorStart);
if (callout.margin > 0 || options.borderWidth === 0) {
ctx.moveTo(separatorStart.x, separatorStart.y);
ctx.lineTo(separatorEnd.x, separatorEnd.y);
}
ctx.moveTo(sideStart.x, sideStart.y);
ctx.lineTo(sideEnd.x, sideEnd.y);
ctx.lineTo(pointX, pointY);
ctx.stroke();
ctx.restore();
}
function getCalloutSeparatorCoord(element, position) {
const {x, y, width, height} = element;
const adjust = getCalloutSeparatorAdjust(element, position);
let separatorStart, separatorEnd;
if (position === 'left' || position === 'right') {
separatorStart = {x: x + adjust, y};
separatorEnd = {x: separatorStart.x, y: separatorStart.y + height};
} else {
// position 'top' or 'bottom'
separatorStart = {x, y: y + adjust};
separatorEnd = {x: separatorStart.x + width, y: separatorStart.y};
}
return {separatorStart, separatorEnd};
}
function getCalloutSeparatorAdjust(element, position) {
const {width, height, options} = element;
const adjust = options.callout.margin + options.borderWidth / 2;
if (position === 'right') {
return width + adjust;
} else if (position === 'bottom') {
return height + adjust;
}
return -adjust;
}
function getCalloutSideCoord(element, position, separatorStart) {
const {y, width, height, options} = element;
const start = options.callout.start;
const side = getCalloutSideAdjust(position, options.callout);
let sideStart, sideEnd;
if (position === 'left' || position === 'right') {
sideStart = {x: separatorStart.x, y: y + getSize(height, start)};
sideEnd = {x: sideStart.x + side, y: sideStart.y};
} else {
// position 'top' or 'bottom'
sideStart = {x: separatorStart.x + getSize(width, start), y: separatorStart.y};
sideEnd = {x: sideStart.x, y: sideStart.y + side};
}
return {sideStart, sideEnd};
}
function getCalloutSideAdjust(position, options) {
const side = options.side;
if (position === 'left' || position === 'top') {
return -side;
}
return side;
}
function resolveCalloutPosition(element, options) {
const position = options.position;
if (position === 'left' || position === 'right' || position === 'top' || position === 'bottom') {
return position;
}
return resolveCalloutAutoPosition(element, options);
}
function resolveCalloutAutoPosition(element, options) {
const {x, y, width, height, pointX, pointY} = element;
const {margin, side} = options;
const adjust = margin + side;
if (pointX < (x - adjust)) {
return 'left';
} else if (pointX > (x + width + adjust)) {
return 'right';
} else if (pointY < (y - adjust)) {
return 'top';
} else if (pointY > (y + height + adjust)) {
return 'bottom';
}
}
class PointAnnotation extends Element {
inRange(mouseX, mouseY, useFinalPosition) {
const {width} = this.getProps(['width'], useFinalPosition);
return inPointRange({x: mouseX, y: mouseY}, this.getCenterPoint(useFinalPosition), width / 2, this.options.borderWidth);
}
getCenterPoint(useFinalPosition) {
return getElementCenterPoint(this, useFinalPosition);
}
draw(ctx) {
const options = this.options;
const borderWidth = options.borderWidth;
if (options.radius < 0.1) {
return;
}
ctx.save();
ctx.fillStyle = options.backgroundColor;
setShadowStyle(ctx, options);
const stroke = setBorderStyle(ctx, options);
options.borderWidth = 0;
drawPoint(ctx, options, this.x, this.y);
if (stroke && !isImageOrCanvas(options.pointStyle)) {
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
}
ctx.restore();
options.borderWidth = borderWidth;
}
resolveElementProperties(chart, options) {
return resolvePointPosition(chart, options);
}
}
PointAnnotation.id = 'pointAnnotation';
PointAnnotation.defaults = {
adjustScaleRange: true,
backgroundShadowColor: 'transparent',
borderDash: [],
borderDashOffset: 0,
borderShadowColor: 'transparent',
borderWidth: 1,
display: true,
pointStyle: 'circle',
radius: 10,
rotation: 0,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
xAdjust: 0,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
xValue: undefined,
yAdjust: 0,
yMax: undefined,
yMin: undefined,
yScaleID: 'y',
yValue: undefined
};
PointAnnotation.defaultRoutes = {
borderColor: 'color',
backgroundColor: 'color'
};
class PolygonAnnotation extends Element {
inRange(mouseX, mouseY, useFinalPosition) {
return this.options.radius >= 0.1 && this.elements.length > 1 && pointIsInPolygon(this.elements, mouseX, mouseY, useFinalPosition);
}
getCenterPoint(useFinalPosition) {
return getElementCenterPoint(this, useFinalPosition);
}
draw(ctx) {
const {elements, options} = this;
ctx.save();
ctx.beginPath();
ctx.fillStyle = options.backgroundColor;
setShadowStyle(ctx, options);
const stroke = setBorderStyle(ctx, options);
let first = true;
for (const el of elements) {
if (first) {
ctx.moveTo(el.x, el.y);
first = false;
} else {
ctx.lineTo(el.x, el.y);
}
}
ctx.closePath();
ctx.fill();
// If no border, don't draw it
if (stroke) {
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
}
ctx.restore();
}
resolveElementProperties(chart, options) {
const {x, y, width, height} = resolvePointPosition(chart, options);
const {sides, radius, rotation, borderWidth} = options;
const halfBorder = borderWidth / 2;
const elements = [];
const angle = (2 * PI) / sides;
let rad = rotation * RAD_PER_DEG;
for (let i = 0; i < sides; i++, rad += angle) {
const sin = Math.sin(rad);
const cos = Math.cos(rad);
elements.push({
type: 'point',
optionScope: 'point',
properties: {
x: x + sin * radius,
y: y - cos * radius,
bX: x + sin * (radius + halfBorder),
bY: y - cos * (radius + halfBorder)
}
});
}
return {x, y, width, height, elements, initProperties: {x, y}};
}
}
PolygonAnnotation.id = 'polygonAnnotation';
PolygonAnnotation.defaults = {
adjustScaleRange: true,
backgroundShadowColor: 'transparent',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0,
borderJoinStyle: 'miter',
borderShadowColor: 'transparent',
borderWidth: 1,
display: true,
point: {
radius: 0
},
radius: 10,
rotation: 0,
shadowBlur: 0,
shadowOffsetX: 0,
shadowOffsetY: 0,
sides: 3,
xAdjust: 0,
xMax: undefined,
xMin: undefined,
xScaleID: 'x',
xValue: undefined,
yAdjust: 0,
yMax: undefined,
yMin: undefined,
yScaleID: 'y',
yValue: undefined
};
PolygonAnnotation.defaultRoutes = {
borderColor: 'color',
backgroundColor: 'color'
};
function pointIsInPolygon(points, x, y, useFinalPosition) {
let isInside = false;
let A = points[points.length - 1].getProps(['bX', 'bY'], useFinalPosition);
for (const point of points) {
const B = point.getProps(['bX', 'bY'], useFinalPosition);
if ((B.bY > y) !== (A.bY > y) && x < (A.bX - B.bX) * (y - B.bY) / (A.bY - B.bY) + B.bX) {
isInside = !isInside;
}
A = B;
}
return isInside;
}
const annotationTypes = {
box: BoxAnnotation,
ellipse: EllipseAnnotation,
label: LabelAnnotation,
line: LineAnnotation,
point: PointAnnotation,
polygon: PolygonAnnotation
};
/**
* Register fallback for annotation elements
* For example lineAnnotation options would be looked through:
* - the annotation object (options.plugins.annotation.annotations[id])
* - element options (options.elements.lineAnnotation)
* - element defaults (defaults.elements.lineAnnotation)
* - annotation plugin defaults (defaults.plugins.annotation, this is what we are registering here)
*/
Object.keys(annotationTypes).forEach(key => {
defaults.describe(`elements.${annotationTypes[key].id}`, {
_fallback: 'plugins.annotation'
});
});
var name = "chartjs-plugin-annotation";
var version = "1.3.1";
const chartStates = new Map();
var annotation = {
id: 'annotation',
version,
/* TODO: enable in v2
beforeRegister() {
requireVersion('chart.js', '3.7', Chart.version);
},
*/
afterRegister() {
Chart.register(annotationTypes);
// TODO: Remove this check, warning and workaround in v2
if (!requireVersion('chart.js', '3.7', Chart.version, false)) {
console.warn(`${name} has known issues with chart.js versions prior to 3.7, please consider upgrading.`);
// Workaround for https://github.com/chartjs/chartjs-plugin-annotation/issues/572
Chart.defaults.set('elements.lineAnnotation', {
callout: {},
font: {},
padding: 6
});
}
},
afterUnregister() {
Chart.unregister(annotationTypes);
},
beforeInit(chart) {
chartStates.set(chart, {
annotations: [],
elements: [],
visibleElements: [],
listeners: {},
listened: false,
moveListened: false
});
},
beforeUpdate(chart, args, options) {
const state = chartStates.get(chart);
const annotations = state.annotations = [];
let annotationOptions = options.annotations;
if (isObject(annotationOptions)) {
Object.keys(annotationOptions).forEach(key => {
const value = annotationOptions[key];
if (isObject(value)) {
value.id = key;
annotations.push(value);
}
});
} else if (isArray(annotationOptions)) {
annotations.push(...annotationOptions);
}
verifyScaleOptions(annotations, chart.scales);
},
afterDataLimits(chart, args) {
const state = chartStates.get(chart);
adjustScaleRange(chart, args.scale, state.annotations.filter(a => a.display && a.adjustScaleRange));
},
afterUpdate(chart, args, options) {
const state = chartStates.get(chart);
updateListeners(chart, state, options);
updateElements(chart, state, options, args.mode);
state.visibleElements = state.elements.filter(el => !el.skip && el.options.display);
},
beforeDatasetsDraw(chart, _args, options) {
draw(chart, 'beforeDatasetsDraw', options.clip);
},
afterDatasetsDraw(chart, _args, options) {
draw(chart, 'afterDatasetsDraw', options.clip);
},
beforeDraw(chart, _args, options) {
draw(chart, 'beforeDraw', options.clip);
},
afterDraw(chart, _args, options) {
draw(chart, 'afterDraw', options.clip);
},
beforeEvent(chart, args, options) {
const state = chartStates.get(chart);
handleEvent(state, args.event, options);
},
destroy(chart) {
chartStates.delete(chart);
},
_getState(chart) {
return chartStates.get(chart);
},
defaults: {
animations: {
numbers: {
properties: ['x', 'y', 'x2', 'y2', 'width', 'height', 'pointX', 'pointY', 'labelX', 'labelY', 'labelWidth', 'labelHeight', 'radius'],
type: 'number'
},
},
clip: true,
dblClickSpeed: 350, // ms
drawTime: 'afterDatasetsDraw',
label: {
drawTime: null
}
},
descriptors: {
_indexable: false,
_scriptable: (prop) => !hooks.includes(prop),
annotations: {
_allKeys: false,
_fallback: (prop, opts) => `elements.${annotationTypes[resolveType(opts.type)].id}`,
},
},
additionalOptionScopes: ['']
};
const directUpdater = {
update: Object.assign
};
function resolveAnimations(chart, animOpts, mode) {
if (mode === 'reset' || mode === 'none' || mode === 'resize') {
return directUpdater;
}
return new Animations(chart, animOpts);
}
function resolveType(type = 'line') {
if (annotationTypes[type]) {
return type;
}
console.warn(`Unknown annotation type: '${type}', defaulting to 'line'`);
return 'line';
}
function updateElements(chart, state, options, mode) {
const animations = resolveAnimations(chart, options.animations, mode);
const annotations = state.annotations;
const elements = resyncElements(state.elements, annotations);
for (let i = 0; i < annotations.length; i++) {
const annotationOptions = annotations[i];
const element = getOrCreateElement(elements, i, annotationOptions.type);
const resolver = annotationOptions.setContext(getContext(chart, element, annotationOptions));
const properties = element.resolveElementProperties(chart, resolver);
properties.skip = isNaN(properties.x) || isNaN(properties.y);
if ('elements' in properties) {
updateSubElements(element, properties, resolver, animations);
// Remove the sub-element definitions from properties, so the actual elements
// are not overwritten by their definitions
delete properties.elements;
}
if (!defined(element.x)) {
// If the element is newly created, assing the properties directly - to
// make them readily awailable to any scriptable options. If we do not do this,
// the properties retruned by `resolveElementProperties` are available only
// after options resolution.
Object.assign(element, properties);
}
properties.options = resolveAnnotationOptions(resolver);
animations.update(element, properties);
}
}
function updateSubElements(mainElement, {elements, initProperties}, resolver, animations) {
const subElements = mainElement.elements || (mainElement.elements = []);
subElements.length = elements.length;
for (let i = 0; i < elements.length; i++) {
const definition = elements[i];
const properties = definition.properties;
const subElement = getOrCreateElement(subElements, i, definition.type, initProperties);
const subResolver = resolver[definition.optionScope].override(definition);
properties.options = resolveAnnotationOptions(subResolver);
animations.update(subElement, properties);
}
}
function getOrCreateElement(elements, index, type, initProperties) {
const elementClass = annotationTypes[resolveType(type)];
let element = elements[index];
if (!element || !(element instanceof elementClass)) {
element = elements[index] = new elementClass();
if (isObject(initProperties)) {
Object.assign(element, initProperties);
}
}
return element;
}
function resolveAnnotationOptions(resolver) {
const elementClass = annotationTypes[resolveType(resolver.type)];
const result = {};
result.id = resolver.id;
result.type = resolver.type;
result.drawTime = resolver.drawTime;
Object.assign(result,
resolveObj(resolver, elementClass.defaults),
resolveObj(resolver, elementClass.defaultRoutes));
for (const hook of hooks) {
result[hook] = resolver[hook];
}
return result;
}
function resolveObj(resolver, defs) {
const result = {};
for (const prop of Object.keys(defs)) {
const optDefs = defs[prop];
const value = resolver[prop];
result[prop] = isObject(optDefs) ? resolveObj(value, optDefs) : value;
}
return result;
}
function getContext(chart, element, annotation) {
return element.$context || (element.$context = Object.assign(Object.create(chart.getContext()), {
element,
id: annotation.id,
type: 'annotation'
}));
}
function resyncElements(elements, annotations) {
const count = annotations.length;
const start = elements.length;
if (start < count) {
const add = count - start;
elements.splice(start, 0, ...new Array(add));
} else if (start > count) {
elements.splice(count, start - count);
}
return elements;
}
function draw(chart, caller, clip) {
const {ctx, chartArea} = chart;
const {visibleElements} = chartStates.get(chart);
if (clip) {
clipArea(ctx, chartArea);
}
drawElements(ctx, visibleElements, caller);
drawSubElements(ctx, visibleElements, caller);
if (clip) {
unclipArea(ctx);
}
visibleElements.forEach(el => {
if (!('drawLabel' in el)) {
return;
}
const label = el.options.label;
if (label && label.enabled && label.content && (label.drawTime || el.options.drawTime) === caller) {
el.drawLabel(ctx, chartArea);
}
});
}
function drawElements(ctx, elements, caller) {
for (const el of elements) {
if (el.options.drawTime === caller) {
el.draw(ctx);
}
}
}
function drawSubElements(ctx, elements, caller) {
for (const el of elements) {
if (isArray(el.elements)) {
drawElements(ctx, el.elements, caller);
}
}
}
export { annotation as default };
| cdnjs/cdnjs | ajax/libs/chartjs-plugin-annotation/1.3.1/chartjs-plugin-annotation.esm.js | JavaScript | mit | 57,862 |
/**
* @license Highstock JS v8.0.2 (2020-03-03)
*
* Indicator series type for Highstock
*
* (c) 2010-2019 Paweł Fus
*
* 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/bollinger-bands', ['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, 'mixins/multipe-lines.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) {
/**
*
* (c) 2010-2020 Wojciech Chmiel
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var defined = U.defined,
error = U.error,
merge = U.merge;
var each = H.each,
SMA = H.seriesTypes.sma;
/**
* Mixin useful for all indicators that have more than one line.
* Merge it with your implementation where you will provide
* getValues method appropriate to your indicator and pointArrayMap,
* pointValKey, linesApiNames properites. Notice that pointArrayMap
* should be consistent with amount of lines calculated in getValues method.
*
* @private
* @mixin multipleLinesMixin
*/
var multipleLinesMixin = {
/* eslint-disable valid-jsdoc */
/**
* Lines ids. Required to plot appropriate amount of lines.
* Notice that pointArrayMap should have more elements than
* linesApiNames, because it contains main line and additional lines ids.
* Also it should be consistent with amount of lines calculated in
* getValues method from your implementation.
*
* @private
* @name multipleLinesMixin.pointArrayMap
* @type {Array<string>}
*/
pointArrayMap: ['top', 'bottom'],
/**
* Main line id.
*
* @private
* @name multipleLinesMixin.pointValKey
* @type {string}
*/
pointValKey: 'top',
/**
* Additional lines DOCS names. Elements of linesApiNames array should
* be consistent with DOCS line names defined in your implementation.
* Notice that linesApiNames should have decreased amount of elements
* relative to pointArrayMap (without pointValKey).
*
* @private
* @name multipleLinesMixin.linesApiNames
* @type {Array<string>}
*/
linesApiNames: ['bottomLine'],
/**
* Create translatedLines Collection based on pointArrayMap.
*
* @private
* @function multipleLinesMixin.getTranslatedLinesNames
* @param {string} [excludedValue]
* Main line id
* @return {Array<string>}
* Returns translated lines names without excluded value.
*/
getTranslatedLinesNames: function (excludedValue) {
var translatedLines = [];
each(this.pointArrayMap, function (propertyName) {
if (propertyName !== excludedValue) {
translatedLines.push('plot' +
propertyName.charAt(0).toUpperCase() +
propertyName.slice(1));
}
});
return translatedLines;
},
/**
* @private
* @function multipleLinesMixin.toYData
* @param {Highcharts.Point} point
* Indicator point
* @return {Array<number>}
* Returns point Y value for all lines
*/
toYData: function (point) {
var pointColl = [];
each(this.pointArrayMap, function (propertyName) {
pointColl.push(point[propertyName]);
});
return pointColl;
},
/**
* Add lines plot pixel values.
*
* @private
* @function multipleLinesMixin.translate
* @return {void}
*/
translate: function () {
var indicator = this,
pointArrayMap = indicator.pointArrayMap,
LinesNames = [],
value;
LinesNames = indicator.getTranslatedLinesNames();
SMA.prototype.translate.apply(indicator, arguments);
each(indicator.points, function (point) {
each(pointArrayMap, function (propertyName, i) {
value = point[propertyName];
if (value !== null) {
point[LinesNames[i]] = indicator.yAxis.toPixels(value, true);
}
});
});
},
/**
* Draw main and additional lines.
*
* @private
* @function multipleLinesMixin.drawGraph
* @return {void}
*/
drawGraph: function () {
var indicator = this,
pointValKey = indicator.pointValKey,
linesApiNames = indicator.linesApiNames,
mainLinePoints = indicator.points,
pointsLength = mainLinePoints.length,
mainLineOptions = indicator.options,
mainLinePath = indicator.graph,
gappedExtend = {
options: {
gapSize: mainLineOptions.gapSize
}
},
// additional lines point place holders:
secondaryLines = [],
secondaryLinesNames = indicator.getTranslatedLinesNames(pointValKey),
point;
// Generate points for additional lines:
each(secondaryLinesNames, function (plotLine, index) {
// create additional lines point place holders
secondaryLines[index] = [];
while (pointsLength--) {
point = mainLinePoints[pointsLength];
secondaryLines[index].push({
x: point.x,
plotX: point.plotX,
plotY: point[plotLine],
isNull: !defined(point[plotLine])
});
}
pointsLength = mainLinePoints.length;
});
// Modify options and generate additional lines:
each(linesApiNames, function (lineName, i) {
if (secondaryLines[i]) {
indicator.points = secondaryLines[i];
if (mainLineOptions[lineName]) {
indicator.options = merge(mainLineOptions[lineName].styles, gappedExtend);
}
else {
error('Error: "There is no ' + lineName +
' in DOCS options declared. Check if linesApiNames' +
' are consistent with your DOCS line names."' +
' at mixin/multiple-line.js:34');
}
indicator.graph = indicator['graph' + lineName];
SMA.prototype.drawGraph.call(indicator);
// Now save lines:
indicator['graph' + lineName] = indicator.graph;
}
else {
error('Error: "' + lineName + ' doesn\'t have equivalent ' +
'in pointArrayMap. To many elements in linesApiNames ' +
'relative to pointArrayMap."');
}
});
// Restore options and draw a main line:
indicator.points = mainLinePoints;
indicator.options = mainLineOptions;
indicator.graph = mainLinePath;
SMA.prototype.drawGraph.call(indicator);
}
};
return multipleLinesMixin;
});
_registerModule(_modules, 'indicators/bollinger-bands.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js'], _modules['mixins/multipe-lines.js']], function (H, U, multipleLinesMixin) {
/**
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
var isArray = U.isArray,
merge = U.merge,
seriesType = U.seriesType;
var SMA = H.seriesTypes.sma;
/* eslint-disable valid-jsdoc */
// Utils:
/**
* @private
*/
function getStandardDeviation(arr, index, isOHLC, mean) {
var variance = 0,
arrLen = arr.length,
std = 0,
i = 0,
value;
for (; i < arrLen; i++) {
value = (isOHLC ? arr[i][index] : arr[i]) - mean;
variance += value * value;
}
variance = variance / (arrLen - 1);
std = Math.sqrt(variance);
return std;
}
/* eslint-enable valid-jsdoc */
/**
* Bollinger Bands series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.bb
*
* @augments Highcharts.Series
*/
seriesType('bb', 'sma',
/**
* Bollinger bands (BB). This series requires the `linkedTo` option to be
* set and should be loaded after the `stock/indicators/indicators.js` file.
*
* @sample stock/indicators/bollinger-bands
* Bollinger bands
*
* @extends plotOptions.sma
* @since 6.0.0
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/bollinger-bands
* @optionparent plotOptions.bb
*/
{
params: {
period: 20,
/**
* Standard deviation for top and bottom bands.
*/
standardDeviation: 2,
index: 3
},
/**
* Bottom line options.
*/
bottomLine: {
/**
* Styles for a bottom line.
*/
styles: {
/**
* Pixel width of the line.
*/
lineWidth: 1,
/**
* Color of the line. If not set, it's inherited from
* [plotOptions.bb.color](#plotOptions.bb.color).
*
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
/**
* Top line options.
*
* @extends plotOptions.bb.bottomLine
*/
topLine: {
styles: {
lineWidth: 1,
/**
* @type {Highcharts.ColorString}
*/
lineColor: void 0
}
},
tooltip: {
pointFormat: '<span style="color:{point.color}">\u25CF</span><b> {series.name}</b><br/>Top: {point.top}<br/>Middle: {point.middle}<br/>Bottom: {point.bottom}<br/>'
},
marker: {
enabled: false
},
dataGrouping: {
approximation: 'averages'
}
},
/**
* @lends Highcharts.Series#
*/
merge(multipleLinesMixin, {
pointArrayMap: ['top', 'middle', 'bottom'],
pointValKey: 'middle',
nameComponents: ['period', 'standardDeviation'],
linesApiNames: ['topLine', 'bottomLine'],
init: function () {
SMA.prototype.init.apply(this, arguments);
// Set default color for lines:
this.options = merge({
topLine: {
styles: {
lineColor: this.color
}
},
bottomLine: {
styles: {
lineColor: this.color
}
}
}, this.options);
},
getValues: function (series, params) {
var period = params.period,
standardDeviation = params.standardDeviation,
xVal = series.xData,
yVal = series.yData,
yValLen = yVal ? yVal.length : 0,
// 0- date, 1-middle line, 2-top line, 3-bottom line
BB = [],
// middle line, top line and bottom line
ML,
TL,
BL,
date,
xData = [],
yData = [],
slicedX,
slicedY,
stdDev,
isOHLC,
point,
i;
if (xVal.length < period) {
return;
}
isOHLC = isArray(yVal[0]);
for (i = period; i <= yValLen; i++) {
slicedX = xVal.slice(i - period, i);
slicedY = yVal.slice(i - period, i);
point = SMA.prototype.getValues.call(this, {
xData: slicedX,
yData: slicedY
}, params);
date = point.xData[0];
ML = point.yData[0];
stdDev = getStandardDeviation(slicedY, params.index, isOHLC, ML);
TL = ML + standardDeviation * stdDev;
BL = ML - standardDeviation * stdDev;
BB.push([date, TL, ML, BL]);
xData.push(date);
yData.push([TL, ML, BL]);
}
return {
values: BB,
xData: xData,
yData: yData
};
}
}));
/**
* A bollinger bands indicator. If the [type](#series.bb.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.bb
* @since 6.0.0
* @excluding dataParser, dataURL
* @product highstock
* @requires stock/indicators/indicators
* @requires stock/indicators/bollinger-bands
* @apioption series.bb
*/
''; // to include the above in the js output
});
_registerModule(_modules, 'masters/indicators/bollinger-bands.src.js', [], function () {
});
})); | cdnjs/cdnjs | ajax/libs/highcharts/8.0.2/indicators/bollinger-bands.src.js | JavaScript | mit | 16,410 |
wcn.view.view = (function() {
var views = {};
class view extends whitecrow.control {
initialize() {
super.initialize();
}
static register(name,layoutName){
if(!views[name]){
views[name] = this;
this.layoutName = layoutName;
return this;
}
else
throw new Error("View with the name '"+name+"' is already registered");
}
static resolve(name){
return views[name];
}
}
return view;
})();
| kanaxz/video-station | project/lib/whitecrow/namespace/view/view.js | JavaScript | cc0-1.0 | 473 |
jsonp({"cep":"57035390","logradouro":"Rua Jos\u00e9 J\u00falio Sawer","bairro":"Ponta Verde","cidade":"Macei\u00f3","uf":"AL","estado":"Alagoas"});
| lfreneda/cepdb | api/v1/57035390.jsonp.js | JavaScript | cc0-1.0 | 148 |
jsonp({"cep":"13218872","logradouro":"Travessa Deolinda Navile Fontebasso","bairro":"Roseira","cidade":"Jundia\u00ed","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/13218872.jsonp.js | JavaScript | cc0-1.0 | 157 |
jsonp({"cep":"90250148","logradouro":"Beco Um A","bairro":"Humait\u00e1","cidade":"Porto Alegre","uf":"RS","estado":"Rio Grande do Sul"});
| lfreneda/cepdb | api/v1/90250148.jsonp.js | JavaScript | cc0-1.0 | 139 |
jsonp({"cep":"64064280","logradouro":"Rua Vereador Albino Alencar","bairro":"Zoobot\u00e2nico","cidade":"Teresina","uf":"PI","estado":"Piau\u00ed"});
| lfreneda/cepdb | api/v1/64064280.jsonp.js | JavaScript | cc0-1.0 | 150 |
jsonp({"cep":"87505510","logradouro":"Rua Tim\u00f3teo Polo Gimenis","bairro":"Jardim Imperial I","cidade":"Umuarama","uf":"PR","estado":"Paran\u00e1"});
| lfreneda/cepdb | api/v1/87505510.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"13056344","logradouro":"Rua Ant\u00f4nio Nunes","bairro":"Dic I (Conjunto Habitacional Monsenhor Luiz Fernando Abreu)","cidade":"Campinas","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/13056344.jsonp.js | JavaScript | cc0-1.0 | 192 |
jsonp({"cep":"93520150","logradouro":"Rua S\u00e3o Carlos","bairro":"Guarani","cidade":"Novo Hamburgo","uf":"RS","estado":"Rio Grande do Sul"});
| lfreneda/cepdb | api/v1/93520150.jsonp.js | JavaScript | cc0-1.0 | 145 |
jsonp({"cep":"66040640","logradouro":"Vila Silva","bairro":"Crema\u00e7\u00e3o","cidade":"Bel\u00e9m","uf":"PA","estado":"Par\u00e1"});
| lfreneda/cepdb | api/v1/66040640.jsonp.js | JavaScript | cc0-1.0 | 136 |
jsonp({"cep":"38445212","logradouro":"Travessa Vinte e Seis","bairro":"Sibipiruna","cidade":"Araguari","uf":"MG","estado":"Minas Gerais"});
| lfreneda/cepdb | api/v1/38445212.jsonp.js | JavaScript | cc0-1.0 | 140 |
jsonp({"cep":"56325690","logradouro":"Rua Equador","bairro":"Top\u00e1zio","cidade":"Petrolina","uf":"PE","estado":"Pernambuco"});
| lfreneda/cepdb | api/v1/56325690.jsonp.js | JavaScript | cc0-1.0 | 131 |
jsonp({"cep":"24933530","logradouro":"Rua Manoel Camilo da Silva","bairro":"Jardim Atl\u00e2ntico Leste (Itaipua\u00e7u)","cidade":"Maric\u00e1","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/24933530.jsonp.js | JavaScript | cc0-1.0 | 184 |
jsonp({"cep":"65635468","logradouro":"Avenida Luis Firmino de Sousa","bairro":"Mutir\u00e3o","cidade":"Timon","uf":"MA","estado":"Maranh\u00e3o"});
| lfreneda/cepdb | api/v1/65635468.jsonp.js | JavaScript | cc0-1.0 | 148 |
jsonp({"cep":"03985140","logradouro":"Rua Hermilo Alves","bairro":"Jardim \u00c2ngela (Zona Leste)","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/03985140.jsonp.js | JavaScript | cc0-1.0 | 165 |
jsonp({"cep":"45077400","logradouro":"Rua Dezesseis","bairro":"Zabel\u00ea","cidade":"Vit\u00f3ria da Conquista","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/45077400.jsonp.js | JavaScript | cc0-1.0 | 143 |
jsonp({"cep":"29176599","logradouro":"Rua Leonor Miguel Feu Rosa","bairro":"Palmeiras","cidade":"Serra","uf":"ES","estado":"Esp\u00edrito Santo"});
| lfreneda/cepdb | api/v1/29176599.jsonp.js | JavaScript | cc0-1.0 | 148 |
jsonp({"cep":"65068639","logradouro":"Rua S\u00e3o Jos\u00e9","bairro":"Vila Luiz\u00e3o","cidade":"S\u00e3o Lu\u00eds","uf":"MA","estado":"Maranh\u00e3o"});
| lfreneda/cepdb | api/v1/65068639.jsonp.js | JavaScript | cc0-1.0 | 158 |
jsonp({"cep":"02277010","logradouro":"Rua C\u00e2ndido Freire","bairro":"Vila Nilo","cidade":"S\u00e3o Paulo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/02277010.jsonp.js | JavaScript | cc0-1.0 | 149 |
jsonp({"cep":"09764340","logradouro":"Passagem Padre \u00c2ngelo","bairro":"Nova Baeta","cidade":"S\u00e3o Bernardo do Campo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/09764340.jsonp.js | JavaScript | cc0-1.0 | 165 |
jsonp({"cep":"69316464","logradouro":"Rua HC-05","bairro":"Senador H\u00e9lio Campos","cidade":"Boa Vista","uf":"RR","estado":"Roraima"});
| lfreneda/cepdb | api/v1/69316464.jsonp.js | JavaScript | cc0-1.0 | 139 |
jsonp({"cep":"58300490","logradouro":"Rua Frei Martinho","bairro":"Liberdade","cidade":"Santa Rita","uf":"PB","estado":"Para\u00edba"});
| lfreneda/cepdb | api/v1/58300490.jsonp.js | JavaScript | cc0-1.0 | 137 |
jsonp({"cep":"41510856","logradouro":"1\u00aa Travessa Adutora","bairro":"S\u00e3o Crist\u00f3v\u00e3o","cidade":"Salvador","uf":"BA","estado":"Bahia"});
| lfreneda/cepdb | api/v1/41510856.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"09790490","logradouro":"Rua Augusto D\u00e1rio Tonizza","bairro":"Ferraz\u00f3polis","cidade":"S\u00e3o Bernardo do Campo","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/09790490.jsonp.js | JavaScript | cc0-1.0 | 176 |
jsonp({"cep":"60337240","logradouro":"Vila Amaraji","bairro":"\u00c1lvaro Weyne","cidade":"Fortaleza","uf":"CE","estado":"Cear\u00e1"});
| lfreneda/cepdb | api/v1/60337240.jsonp.js | JavaScript | cc0-1.0 | 137 |
jsonp({"cep":"13339320","logradouro":"Rua Itu","bairro":"Vila Furlan","cidade":"Indaiatuba","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/13339320.jsonp.js | JavaScript | cc0-1.0 | 131 |
jsonp({"cep":"16022034","logradouro":"Rua Gentil Mazarin","bairro":"Morada dos Nobres","cidade":"Ara\u00e7atuba","uf":"SP","estado":"S\u00e3o Paulo"});
| lfreneda/cepdb | api/v1/16022034.jsonp.js | JavaScript | cc0-1.0 | 152 |
jsonp({"cep":"70043900","logradouro":"Esplanada dos Minist\u00e9rios","bairro":"Zona C\u00edvico-Administrativa","cidade":"Bras\u00edlia","uf":"DF","estado":"Distrito Federal"});
| lfreneda/cepdb | api/v1/70043900.jsonp.js | JavaScript | cc0-1.0 | 179 |
jsonp({"cep":"68627494","logradouro":"Avenida Pasteur","bairro":"La\u00e9rcio Cabeline","cidade":"Paragominas","uf":"PA","estado":"Par\u00e1"});
| lfreneda/cepdb | api/v1/68627494.jsonp.js | JavaScript | cc0-1.0 | 145 |
jsonp({"cep":"69318040","logradouro":"Rua CC-09","bairro":"Senador H\u00e9lio Campos","cidade":"Boa Vista","uf":"RR","estado":"Roraima"});
| lfreneda/cepdb | api/v1/69318040.jsonp.js | JavaScript | cc0-1.0 | 139 |
jsonp({"cep":"23016030","logradouro":"Pra\u00e7a Catulle Mendes","bairro":"Campo Grande","cidade":"Rio de Janeiro","uf":"RJ","estado":"Rio de Janeiro"});
| lfreneda/cepdb | api/v1/23016030.jsonp.js | JavaScript | cc0-1.0 | 154 |
jsonp({"cep":"77815060","logradouro":"Rua 66","bairro":"Loteamento Nova Aragua\u00edna","cidade":"Aragua\u00edna","uf":"TO","estado":"Tocantins"});
| lfreneda/cepdb | api/v1/77815060.jsonp.js | JavaScript | cc0-1.0 | 148 |
Subsets and Splits