code
stringlengths 2
1.05M
|
---|
var test = require('tape');
var watchify = require('../');
var browserify = require('browserify');
var vm = require('vm');
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var os = require('os');
var tmpdir = path.join((os.tmpdir || os.tmpDir)(), 'watchify-' + Math.random());
var files = {
main: path.join(tmpdir, 'main.js'),
beep: path.join(tmpdir, 'beep.js'),
boop: path.join(tmpdir, 'boop.js'),
abc: path.join(tmpdir, 'lib', 'abc.js'),
xyz: path.join(tmpdir, 'lib', 'xyz.js')
};
mkdirp.sync(tmpdir);
mkdirp.sync(path.join(tmpdir, 'lib'));
fs.writeFileSync(files.main, [
'var abc = require("abc");',
'var xyz = require("xyz");',
'var beep = require("./beep");',
'console.log(abc + " " + xyz + " " + beep);'
].join('\n'));
fs.writeFileSync(files.beep, 'module.exports = require("./boop");');
fs.writeFileSync(files.boop, 'module.exports = require("xyz");');
fs.writeFileSync(files.abc, 'module.exports = "abc";');
fs.writeFileSync(files.xyz, 'module.exports = "xyz";');
test('properly caches exposed files', function (t) {
t.plan(4);
var cache = {};
var w = watchify(browserify({
entries: [files.main],
basedir: tmpdir,
cache: cache,
packageCache: {}
}));
w.require('./lib/abc', {expose: 'abc'});
w.require('./lib/xyz', {expose: 'xyz'});
w.on('update', function () {
w.bundle(function (err, src) {
t.ifError(err);
t.equal(run(src), 'ABC XYZ XYZ\n');
w.close();
});
});
w.bundle(function (err, src) {
t.ifError(err);
t.equal(run(src), 'abc xyz xyz\n');
setTimeout(function () {
// If we're incorrectly caching exposed files,
// then "files.abc" would be re-read from disk.
cache[files.abc].source = 'module.exports = "ABC";';
fs.writeFileSync(files.xyz, 'module.exports = "XYZ";');
}, 1000);
});
});
function run (src) {
var output = '';
function log (msg) { output += msg + '\n' }
vm.runInNewContext(src, { console: { log: log } });
return output;
}
|
YUI.add('datatable-body', function(Y) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object,
ClassNameManager = Y.ClassNameManager,
_getClassName = ClassNameManager.getClassName;
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or ammended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {HTML}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation after
setting up the `_cssPrefix` for the instance.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation after
setting up the `_cssPrefix` for the instance.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {HTML}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `source` property of
the configuration object passed to the constructor.
@property source
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//source: null,
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.taregt, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.get('container'),
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (Y.instanceOf(seed, Y.Node)) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
// TODO this should be a static object map
switch (shift) {
case 'above' : shift = [-1, 0]; break;
case 'below' : shift = [1, 0]; break;
case 'next' : shift = [0, 1]; break;
case 'previous': shift = [0, -1]; break;
}
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Builds a CSS class name from the provided tokens. If the instance is
created with `cssPrefix` or `source` in the configuration, it will use this
prefix (the `_cssPrefix` of the `source` object) as the base token. This
allows class instances to generate markup with class names that correspond
to the parent class that is consuming them.
@method getClassName
@param {String} token* Any number of tokens to include in the class name
@return {String} The generated class name
@since 3.5.0
**/
getClassName: function () {
var args = toArray(arguments);
args.unshift(this._cssPrefix);
args.push(true);
return _getClassName.apply(ClassNameManager, args);
},
/**
Returns the Model associated to the record `id`, `clientId`, or index (not
row index). If a DOM element id or Node for a table row or child of a row
is passed, that will work, too.
If no Model can be found, `null` is returned.
@method getRecord
@param {Number|String|Node} seed Record `id`, `clientId`, index, Node, or
identifier for a row or child element
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.get('container'),
row = null,
record;
if (tbody) {
if (isString(seed)) {
if (!record) {
seed = tbody.one('#' + seed);
}
}
if (Y.instanceOf(seed, Y.Node)) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.get('container') || null;
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
return tbody &&
Y.one(isNumber(id) ? tbody.get('children').item(id) : '#' + id);
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` property and `modelList` attribute.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` property (see
`_createRowTemplate`)
2. An HTML string is built up by concatening the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@return {BodyView} The instance
@chainable
@since 3.5.0
**/
render: function () {
var tbody = this.get('container'),
data = this.get('modelList'),
columns = this.columns;
// Needed for mutation
this._createRowTemplate(columns);
if (tbody && data) {
tbody.setContent(this._createDataHTML(columns));
this._applyNodeFormatters(tbody, columns);
}
this.bindUI();
return this;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function (e) {
this.columns = this._parseColumns(e.newVal);
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
// Baseline view will just rerender the tbody entirely
this.render();
},
/**
Reacts to a change in the instance's `modelList` attribute by breaking
down the bubbling relationship with the previous `modelList` and setting up
that relationship with the new one.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.5.0
**/
_afterModelListChange: function (e) {
var old = e.prevVal,
now = e.newVal;
if (old && old.removeTarget) {
old.removeTarget(this);
}
if (now && now.addTarget(this)) {
now.addTarget(this);
}
this._idMap = {};
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} columns The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, columns) {
var source = this.source,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = columns.length; i < len; ++i) {
if (columns[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = columns[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(source,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the source (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles;
if (this.source && !handles.columnsChange) {
handles.columnsChange = this.source.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (!handles.dataChange) {
handles.dataChange = this.after(
['modelListChange', '*:change', '*:add', '*:remove', '*:reset'],
bind('_afterDataChange', this));
}
},
/**
The base token for classes created with the `getClassName` method.
@property _cssPrefix
@type {String}
@default 'yui3-table'
@protected
@since 3.5.0
**/
_cssPrefix: ClassNameManager.getClassName('table'),
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} columns The column configurations to customize the
generated cell content or class names
@return {HTML} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (columns) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@return {HTML} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
source = this.source || this,
columns = this.columns,
i, len, col, token, value, formatterData;
for (i = 0, len = columns.length; i < len; ++i) {
col = columns[i];
value = data[col.key];
token = col._id;
values[token + '-className'] = '';
if (col.formatter) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
if (typeof col.formatter === 'string') {
if (value !== undefined) {
// TODO: look for known formatters by string name
value = fromTemplate(col.formatter, formatterData);
}
} else {
// Formatters can either return a value
value = col.formatter.call(source, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
}
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
}
return fromTemplate(this._rowTemplate, values);
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} columns Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (columns) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues;
for (i = 0, len = columns.length; i < len; ++i) {
col = columns[i];
key = col.key;
token = col._id;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
// will unbind the bubble relationship and clear the table if necessary
this.set('modelList', null);
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `cssPrefix` - The base string for classes generated by `getClassName`
* `source` - The object to serve as source of truth for column info
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
var cssPrefix = config.cssPrefix || (config.source || {}).cssPrefix,
modelList = this.get('modelList');
this.source = config.source;
this.columns = this._parseColumns(config.columns);
this._eventHandles = {};
this._idMap = {};
if (cssPrefix) {
this._cssPrefix = cssPrefix;
}
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
this.after('modelListChange', bind('_afterModelListChange', this));
if (modelList && modelList.addTarget) {
modelList.addTarget(this);
}
},
/**
Flattens an array of potentially nested column configurations into a single
depth array of data columns. Columns that have children are disregarded in
favor of searching their child columns. The resulting array corresponds 1:1
with columns that will contain data in the `<tbody>`.
@method _parseColumns
@param {Object[]} data Array of unfiltered column configuration objects
@param {Object[]} columns Working array of data columns. Used for recursion.
@return {Object[]} Only those columns that will be rendered.
@protected
@since 3.5.0
**/
_parseColumns: function (data, columns) {
var col, i, len;
columns || (columns = []);
if (isArray(data) && data.length) {
for (i = 0, len = data.length; i < len; ++i) {
col = data[i];
if (typeof col === 'string') {
col = { key: col };
}
if (col.key || col.formatter || col.nodeFormatter) {
col.index = columns.length;
columns.push(col);
} else if (col.children) {
this._parseColumns(col.children, columns);
}
}
}
return columns;
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {HTML}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
}, {
ATTRS: {
modelList: {
setter: '_setModelList'
}
}
});
}, '@VERSION@' ,{requires:['datatable-core', 'view', 'classnamemanager']});
|
/**
* Parse JavaScript SDK v1.10.1
*
* The source tree of this library can be found at
* https://github.com/ParsePlatform/Parse-SDK-JS
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Parse = f()}})(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(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.track = track;
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Parse.Analytics provides an interface to Parse's logging and analytics
* backend.
*
* @class Parse.Analytics
* @static
*/
/**
* Tracks the occurrence of a custom event with additional dimensions.
* Parse will store a data point at the time of invocation with the given
* event name.
*
* Dimensions will allow segmentation of the occurrences of this custom
* event. Keys and values should be {@code String}s, and will throw
* otherwise.
*
* To track a user signup along with additional metadata, consider the
* following:
* <pre>
* var dimensions = {
* gender: 'm',
* source: 'web',
* dayType: 'weekend'
* };
* Parse.Analytics.track('signup', dimensions);
* </pre>
*
* There is a default limit of 8 dimensions per event tracked.
*
* @method track
* @param {String} name The name of the custom event to report to Parse as
* having happened.
* @param {Object} dimensions The dictionary of information by which to
* segment this event.
* @param {Object} options A Backbone-style callback object.
* @return {Parse.Promise} A promise that is resolved when the round-trip
* to the server completes.
*/
function track(name, dimensions, options) {
name = name || '';
name = name.replace(/^\s*/, '');
name = name.replace(/\s*$/, '');
if (name.length === 0) {
throw new TypeError('A name for the custom event must be provided');
}
for (var key in dimensions) {
if (typeof key !== 'string' || typeof dimensions[key] !== 'string') {
throw new TypeError('track() dimensions expects keys and values of type "string".');
}
}
options = options || {};
return _CoreManager2.default.getAnalyticsController().track(name, dimensions)._thenRunCallbacks(options);
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var DefaultController = {
track: function (name, dimensions) {
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('POST', 'events/' + name, { dimensions: dimensions });
}
};
_CoreManager2.default.setAnalyticsController(DefaultController);
},{"./CoreManager":3}],2:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.run = run;
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _decode = _dereq_('./decode');
var _decode2 = _interopRequireDefault(_decode);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Contains functions for calling and declaring
* <a href="/docs/cloud_code_guide#functions">cloud functions</a>.
* <p><strong><em>
* Some functions are only available from Cloud Code.
* </em></strong></p>
*
* @class Parse.Cloud
* @static
*/
/**
* Makes a call to a cloud function.
* @method run
* @param {String} name The function name.
* @param {Object} data The parameters to send to the cloud function.
* @param {Object} options A Backbone-style options object
* options.success, if set, should be a function to handle a successful
* call to a cloud function. options.error should be a function that
* handles an error running the cloud function. Both functions are
* optional. Both functions take a single argument.
* @return {Parse.Promise} A promise that will be resolved with the result
* of the function.
*/
function run(name, data, options) {
options = options || {};
if (typeof name !== 'string' || name.length === 0) {
throw new TypeError('Cloud function name must be a string.');
}
var requestOptions = {};
if (options.useMasterKey) {
requestOptions.useMasterKey = options.useMasterKey;
}
if (options.sessionToken) {
requestOptions.sessionToken = options.sessionToken;
}
return _CoreManager2.default.getCloudController().run(name, data, requestOptions)._thenRunCallbacks(options);
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var DefaultController = {
run: function (name, data, options) {
var RESTController = _CoreManager2.default.getRESTController();
var payload = (0, _encode2.default)(data, true);
var requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
requestOptions.sessionToken = options.sessionToken;
}
var request = RESTController.request('POST', 'functions/' + name, payload, requestOptions);
return request.then(function (res) {
var decoded = (0, _decode2.default)(res);
if (decoded && decoded.hasOwnProperty('result')) {
return _ParsePromise2.default.as(decoded.result);
}
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'The server returned an invalid response.'));
})._thenRunCallbacks(options);
}
};
_CoreManager2.default.setCloudController(DefaultController);
},{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./decode":36,"./encode":37}],3:[function(_dereq_,module,exports){
(function (process){
'use strict';
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var config = {
// Defaults
IS_NODE: typeof process !== 'undefined' && !!process.versions && !!process.versions.node && !process.versions.electron,
REQUEST_ATTEMPT_LIMIT: 5,
SERVER_URL: 'https://api.parse.com/1',
LIVEQUERY_SERVER_URL: null,
VERSION: 'js' + '1.10.1',
APPLICATION_ID: null,
JAVASCRIPT_KEY: null,
MASTER_KEY: null,
USE_MASTER_KEY: false,
PERFORM_USER_REWRITE: true,
FORCE_REVOCABLE_SESSION: false
};
function requireMethods(name, methods, controller) {
methods.forEach(function (func) {
if (typeof controller[func] !== 'function') {
throw new Error(name + ' must implement ' + func + '()');
}
});
}
module.exports = {
get: function (key) {
if (config.hasOwnProperty(key)) {
return config[key];
}
throw new Error('Configuration key not found: ' + key);
},
set: function (key, value) {
config[key] = value;
},
/* Specialized Controller Setters/Getters */
setAnalyticsController: function (controller) {
requireMethods('AnalyticsController', ['track'], controller);
config['AnalyticsController'] = controller;
},
getAnalyticsController: function () {
return config['AnalyticsController'];
},
setCloudController: function (controller) {
requireMethods('CloudController', ['run'], controller);
config['CloudController'] = controller;
},
getCloudController: function () {
return config['CloudController'];
},
setConfigController: function (controller) {
requireMethods('ConfigController', ['current', 'get'], controller);
config['ConfigController'] = controller;
},
getConfigController: function () {
return config['ConfigController'];
},
setFileController: function (controller) {
requireMethods('FileController', ['saveFile', 'saveBase64'], controller);
config['FileController'] = controller;
},
getFileController: function () {
return config['FileController'];
},
setInstallationController: function (controller) {
requireMethods('InstallationController', ['currentInstallationId'], controller);
config['InstallationController'] = controller;
},
getInstallationController: function () {
return config['InstallationController'];
},
setObjectController: function (controller) {
requireMethods('ObjectController', ['save', 'fetch', 'destroy'], controller);
config['ObjectController'] = controller;
},
getObjectController: function () {
return config['ObjectController'];
},
setObjectStateController: function (controller) {
requireMethods('ObjectStateController', ['getState', 'initializeState', 'removeState', 'getServerData', 'setServerData', 'getPendingOps', 'setPendingOp', 'pushPendingState', 'popPendingState', 'mergeFirstPendingState', 'getObjectCache', 'estimateAttribute', 'estimateAttributes', 'commitServerChanges', 'enqueueTask', 'clearAllState'], controller);
config['ObjectStateController'] = controller;
},
getObjectStateController: function () {
return config['ObjectStateController'];
},
setPushController: function (controller) {
requireMethods('PushController', ['send'], controller);
config['PushController'] = controller;
},
getPushController: function () {
return config['PushController'];
},
setQueryController: function (controller) {
requireMethods('QueryController', ['find'], controller);
config['QueryController'] = controller;
},
getQueryController: function () {
return config['QueryController'];
},
setRESTController: function (controller) {
requireMethods('RESTController', ['request', 'ajax'], controller);
config['RESTController'] = controller;
},
getRESTController: function () {
return config['RESTController'];
},
setSessionController: function (controller) {
requireMethods('SessionController', ['getSession'], controller);
config['SessionController'] = controller;
},
getSessionController: function () {
return config['SessionController'];
},
setStorageController: function (controller) {
if (controller.async) {
requireMethods('An async StorageController', ['getItemAsync', 'setItemAsync', 'removeItemAsync'], controller);
} else {
requireMethods('A synchronous StorageController', ['getItem', 'setItem', 'removeItem'], controller);
}
config['StorageController'] = controller;
},
getStorageController: function () {
return config['StorageController'];
},
setUserController: function (controller) {
requireMethods('UserController', ['setCurrentUser', 'currentUser', 'currentUserAsync', 'signUp', 'logIn', 'become', 'logOut', 'requestPasswordReset', 'upgradeToRevocableSession', 'linkWith'], controller);
config['UserController'] = controller;
},
getUserController: function () {
return config['UserController'];
},
setLiveQueryController: function (controller) {
requireMethods('LiveQueryController', ['subscribe', 'unsubscribe', 'open', 'close'], controller);
config['LiveQueryController'] = controller;
},
getLiveQueryController: function () {
return config['LiveQueryController'];
},
setHooksController: function (controller) {
requireMethods('HooksController', ['create', 'get', 'update', 'remove'], controller);
config['HooksController'] = controller;
},
getHooksController: function () {
return config['HooksController'];
}
};
}).call(this,_dereq_('_process'))
},{"_process":63}],4:[function(_dereq_,module,exports){
'use strict';
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* This is a simple wrapper to unify EventEmitter implementations across platforms.
*/
module.exports = _dereq_('events').EventEmitter;
var EventEmitter;
},{"events":170}],5:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _parseDate = _dereq_('./parseDate');
var _parseDate2 = _interopRequireDefault(_parseDate);
var _ParseUser = _dereq_('./ParseUser');
var _ParseUser2 = _interopRequireDefault(_ParseUser);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* -weak
*/
var PUBLIC_KEY = "*";
var initialized = false;
var requestedPermissions;
var initOptions;
var provider = {
authenticate: function (options) {
var _this = this;
if (typeof FB === 'undefined') {
options.error(this, 'Facebook SDK not found.');
}
FB.login(function (response) {
if (response.authResponse) {
if (options.success) {
options.success(_this, {
id: response.authResponse.userID,
access_token: response.authResponse.accessToken,
expiration_date: new Date(response.authResponse.expiresIn * 1000 + new Date().getTime()).toJSON()
});
}
} else {
if (options.error) {
options.error(_this, response);
}
}
}, {
scope: requestedPermissions
});
},
restoreAuthentication: function (authData) {
if (authData) {
var expiration = (0, _parseDate2.default)(authData.expiration_date);
var expiresIn = expiration ? (expiration.getTime() - new Date().getTime()) / 1000 : 0;
var authResponse = {
userID: authData.id,
accessToken: authData.access_token,
expiresIn: expiresIn
};
var newOptions = {};
if (initOptions) {
for (var key in initOptions) {
newOptions[key] = initOptions[key];
}
}
newOptions.authResponse = authResponse;
// Suppress checks for login status from the browser.
newOptions.status = false;
// If the user doesn't match the one known by the FB SDK, log out.
// Most of the time, the users will match -- it's only in cases where
// the FB SDK knows of a different user than the one being restored
// from a Parse User that logged in with username/password.
var existingResponse = FB.getAuthResponse();
if (existingResponse && existingResponse.userID !== authResponse.userID) {
FB.logout();
}
FB.init(newOptions);
}
return true;
},
getAuthType: function () {
return 'facebook';
},
deauthenticate: function () {
this.restoreAuthentication(null);
}
};
/**
* Provides a set of utilities for using Parse with Facebook.
* @class Parse.FacebookUtils
* @static
*/
var FacebookUtils = {
/**
* Initializes Parse Facebook integration. Call this function after you
* have loaded the Facebook Javascript SDK with the same parameters
* as you would pass to<code>
* <a href=
* "https://developers.facebook.com/docs/reference/javascript/FB.init/">
* FB.init()</a></code>. Parse.FacebookUtils will invoke FB.init() for you
* with these arguments.
*
* @method init
* @param {Object} options Facebook options argument as described here:
* <a href=
* "https://developers.facebook.com/docs/reference/javascript/FB.init/">
* FB.init()</a>. The status flag will be coerced to 'false' because it
* interferes with Parse Facebook integration. Call FB.getLoginStatus()
* explicitly if this behavior is required by your application.
*/
init: function (options) {
if (typeof FB === 'undefined') {
throw new Error('The Facebook JavaScript SDK must be loaded before calling init.');
}
initOptions = {};
if (options) {
for (var key in options) {
initOptions[key] = options[key];
}
}
if (initOptions.status && typeof console !== 'undefined') {
var warn = console.warn || console.log || function () {};
warn.call(console, 'The "status" flag passed into' + ' FB.init, when set to true, can interfere with Parse Facebook' + ' integration, so it has been suppressed. Please call' + ' FB.getLoginStatus() explicitly if you require this behavior.');
}
initOptions.status = false;
FB.init(initOptions);
_ParseUser2.default._registerAuthenticationProvider(provider);
initialized = true;
},
/**
* Gets whether the user has their account linked to Facebook.
*
* @method isLinked
* @param {Parse.User} user User to check for a facebook link.
* The user must be logged in on this device.
* @return {Boolean} <code>true</code> if the user has their account
* linked to Facebook.
*/
isLinked: function (user) {
return user._isLinked('facebook');
},
/**
* Logs in a user using Facebook. This method delegates to the Facebook
* SDK to authenticate the user, and then automatically logs in (or
* creates, in the case where it is a new user) a Parse.User.
*
* @method logIn
* @param {String, Object} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
logIn: function (permissions, options) {
if (!permissions || typeof permissions === 'string') {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling logIn.');
}
requestedPermissions = permissions;
return _ParseUser2.default._logInWith('facebook', options);
} else {
var newOptions = {};
if (options) {
for (var key in options) {
newOptions[key] = options[key];
}
}
newOptions.authData = permissions;
return _ParseUser2.default._logInWith('facebook', newOptions);
}
},
/**
* Links Facebook to an existing PFUser. This method delegates to the
* Facebook SDK to authenticate the user, and then automatically links
* the account to the Parse.User.
*
* @method link
* @param {Parse.User} user User to link to Facebook. This must be the
* current user.
* @param {String, Object} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
link: function (user, permissions, options) {
if (!permissions || typeof permissions === 'string') {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling link.');
}
requestedPermissions = permissions;
return user._linkWith('facebook', options);
} else {
var newOptions = {};
if (options) {
for (var key in options) {
newOptions[key] = options[key];
}
}
newOptions.authData = permissions;
return user._linkWith('facebook', newOptions);
}
},
/**
* Unlinks the Parse.User from a Facebook account.
*
* @method unlink
* @param {Parse.User} user User to unlink from Facebook. This must be the
* current user.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
unlink: function (user, options) {
if (!initialized) {
throw new Error('You must initialize FacebookUtils before calling unlink.');
}
return user._unlinkFrom('facebook', options);
}
};
exports.default = FacebookUtils;
},{"./ParseUser":26,"./parseDate":41}],6:[function(_dereq_,module,exports){
'use strict';
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _Storage = _dereq_('./Storage');
var _Storage2 = _interopRequireDefault(_Storage);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var iidCache = null; /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function hexOctet() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
function generateId() {
return hexOctet() + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + '-' + hexOctet() + hexOctet() + hexOctet();
}
var InstallationController = {
currentInstallationId: function () {
if (typeof iidCache === 'string') {
return _ParsePromise2.default.as(iidCache);
}
var path = _Storage2.default.generatePath('installationId');
return _Storage2.default.getItemAsync(path).then(function (iid) {
if (!iid) {
iid = generateId();
return _Storage2.default.setItemAsync(path, iid).then(function () {
iidCache = iid;
return iid;
});
}
iidCache = iid;
return iid;
});
},
_clearCache: function () {
iidCache = null;
},
_setInstallationIdCache: function (iid) {
iidCache = iid;
}
};
module.exports = InstallationController;
},{"./CoreManager":3,"./ParsePromise":21,"./Storage":30}],7:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _getIterator2 = _dereq_('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _map = _dereq_('babel-runtime/core-js/map');
var _map2 = _interopRequireDefault(_map);
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _EventEmitter2 = _dereq_('./EventEmitter');
var _EventEmitter3 = _interopRequireDefault(_EventEmitter2);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _LiveQuerySubscription = _dereq_('./LiveQuerySubscription');
var _LiveQuerySubscription2 = _interopRequireDefault(_LiveQuerySubscription);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
// The LiveQuery client inner state
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
var CLIENT_STATE = {
INITIALIZED: 'initialized',
CONNECTING: 'connecting',
CONNECTED: 'connected',
CLOSED: 'closed',
RECONNECTING: 'reconnecting',
DISCONNECTED: 'disconnected'
};
// The event type the LiveQuery client should sent to server
var OP_TYPES = {
CONNECT: 'connect',
SUBSCRIBE: 'subscribe',
UNSUBSCRIBE: 'unsubscribe',
ERROR: 'error'
};
// The event we get back from LiveQuery server
var OP_EVENTS = {
CONNECTED: 'connected',
SUBSCRIBED: 'subscribed',
UNSUBSCRIBED: 'unsubscribed',
ERROR: 'error',
CREATE: 'create',
UPDATE: 'update',
ENTER: 'enter',
LEAVE: 'leave',
DELETE: 'delete'
};
// The event the LiveQuery client should emit
var CLIENT_EMMITER_TYPES = {
CLOSE: 'close',
ERROR: 'error',
OPEN: 'open'
};
// The event the LiveQuery subscription should emit
var SUBSCRIPTION_EMMITER_TYPES = {
OPEN: 'open',
CLOSE: 'close',
ERROR: 'error',
CREATE: 'create',
UPDATE: 'update',
ENTER: 'enter',
LEAVE: 'leave',
DELETE: 'delete'
};
var generateInterval = function (k) {
return Math.random() * Math.min(30, Math.pow(2, k) - 1) * 1000;
};
/**
* Creates a new LiveQueryClient.
* Extends events.EventEmitter
* <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>.
*
* A wrapper of a standard WebSocket client. We add several useful methods to
* help you connect/disconnect to LiveQueryServer, subscribe/unsubscribe a ParseQuery easily.
*
* javascriptKey and masterKey are used for verifying the LiveQueryClient when it tries
* to connect to the LiveQuery server
*
* @class Parse.LiveQueryClient
* @constructor
* @param {Object} options
* @param {string} options.applicationId - applicationId of your Parse app
* @param {string} options.serverURL - <b>the URL of your LiveQuery server</b>
* @param {string} options.javascriptKey (optional)
* @param {string} options.masterKey (optional) Your Parse Master Key. (Node.js only!)
* @param {string} options.sessionToken (optional)
*
*
* We expose three events to help you monitor the status of the LiveQueryClient.
*
* <pre>
* let Parse = require('parse/node');
* let LiveQueryClient = Parse.LiveQueryClient;
* let client = new LiveQueryClient({
* applicationId: '',
* serverURL: '',
* javascriptKey: '',
* masterKey: ''
* });
* </pre>
*
* Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
* <pre>
* client.on('open', () => {
*
* });</pre>
*
* Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
* <pre>
* client.on('close', () => {
*
* });</pre>
*
* Error - When some network error or LiveQuery server error happens, you'll get this event.
* <pre>
* client.on('error', (error) => {
*
* });</pre>
*
*
*/
var LiveQueryClient = function (_EventEmitter) {
(0, _inherits3.default)(LiveQueryClient, _EventEmitter);
function LiveQueryClient(_ref) {
var applicationId = _ref.applicationId,
serverURL = _ref.serverURL,
javascriptKey = _ref.javascriptKey,
masterKey = _ref.masterKey,
sessionToken = _ref.sessionToken;
(0, _classCallCheck3.default)(this, LiveQueryClient);
var _this = (0, _possibleConstructorReturn3.default)(this, (LiveQueryClient.__proto__ || (0, _getPrototypeOf2.default)(LiveQueryClient)).call(this));
if (!serverURL || serverURL.indexOf('ws') !== 0) {
throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
}
_this.reconnectHandle = null;
_this.attempts = 1;
_this.id = 0;
_this.requestId = 1;
_this.serverURL = serverURL;
_this.applicationId = applicationId;
_this.javascriptKey = javascriptKey;
_this.masterKey = masterKey;
_this.sessionToken = sessionToken;
_this.connectPromise = new _ParsePromise2.default();
_this.subscriptions = new _map2.default();
_this.state = CLIENT_STATE.INITIALIZED;
return _this;
}
(0, _createClass3.default)(LiveQueryClient, [{
key: 'shouldOpen',
value: function () {
return this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED;
}
/**
* Subscribes to a ParseQuery
*
* If you provide the sessionToken, when the LiveQuery server gets ParseObject's
* updates from parse server, it'll try to check whether the sessionToken fulfills
* the ParseObject's ACL. The LiveQuery server will only send updates to clients whose
* sessionToken is fit for the ParseObject's ACL. You can check the LiveQuery protocol
* <a href="https://github.com/ParsePlatform/parse-server/wiki/Parse-LiveQuery-Protocol-Specification">here</a> for more details. The subscription you get is the same subscription you get
* from our Standard API.
*
* @method subscribe
* @param {Object} query - the ParseQuery you want to subscribe to
* @param {string} sessionToken (optional)
* @return {Object} subscription
*/
}, {
key: 'subscribe',
value: function (query, sessionToken) {
var _this2 = this;
if (!query) {
return;
}
var where = query.toJSON().where;
var className = query.className;
var subscribeRequest = {
op: OP_TYPES.SUBSCRIBE,
requestId: this.requestId,
query: {
className: className,
where: where
}
};
if (sessionToken) {
subscribeRequest.sessionToken = sessionToken;
}
var subscription = new _LiveQuerySubscription2.default(this.requestId, query, sessionToken);
this.subscriptions.set(this.requestId, subscription);
this.requestId += 1;
this.connectPromise.then(function () {
_this2.socket.send((0, _stringify2.default)(subscribeRequest));
});
// adding listener so process does not crash
// best practice is for developer to register their own listener
subscription.on('error', function () {});
return subscription;
}
/**
* After calling unsubscribe you'll stop receiving events from the subscription object.
*
* @method unsubscribe
* @param {Object} subscription - subscription you would like to unsubscribe from.
*/
}, {
key: 'unsubscribe',
value: function (subscription) {
var _this3 = this;
if (!subscription) {
return;
}
this.subscriptions.delete(subscription.id);
var unsubscribeRequest = {
op: OP_TYPES.UNSUBSCRIBE,
requestId: subscription.id
};
this.connectPromise.then(function () {
_this3.socket.send((0, _stringify2.default)(unsubscribeRequest));
});
}
/**
* After open is called, the LiveQueryClient will try to send a connect request
* to the LiveQuery server.
*
* @method open
*/
}, {
key: 'open',
value: function () {
var _this4 = this;
var WebSocketImplementation = this._getWebSocketImplementation();
if (!WebSocketImplementation) {
this.emit(CLIENT_EMMITER_TYPES.ERROR, 'Can not find WebSocket implementation');
return;
}
if (this.state !== CLIENT_STATE.RECONNECTING) {
this.state = CLIENT_STATE.CONNECTING;
}
// Get WebSocket implementation
this.socket = new WebSocketImplementation(this.serverURL);
// Bind WebSocket callbacks
this.socket.onopen = function () {
_this4._handleWebSocketOpen();
};
this.socket.onmessage = function (event) {
_this4._handleWebSocketMessage(event);
};
this.socket.onclose = function () {
_this4._handleWebSocketClose();
};
this.socket.onerror = function (error) {
_this4._handleWebSocketError(error);
};
}
}, {
key: 'resubscribe',
value: function () {
var _this5 = this;
this.subscriptions.forEach(function (subscription, requestId) {
var query = subscription.query;
var where = query.toJSON().where;
var className = query.className;
var sessionToken = subscription.sessionToken;
var subscribeRequest = {
op: OP_TYPES.SUBSCRIBE,
requestId: requestId,
query: {
className: className,
where: where
}
};
if (sessionToken) {
subscribeRequest.sessionToken = sessionToken;
}
_this5.connectPromise.then(function () {
_this5.socket.send((0, _stringify2.default)(subscribeRequest));
});
});
}
/**
* This method will close the WebSocket connection to this LiveQueryClient,
* cancel the auto reconnect and unsubscribe all subscriptions based on it.
*
* @method close
*/
}, {
key: 'close',
value: function () {
if (this.state === CLIENT_STATE.INITIALIZED || this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.DISCONNECTED;
this.socket.close();
// Notify each subscription about the close
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(this.subscriptions.values()), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var subscription = _step.value;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
this._handleReset();
this.emit(CLIENT_EMMITER_TYPES.CLOSE);
}
}, {
key: '_getWebSocketImplementation',
value: function () {
return typeof WebSocket === 'function' || (typeof WebSocket === 'undefined' ? 'undefined' : (0, _typeof3.default)(WebSocket)) === 'object' ? WebSocket : null;
}
// ensure we start with valid state if connect is called again after close
}, {
key: '_handleReset',
value: function () {
this.attempts = 1;
this.id = 0;
this.requestId = 1;
this.connectPromise = new _ParsePromise2.default();
this.subscriptions = new _map2.default();
}
}, {
key: '_handleWebSocketOpen',
value: function () {
this.attempts = 1;
var connectRequest = {
op: OP_TYPES.CONNECT,
applicationId: this.applicationId,
javascriptKey: this.javascriptKey,
masterKey: this.masterKey,
sessionToken: this.sessionToken
};
this.socket.send((0, _stringify2.default)(connectRequest));
}
}, {
key: '_handleWebSocketMessage',
value: function (event) {
var data = event.data;
if (typeof data === 'string') {
data = JSON.parse(data);
}
var subscription = null;
if (data.requestId) {
subscription = this.subscriptions.get(data.requestId);
}
switch (data.op) {
case OP_EVENTS.CONNECTED:
if (this.state === CLIENT_STATE.RECONNECTING) {
this.resubscribe();
}
this.emit(CLIENT_EMMITER_TYPES.OPEN);
this.id = data.clientId;
this.connectPromise.resolve();
this.state = CLIENT_STATE.CONNECTED;
break;
case OP_EVENTS.SUBSCRIBED:
if (subscription) {
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.OPEN);
}
break;
case OP_EVENTS.ERROR:
if (data.requestId) {
if (subscription) {
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR, data.error);
}
} else {
this.emit(CLIENT_EMMITER_TYPES.ERROR, data.error);
}
break;
case OP_EVENTS.UNSUBSCRIBED:
// We have already deleted subscription in unsubscribe(), do nothing here
break;
default:
// create, update, enter, leave, delete cases
var className = data.object.className;
// Delete the extrea __type and className fields during transfer to full JSON
delete data.object.__type;
delete data.object.className;
var parseObject = new _ParseObject2.default(className);
parseObject._finishFetch(data.object);
if (!subscription) {
break;
}
subscription.emit(data.op, parseObject);
}
}
}, {
key: '_handleWebSocketClose',
value: function () {
if (this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.CLOSED;
this.emit(CLIENT_EMMITER_TYPES.CLOSE);
// Notify each subscription about the close
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = (0, _getIterator3.default)(this.subscriptions.values()), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var subscription = _step2.value;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.CLOSE);
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
this._handleReconnect();
}
}, {
key: '_handleWebSocketError',
value: function (error) {
this.emit(CLIENT_EMMITER_TYPES.ERROR, error);
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = undefined;
try {
for (var _iterator3 = (0, _getIterator3.default)(this.subscriptions.values()), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
var subscription = _step3.value;
subscription.emit(SUBSCRIPTION_EMMITER_TYPES.ERROR);
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally {
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) {
_iterator3.return();
}
} finally {
if (_didIteratorError3) {
throw _iteratorError3;
}
}
}
this._handleReconnect();
}
}, {
key: '_handleReconnect',
value: function () {
var _this6 = this;
// if closed or currently reconnecting we stop attempting to reconnect
if (this.state === CLIENT_STATE.DISCONNECTED) {
return;
}
this.state = CLIENT_STATE.RECONNECTING;
var time = generateInterval(this.attempts);
// handle case when both close/error occur at frequent rates we ensure we do not reconnect unnecessarily.
// we're unable to distinguish different between close/error when we're unable to reconnect therefore
// we try to reonnect in both cases
// server side ws and browser WebSocket behave differently in when close/error get triggered
if (this.reconnectHandle) {
clearTimeout(this.reconnectHandle);
}
this.reconnectHandle = setTimeout(function () {
_this6.attempts++;
_this6.connectPromise = new _ParsePromise2.default();
_this6.open();
}.bind(this), time);
}
}]);
return LiveQueryClient;
}(_EventEmitter3.default);
exports.default = LiveQueryClient;
},{"./EventEmitter":4,"./LiveQuerySubscription":8,"./ParseObject":18,"./ParsePromise":21,"babel-runtime/core-js/get-iterator":44,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/map":46,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],8:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _EventEmitter2 = _dereq_('./EventEmitter');
var _EventEmitter3 = _interopRequireDefault(_EventEmitter2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Creates a new LiveQuery Subscription.
* Extends events.EventEmitter
* <a href="https://nodejs.org/api/events.html#events_class_eventemitter">cloud functions</a>.
*
* @constructor
* @param {string} id - subscription id
* @param {string} query - query to subscribe to
* @param {string} sessionToken - optional session token
*
* <p>Open Event - When you call query.subscribe(), we send a subscribe request to
* the LiveQuery server, when we get the confirmation from the LiveQuery server,
* this event will be emitted. When the client loses WebSocket connection to the
* LiveQuery server, we will try to auto reconnect the LiveQuery server. If we
* reconnect the LiveQuery server and successfully resubscribe the ParseQuery,
* you'll also get this event.
*
* <pre>
* subscription.on('open', () => {
*
* });</pre></p>
*
* <p>Create Event - When a new ParseObject is created and it fulfills the ParseQuery you subscribe,
* you'll get this event. The object is the ParseObject which is created.
*
* <pre>
* subscription.on('create', (object) => {
*
* });</pre></p>
*
* <p>Update Event - When an existing ParseObject which fulfills the ParseQuery you subscribe
* is updated (The ParseObject fulfills the ParseQuery before and after changes),
* you'll get this event. The object is the ParseObject which is updated.
* Its content is the latest value of the ParseObject.
*
* <pre>
* subscription.on('update', (object) => {
*
* });</pre></p>
*
* <p>Enter Event - When an existing ParseObject's old value doesn't fulfill the ParseQuery
* but its new value fulfills the ParseQuery, you'll get this event. The object is the
* ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject.
*
* <pre>
* subscription.on('enter', (object) => {
*
* });</pre></p>
*
*
* <p>Update Event - When an existing ParseObject's old value fulfills the ParseQuery but its new value
* doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject
* which leaves the ParseQuery. Its content is the latest value of the ParseObject.
*
* <pre>
* subscription.on('leave', (object) => {
*
* });</pre></p>
*
*
* <p>Delete Event - When an existing ParseObject which fulfills the ParseQuery is deleted, you'll
* get this event. The object is the ParseObject which is deleted.
*
* <pre>
* subscription.on('delete', (object) => {
*
* });</pre></p>
*
*
* <p>Close Event - When the client loses the WebSocket connection to the LiveQuery
* server and we stop receiving events, you'll get this event.
*
* <pre>
* subscription.on('close', () => {
*
* });</pre></p>
*
*
*/
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
var Subscription = function (_EventEmitter) {
(0, _inherits3.default)(Subscription, _EventEmitter);
function Subscription(id, query, sessionToken) {
(0, _classCallCheck3.default)(this, Subscription);
var _this2 = (0, _possibleConstructorReturn3.default)(this, (Subscription.__proto__ || (0, _getPrototypeOf2.default)(Subscription)).call(this));
_this2.id = id;
_this2.query = query;
_this2.sessionToken = sessionToken;
return _this2;
}
/**
* @method unsubscribe
*/
(0, _createClass3.default)(Subscription, [{
key: 'unsubscribe',
value: function () {
var _this3 = this;
var _this = this;
_CoreManager2.default.getLiveQueryController().getDefaultLiveQueryClient().then(function (liveQueryClient) {
liveQueryClient.unsubscribe(_this);
_this.emit('close');
_this3.resolve();
});
}
}]);
return Subscription;
}(_EventEmitter3.default);
exports.default = Subscription;
},{"./CoreManager":3,"./EventEmitter":4,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],9:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.defaultState = defaultState;
exports.setServerData = setServerData;
exports.setPendingOp = setPendingOp;
exports.pushPendingState = pushPendingState;
exports.popPendingState = popPendingState;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.commitServerChanges = commitServerChanges;
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
var _TaskQueue = _dereq_('./TaskQueue');
var _TaskQueue2 = _interopRequireDefault(_TaskQueue);
var _ParseOp = _dereq_('./ParseOp');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function defaultState() {
return {
serverData: {},
pendingOps: [{}],
objectCache: {},
tasks: new _TaskQueue2.default(),
existed: false
};
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function setServerData(serverData, attributes) {
for (var _attr in attributes) {
if (typeof attributes[_attr] !== 'undefined') {
serverData[_attr] = attributes[_attr];
} else {
delete serverData[_attr];
}
}
}
function setPendingOp(pendingOps, attr, op) {
var last = pendingOps.length - 1;
if (op) {
pendingOps[last][attr] = op;
} else {
delete pendingOps[last][attr];
}
}
function pushPendingState(pendingOps) {
pendingOps.push({});
}
function popPendingState(pendingOps) {
var first = pendingOps.shift();
if (!pendingOps.length) {
pendingOps[0] = {};
}
return first;
}
function mergeFirstPendingState(pendingOps) {
var first = popPendingState(pendingOps);
var next = pendingOps[0];
for (var _attr2 in first) {
if (next[_attr2] && first[_attr2]) {
var merged = next[_attr2].mergeWith(first[_attr2]);
if (merged) {
next[_attr2] = merged;
}
} else {
next[_attr2] = first[_attr2];
}
}
}
function estimateAttribute(serverData, pendingOps, className, id, attr) {
var value = serverData[attr];
for (var i = 0; i < pendingOps.length; i++) {
if (pendingOps[i][attr]) {
if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
if (id) {
value = pendingOps[i][attr].applyTo(value, { className: className, id: id }, attr);
}
} else {
value = pendingOps[i][attr].applyTo(value);
}
}
}
return value;
}
function estimateAttributes(serverData, pendingOps, className, id) {
var data = {};
var attr = void 0;
for (attr in serverData) {
data[attr] = serverData[attr];
}
for (var i = 0; i < pendingOps.length; i++) {
for (attr in pendingOps[i]) {
if (pendingOps[i][attr] instanceof _ParseOp.RelationOp) {
if (id) {
data[attr] = pendingOps[i][attr].applyTo(data[attr], { className: className, id: id }, attr);
}
} else {
data[attr] = pendingOps[i][attr].applyTo(data[attr]);
}
}
}
return data;
}
function commitServerChanges(serverData, objectCache, changes) {
for (var _attr3 in changes) {
var val = changes[_attr3];
serverData[_attr3] = val;
if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object' && !(val instanceof _ParseObject2.default) && !(val instanceof _ParseFile2.default) && !(val instanceof _ParseRelation2.default)) {
var json = (0, _encode2.default)(val, false, true);
objectCache[_attr3] = (0, _stringify2.default)(json);
}
}
}
},{"./ParseFile":14,"./ParseObject":18,"./ParseOp":19,"./ParsePromise":21,"./ParseRelation":23,"./TaskQueue":32,"./encode":37,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/typeof":62}],10:[function(_dereq_,module,exports){
'use strict';
var _decode = _dereq_('./decode');
var _decode2 = _interopRequireDefault(_decode);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _InstallationController = _dereq_('./InstallationController');
var _InstallationController2 = _interopRequireDefault(_InstallationController);
var _ParseOp = _dereq_('./ParseOp');
var ParseOp = _interopRequireWildcard(_ParseOp);
var _RESTController = _dereq_('./RESTController');
var _RESTController2 = _interopRequireDefault(_RESTController);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj.default = obj;return newObj;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Contains all Parse API classes and functions.
* @class Parse
* @static
*/
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var Parse = {
/**
* Call this method first to set up your authentication tokens for Parse.
* You can get your keys from the Data Browser on parse.com.
* @method initialize
* @param {String} applicationId Your Parse Application ID.
* @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server)
* @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!)
* @static
*/
initialize: function (applicationId, javaScriptKey) {
if ('browser' === 'browser' && _CoreManager2.default.get('IS_NODE') && !undefined) {
console.log('It looks like you\'re using the browser version of the SDK in a ' + 'node.js environment. You should require(\'parse/node\') instead.');
}
Parse._initialize(applicationId, javaScriptKey);
},
_initialize: function (applicationId, javaScriptKey, masterKey) {
_CoreManager2.default.set('APPLICATION_ID', applicationId);
_CoreManager2.default.set('JAVASCRIPT_KEY', javaScriptKey);
_CoreManager2.default.set('MASTER_KEY', masterKey);
_CoreManager2.default.set('USE_MASTER_KEY', false);
}
};
/** These legacy setters may eventually be deprecated **/
Object.defineProperty(Parse, 'applicationId', {
get: function () {
return _CoreManager2.default.get('APPLICATION_ID');
},
set: function (value) {
_CoreManager2.default.set('APPLICATION_ID', value);
}
});
Object.defineProperty(Parse, 'javaScriptKey', {
get: function () {
return _CoreManager2.default.get('JAVASCRIPT_KEY');
},
set: function (value) {
_CoreManager2.default.set('JAVASCRIPT_KEY', value);
}
});
Object.defineProperty(Parse, 'masterKey', {
get: function () {
return _CoreManager2.default.get('MASTER_KEY');
},
set: function (value) {
_CoreManager2.default.set('MASTER_KEY', value);
}
});
Object.defineProperty(Parse, 'serverURL', {
get: function () {
return _CoreManager2.default.get('SERVER_URL');
},
set: function (value) {
_CoreManager2.default.set('SERVER_URL', value);
}
});
Object.defineProperty(Parse, 'liveQueryServerURL', {
get: function () {
return _CoreManager2.default.get('LIVEQUERY_SERVER_URL');
},
set: function (value) {
_CoreManager2.default.set('LIVEQUERY_SERVER_URL', value);
}
});
/** End setters **/
Parse.ACL = _dereq_('./ParseACL').default;
Parse.Analytics = _dereq_('./Analytics');
Parse.Cloud = _dereq_('./Cloud');
Parse.CoreManager = _dereq_('./CoreManager');
Parse.Config = _dereq_('./ParseConfig').default;
Parse.Error = _dereq_('./ParseError').default;
Parse.FacebookUtils = _dereq_('./FacebookUtils').default;
Parse.File = _dereq_('./ParseFile').default;
Parse.GeoPoint = _dereq_('./ParseGeoPoint').default;
Parse.Polygon = _dereq_('./ParsePolygon').default;
Parse.Installation = _dereq_('./ParseInstallation').default;
Parse.Object = _dereq_('./ParseObject').default;
Parse.Op = {
Set: ParseOp.SetOp,
Unset: ParseOp.UnsetOp,
Increment: ParseOp.IncrementOp,
Add: ParseOp.AddOp,
Remove: ParseOp.RemoveOp,
AddUnique: ParseOp.AddUniqueOp,
Relation: ParseOp.RelationOp
};
Parse.Promise = _dereq_('./ParsePromise').default;
Parse.Push = _dereq_('./Push');
Parse.Query = _dereq_('./ParseQuery').default;
Parse.Relation = _dereq_('./ParseRelation').default;
Parse.Role = _dereq_('./ParseRole').default;
Parse.Session = _dereq_('./ParseSession').default;
Parse.Storage = _dereq_('./Storage');
Parse.User = _dereq_('./ParseUser').default;
Parse.LiveQuery = _dereq_('./ParseLiveQuery').default;
Parse.LiveQueryClient = _dereq_('./LiveQueryClient').default;
Parse._request = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _CoreManager2.default.getRESTController().request.apply(null, args);
};
Parse._ajax = function () {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return _CoreManager2.default.getRESTController().ajax.apply(null, args);
};
// We attempt to match the signatures of the legacy versions of these methods
Parse._decode = function (_, value) {
return (0, _decode2.default)(value);
};
Parse._encode = function (value, _, disallowObjects) {
return (0, _encode2.default)(value, disallowObjects);
};
Parse._getInstallationId = function () {
return _CoreManager2.default.getInstallationController().currentInstallationId();
};
_CoreManager2.default.setInstallationController(_InstallationController2.default);
_CoreManager2.default.setRESTController(_RESTController2.default);
// For legacy requires, of the form `var Parse = require('parse').Parse`
Parse.Parse = Parse;
module.exports = Parse;
},{"./Analytics":1,"./Cloud":2,"./CoreManager":3,"./FacebookUtils":5,"./InstallationController":6,"./LiveQueryClient":7,"./ParseACL":11,"./ParseConfig":12,"./ParseError":13,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseInstallation":16,"./ParseLiveQuery":17,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParsePromise":21,"./ParseQuery":22,"./ParseRelation":23,"./ParseRole":24,"./ParseSession":25,"./ParseUser":26,"./Push":27,"./RESTController":28,"./Storage":30,"./decode":36,"./encode":37}],11:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = _dereq_('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _ParseRole = _dereq_('./ParseRole');
var _ParseRole2 = _interopRequireDefault(_ParseRole);
var _ParseUser = _dereq_('./ParseUser');
var _ParseUser2 = _interopRequireDefault(_ParseUser);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var PUBLIC_KEY = '*';
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a Parse.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
* @class Parse.ACL
* @constructor
*
* <p>An ACL, or Access Control List can be added to any
* <code>Parse.Object</code> to restrict access to only a subset of users
* of your application.</p>
*/
var ParseACL = function () {
function ParseACL(arg1) {
(0, _classCallCheck3.default)(this, ParseACL);
this.permissionsById = {};
if (arg1 && (typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object') {
if (arg1 instanceof _ParseUser2.default) {
this.setReadAccess(arg1, true);
this.setWriteAccess(arg1, true);
} else {
for (var userId in arg1) {
var accessList = arg1[userId];
if (typeof userId !== 'string') {
throw new TypeError('Tried to create an ACL with an invalid user id.');
}
this.permissionsById[userId] = {};
for (var permission in accessList) {
var allowed = accessList[permission];
if (permission !== 'read' && permission !== 'write') {
throw new TypeError('Tried to create an ACL with an invalid permission type.');
}
if (typeof allowed !== 'boolean') {
throw new TypeError('Tried to create an ACL with an invalid permission value.');
}
this.permissionsById[userId][permission] = allowed;
}
}
}
} else if (typeof arg1 === 'function') {
throw new TypeError('ParseACL constructed with a function. Did you forget ()?');
}
}
/**
* Returns a JSON-encoded version of the ACL.
* @method toJSON
* @return {Object}
*/
(0, _createClass3.default)(ParseACL, [{
key: 'toJSON',
value: function () {
var permissions = {};
for (var p in this.permissionsById) {
permissions[p] = this.permissionsById[p];
}
return permissions;
}
/**
* Returns whether this ACL is equal to another object
* @method equals
* @param other The other object to compare to
* @return {Boolean}
*/
}, {
key: 'equals',
value: function (other) {
if (!(other instanceof ParseACL)) {
return false;
}
var users = (0, _keys2.default)(this.permissionsById);
var otherUsers = (0, _keys2.default)(other.permissionsById);
if (users.length !== otherUsers.length) {
return false;
}
for (var u in this.permissionsById) {
if (!other.permissionsById[u]) {
return false;
}
if (this.permissionsById[u].read !== other.permissionsById[u].read) {
return false;
}
if (this.permissionsById[u].write !== other.permissionsById[u].write) {
return false;
}
}
return true;
}
}, {
key: '_setAccess',
value: function (accessType, userId, allowed) {
if (userId instanceof _ParseUser2.default) {
userId = userId.id;
} else if (userId instanceof _ParseRole2.default) {
var name = userId.getName();
if (!name) {
throw new TypeError('Role must have a name');
}
userId = 'role:' + name;
}
if (typeof userId !== 'string') {
throw new TypeError('userId must be a string.');
}
if (typeof allowed !== 'boolean') {
throw new TypeError('allowed must be either true or false.');
}
var permissions = this.permissionsById[userId];
if (!permissions) {
if (!allowed) {
// The user already doesn't have this permission, so no action is needed
return;
} else {
permissions = {};
this.permissionsById[userId] = permissions;
}
}
if (allowed) {
this.permissionsById[userId][accessType] = true;
} else {
delete permissions[accessType];
if ((0, _keys2.default)(permissions).length === 0) {
delete this.permissionsById[userId];
}
}
}
}, {
key: '_getAccess',
value: function (accessType, userId) {
if (userId instanceof _ParseUser2.default) {
userId = userId.id;
if (!userId) {
throw new Error('Cannot get access for a ParseUser without an ID');
}
} else if (userId instanceof _ParseRole2.default) {
var name = userId.getName();
if (!name) {
throw new TypeError('Role must have a name');
}
userId = 'role:' + name;
}
var permissions = this.permissionsById[userId];
if (!permissions) {
return false;
}
return !!permissions[accessType];
}
/**
* Sets whether the given user is allowed to read this object.
* @method setReadAccess
* @param userId An instance of Parse.User or its objectId.
* @param {Boolean} allowed Whether that user should have read access.
*/
}, {
key: 'setReadAccess',
value: function (userId, allowed) {
this._setAccess('read', userId, allowed);
}
/**
* Get whether the given user id is *explicitly* allowed to read this object.
* Even if this returns false, the user may still be able to access it if
* getPublicReadAccess returns true or a role that the user belongs to has
* write access.
* @method getReadAccess
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @return {Boolean}
*/
}, {
key: 'getReadAccess',
value: function (userId) {
return this._getAccess('read', userId);
}
/**
* Sets whether the given user id is allowed to write this object.
* @method setWriteAccess
* @param userId An instance of Parse.User or its objectId, or a Parse.Role..
* @param {Boolean} allowed Whether that user should have write access.
*/
}, {
key: 'setWriteAccess',
value: function (userId, allowed) {
this._setAccess('write', userId, allowed);
}
/**
* Gets whether the given user id is *explicitly* allowed to write this object.
* Even if this returns false, the user may still be able to write it if
* getPublicWriteAccess returns true or a role that the user belongs to has
* write access.
* @method getWriteAccess
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @return {Boolean}
*/
}, {
key: 'getWriteAccess',
value: function (userId) {
return this._getAccess('write', userId);
}
/**
* Sets whether the public is allowed to read this object.
* @method setPublicReadAccess
* @param {Boolean} allowed
*/
}, {
key: 'setPublicReadAccess',
value: function (allowed) {
this.setReadAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to read this object.
* @method getPublicReadAccess
* @return {Boolean}
*/
}, {
key: 'getPublicReadAccess',
value: function () {
return this.getReadAccess(PUBLIC_KEY);
}
/**
* Sets whether the public is allowed to write this object.
* @method setPublicWriteAccess
* @param {Boolean} allowed
*/
}, {
key: 'setPublicWriteAccess',
value: function (allowed) {
this.setWriteAccess(PUBLIC_KEY, allowed);
}
/**
* Gets whether the public is allowed to write this object.
* @method getPublicWriteAccess
* @return {Boolean}
*/
}, {
key: 'getPublicWriteAccess',
value: function () {
return this.getWriteAccess(PUBLIC_KEY);
}
/**
* Gets whether users belonging to the given role are allowed
* to read this object. Even if this returns false, the role may
* still be able to write it if a parent role has read access.
*
* @method getRoleReadAccess
* @param role The name of the role, or a Parse.Role object.
* @return {Boolean} true if the role has read access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
}, {
key: 'getRoleReadAccess',
value: function (role) {
if (role instanceof _ParseRole2.default) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
return this.getReadAccess('role:' + role);
}
/**
* Gets whether users belonging to the given role are allowed
* to write this object. Even if this returns false, the role may
* still be able to write it if a parent role has write access.
*
* @method getRoleWriteAccess
* @param role The name of the role, or a Parse.Role object.
* @return {Boolean} true if the role has write access. false otherwise.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
}, {
key: 'getRoleWriteAccess',
value: function (role) {
if (role instanceof _ParseRole2.default) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
return this.getWriteAccess('role:' + role);
}
/**
* Sets whether users belonging to the given role are allowed
* to read this object.
*
* @method setRoleReadAccess
* @param role The name of the role, or a Parse.Role object.
* @param {Boolean} allowed Whether the given role can read this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
}, {
key: 'setRoleReadAccess',
value: function (role, allowed) {
if (role instanceof _ParseRole2.default) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
this.setReadAccess('role:' + role, allowed);
}
/**
* Sets whether users belonging to the given role are allowed
* to write this object.
*
* @method setRoleWriteAccess
* @param role The name of the role, or a Parse.Role object.
* @param {Boolean} allowed Whether the given role can write this object.
* @throws {TypeError} If role is neither a Parse.Role nor a String.
*/
}, {
key: 'setRoleWriteAccess',
value: function (role, allowed) {
if (role instanceof _ParseRole2.default) {
// Normalize to the String name
role = role.getName();
}
if (typeof role !== 'string') {
throw new TypeError('role must be a ParseRole or a String');
}
this.setWriteAccess('role:' + role, allowed);
}
}]);
return ParseACL;
}();
exports.default = ParseACL;
},{"./ParseRole":24,"./ParseUser":26,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],12:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _decode = _dereq_('./decode');
var _decode2 = _interopRequireDefault(_decode);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _escape2 = _dereq_('./escape');
var _escape3 = _interopRequireDefault(_escape2);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _Storage = _dereq_('./Storage');
var _Storage2 = _interopRequireDefault(_Storage);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Parse.Config is a local representation of configuration data that
* can be set from the Parse dashboard.
*
* @class Parse.Config
* @constructor
*/
var ParseConfig = function () {
function ParseConfig() {
(0, _classCallCheck3.default)(this, ParseConfig);
this.attributes = {};
this._escapedAttributes = {};
}
/**
* Gets the value of an attribute.
* @method get
* @param {String} attr The name of an attribute.
*/
(0, _createClass3.default)(ParseConfig, [{
key: 'get',
value: function (attr) {
return this.attributes[attr];
}
/**
* Gets the HTML-escaped value of an attribute.
* @method escape
* @param {String} attr The name of an attribute.
*/
}, {
key: 'escape',
value: function (attr) {
var html = this._escapedAttributes[attr];
if (html) {
return html;
}
var val = this.attributes[attr];
var escaped = '';
if (val != null) {
escaped = (0, _escape3.default)(val.toString());
}
this._escapedAttributes[attr] = escaped;
return escaped;
}
/**
* Retrieves the most recently-fetched configuration object, either from
* memory or from local storage if necessary.
*
* @method current
* @static
* @return {Config} The most recently-fetched Parse.Config if it
* exists, else an empty Parse.Config.
*/
}], [{
key: 'current',
value: function () {
var controller = _CoreManager2.default.getConfigController();
return controller.current();
}
/**
* Gets a new configuration object from the server.
* @method get
* @static
* @param {Object} options A Backbone-style options object.
* Valid options are:<ul>
* <li>success: Function to call when the get completes successfully.
* <li>error: Function to call when the get fails.
* </ul>
* @return {Parse.Promise} A promise that is resolved with a newly-created
* configuration object when the get completes.
*/
}, {
key: 'get',
value: function (options) {
options = options || {};
var controller = _CoreManager2.default.getConfigController();
return controller.get()._thenRunCallbacks(options);
}
}]);
return ParseConfig;
}(); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParseConfig;
var currentConfig = null;
var CURRENT_CONFIG_KEY = 'currentConfig';
function decodePayload(data) {
try {
var json = JSON.parse(data);
if (json && (typeof json === 'undefined' ? 'undefined' : (0, _typeof3.default)(json)) === 'object') {
return (0, _decode2.default)(json);
}
} catch (e) {
return null;
}
}
var DefaultController = {
current: function () {
if (currentConfig) {
return currentConfig;
}
var config = new ParseConfig();
var storagePath = _Storage2.default.generatePath(CURRENT_CONFIG_KEY);
var configData;
if (!_Storage2.default.async()) {
configData = _Storage2.default.getItem(storagePath);
if (configData) {
var attributes = decodePayload(configData);
if (attributes) {
config.attributes = attributes;
currentConfig = config;
}
}
return config;
}
// Return a promise for async storage controllers
return _Storage2.default.getItemAsync(storagePath).then(function (configData) {
if (configData) {
var attributes = decodePayload(configData);
if (attributes) {
config.attributes = attributes;
currentConfig = config;
}
}
return config;
});
},
get: function () {
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('GET', 'config', {}, {}).then(function (response) {
if (!response || !response.params) {
var error = new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'Config JSON response invalid.');
return _ParsePromise2.default.error(error);
}
var config = new ParseConfig();
config.attributes = {};
for (var attr in response.params) {
config.attributes[attr] = (0, _decode2.default)(response.params[attr]);
}
currentConfig = config;
return _Storage2.default.setItemAsync(_Storage2.default.generatePath(CURRENT_CONFIG_KEY), (0, _stringify2.default)(response.params)).then(function () {
return config;
});
});
}
};
_CoreManager2.default.setConfigController(DefaultController);
},{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./Storage":30,"./decode":36,"./encode":37,"./escape":39,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],13:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
/**
* Constructs a new Parse.Error object with the given code and message.
* @class Parse.Error
* @constructor
* @param {Number} code An error code constant from <code>Parse.Error</code>.
* @param {String} message A detailed description of the error.
*/
var ParseError = function () {
function ParseError(code, message) {
(0, _classCallCheck3.default)(this, ParseError);
this.code = code;
this.message = message;
}
(0, _createClass3.default)(ParseError, [{
key: 'toString',
value: function () {
return 'ParseError: ' + this.code + ' ' + this.message;
}
}]);
return ParseError;
}();
/**
* Error code indicating some error other than those enumerated here.
* @property OTHER_CAUSE
* @static
* @final
*/
exports.default = ParseError;
ParseError.OTHER_CAUSE = -1;
/**
* Error code indicating that something has gone wrong with the server.
* If you get this error code, it is Parse's fault. Contact us at
* https://parse.com/help
* @property INTERNAL_SERVER_ERROR
* @static
* @final
*/
ParseError.INTERNAL_SERVER_ERROR = 1;
/**
* Error code indicating the connection to the Parse servers failed.
* @property CONNECTION_FAILED
* @static
* @final
*/
ParseError.CONNECTION_FAILED = 100;
/**
* Error code indicating the specified object doesn't exist.
* @property OBJECT_NOT_FOUND
* @static
* @final
*/
ParseError.OBJECT_NOT_FOUND = 101;
/**
* Error code indicating you tried to query with a datatype that doesn't
* support it, like exact matching an array or object.
* @property INVALID_QUERY
* @static
* @final
*/
ParseError.INVALID_QUERY = 102;
/**
* Error code indicating a missing or invalid classname. Classnames are
* case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
* only valid characters.
* @property INVALID_CLASS_NAME
* @static
* @final
*/
ParseError.INVALID_CLASS_NAME = 103;
/**
* Error code indicating an unspecified object id.
* @property MISSING_OBJECT_ID
* @static
* @final
*/
ParseError.MISSING_OBJECT_ID = 104;
/**
* Error code indicating an invalid key name. Keys are case-sensitive. They
* must start with a letter, and a-zA-Z0-9_ are the only valid characters.
* @property INVALID_KEY_NAME
* @static
* @final
*/
ParseError.INVALID_KEY_NAME = 105;
/**
* Error code indicating a malformed pointer. You should not see this unless
* you have been mucking about changing internal Parse code.
* @property INVALID_POINTER
* @static
* @final
*/
ParseError.INVALID_POINTER = 106;
/**
* Error code indicating that badly formed JSON was received upstream. This
* either indicates you have done something unusual with modifying how
* things encode to JSON, or the network is failing badly.
* @property INVALID_JSON
* @static
* @final
*/
ParseError.INVALID_JSON = 107;
/**
* Error code indicating that the feature you tried to access is only
* available internally for testing purposes.
* @property COMMAND_UNAVAILABLE
* @static
* @final
*/
ParseError.COMMAND_UNAVAILABLE = 108;
/**
* You must call Parse.initialize before using the Parse library.
* @property NOT_INITIALIZED
* @static
* @final
*/
ParseError.NOT_INITIALIZED = 109;
/**
* Error code indicating that a field was set to an inconsistent type.
* @property INCORRECT_TYPE
* @static
* @final
*/
ParseError.INCORRECT_TYPE = 111;
/**
* Error code indicating an invalid channel name. A channel name is either
* an empty string (the broadcast channel) or contains only a-zA-Z0-9_
* characters and starts with a letter.
* @property INVALID_CHANNEL_NAME
* @static
* @final
*/
ParseError.INVALID_CHANNEL_NAME = 112;
/**
* Error code indicating that push is misconfigured.
* @property PUSH_MISCONFIGURED
* @static
* @final
*/
ParseError.PUSH_MISCONFIGURED = 115;
/**
* Error code indicating that the object is too large.
* @property OBJECT_TOO_LARGE
* @static
* @final
*/
ParseError.OBJECT_TOO_LARGE = 116;
/**
* Error code indicating that the operation isn't allowed for clients.
* @property OPERATION_FORBIDDEN
* @static
* @final
*/
ParseError.OPERATION_FORBIDDEN = 119;
/**
* Error code indicating the result was not found in the cache.
* @property CACHE_MISS
* @static
* @final
*/
ParseError.CACHE_MISS = 120;
/**
* Error code indicating that an invalid key was used in a nested
* JSONObject.
* @property INVALID_NESTED_KEY
* @static
* @final
*/
ParseError.INVALID_NESTED_KEY = 121;
/**
* Error code indicating that an invalid filename was used for ParseFile.
* A valid file name contains only a-zA-Z0-9_. characters and is between 1
* and 128 characters.
* @property INVALID_FILE_NAME
* @static
* @final
*/
ParseError.INVALID_FILE_NAME = 122;
/**
* Error code indicating an invalid ACL was provided.
* @property INVALID_ACL
* @static
* @final
*/
ParseError.INVALID_ACL = 123;
/**
* Error code indicating that the request timed out on the server. Typically
* this indicates that the request is too expensive to run.
* @property TIMEOUT
* @static
* @final
*/
ParseError.TIMEOUT = 124;
/**
* Error code indicating that the email address was invalid.
* @property INVALID_EMAIL_ADDRESS
* @static
* @final
*/
ParseError.INVALID_EMAIL_ADDRESS = 125;
/**
* Error code indicating a missing content type.
* @property MISSING_CONTENT_TYPE
* @static
* @final
*/
ParseError.MISSING_CONTENT_TYPE = 126;
/**
* Error code indicating a missing content length.
* @property MISSING_CONTENT_LENGTH
* @static
* @final
*/
ParseError.MISSING_CONTENT_LENGTH = 127;
/**
* Error code indicating an invalid content length.
* @property INVALID_CONTENT_LENGTH
* @static
* @final
*/
ParseError.INVALID_CONTENT_LENGTH = 128;
/**
* Error code indicating a file that was too large.
* @property FILE_TOO_LARGE
* @static
* @final
*/
ParseError.FILE_TOO_LARGE = 129;
/**
* Error code indicating an error saving a file.
* @property FILE_SAVE_ERROR
* @static
* @final
*/
ParseError.FILE_SAVE_ERROR = 130;
/**
* Error code indicating that a unique field was given a value that is
* already taken.
* @property DUPLICATE_VALUE
* @static
* @final
*/
ParseError.DUPLICATE_VALUE = 137;
/**
* Error code indicating that a role's name is invalid.
* @property INVALID_ROLE_NAME
* @static
* @final
*/
ParseError.INVALID_ROLE_NAME = 139;
/**
* Error code indicating that an application quota was exceeded. Upgrade to
* resolve.
* @property EXCEEDED_QUOTA
* @static
* @final
*/
ParseError.EXCEEDED_QUOTA = 140;
/**
* Error code indicating that a Cloud Code script failed.
* @property SCRIPT_FAILED
* @static
* @final
*/
ParseError.SCRIPT_FAILED = 141;
/**
* Error code indicating that a Cloud Code validation failed.
* @property VALIDATION_ERROR
* @static
* @final
*/
ParseError.VALIDATION_ERROR = 142;
/**
* Error code indicating that invalid image data was provided.
* @property INVALID_IMAGE_DATA
* @static
* @final
*/
ParseError.INVALID_IMAGE_DATA = 143;
/**
* Error code indicating an unsaved file.
* @property UNSAVED_FILE_ERROR
* @static
* @final
*/
ParseError.UNSAVED_FILE_ERROR = 151;
/**
* Error code indicating an invalid push time.
* @property INVALID_PUSH_TIME_ERROR
* @static
* @final
*/
ParseError.INVALID_PUSH_TIME_ERROR = 152;
/**
* Error code indicating an error deleting a file.
* @property FILE_DELETE_ERROR
* @static
* @final
*/
ParseError.FILE_DELETE_ERROR = 153;
/**
* Error code indicating that the application has exceeded its request
* limit.
* @property REQUEST_LIMIT_EXCEEDED
* @static
* @final
*/
ParseError.REQUEST_LIMIT_EXCEEDED = 155;
/**
* Error code indicating an invalid event name.
* @property INVALID_EVENT_NAME
* @static
* @final
*/
ParseError.INVALID_EVENT_NAME = 160;
/**
* Error code indicating that the username is missing or empty.
* @property USERNAME_MISSING
* @static
* @final
*/
ParseError.USERNAME_MISSING = 200;
/**
* Error code indicating that the password is missing or empty.
* @property PASSWORD_MISSING
* @static
* @final
*/
ParseError.PASSWORD_MISSING = 201;
/**
* Error code indicating that the username has already been taken.
* @property USERNAME_TAKEN
* @static
* @final
*/
ParseError.USERNAME_TAKEN = 202;
/**
* Error code indicating that the email has already been taken.
* @property EMAIL_TAKEN
* @static
* @final
*/
ParseError.EMAIL_TAKEN = 203;
/**
* Error code indicating that the email is missing, but must be specified.
* @property EMAIL_MISSING
* @static
* @final
*/
ParseError.EMAIL_MISSING = 204;
/**
* Error code indicating that a user with the specified email was not found.
* @property EMAIL_NOT_FOUND
* @static
* @final
*/
ParseError.EMAIL_NOT_FOUND = 205;
/**
* Error code indicating that a user object without a valid session could
* not be altered.
* @property SESSION_MISSING
* @static
* @final
*/
ParseError.SESSION_MISSING = 206;
/**
* Error code indicating that a user can only be created through signup.
* @property MUST_CREATE_USER_THROUGH_SIGNUP
* @static
* @final
*/
ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207;
/**
* Error code indicating that an an account being linked is already linked
* to another user.
* @property ACCOUNT_ALREADY_LINKED
* @static
* @final
*/
ParseError.ACCOUNT_ALREADY_LINKED = 208;
/**
* Error code indicating that the current session token is invalid.
* @property INVALID_SESSION_TOKEN
* @static
* @final
*/
ParseError.INVALID_SESSION_TOKEN = 209;
/**
* Error code indicating that a user cannot be linked to an account because
* that account's id could not be found.
* @property LINKED_ID_MISSING
* @static
* @final
*/
ParseError.LINKED_ID_MISSING = 250;
/**
* Error code indicating that a user with a linked (e.g. Facebook) account
* has an invalid session.
* @property INVALID_LINKED_SESSION
* @static
* @final
*/
ParseError.INVALID_LINKED_SESSION = 251;
/**
* Error code indicating that a service being linked (e.g. Facebook or
* Twitter) is unsupported.
* @property UNSUPPORTED_SERVICE
* @static
* @final
*/
ParseError.UNSUPPORTED_SERVICE = 252;
/**
* Error code indicating that there were multiple errors. Aggregate errors
* have an "errors" property, which is an array of error objects with more
* detail about each error that occurred.
* @property AGGREGATE_ERROR
* @static
* @final
*/
ParseError.AGGREGATE_ERROR = 600;
/**
* Error code indicating the client was unable to read an input file.
* @property FILE_READ_ERROR
* @static
* @final
*/
ParseError.FILE_READ_ERROR = 601;
/**
* Error code indicating a real error code is unavailable because
* we had to use an XDomainRequest object to allow CORS requests in
* Internet Explorer, which strips the body from HTTP responses that have
* a non-2XX status code.
* @property X_DOMAIN_REQUEST
* @static
* @final
*/
ParseError.X_DOMAIN_REQUEST = 602;
},{"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],14:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var dataUriRegexp = /^data:([a-zA-Z]*\/[a-zA-Z+.-]*);(charset=[a-zA-Z0-9\-\/\s]*,)?base64,/;
function b64Digit(number) {
if (number < 26) {
return String.fromCharCode(65 + number);
}
if (number < 52) {
return String.fromCharCode(97 + (number - 26));
}
if (number < 62) {
return String.fromCharCode(48 + (number - 52));
}
if (number === 62) {
return '+';
}
if (number === 63) {
return '/';
}
throw new TypeError('Tried to encode large digit ' + number + ' in base64.');
}
/**
* A Parse.File is a local representation of a file that is saved to the Parse
* cloud.
* @class Parse.File
* @constructor
* @param name {String} The file's name. This will be prefixed by a unique
* value once the file has finished saving. The file name must begin with
* an alphanumeric character, and consist of alphanumeric characters,
* periods, spaces, underscores, or dashes.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:<pre>
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var parseFile = new Parse.File(name, file);
* parseFile.save().then(function() {
* // The file has been saved to Parse.
* }, function(error) {
* // The file either could not be read, or could not be saved to Parse.
* });
* }</pre>
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
*/
var ParseFile = function () {
function ParseFile(name, data, type) {
(0, _classCallCheck3.default)(this, ParseFile);
var specifiedType = type || '';
this._name = name;
if (data !== undefined) {
if (Array.isArray(data)) {
this._source = {
format: 'base64',
base64: ParseFile.encodeBase64(data),
type: specifiedType
};
} else if (typeof File !== 'undefined' && data instanceof File) {
this._source = {
format: 'file',
file: data,
type: specifiedType
};
} else if (data && typeof data.base64 === 'string') {
var _base = data.base64;
var commaIndex = _base.indexOf(',');
if (commaIndex !== -1) {
var matches = dataUriRegexp.exec(_base.slice(0, commaIndex + 1));
// if data URI with type and charset, there will be 4 matches.
this._source = {
format: 'base64',
base64: _base.slice(commaIndex + 1),
type: matches[1]
};
} else {
this._source = {
format: 'base64',
base64: _base,
type: specifiedType
};
}
} else {
throw new TypeError('Cannot create a Parse.File with that data.');
}
}
}
/**
* Gets the name of the file. Before save is called, this is the filename
* given by the user. After save is called, that name gets prefixed with a
* unique identifier.
* @method name
* @return {String}
*/
(0, _createClass3.default)(ParseFile, [{
key: 'name',
value: function () {
return this._name;
}
/**
* Gets the url of the file. It is only available after you save the file or
* after you get the file from a Parse.Object.
* @method url
* @param {Object} options An object to specify url options
* @return {String}
*/
}, {
key: 'url',
value: function (options) {
options = options || {};
if (!this._url) {
return;
}
if (options.forceSecure) {
return this._url.replace(/^http:\/\//i, 'https://');
} else {
return this._url;
}
}
/**
* Saves the file to the Parse cloud.
* @method save
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} Promise that is resolved when the save finishes.
*/
}, {
key: 'save',
value: function (options) {
var _this = this;
options = options || {};
var controller = _CoreManager2.default.getFileController();
if (!this._previousSave) {
if (this._source.format === 'file') {
this._previousSave = controller.saveFile(this._name, this._source, options).then(function (res) {
_this._name = res.name;
_this._url = res.url;
return _this;
});
} else {
this._previousSave = controller.saveBase64(this._name, this._source, options).then(function (res) {
_this._name = res.name;
_this._url = res.url;
return _this;
});
}
}
if (this._previousSave) {
return this._previousSave._thenRunCallbacks(options);
}
}
}, {
key: 'toJSON',
value: function () {
return {
__type: 'File',
name: this._name,
url: this._url
};
}
}, {
key: 'equals',
value: function (other) {
if (this === other) {
return true;
}
// Unsaved Files are never equal, since they will be saved to different URLs
return other instanceof ParseFile && this.name() === other.name() && this.url() === other.url() && typeof this.url() !== 'undefined';
}
}], [{
key: 'fromJSON',
value: function (obj) {
if (obj.__type !== 'File') {
throw new TypeError('JSON object does not represent a ParseFile');
}
var file = new ParseFile(obj.name);
file._url = obj.url;
return file;
}
}, {
key: 'encodeBase64',
value: function (bytes) {
var chunks = [];
chunks.length = Math.ceil(bytes.length / 3);
for (var i = 0; i < chunks.length; i++) {
var b1 = bytes[i * 3];
var b2 = bytes[i * 3 + 1] || 0;
var b3 = bytes[i * 3 + 2] || 0;
var has2 = i * 3 + 1 < bytes.length;
var has3 = i * 3 + 2 < bytes.length;
chunks[i] = [b64Digit(b1 >> 2 & 0x3F), b64Digit(b1 << 4 & 0x30 | b2 >> 4 & 0x0F), has2 ? b64Digit(b2 << 2 & 0x3C | b3 >> 6 & 0x03) : '=', has3 ? b64Digit(b3 & 0x3F) : '='].join('');
}
return chunks.join('');
}
}]);
return ParseFile;
}();
exports.default = ParseFile;
var DefaultController = {
saveFile: function (name, source) {
if (source.format !== 'file') {
throw new Error('saveFile can only be used with File-type sources.');
}
// To directly upload a File, we use a REST-style AJAX request
var headers = {
'X-Parse-Application-ID': _CoreManager2.default.get('APPLICATION_ID'),
'X-Parse-JavaScript-Key': _CoreManager2.default.get('JAVASCRIPT_KEY'),
'Content-Type': source.type || (source.file ? source.file.type : null)
};
var url = _CoreManager2.default.get('SERVER_URL');
if (url[url.length - 1] !== '/') {
url += '/';
}
url += 'files/' + name;
return _CoreManager2.default.getRESTController().ajax('POST', url, source.file, headers);
},
saveBase64: function (name, source, options) {
if (source.format !== 'base64') {
throw new Error('saveBase64 can only be used with Base64-type sources.');
}
var data = {
base64: source.base64
};
if (source.type) {
data._ContentType = source.type;
}
return _CoreManager2.default.getRESTController().request('POST', 'files/' + name, data, options);
}
};
_CoreManager2.default.setFileController(DefaultController);
},{"./CoreManager":3,"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],15:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Creates a new GeoPoint with any of the following forms:<br>
* <pre>
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
* </pre>
* @class Parse.GeoPoint
* @constructor
*
* <p>Represents a latitude / longitude point that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.</p>
*
* <p>Only one key in a class may contain a GeoPoint.</p>
*
* <p>Example:<pre>
* var point = new Parse.GeoPoint(30.0, -20.0);
* var object = new Parse.Object("PlaceObject");
* object.set("location", point);
* object.save();</pre></p>
*/
var ParseGeoPoint = function () {
function ParseGeoPoint(arg1, arg2) {
(0, _classCallCheck3.default)(this, ParseGeoPoint);
if (Array.isArray(arg1)) {
ParseGeoPoint._validate(arg1[0], arg1[1]);
this._latitude = arg1[0];
this._longitude = arg1[1];
} else if ((typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object') {
ParseGeoPoint._validate(arg1.latitude, arg1.longitude);
this._latitude = arg1.latitude;
this._longitude = arg1.longitude;
} else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
ParseGeoPoint._validate(arg1, arg2);
this._latitude = arg1;
this._longitude = arg2;
} else {
this._latitude = 0;
this._longitude = 0;
}
}
/**
* North-south portion of the coordinate, in range [-90, 90].
* Throws an exception if set out of range in a modern browser.
* @property latitude
* @type Number
*/
(0, _createClass3.default)(ParseGeoPoint, [{
key: 'toJSON',
/**
* Returns a JSON representation of the GeoPoint, suitable for Parse.
* @method toJSON
* @return {Object}
*/
value: function () {
ParseGeoPoint._validate(this._latitude, this._longitude);
return {
__type: 'GeoPoint',
latitude: this._latitude,
longitude: this._longitude
};
}
}, {
key: 'equals',
value: function (other) {
return other instanceof ParseGeoPoint && this.latitude === other.latitude && this.longitude === other.longitude;
}
/**
* Returns the distance from this GeoPoint to another in radians.
* @method radiansTo
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
}, {
key: 'radiansTo',
value: function (point) {
var d2r = Math.PI / 180.0;
var lat1rad = this.latitude * d2r;
var long1rad = this.longitude * d2r;
var lat2rad = point.latitude * d2r;
var long2rad = point.longitude * d2r;
var sinDeltaLatDiv2 = Math.sin((lat1rad - lat2rad) / 2);
var sinDeltaLongDiv2 = Math.sin((long1rad - long2rad) / 2);
// Square of half the straight line chord distance between both points.
var a = sinDeltaLatDiv2 * sinDeltaLatDiv2 + Math.cos(lat1rad) * Math.cos(lat2rad) * sinDeltaLongDiv2 * sinDeltaLongDiv2;
a = Math.min(1.0, a);
return 2 * Math.asin(Math.sqrt(a));
}
/**
* Returns the distance from this GeoPoint to another in kilometers.
* @method kilometersTo
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
}, {
key: 'kilometersTo',
value: function (point) {
return this.radiansTo(point) * 6371.0;
}
/**
* Returns the distance from this GeoPoint to another in miles.
* @method milesTo
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
}, {
key: 'milesTo',
value: function (point) {
return this.radiansTo(point) * 3958.8;
}
/**
* Throws an exception if the given lat-long is out of bounds.
*/
}, {
key: 'latitude',
get: function () {
return this._latitude;
},
set: function (val) {
ParseGeoPoint._validate(val, this.longitude);
this._latitude = val;
}
/**
* East-west portion of the coordinate, in range [-180, 180].
* Throws if set out of range in a modern browser.
* @property longitude
* @type Number
*/
}, {
key: 'longitude',
get: function () {
return this._longitude;
},
set: function (val) {
ParseGeoPoint._validate(this.latitude, val);
this._longitude = val;
}
}], [{
key: '_validate',
value: function (latitude, longitude) {
if (latitude !== latitude || longitude !== longitude) {
throw new TypeError('GeoPoint latitude and longitude must be valid numbers');
}
if (latitude < -90.0) {
throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' < -90.0.');
}
if (latitude > 90.0) {
throw new TypeError('GeoPoint latitude out of bounds: ' + latitude + ' > 90.0.');
}
if (longitude < -180.0) {
throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' < -180.0.');
}
if (longitude > 180.0) {
throw new TypeError('GeoPoint longitude out of bounds: ' + longitude + ' > 180.0.');
}
}
/**
* Creates a GeoPoint with the user's current location, if available.
* Calls options.success with a new GeoPoint instance or calls options.error.
* @method current
* @param {Object} options An object with success and error callbacks.
* @static
*/
}, {
key: 'current',
value: function (options) {
var promise = new _ParsePromise2.default();
navigator.geolocation.getCurrentPosition(function (location) {
promise.resolve(new ParseGeoPoint(location.coords.latitude, location.coords.longitude));
}, function (error) {
promise.reject(error);
});
return promise._thenRunCallbacks(options);
}
}]);
return ParseGeoPoint;
}(); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParseGeoPoint;
},{"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],16:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _ParseObject2 = _dereq_('./ParseObject');
var _ParseObject3 = _interopRequireDefault(_ParseObject2);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var Installation = function (_ParseObject) {
(0, _inherits3.default)(Installation, _ParseObject);
function Installation(attributes) {
(0, _classCallCheck3.default)(this, Installation);
var _this = (0, _possibleConstructorReturn3.default)(this, (Installation.__proto__ || (0, _getPrototypeOf2.default)(Installation)).call(this, '_Installation'));
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
if (!_this.set(attributes || {})) {
throw new Error('Can\'t create an invalid Session');
}
}
return _this;
}
return Installation;
}(_ParseObject3.default); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = Installation;
_ParseObject3.default.registerSubclass('_Installation', Installation);
},{"./ParseObject":18,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],17:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _EventEmitter = _dereq_('./EventEmitter');
var _EventEmitter2 = _interopRequireDefault(_EventEmitter);
var _LiveQueryClient = _dereq_('./LiveQueryClient');
var _LiveQueryClient2 = _interopRequireDefault(_LiveQueryClient);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function open() {
var LiveQueryController = _CoreManager2.default.getLiveQueryController();
LiveQueryController.open();
}
function close() {
var LiveQueryController = _CoreManager2.default.getLiveQueryController();
LiveQueryController.close();
}
/**
*
* We expose three events to help you monitor the status of the WebSocket connection:
*
* <p>Open - When we establish the WebSocket connection to the LiveQuery server, you'll get this event.
*
* <pre>
* Parse.LiveQuery.on('open', () => {
*
* });</pre></p>
*
* <p>Close - When we lose the WebSocket connection to the LiveQuery server, you'll get this event.
*
* <pre>
* Parse.LiveQuery.on('close', () => {
*
* });</pre></p>
*
* <p>Error - When some network error or LiveQuery server error happens, you'll get this event.
*
* <pre>
* Parse.LiveQuery.on('error', (error) => {
*
* });</pre></p>
*
* @class Parse.LiveQuery
* @static
*
*/
var LiveQuery = new _EventEmitter2.default();
/**
* After open is called, the LiveQuery will try to send a connect request
* to the LiveQuery server.
*
* @method open
*/
LiveQuery.open = open;
/**
* When you're done using LiveQuery, you can call Parse.LiveQuery.close().
* This function will close the WebSocket connection to the LiveQuery server,
* cancel the auto reconnect, and unsubscribe all subscriptions based on it.
* If you call query.subscribe() after this, we'll create a new WebSocket
* connection to the LiveQuery server.
*
* @method close
*/
LiveQuery.close = close;
// Register a default onError callback to make sure we do not crash on error
LiveQuery.on('error', function () {});
exports.default = LiveQuery;
function getSessionToken() {
var controller = _CoreManager2.default.getUserController();
return controller.currentUserAsync().then(function (currentUser) {
return currentUser ? currentUser.getSessionToken() : undefined;
});
}
function getLiveQueryClient() {
return _CoreManager2.default.getLiveQueryController().getDefaultLiveQueryClient();
}
var defaultLiveQueryClient = void 0;
var DefaultLiveQueryController = {
setDefaultLiveQueryClient: function (liveQueryClient) {
defaultLiveQueryClient = liveQueryClient;
},
getDefaultLiveQueryClient: function () {
if (defaultLiveQueryClient) {
return _ParsePromise2.default.as(defaultLiveQueryClient);
}
return getSessionToken().then(function (sessionToken) {
var liveQueryServerURL = _CoreManager2.default.get('LIVEQUERY_SERVER_URL');
if (liveQueryServerURL && liveQueryServerURL.indexOf('ws') !== 0) {
throw new Error('You need to set a proper Parse LiveQuery server url before using LiveQueryClient');
}
// If we can not find Parse.liveQueryServerURL, we try to extract it from Parse.serverURL
if (!liveQueryServerURL) {
var tempServerURL = _CoreManager2.default.get('SERVER_URL');
var protocol = 'ws://';
// If Parse is being served over SSL/HTTPS, ensure LiveQuery Server uses 'wss://' prefix
if (tempServerURL.indexOf('https') === 0) {
protocol = 'wss://';
}
var host = tempServerURL.replace(/^https?:\/\//, '');
liveQueryServerURL = protocol + host;
_CoreManager2.default.set('LIVEQUERY_SERVER_URL', liveQueryServerURL);
}
var applicationId = _CoreManager2.default.get('APPLICATION_ID');
var javascriptKey = _CoreManager2.default.get('JAVASCRIPT_KEY');
var masterKey = _CoreManager2.default.get('MASTER_KEY');
// Get currentUser sessionToken if possible
defaultLiveQueryClient = new _LiveQueryClient2.default({
applicationId: applicationId,
serverURL: liveQueryServerURL,
javascriptKey: javascriptKey,
masterKey: masterKey,
sessionToken: sessionToken
});
// Register a default onError callback to make sure we do not crash on error
// Cannot create these events on a nested way because of EventEmiiter from React Native
defaultLiveQueryClient.on('error', function (error) {
LiveQuery.emit('error', error);
});
defaultLiveQueryClient.on('open', function () {
LiveQuery.emit('open');
});
defaultLiveQueryClient.on('close', function () {
LiveQuery.emit('close');
});
return defaultLiveQueryClient;
});
},
open: function () {
var _this = this;
getLiveQueryClient().then(function (liveQueryClient) {
_this.resolve(liveQueryClient.open());
});
},
close: function () {
var _this2 = this;
getLiveQueryClient().then(function (liveQueryClient) {
_this2.resolve(liveQueryClient.close());
});
},
subscribe: function (query) {
var _this3 = this;
var subscriptionWrap = new _EventEmitter2.default();
getLiveQueryClient().then(function (liveQueryClient) {
if (liveQueryClient.shouldOpen()) {
liveQueryClient.open();
}
var promiseSessionToken = getSessionToken();
// new event emitter
return promiseSessionToken.then(function (sessionToken) {
var subscription = liveQueryClient.subscribe(query, sessionToken);
// enter, leave create, etc
subscriptionWrap.id = subscription.id;
subscriptionWrap.query = subscription.query;
subscriptionWrap.sessionToken = subscription.sessionToken;
subscriptionWrap.unsubscribe = subscription.unsubscribe;
// Cannot create these events on a nested way because of EventEmiiter from React Native
subscription.on('open', function () {
subscriptionWrap.emit('open');
});
subscription.on('create', function (object) {
subscriptionWrap.emit('create', object);
});
subscription.on('update', function (object) {
subscriptionWrap.emit('update', object);
});
subscription.on('enter', function (object) {
subscriptionWrap.emit('enter', object);
});
subscription.on('leave', function (object) {
subscriptionWrap.emit('leave', object);
});
subscription.on('delete', function (object) {
subscriptionWrap.emit('delete', object);
});
subscription.on('close', function (object) {
subscriptionWrap.emit('close', object);
});
subscription.on('error', function (object) {
subscriptionWrap.emit('error', object);
});
_this3.resolve();
});
});
return subscriptionWrap;
},
unsubscribe: function (subscription) {
var _this4 = this;
getLiveQueryClient().then(function (liveQueryClient) {
_this4.resolve(liveQueryClient.unsubscribe(subscription));
});
},
_clearCachedDefaultClient: function () {
defaultLiveQueryClient = null;
}
};
_CoreManager2.default.setLiveQueryController(DefaultLiveQueryController);
},{"./CoreManager":3,"./EventEmitter":4,"./LiveQueryClient":7,"./ParsePromise":21}],18:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _defineProperty = _dereq_('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _create = _dereq_('babel-runtime/core-js/object/create');
var _create2 = _interopRequireDefault(_create);
var _freeze = _dereq_('babel-runtime/core-js/object/freeze');
var _freeze2 = _interopRequireDefault(_freeze);
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _keys = _dereq_('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _canBeSerialized = _dereq_('./canBeSerialized');
var _canBeSerialized2 = _interopRequireDefault(_canBeSerialized);
var _decode = _dereq_('./decode');
var _decode2 = _interopRequireDefault(_decode);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _equals = _dereq_('./equals');
var _equals2 = _interopRequireDefault(_equals);
var _escape2 = _dereq_('./escape');
var _escape3 = _interopRequireDefault(_escape2);
var _ParseACL = _dereq_('./ParseACL');
var _ParseACL2 = _interopRequireDefault(_ParseACL);
var _parseDate = _dereq_('./parseDate');
var _parseDate2 = _interopRequireDefault(_parseDate);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseOp = _dereq_('./ParseOp');
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _ParseQuery = _dereq_('./ParseQuery');
var _ParseQuery2 = _interopRequireDefault(_ParseQuery);
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
var _SingleInstanceStateController = _dereq_('./SingleInstanceStateController');
var SingleInstanceStateController = _interopRequireWildcard(_SingleInstanceStateController);
var _unique = _dereq_('./unique');
var _unique2 = _interopRequireDefault(_unique);
var _UniqueInstanceStateController = _dereq_('./UniqueInstanceStateController');
var UniqueInstanceStateController = _interopRequireWildcard(_UniqueInstanceStateController);
var _unsavedChildren = _dereq_('./unsavedChildren');
var _unsavedChildren2 = _interopRequireDefault(_unsavedChildren);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj.default = obj;return newObj;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
// Mapping of class names to constructors, so we can populate objects from the
// server with appropriate subclasses of ParseObject
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var classMap = {};
// Global counter for generating unique local Ids
var localCount = 0;
// Global counter for generating unique Ids for non-single-instance objects
var objectCount = 0;
// On web clients, objects are single-instance: any two objects with the same Id
// will have the same attributes. However, this may be dangerous default
// behavior in a server scenario
var singleInstance = !_CoreManager2.default.get('IS_NODE');
if (singleInstance) {
_CoreManager2.default.setObjectStateController(SingleInstanceStateController);
} else {
_CoreManager2.default.setObjectStateController(UniqueInstanceStateController);
}
function getServerUrlPath() {
var serverUrl = _CoreManager2.default.get('SERVER_URL');
if (serverUrl[serverUrl.length - 1] !== '/') {
serverUrl += '/';
}
var url = serverUrl.replace(/https?:\/\//, '');
return url.substr(url.indexOf('/'));
}
/**
* Creates a new model with defined attributes.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>Parse.Object</code> instead, created by calling
* <code>extend</code>.</p>
*
* <p>However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:<pre>
* var object = new Parse.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @class Parse.Object
* @constructor
* @param {String} className The class name for the object
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options The options for this object instance.
*/
var ParseObject = function () {
/**
* The ID of this object, unique within its class.
* @property id
* @type String
*/
function ParseObject(className, attributes, options) {
(0, _classCallCheck3.default)(this, ParseObject);
// Enable legacy initializers
if (typeof this.initialize === 'function') {
this.initialize.apply(this, arguments);
}
var toSet = null;
this._objCount = objectCount++;
if (typeof className === 'string') {
this.className = className;
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
toSet = attributes;
}
} else if (className && (typeof className === 'undefined' ? 'undefined' : (0, _typeof3.default)(className)) === 'object') {
this.className = className.className;
toSet = {};
for (var attr in className) {
if (attr !== 'className') {
toSet[attr] = className[attr];
}
}
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
options = attributes;
}
}
if (toSet && !this.set(toSet, options)) {
throw new Error('Can\'t create an invalid Parse Object');
}
}
/** Prototype getters / setters **/
(0, _createClass3.default)(ParseObject, [{
key: '_getId',
/** Private methods **/
/**
* Returns a local or server Id used uniquely identify this object
*/
value: function () {
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
var localId = 'local' + String(localCount++);
this._localId = localId;
return localId;
}
/**
* Returns a unique identifier used to pull data from the State Controller.
*/
}, {
key: '_getStateIdentifier',
value: function () {
if (singleInstance) {
var _id = this.id;
if (!_id) {
_id = this._getId();
}
return {
id: _id,
className: this.className
};
} else {
return this;
}
}
}, {
key: '_getServerData',
value: function () {
var stateController = _CoreManager2.default.getObjectStateController();
return stateController.getServerData(this._getStateIdentifier());
}
}, {
key: '_clearServerData',
value: function () {
var serverData = this._getServerData();
var unset = {};
for (var attr in serverData) {
unset[attr] = undefined;
}
var stateController = _CoreManager2.default.getObjectStateController();
stateController.setServerData(this._getStateIdentifier(), unset);
}
}, {
key: '_getPendingOps',
value: function () {
var stateController = _CoreManager2.default.getObjectStateController();
return stateController.getPendingOps(this._getStateIdentifier());
}
}, {
key: '_clearPendingOps',
value: function () {
var pending = this._getPendingOps();
var latest = pending[pending.length - 1];
var keys = (0, _keys2.default)(latest);
keys.forEach(function (key) {
delete latest[key];
});
}
}, {
key: '_getDirtyObjectAttributes',
value: function () {
var attributes = this.attributes;
var stateController = _CoreManager2.default.getObjectStateController();
var objectCache = stateController.getObjectCache(this._getStateIdentifier());
var dirty = {};
for (var attr in attributes) {
var val = attributes[attr];
if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object' && !(val instanceof ParseObject) && !(val instanceof _ParseFile2.default) && !(val instanceof _ParseRelation2.default)) {
// Due to the way browsers construct maps, the key order will not change
// unless the object is changed
try {
var json = (0, _encode2.default)(val, false, true);
var stringified = (0, _stringify2.default)(json);
if (objectCache[attr] !== stringified) {
dirty[attr] = val;
}
} catch (e) {
// Error occurred, possibly by a nested unsaved pointer in a mutable container
// No matter how it happened, it indicates a change in the attribute
dirty[attr] = val;
}
}
}
return dirty;
}
}, {
key: '_toFullJSON',
value: function (seen) {
var json = this.toJSON(seen);
json.__type = 'Object';
json.className = this.className;
return json;
}
}, {
key: '_getSaveJSON',
value: function () {
var pending = this._getPendingOps();
var dirtyObjects = this._getDirtyObjectAttributes();
var json = {};
for (var attr in dirtyObjects) {
json[attr] = new _ParseOp.SetOp(dirtyObjects[attr]).toJSON();
}
for (attr in pending[0]) {
json[attr] = pending[0][attr].toJSON();
}
return json;
}
}, {
key: '_getSaveParams',
value: function () {
var method = this.id ? 'PUT' : 'POST';
var body = this._getSaveJSON();
var path = 'classes/' + this.className;
if (this.id) {
path += '/' + this.id;
} else if (this.className === '_User') {
path = 'users';
}
return {
method: method,
body: body,
path: path
};
}
}, {
key: '_finishFetch',
value: function (serverData) {
if (!this.id && serverData.objectId) {
this.id = serverData.objectId;
}
var stateController = _CoreManager2.default.getObjectStateController();
stateController.initializeState(this._getStateIdentifier());
var decoded = {};
for (var attr in serverData) {
if (attr === 'ACL') {
decoded[attr] = new _ParseACL2.default(serverData[attr]);
} else if (attr !== 'objectId') {
decoded[attr] = (0, _decode2.default)(serverData[attr]);
if (decoded[attr] instanceof _ParseRelation2.default) {
decoded[attr]._ensureParentAndKey(this, attr);
}
}
}
if (decoded.createdAt && typeof decoded.createdAt === 'string') {
decoded.createdAt = (0, _parseDate2.default)(decoded.createdAt);
}
if (decoded.updatedAt && typeof decoded.updatedAt === 'string') {
decoded.updatedAt = (0, _parseDate2.default)(decoded.updatedAt);
}
if (!decoded.updatedAt && decoded.createdAt) {
decoded.updatedAt = decoded.createdAt;
}
stateController.commitServerChanges(this._getStateIdentifier(), decoded);
}
}, {
key: '_setExisted',
value: function (existed) {
var stateController = _CoreManager2.default.getObjectStateController();
var state = stateController.getState(this._getStateIdentifier());
if (state) {
state.existed = existed;
}
}
}, {
key: '_migrateId',
value: function (serverId) {
if (this._localId && serverId) {
if (singleInstance) {
var stateController = _CoreManager2.default.getObjectStateController();
var oldState = stateController.removeState(this._getStateIdentifier());
this.id = serverId;
delete this._localId;
if (oldState) {
stateController.initializeState(this._getStateIdentifier(), oldState);
}
} else {
this.id = serverId;
delete this._localId;
}
}
}
}, {
key: '_handleSaveResponse',
value: function (response, status) {
var changes = {};
var stateController = _CoreManager2.default.getObjectStateController();
var pending = stateController.popPendingState(this._getStateIdentifier());
for (var attr in pending) {
if (pending[attr] instanceof _ParseOp.RelationOp) {
changes[attr] = pending[attr].applyTo(undefined, this, attr);
} else if (!(attr in response)) {
// Only SetOps and UnsetOps should not come back with results
changes[attr] = pending[attr].applyTo(undefined);
}
}
for (attr in response) {
if ((attr === 'createdAt' || attr === 'updatedAt') && typeof response[attr] === 'string') {
changes[attr] = (0, _parseDate2.default)(response[attr]);
} else if (attr === 'ACL') {
changes[attr] = new _ParseACL2.default(response[attr]);
} else if (attr !== 'objectId') {
changes[attr] = (0, _decode2.default)(response[attr]);
if (changes[attr] instanceof _ParseOp.UnsetOp) {
changes[attr] = undefined;
}
}
}
if (changes.createdAt && !changes.updatedAt) {
changes.updatedAt = changes.createdAt;
}
this._migrateId(response.objectId);
if (status !== 201) {
this._setExisted(true);
}
stateController.commitServerChanges(this._getStateIdentifier(), changes);
}
}, {
key: '_handleSaveError',
value: function () {
this._getPendingOps();
var stateController = _CoreManager2.default.getObjectStateController();
stateController.mergeFirstPendingState(this._getStateIdentifier());
}
/** Public methods **/
}, {
key: 'initialize',
value: function () {}
// NOOP
/**
* Returns a JSON version of the object suitable for saving to Parse.
* @method toJSON
* @return {Object}
*/
}, {
key: 'toJSON',
value: function (seen) {
var seenEntry = this.id ? this.className + ':' + this.id : this;
var seen = seen || [seenEntry];
var json = {};
var attrs = this.attributes;
for (var attr in attrs) {
if ((attr === 'createdAt' || attr === 'updatedAt') && attrs[attr].toJSON) {
json[attr] = attrs[attr].toJSON();
} else {
json[attr] = (0, _encode2.default)(attrs[attr], false, false, seen);
}
}
var pending = this._getPendingOps();
for (var attr in pending[0]) {
json[attr] = pending[0][attr].toJSON();
}
if (this.id) {
json.objectId = this.id;
}
return json;
}
/**
* Determines whether this ParseObject is equal to another ParseObject
* @method equals
* @return {Boolean}
*/
}, {
key: 'equals',
value: function (other) {
if (this === other) {
return true;
}
return other instanceof ParseObject && this.className === other.className && this.id === other.id && typeof this.id !== 'undefined';
}
/**
* Returns true if this object has been modified since its last
* save/refresh. If an attribute is specified, it returns true only if that
* particular attribute has been modified since the last save/refresh.
* @method dirty
* @param {String} attr An attribute name (optional).
* @return {Boolean}
*/
}, {
key: 'dirty',
value: function (attr) {
if (!this.id) {
return true;
}
var pendingOps = this._getPendingOps();
var dirtyObjects = this._getDirtyObjectAttributes();
if (attr) {
if (dirtyObjects.hasOwnProperty(attr)) {
return true;
}
for (var i = 0; i < pendingOps.length; i++) {
if (pendingOps[i].hasOwnProperty(attr)) {
return true;
}
}
return false;
}
if ((0, _keys2.default)(pendingOps[0]).length !== 0) {
return true;
}
if ((0, _keys2.default)(dirtyObjects).length !== 0) {
return true;
}
return false;
}
/**
* Returns an array of keys that have been modified since last save/refresh
* @method dirtyKeys
* @return {Array of string}
*/
}, {
key: 'dirtyKeys',
value: function () {
var pendingOps = this._getPendingOps();
var keys = {};
for (var i = 0; i < pendingOps.length; i++) {
for (var attr in pendingOps[i]) {
keys[attr] = true;
}
}
var dirtyObjects = this._getDirtyObjectAttributes();
for (var attr in dirtyObjects) {
keys[attr] = true;
}
return (0, _keys2.default)(keys);
}
/**
* Gets a Pointer referencing this Object.
* @method toPointer
* @return {Object}
*/
}, {
key: 'toPointer',
value: function () {
if (!this.id) {
throw new Error('Cannot create a pointer to an unsaved ParseObject');
}
return {
__type: 'Pointer',
className: this.className,
objectId: this.id
};
}
/**
* Gets the value of an attribute.
* @method get
* @param {String} attr The string name of an attribute.
*/
}, {
key: 'get',
value: function (attr) {
return this.attributes[attr];
}
/**
* Gets a relation on the given class for the attribute.
* @method relation
* @param String attr The attribute to get the relation for.
*/
}, {
key: 'relation',
value: function (attr) {
var value = this.get(attr);
if (value) {
if (!(value instanceof _ParseRelation2.default)) {
throw new Error('Called relation() on non-relation field ' + attr);
}
value._ensureParentAndKey(this, attr);
return value;
}
return new _ParseRelation2.default(this, attr);
}
/**
* Gets the HTML-escaped value of an attribute.
* @method escape
* @param {String} attr The string name of an attribute.
*/
}, {
key: 'escape',
value: function (attr) {
var val = this.attributes[attr];
if (val == null) {
return '';
}
if (typeof val !== 'string') {
if (typeof val.toString !== 'function') {
return '';
}
val = val.toString();
}
return (0, _escape3.default)(val);
}
/**
* Returns <code>true</code> if the attribute contains a value that is not
* null or undefined.
* @method has
* @param {String} attr The string name of the attribute.
* @return {Boolean}
*/
}, {
key: 'has',
value: function (attr) {
var attributes = this.attributes;
if (attributes.hasOwnProperty(attr)) {
return attributes[attr] != null;
}
return false;
}
/**
* Sets a hash of model attributes on the object.
*
* <p>You can call it with an object containing keys and values, or with one
* key and value. For example:<pre>
* gameTurn.set({
* player: player1,
* diceRoll: 2
* }, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("currentPlayer", player2, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("finished", true);</pre></p>
*
* @method set
* @param {String} key The key to set.
* @param {} value The value to give it.
* @param {Object} options A set of options for the set.
* The only supported option is <code>error</code>.
* @return {Boolean} true if the set succeeded.
*/
}, {
key: 'set',
value: function (key, value, options) {
var changes = {};
var newOps = {};
if (key && (typeof key === 'undefined' ? 'undefined' : (0, _typeof3.default)(key)) === 'object') {
changes = key;
options = value;
} else if (typeof key === 'string') {
changes[key] = value;
} else {
return this;
}
options = options || {};
var readonly = [];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = readonly.concat(this.constructor.readOnlyAttributes());
}
for (var k in changes) {
if (k === 'createdAt' || k === 'updatedAt') {
// This property is read-only, but for legacy reasons we silently
// ignore it
continue;
}
if (readonly.indexOf(k) > -1) {
throw new Error('Cannot modify readonly attribute: ' + k);
}
if (options.unset) {
newOps[k] = new _ParseOp.UnsetOp();
} else if (changes[k] instanceof _ParseOp.Op) {
newOps[k] = changes[k];
} else if (changes[k] && (0, _typeof3.default)(changes[k]) === 'object' && typeof changes[k].__op === 'string') {
newOps[k] = (0, _ParseOp.opFromJSON)(changes[k]);
} else if (k === 'objectId' || k === 'id') {
if (typeof changes[k] === 'string') {
this.id = changes[k];
}
} else if (k === 'ACL' && (0, _typeof3.default)(changes[k]) === 'object' && !(changes[k] instanceof _ParseACL2.default)) {
newOps[k] = new _ParseOp.SetOp(new _ParseACL2.default(changes[k]));
} else {
newOps[k] = new _ParseOp.SetOp(changes[k]);
}
}
// Calculate new values
var currentAttributes = this.attributes;
var newValues = {};
for (var attr in newOps) {
if (newOps[attr] instanceof _ParseOp.RelationOp) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr], this, attr);
} else if (!(newOps[attr] instanceof _ParseOp.UnsetOp)) {
newValues[attr] = newOps[attr].applyTo(currentAttributes[attr]);
}
}
// Validate changes
if (!options.ignoreValidation) {
var validation = this.validate(newValues);
if (validation) {
if (typeof options.error === 'function') {
options.error(this, validation);
}
return false;
}
}
// Consolidate Ops
var pendingOps = this._getPendingOps();
var last = pendingOps.length - 1;
var stateController = _CoreManager2.default.getObjectStateController();
for (var attr in newOps) {
var nextOp = newOps[attr].mergeWith(pendingOps[last][attr]);
stateController.setPendingOp(this._getStateIdentifier(), attr, nextOp);
}
return this;
}
/**
* Remove an attribute from the model. This is a noop if the attribute doesn't
* exist.
* @method unset
* @param {String} attr The string name of an attribute.
*/
}, {
key: 'unset',
value: function (attr, options) {
options = options || {};
options.unset = true;
return this.set(attr, null, options);
}
/**
* Atomically increments the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @method increment
* @param attr {String} The key.
* @param amount {Number} The amount to increment by (optional).
*/
}, {
key: 'increment',
value: function (attr, amount) {
if (typeof amount === 'undefined') {
amount = 1;
}
if (typeof amount !== 'number') {
throw new Error('Cannot increment by a non-numeric amount.');
}
return this.set(attr, new _ParseOp.IncrementOp(amount));
}
/**
* Atomically add an object to the end of the array associated with a given
* key.
* @method add
* @param attr {String} The key.
* @param item {} The item to add.
*/
}, {
key: 'add',
value: function (attr, item) {
return this.set(attr, new _ParseOp.AddOp([item]));
}
/**
* Atomically add the objects to the end of the array associated with a given
* key.
* @method addAll
* @param attr {String} The key.
* @param items {[]} The items to add.
*/
}, {
key: 'addAll',
value: function (attr, items) {
return this.set(attr, new _ParseOp.AddOp(items));
}
/**
* Atomically add an object to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @method addUnique
* @param attr {String} The key.
* @param item {} The object to add.
*/
}, {
key: 'addUnique',
value: function (attr, item) {
return this.set(attr, new _ParseOp.AddUniqueOp([item]));
}
/**
* Atomically add the objects to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @method addAllUnique
* @param attr {String} The key.
* @param items {[]} The objects to add.
*/
}, {
key: 'addAllUnique',
value: function (attr, items) {
return this.set(attr, new _ParseOp.AddUniqueOp(items));
}
/**
* Atomically remove all instances of an object from the array associated
* with a given key.
*
* @method remove
* @param attr {String} The key.
* @param item {} The object to remove.
*/
}, {
key: 'remove',
value: function (attr, item) {
return this.set(attr, new _ParseOp.RemoveOp([item]));
}
/**
* Atomically remove all instances of the objects from the array associated
* with a given key.
*
* @method removeAll
* @param attr {String} The key.
* @param items {[]} The object to remove.
*/
}, {
key: 'removeAll',
value: function (attr, items) {
return this.set(attr, new _ParseOp.RemoveOp(items));
}
/**
* Returns an instance of a subclass of Parse.Op describing what kind of
* modification has been performed on this field since the last time it was
* saved. For example, after calling object.increment("x"), calling
* object.op("x") would return an instance of Parse.Op.Increment.
*
* @method op
* @param attr {String} The key.
* @returns {Parse.Op} The operation, or undefined if none.
*/
}, {
key: 'op',
value: function (attr) {
var pending = this._getPendingOps();
for (var i = pending.length; i--;) {
if (pending[i][attr]) {
return pending[i][attr];
}
}
}
/**
* Creates a new model with identical attributes to this one, similar to Backbone.Model's clone()
* @method clone
* @return {Parse.Object}
*/
}, {
key: 'clone',
value: function () {
var clone = new this.constructor();
if (!clone.className) {
clone.className = this.className;
}
var attributes = this.attributes;
if (typeof this.constructor.readOnlyAttributes === 'function') {
var readonly = this.constructor.readOnlyAttributes() || [];
// Attributes are frozen, so we have to rebuild an object,
// rather than delete readonly keys
var copy = {};
for (var a in attributes) {
if (readonly.indexOf(a) < 0) {
copy[a] = attributes[a];
}
}
attributes = copy;
}
if (clone.set) {
clone.set(attributes);
}
return clone;
}
/**
* Creates a new instance of this object. Not to be confused with clone()
* @method newInstance
* @return {Parse.Object}
*/
}, {
key: 'newInstance',
value: function () {
var clone = new this.constructor();
if (!clone.className) {
clone.className = this.className;
}
clone.id = this.id;
if (singleInstance) {
// Just return an object with the right id
return clone;
}
var stateController = _CoreManager2.default.getObjectStateController();
if (stateController) {
stateController.duplicateState(this._getStateIdentifier(), clone._getStateIdentifier());
}
return clone;
}
/**
* Returns true if this object has never been saved to Parse.
* @method isNew
* @return {Boolean}
*/
}, {
key: 'isNew',
value: function () {
return !this.id;
}
/**
* Returns true if this object was created by the Parse server when the
* object might have already been there (e.g. in the case of a Facebook
* login)
* @method existed
* @return {Boolean}
*/
}, {
key: 'existed',
value: function () {
if (!this.id) {
return false;
}
var stateController = _CoreManager2.default.getObjectStateController();
var state = stateController.getState(this._getStateIdentifier());
if (state) {
return state.existed;
}
return false;
}
/**
* Checks if the model is currently in a valid state.
* @method isValid
* @return {Boolean}
*/
}, {
key: 'isValid',
value: function () {
return !this.validate(this.attributes);
}
/**
* You should not call this function directly unless you subclass
* <code>Parse.Object</code>, in which case you can override this method
* to provide additional validation on <code>set</code> and
* <code>save</code>. Your implementation should return
*
* @method validate
* @param {Object} attrs The current data to validate.
* @return {} False if the data is valid. An error object otherwise.
* @see Parse.Object#set
*/
}, {
key: 'validate',
value: function (attrs) {
if (attrs.hasOwnProperty('ACL') && !(attrs.ACL instanceof _ParseACL2.default)) {
return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'ACL must be a Parse ACL.');
}
for (var key in attrs) {
if (!/^[A-Za-z][0-9A-Za-z_]*$/.test(key)) {
return new _ParseError2.default(_ParseError2.default.INVALID_KEY_NAME);
}
}
return false;
}
/**
* Returns the ACL for this object.
* @method getACL
* @returns {Parse.ACL} An instance of Parse.ACL.
* @see Parse.Object#get
*/
}, {
key: 'getACL',
value: function () {
var acl = this.get('ACL');
if (acl instanceof _ParseACL2.default) {
return acl;
}
return null;
}
/**
* Sets the ACL to be used for this object.
* @method setACL
* @param {Parse.ACL} acl An instance of Parse.ACL.
* @param {Object} options Optional Backbone-like options object to be
* passed in to set.
* @return {Boolean} Whether the set passed validation.
* @see Parse.Object#set
*/
}, {
key: 'setACL',
value: function (acl, options) {
return this.set('ACL', acl, options);
}
/**
* Clears any changes to this object made since the last call to save()
* @method revert
*/
}, {
key: 'revert',
value: function () {
this._clearPendingOps();
}
/**
* Clears all attributes on a model
* @method clear
*/
}, {
key: 'clear',
value: function () {
var attributes = this.attributes;
var erasable = {};
var readonly = ['createdAt', 'updatedAt'];
if (typeof this.constructor.readOnlyAttributes === 'function') {
readonly = readonly.concat(this.constructor.readOnlyAttributes());
}
for (var attr in attributes) {
if (readonly.indexOf(attr) < 0) {
erasable[attr] = true;
}
}
return this.set(erasable, { unset: true });
}
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden.
*
* @method fetch
* @param {Object} options A Backbone-style callback object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback.
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that is fulfilled when the fetch
* completes.
*/
}, {
key: 'fetch',
value: function (options) {
options = options || {};
var fetchOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
fetchOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
fetchOptions.sessionToken = options.sessionToken;
}
var controller = _CoreManager2.default.getObjectController();
return controller.fetch(this, true, fetchOptions)._thenRunCallbacks(options);
}
/**
* Set a hash of model attributes, and save the model to the server.
* updatedAt will be updated when the request returns.
* You can either call it as:<pre>
* object.save();</pre>
* or<pre>
* object.save(null, options);</pre>
* or<pre>
* object.save(attrs, options);</pre>
* or<pre>
* object.save(key, value, options);</pre>
*
* For example, <pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }, {
* success: function(gameTurnAgain) {
* // The save was successful.
* },
* error: function(gameTurnAgain, error) {
* // The save failed. Error is an instance of Parse.Error.
* }
* });</pre>
* or with promises:<pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }).then(function(gameTurnAgain) {
* // The save was successful.
* }, function(error) {
* // The save failed. Error is an instance of Parse.Error.
* });</pre>
*
* @method save
* @param {Object} options A Backbone-style callback object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback.
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that is fulfilled when the save
* completes.
*/
}, {
key: 'save',
value: function (arg1, arg2, arg3) {
var _this = this;
var attrs;
var options;
if ((typeof arg1 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg1)) === 'object' || typeof arg1 === 'undefined') {
attrs = arg1;
if ((typeof arg2 === 'undefined' ? 'undefined' : (0, _typeof3.default)(arg2)) === 'object') {
options = arg2;
}
} else {
attrs = {};
attrs[arg1] = arg2;
options = arg3;
}
// Support save({ success: function() {}, error: function() {} })
if (!options && attrs) {
options = {};
if (typeof attrs.success === 'function') {
options.success = attrs.success;
delete attrs.success;
}
if (typeof attrs.error === 'function') {
options.error = attrs.error;
delete attrs.error;
}
}
if (attrs) {
var validation = this.validate(attrs);
if (validation) {
if (options && typeof options.error === 'function') {
options.error(this, validation);
}
return _ParsePromise2.default.error(validation);
}
this.set(attrs, options);
}
options = options || {};
var saveOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
saveOptions.useMasterKey = !!options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken') && typeof options.sessionToken === 'string') {
saveOptions.sessionToken = options.sessionToken;
}
var controller = _CoreManager2.default.getObjectController();
var unsaved = (0, _unsavedChildren2.default)(this);
return controller.save(unsaved, saveOptions).then(function () {
return controller.save(_this, saveOptions);
})._thenRunCallbacks(options, this);
}
/**
* Destroy this model on the server if it was already persisted.
* If `wait: true` is passed, waits for the server to respond
* before removal.
*
* @method destroy
* @param {Object} options A Backbone-style callback object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that is fulfilled when the destroy
* completes.
*/
}, {
key: 'destroy',
value: function (options) {
options = options || {};
var destroyOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
destroyOptions.sessionToken = options.sessionToken;
}
if (!this.id) {
return _ParsePromise2.default.as()._thenRunCallbacks(options);
}
return _CoreManager2.default.getObjectController().destroy(this, destroyOptions)._thenRunCallbacks(options);
}
/** Static methods **/
}, {
key: 'attributes',
get: function () {
var stateController = _CoreManager2.default.getObjectStateController();
return (0, _freeze2.default)(stateController.estimateAttributes(this._getStateIdentifier()));
}
/**
* The first time this object was saved on the server.
* @property createdAt
* @type Date
*/
}, {
key: 'createdAt',
get: function () {
return this._getServerData().createdAt;
}
/**
* The last time this object was updated on the server.
* @property updatedAt
* @type Date
*/
}, {
key: 'updatedAt',
get: function () {
return this._getServerData().updatedAt;
}
}], [{
key: '_clearAllState',
value: function () {
var stateController = _CoreManager2.default.getObjectStateController();
stateController.clearAllState();
}
/**
* Fetches the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
* <pre>
* Parse.Object.fetchAll([object1, object2, ...], {
* success: function(list) {
* // All the objects were fetched.
* },
* error: function(error) {
* // An error occurred while fetching one of the objects.
* },
* });
* </pre>
*
* @method fetchAll
* @param {Array} list A list of <code>Parse.Object</code>.
* @param {Object} options A Backbone-style callback object.
* @static
* Valid options are:<ul>
* <li>success: A Backbone-style success callback.
* <li>error: An Backbone-style error callback.
* </ul>
*/
}, {
key: 'fetchAll',
value: function (list, options) {
var options = options || {};
var queryOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
queryOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
queryOptions.sessionToken = options.sessionToken;
}
return _CoreManager2.default.getObjectController().fetch(list, true, queryOptions)._thenRunCallbacks(options);
}
/**
* Fetches the given list of Parse.Object if needed.
* If any error is encountered, stops and calls the error handler.
*
* <pre>
* Parse.Object.fetchAllIfNeeded([object1, ...], {
* success: function(list) {
* // Objects were fetched and updated.
* },
* error: function(error) {
* // An error occurred while fetching one of the objects.
* },
* });
* </pre>
*
* @method fetchAllIfNeeded
* @param {Array} list A list of <code>Parse.Object</code>.
* @param {Object} options A Backbone-style callback object.
* @static
* Valid options are:<ul>
* <li>success: A Backbone-style success callback.
* <li>error: An Backbone-style error callback.
* </ul>
*/
}, {
key: 'fetchAllIfNeeded',
value: function (list, options) {
var options = options || {};
var queryOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
queryOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
queryOptions.sessionToken = options.sessionToken;
}
return _CoreManager2.default.getObjectController().fetch(list, false, queryOptions)._thenRunCallbacks(options);
}
/**
* Destroy the given list of models on the server if it was already persisted.
*
* <p>Unlike saveAll, if an error occurs while deleting an individual model,
* this method will continue trying to delete the rest of the models if
* possible, except in the case of a fatal error like a connection error.
*
* <p>In particular, the Parse.Error object returned in the case of error may
* be one of two types:
*
* <ul>
* <li>A Parse.Error.AGGREGATE_ERROR. This object's "errors" property is an
* array of other Parse.Error objects. Each error object in this array
* has an "object" property that references the object that could not be
* deleted (for instance, because that object could not be found).</li>
* <li>A non-aggregate Parse.Error. This indicates a serious error that
* caused the delete operation to be aborted partway through (for
* instance, a connection failure in the middle of the delete).</li>
* </ul>
*
* <pre>
* Parse.Object.destroyAll([object1, object2, ...], {
* success: function() {
* // All the objects were deleted.
* },
* error: function(error) {
* // An error occurred while deleting one or more of the objects.
* // If this is an aggregate error, then we can inspect each error
* // object individually to determine the reason why a particular
* // object was not deleted.
* if (error.code === Parse.Error.AGGREGATE_ERROR) {
* for (var i = 0; i < error.errors.length; i++) {
* console.log("Couldn't delete " + error.errors[i].object.id +
* "due to " + error.errors[i].message);
* }
* } else {
* console.log("Delete aborted because of " + error.message);
* }
* },
* });
* </pre>
*
* @method destroyAll
* @param {Array} list A list of <code>Parse.Object</code>.
* @param {Object} options A Backbone-style callback object.
* @static
* Valid options are:<ul>
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that is fulfilled when the destroyAll
* completes.
*/
}, {
key: 'destroyAll',
value: function (list, options) {
var options = options || {};
var destroyOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
destroyOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
destroyOptions.sessionToken = options.sessionToken;
}
return _CoreManager2.default.getObjectController().destroy(list, destroyOptions)._thenRunCallbacks(options);
}
/**
* Saves the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
*
* <pre>
* Parse.Object.saveAll([object1, object2, ...], {
* success: function(list) {
* // All the objects were saved.
* },
* error: function(error) {
* // An error occurred while saving one of the objects.
* },
* });
* </pre>
*
* @method saveAll
* @param {Array} list A list of <code>Parse.Object</code>.
* @param {Object} options A Backbone-style callback object.
* @static
* Valid options are:<ul>
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*/
}, {
key: 'saveAll',
value: function (list, options) {
var options = options || {};
var saveOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
saveOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
saveOptions.sessionToken = options.sessionToken;
}
return _CoreManager2.default.getObjectController().save(list, saveOptions)._thenRunCallbacks(options);
}
/**
* Creates a reference to a subclass of Parse.Object with the given id. This
* does not exist on Parse.Object, only on subclasses.
*
* <p>A shortcut for: <pre>
* var Foo = Parse.Object.extend("Foo");
* var pointerToFoo = new Foo();
* pointerToFoo.id = "myObjectId";
* </pre>
*
* @method createWithoutData
* @param {String} id The ID of the object to create a reference to.
* @static
* @return {Parse.Object} A Parse.Object reference.
*/
}, {
key: 'createWithoutData',
value: function (id) {
var obj = new this();
obj.id = id;
return obj;
}
/**
* Creates a new instance of a Parse Object from a JSON representation.
* @method fromJSON
* @param {Object} json The JSON map of the Object's data
* @param {boolean} override In single instance mode, all old server data
* is overwritten if this is set to true
* @static
* @return {Parse.Object} A Parse.Object reference
*/
}, {
key: 'fromJSON',
value: function (json, override) {
if (!json.className) {
throw new Error('Cannot create an object without a className');
}
var constructor = classMap[json.className];
var o = constructor ? new constructor() : new ParseObject(json.className);
var otherAttributes = {};
for (var attr in json) {
if (attr !== 'className' && attr !== '__type') {
otherAttributes[attr] = json[attr];
}
}
if (override) {
// id needs to be set before clearServerData can work
if (otherAttributes.objectId) {
o.id = otherAttributes.objectId;
}
var preserved = null;
if (typeof o._preserveFieldsOnFetch === 'function') {
preserved = o._preserveFieldsOnFetch();
}
o._clearServerData();
if (preserved) {
o._finishFetch(preserved);
}
}
o._finishFetch(otherAttributes);
if (json.objectId) {
o._setExisted(true);
}
return o;
}
/**
* Registers a subclass of Parse.Object with a specific class name.
* When objects of that class are retrieved from a query, they will be
* instantiated with this subclass.
* This is only necessary when using ES6 subclassing.
* @method registerSubclass
* @param {String} className The class name of the subclass
* @param {Class} constructor The subclass
*/
}, {
key: 'registerSubclass',
value: function (className, constructor) {
if (typeof className !== 'string') {
throw new TypeError('The first argument must be a valid class name.');
}
if (typeof constructor === 'undefined') {
throw new TypeError('You must supply a subclass constructor.');
}
if (typeof constructor !== 'function') {
throw new TypeError('You must register the subclass constructor. ' + 'Did you attempt to register an instance of the subclass?');
}
classMap[className] = constructor;
if (!constructor.className) {
constructor.className = className;
}
}
/**
* Creates a new subclass of Parse.Object for the given Parse class name.
*
* <p>Every extension of a Parse class will inherit from the most recent
* previous extension of that class. When a Parse.Object is automatically
* created by parsing JSON, it will use the most recent extension of that
* class.</p>
*
* <p>You should call either:<pre>
* var MyClass = Parse.Object.extend("MyClass", {
* <i>Instance methods</i>,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* <i>Other instance properties</i>
* }
* }, {
* <i>Class properties</i>
* });</pre>
* or, for Backbone compatibility:<pre>
* var MyClass = Parse.Object.extend({
* className: "MyClass",
* <i>Instance methods</i>,
* initialize: function(attrs, options) {
* this.someInstanceProperty = [],
* <i>Other instance properties</i>
* }
* }, {
* <i>Class properties</i>
* });</pre></p>
*
* @method extend
* @param {String} className The name of the Parse class backing this model.
* @param {Object} protoProps Instance properties to add to instances of the
* class returned from this method.
* @param {Object} classProps Class properties to add the class returned from
* this method.
* @return {Class} A new subclass of Parse.Object.
*/
}, {
key: 'extend',
value: function (className, protoProps, classProps) {
if (typeof className !== 'string') {
if (className && typeof className.className === 'string') {
return ParseObject.extend(className.className, className, protoProps);
} else {
throw new Error('Parse.Object.extend\'s first argument should be the className.');
}
}
var adjustedClassName = className;
if (adjustedClassName === 'User' && _CoreManager2.default.get('PERFORM_USER_REWRITE')) {
adjustedClassName = '_User';
}
var parentProto = ParseObject.prototype;
if (this.hasOwnProperty('__super__') && this.__super__) {
parentProto = this.prototype;
} else if (classMap[adjustedClassName]) {
parentProto = classMap[adjustedClassName].prototype;
}
var ParseObjectSubclass = function (attributes, options) {
this.className = adjustedClassName;
this._objCount = objectCount++;
// Enable legacy initializers
if (typeof this.initialize === 'function') {
this.initialize.apply(this, arguments);
}
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
if (!this.set(attributes || {}, options)) {
throw new Error('Can\'t create an invalid Parse Object');
}
}
};
ParseObjectSubclass.className = adjustedClassName;
ParseObjectSubclass.__super__ = parentProto;
ParseObjectSubclass.prototype = (0, _create2.default)(parentProto, {
constructor: {
value: ParseObjectSubclass,
enumerable: false,
writable: true,
configurable: true
}
});
if (protoProps) {
for (var prop in protoProps) {
if (prop !== 'className') {
(0, _defineProperty2.default)(ParseObjectSubclass.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
if (classProps) {
for (var prop in classProps) {
if (prop !== 'className') {
(0, _defineProperty2.default)(ParseObjectSubclass, prop, {
value: classProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
ParseObjectSubclass.extend = function (name, protoProps, classProps) {
if (typeof name === 'string') {
return ParseObject.extend.call(ParseObjectSubclass, name, protoProps, classProps);
}
return ParseObject.extend.call(ParseObjectSubclass, adjustedClassName, name, protoProps);
};
ParseObjectSubclass.createWithoutData = ParseObject.createWithoutData;
classMap[adjustedClassName] = ParseObjectSubclass;
return ParseObjectSubclass;
}
/**
* Enable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* This is disabled by default in server environments, since it can lead to
* security issues.
* @method enableSingleInstance
*/
}, {
key: 'enableSingleInstance',
value: function () {
singleInstance = true;
_CoreManager2.default.setObjectStateController(SingleInstanceStateController);
}
/**
* Disable single instance objects, where any local objects with the same Id
* share the same attributes, and stay synchronized with each other.
* When disabled, you can have two instances of the same object in memory
* without them sharing attributes.
* @method disableSingleInstance
*/
}, {
key: 'disableSingleInstance',
value: function () {
singleInstance = false;
_CoreManager2.default.setObjectStateController(UniqueInstanceStateController);
}
}]);
return ParseObject;
}();
exports.default = ParseObject;
var DefaultController = {
fetch: function (target, forceFetch, options) {
if (Array.isArray(target)) {
if (target.length < 1) {
return _ParsePromise2.default.as([]);
}
var objs = [];
var ids = [];
var className = null;
var results = [];
var error = null;
target.forEach(function (el) {
if (error) {
return;
}
if (!className) {
className = el.className;
}
if (className !== el.className) {
error = new _ParseError2.default(_ParseError2.default.INVALID_CLASS_NAME, 'All objects should be of the same class');
}
if (!el.id) {
error = new _ParseError2.default(_ParseError2.default.MISSING_OBJECT_ID, 'All objects must have an ID');
}
if (forceFetch || (0, _keys2.default)(el._getServerData()).length === 0) {
ids.push(el.id);
objs.push(el);
}
results.push(el);
});
if (error) {
return _ParsePromise2.default.error(error);
}
var query = new _ParseQuery2.default(className);
query.containedIn('objectId', ids);
query._limit = ids.length;
return query.find(options).then(function (objects) {
var idMap = {};
objects.forEach(function (o) {
idMap[o.id] = o;
});
for (var i = 0; i < objs.length; i++) {
var obj = objs[i];
if (!obj || !obj.id || !idMap[obj.id]) {
if (forceFetch) {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OBJECT_NOT_FOUND, 'All objects must exist on the server.'));
}
}
}
if (!singleInstance) {
// If single instance objects are disabled, we need to replace the
for (var i = 0; i < results.length; i++) {
var obj = results[i];
if (obj && obj.id && idMap[obj.id]) {
var id = obj.id;
obj._finishFetch(idMap[id].toJSON());
results[i] = idMap[id];
}
}
}
return _ParsePromise2.default.as(results);
});
} else {
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('GET', 'classes/' + target.className + '/' + target._getId(), {}, options).then(function (response) {
if (target instanceof ParseObject) {
target._clearPendingOps();
target._clearServerData();
target._finishFetch(response);
}
return target;
});
}
},
destroy: function (target, options) {
var RESTController = _CoreManager2.default.getRESTController();
if (Array.isArray(target)) {
if (target.length < 1) {
return _ParsePromise2.default.as([]);
}
var batches = [[]];
target.forEach(function (obj) {
if (!obj.id) {
return;
}
batches[batches.length - 1].push(obj);
if (batches[batches.length - 1].length >= 20) {
batches.push([]);
}
});
if (batches[batches.length - 1].length === 0) {
// If the last batch is empty, remove it
batches.pop();
}
var deleteCompleted = _ParsePromise2.default.as();
var errors = [];
batches.forEach(function (batch) {
deleteCompleted = deleteCompleted.then(function () {
return RESTController.request('POST', 'batch', {
requests: batch.map(function (obj) {
return {
method: 'DELETE',
path: getServerUrlPath() + 'classes/' + obj.className + '/' + obj._getId(),
body: {}
};
})
}, options).then(function (results) {
for (var i = 0; i < results.length; i++) {
if (results[i] && results[i].hasOwnProperty('error')) {
var err = new _ParseError2.default(results[i].error.code, results[i].error.error);
err.object = batch[i];
errors.push(err);
}
}
});
});
});
return deleteCompleted.then(function () {
if (errors.length) {
var aggregate = new _ParseError2.default(_ParseError2.default.AGGREGATE_ERROR);
aggregate.errors = errors;
return _ParsePromise2.default.error(aggregate);
}
return _ParsePromise2.default.as(target);
});
} else if (target instanceof ParseObject) {
return RESTController.request('DELETE', 'classes/' + target.className + '/' + target._getId(), {}, options).then(function () {
return _ParsePromise2.default.as(target);
});
}
return _ParsePromise2.default.as(target);
},
save: function (target, options) {
var RESTController = _CoreManager2.default.getRESTController();
var stateController = _CoreManager2.default.getObjectStateController();
if (Array.isArray(target)) {
if (target.length < 1) {
return _ParsePromise2.default.as([]);
}
var unsaved = target.concat();
for (var i = 0; i < target.length; i++) {
if (target[i] instanceof ParseObject) {
unsaved = unsaved.concat((0, _unsavedChildren2.default)(target[i], true));
}
}
unsaved = (0, _unique2.default)(unsaved);
var filesSaved = _ParsePromise2.default.as();
var pending = [];
unsaved.forEach(function (el) {
if (el instanceof _ParseFile2.default) {
filesSaved = filesSaved.then(function () {
return el.save();
});
} else if (el instanceof ParseObject) {
pending.push(el);
}
});
return filesSaved.then(function () {
var objectError = null;
return _ParsePromise2.default._continueWhile(function () {
return pending.length > 0;
}, function () {
var batch = [];
var nextPending = [];
pending.forEach(function (el) {
if (batch.length < 20 && (0, _canBeSerialized2.default)(el)) {
batch.push(el);
} else {
nextPending.push(el);
}
});
pending = nextPending;
if (batch.length < 1) {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Tried to save a batch with a cycle.'));
}
// Queue up tasks for each object in the batch.
// When every task is ready, the API request will execute
var batchReturned = new _ParsePromise2.default();
var batchReady = [];
var batchTasks = [];
batch.forEach(function (obj, index) {
var ready = new _ParsePromise2.default();
batchReady.push(ready);
stateController.pushPendingState(obj._getStateIdentifier());
batchTasks.push(stateController.enqueueTask(obj._getStateIdentifier(), function () {
ready.resolve();
return batchReturned.then(function (responses, status) {
if (responses[index].hasOwnProperty('success')) {
obj._handleSaveResponse(responses[index].success, status);
} else {
if (!objectError && responses[index].hasOwnProperty('error')) {
var serverError = responses[index].error;
objectError = new _ParseError2.default(serverError.code, serverError.error);
// Cancel the rest of the save
pending = [];
}
obj._handleSaveError();
}
});
}));
});
_ParsePromise2.default.when(batchReady).then(function () {
// Kick off the batch request
return RESTController.request('POST', 'batch', {
requests: batch.map(function (obj) {
var params = obj._getSaveParams();
params.path = getServerUrlPath() + params.path;
return params;
})
}, options);
}).then(function (response, status) {
batchReturned.resolve(response, status);
});
return _ParsePromise2.default.when(batchTasks);
}).then(function () {
if (objectError) {
return _ParsePromise2.default.error(objectError);
}
return _ParsePromise2.default.as(target);
});
});
} else if (target instanceof ParseObject) {
// copying target lets Flow guarantee the pointer isn't modified elsewhere
var targetCopy = target;
var task = function () {
var params = targetCopy._getSaveParams();
return RESTController.request(params.method, params.path, params.body, options).then(function (response, status) {
targetCopy._handleSaveResponse(response, status);
}, function (error) {
targetCopy._handleSaveError();
return _ParsePromise2.default.error(error);
});
};
stateController.pushPendingState(target._getStateIdentifier());
return stateController.enqueueTask(target._getStateIdentifier(), task).then(function () {
return target;
}, function (error) {
return _ParsePromise2.default.error(error);
});
}
return _ParsePromise2.default.as();
}
};
_CoreManager2.default.setObjectController(DefaultController);
},{"./CoreManager":3,"./ParseACL":11,"./ParseError":13,"./ParseFile":14,"./ParseOp":19,"./ParsePromise":21,"./ParseQuery":22,"./ParseRelation":23,"./SingleInstanceStateController":29,"./UniqueInstanceStateController":33,"./canBeSerialized":35,"./decode":36,"./encode":37,"./equals":38,"./escape":39,"./parseDate":41,"./unique":42,"./unsavedChildren":43,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/object/create":47,"babel-runtime/core-js/object/define-property":48,"babel-runtime/core-js/object/freeze":49,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],19:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RelationOp = exports.RemoveOp = exports.AddUniqueOp = exports.AddOp = exports.IncrementOp = exports.UnsetOp = exports.SetOp = exports.Op = undefined;
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
exports.opFromJSON = opFromJSON;
var _arrayContainsObject = _dereq_('./arrayContainsObject');
var _arrayContainsObject2 = _interopRequireDefault(_arrayContainsObject);
var _decode = _dereq_('./decode');
var _decode2 = _interopRequireDefault(_decode);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
var _unique = _dereq_('./unique');
var _unique2 = _interopRequireDefault(_unique);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function opFromJSON(json) {
if (!json || !json.__op) {
return null;
}
switch (json.__op) {
case 'Delete':
return new UnsetOp();
case 'Increment':
return new IncrementOp(json.amount);
case 'Add':
return new AddOp((0, _decode2.default)(json.objects));
case 'AddUnique':
return new AddUniqueOp((0, _decode2.default)(json.objects));
case 'Remove':
return new RemoveOp((0, _decode2.default)(json.objects));
case 'AddRelation':
var toAdd = (0, _decode2.default)(json.objects);
if (!Array.isArray(toAdd)) {
return new RelationOp([], []);
}
return new RelationOp(toAdd, []);
case 'RemoveRelation':
var toRemove = (0, _decode2.default)(json.objects);
if (!Array.isArray(toRemove)) {
return new RelationOp([], []);
}
return new RelationOp([], toRemove);
case 'Batch':
var toAdd = [];
var toRemove = [];
for (var i = 0; i < json.ops.length; i++) {
if (json.ops[i].__op === 'AddRelation') {
toAdd = toAdd.concat((0, _decode2.default)(json.ops[i].objects));
} else if (json.ops[i].__op === 'RemoveRelation') {
toRemove = toRemove.concat((0, _decode2.default)(json.ops[i].objects));
}
}
return new RelationOp(toAdd, toRemove);
}
return null;
}
var Op = exports.Op = function () {
function Op() {
(0, _classCallCheck3.default)(this, Op);
}
(0, _createClass3.default)(Op, [{
key: 'applyTo',
// Empty parent class
value: function () {}
}, {
key: 'mergeWith',
value: function () {}
}, {
key: 'toJSON',
value: function () {}
}]);
return Op;
}();
var SetOp = exports.SetOp = function (_Op) {
(0, _inherits3.default)(SetOp, _Op);
function SetOp(value) {
(0, _classCallCheck3.default)(this, SetOp);
var _this = (0, _possibleConstructorReturn3.default)(this, (SetOp.__proto__ || (0, _getPrototypeOf2.default)(SetOp)).call(this));
_this._value = value;
return _this;
}
(0, _createClass3.default)(SetOp, [{
key: 'applyTo',
value: function () {
return this._value;
}
}, {
key: 'mergeWith',
value: function () {
return new SetOp(this._value);
}
}, {
key: 'toJSON',
value: function () {
return (0, _encode2.default)(this._value, false, true);
}
}]);
return SetOp;
}(Op);
var UnsetOp = exports.UnsetOp = function (_Op2) {
(0, _inherits3.default)(UnsetOp, _Op2);
function UnsetOp() {
(0, _classCallCheck3.default)(this, UnsetOp);
return (0, _possibleConstructorReturn3.default)(this, (UnsetOp.__proto__ || (0, _getPrototypeOf2.default)(UnsetOp)).apply(this, arguments));
}
(0, _createClass3.default)(UnsetOp, [{
key: 'applyTo',
value: function () {
return undefined;
}
}, {
key: 'mergeWith',
value: function () {
return new UnsetOp();
}
}, {
key: 'toJSON',
value: function () {
return { __op: 'Delete' };
}
}]);
return UnsetOp;
}(Op);
var IncrementOp = exports.IncrementOp = function (_Op3) {
(0, _inherits3.default)(IncrementOp, _Op3);
function IncrementOp(amount) {
(0, _classCallCheck3.default)(this, IncrementOp);
var _this3 = (0, _possibleConstructorReturn3.default)(this, (IncrementOp.__proto__ || (0, _getPrototypeOf2.default)(IncrementOp)).call(this));
if (typeof amount !== 'number') {
throw new TypeError('Increment Op must be initialized with a numeric amount.');
}
_this3._amount = amount;
return _this3;
}
(0, _createClass3.default)(IncrementOp, [{
key: 'applyTo',
value: function (value) {
if (typeof value === 'undefined') {
return this._amount;
}
if (typeof value !== 'number') {
throw new TypeError('Cannot increment a non-numeric value.');
}
return this._amount + value;
}
}, {
key: 'mergeWith',
value: function (previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._amount);
}
if (previous instanceof IncrementOp) {
return new IncrementOp(this.applyTo(previous._amount));
}
throw new Error('Cannot merge Increment Op with the previous Op');
}
}, {
key: 'toJSON',
value: function () {
return { __op: 'Increment', amount: this._amount };
}
}]);
return IncrementOp;
}(Op);
var AddOp = exports.AddOp = function (_Op4) {
(0, _inherits3.default)(AddOp, _Op4);
function AddOp(value) {
(0, _classCallCheck3.default)(this, AddOp);
var _this4 = (0, _possibleConstructorReturn3.default)(this, (AddOp.__proto__ || (0, _getPrototypeOf2.default)(AddOp)).call(this));
_this4._value = Array.isArray(value) ? value : [value];
return _this4;
}
(0, _createClass3.default)(AddOp, [{
key: 'applyTo',
value: function (value) {
if (value == null) {
return this._value;
}
if (Array.isArray(value)) {
return value.concat(this._value);
}
throw new Error('Cannot add elements to a non-array value');
}
}, {
key: 'mergeWith',
value: function (previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._value);
}
if (previous instanceof AddOp) {
return new AddOp(this.applyTo(previous._value));
}
throw new Error('Cannot merge Add Op with the previous Op');
}
}, {
key: 'toJSON',
value: function () {
return { __op: 'Add', objects: (0, _encode2.default)(this._value, false, true) };
}
}]);
return AddOp;
}(Op);
var AddUniqueOp = exports.AddUniqueOp = function (_Op5) {
(0, _inherits3.default)(AddUniqueOp, _Op5);
function AddUniqueOp(value) {
(0, _classCallCheck3.default)(this, AddUniqueOp);
var _this5 = (0, _possibleConstructorReturn3.default)(this, (AddUniqueOp.__proto__ || (0, _getPrototypeOf2.default)(AddUniqueOp)).call(this));
_this5._value = (0, _unique2.default)(Array.isArray(value) ? value : [value]);
return _this5;
}
(0, _createClass3.default)(AddUniqueOp, [{
key: 'applyTo',
value: function (value) {
if (value == null) {
return this._value || [];
}
if (Array.isArray(value)) {
// copying value lets Flow guarantee the pointer isn't modified elsewhere
var valueCopy = value;
var toAdd = [];
this._value.forEach(function (v) {
if (v instanceof _ParseObject2.default) {
if (!(0, _arrayContainsObject2.default)(valueCopy, v)) {
toAdd.push(v);
}
} else {
if (valueCopy.indexOf(v) < 0) {
toAdd.push(v);
}
}
});
return value.concat(toAdd);
}
throw new Error('Cannot add elements to a non-array value');
}
}, {
key: 'mergeWith',
value: function (previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new SetOp(this._value);
}
if (previous instanceof AddUniqueOp) {
return new AddUniqueOp(this.applyTo(previous._value));
}
throw new Error('Cannot merge AddUnique Op with the previous Op');
}
}, {
key: 'toJSON',
value: function () {
return { __op: 'AddUnique', objects: (0, _encode2.default)(this._value, false, true) };
}
}]);
return AddUniqueOp;
}(Op);
var RemoveOp = exports.RemoveOp = function (_Op6) {
(0, _inherits3.default)(RemoveOp, _Op6);
function RemoveOp(value) {
(0, _classCallCheck3.default)(this, RemoveOp);
var _this6 = (0, _possibleConstructorReturn3.default)(this, (RemoveOp.__proto__ || (0, _getPrototypeOf2.default)(RemoveOp)).call(this));
_this6._value = (0, _unique2.default)(Array.isArray(value) ? value : [value]);
return _this6;
}
(0, _createClass3.default)(RemoveOp, [{
key: 'applyTo',
value: function (value) {
if (value == null) {
return [];
}
if (Array.isArray(value)) {
var i = value.indexOf(this._value);
var removed = value.concat([]);
for (var i = 0; i < this._value.length; i++) {
var index = removed.indexOf(this._value[i]);
while (index > -1) {
removed.splice(index, 1);
index = removed.indexOf(this._value[i]);
}
if (this._value[i] instanceof _ParseObject2.default && this._value[i].id) {
for (var j = 0; j < removed.length; j++) {
if (removed[j] instanceof _ParseObject2.default && this._value[i].id === removed[j].id) {
removed.splice(j, 1);
j--;
}
}
}
}
return removed;
}
throw new Error('Cannot remove elements from a non-array value');
}
}, {
key: 'mergeWith',
value: function (previous) {
if (!previous) {
return this;
}
if (previous instanceof SetOp) {
return new SetOp(this.applyTo(previous._value));
}
if (previous instanceof UnsetOp) {
return new UnsetOp();
}
if (previous instanceof RemoveOp) {
var uniques = previous._value.concat([]);
for (var i = 0; i < this._value.length; i++) {
if (this._value[i] instanceof _ParseObject2.default) {
if (!(0, _arrayContainsObject2.default)(uniques, this._value[i])) {
uniques.push(this._value[i]);
}
} else {
if (uniques.indexOf(this._value[i]) < 0) {
uniques.push(this._value[i]);
}
}
}
return new RemoveOp(uniques);
}
throw new Error('Cannot merge Remove Op with the previous Op');
}
}, {
key: 'toJSON',
value: function () {
return { __op: 'Remove', objects: (0, _encode2.default)(this._value, false, true) };
}
}]);
return RemoveOp;
}(Op);
var RelationOp = exports.RelationOp = function (_Op7) {
(0, _inherits3.default)(RelationOp, _Op7);
function RelationOp(adds, removes) {
(0, _classCallCheck3.default)(this, RelationOp);
var _this7 = (0, _possibleConstructorReturn3.default)(this, (RelationOp.__proto__ || (0, _getPrototypeOf2.default)(RelationOp)).call(this));
_this7._targetClassName = null;
if (Array.isArray(adds)) {
_this7.relationsToAdd = (0, _unique2.default)(adds.map(_this7._extractId, _this7));
}
if (Array.isArray(removes)) {
_this7.relationsToRemove = (0, _unique2.default)(removes.map(_this7._extractId, _this7));
}
return _this7;
}
(0, _createClass3.default)(RelationOp, [{
key: '_extractId',
value: function (obj) {
if (typeof obj === 'string') {
return obj;
}
if (!obj.id) {
throw new Error('You cannot add or remove an unsaved Parse Object from a relation');
}
if (!this._targetClassName) {
this._targetClassName = obj.className;
}
if (this._targetClassName !== obj.className) {
throw new Error('Tried to create a Relation with 2 different object types: ' + this._targetClassName + ' and ' + obj.className + '.');
}
return obj.id;
}
}, {
key: 'applyTo',
value: function (value, object, key) {
if (!value) {
if (!object || !key) {
throw new Error('Cannot apply a RelationOp without either a previous value, or an object and a key');
}
var parent = new _ParseObject2.default(object.className);
if (object.id && object.id.indexOf('local') === 0) {
parent._localId = object.id;
} else if (object.id) {
parent.id = object.id;
}
var relation = new _ParseRelation2.default(parent, key);
relation.targetClassName = this._targetClassName;
return relation;
}
if (value instanceof _ParseRelation2.default) {
if (this._targetClassName) {
if (value.targetClassName) {
if (this._targetClassName !== value.targetClassName) {
throw new Error('Related object must be a ' + value.targetClassName + ', but a ' + this._targetClassName + ' was passed in.');
}
} else {
value.targetClassName = this._targetClassName;
}
}
return value;
} else {
throw new Error('Relation cannot be applied to a non-relation field');
}
}
}, {
key: 'mergeWith',
value: function (previous) {
if (!previous) {
return this;
} else if (previous instanceof UnsetOp) {
throw new Error('You cannot modify a relation after deleting it.');
} else if (previous instanceof RelationOp) {
if (previous._targetClassName && previous._targetClassName !== this._targetClassName) {
throw new Error('Related object must be of class ' + previous._targetClassName + ', but ' + (this._targetClassName || 'null') + ' was passed in.');
}
var newAdd = previous.relationsToAdd.concat([]);
this.relationsToRemove.forEach(function (r) {
var index = newAdd.indexOf(r);
if (index > -1) {
newAdd.splice(index, 1);
}
});
this.relationsToAdd.forEach(function (r) {
var index = newAdd.indexOf(r);
if (index < 0) {
newAdd.push(r);
}
});
var newRemove = previous.relationsToRemove.concat([]);
this.relationsToAdd.forEach(function (r) {
var index = newRemove.indexOf(r);
if (index > -1) {
newRemove.splice(index, 1);
}
});
this.relationsToRemove.forEach(function (r) {
var index = newRemove.indexOf(r);
if (index < 0) {
newRemove.push(r);
}
});
var newRelation = new RelationOp(newAdd, newRemove);
newRelation._targetClassName = this._targetClassName;
return newRelation;
}
throw new Error('Cannot merge Relation Op with the previous Op');
}
}, {
key: 'toJSON',
value: function () {
var _this8 = this;
var idToPointer = function (id) {
return {
__type: 'Pointer',
className: _this8._targetClassName,
objectId: id
};
};
var adds = null;
var removes = null;
var pointers = null;
if (this.relationsToAdd.length > 0) {
pointers = this.relationsToAdd.map(idToPointer);
adds = { __op: 'AddRelation', objects: pointers };
}
if (this.relationsToRemove.length > 0) {
pointers = this.relationsToRemove.map(idToPointer);
removes = { __op: 'RemoveRelation', objects: pointers };
}
if (adds && removes) {
return { __op: 'Batch', ops: [adds, removes] };
}
return adds || removes || {};
}
}]);
return RelationOp;
}(Op);
},{"./ParseObject":18,"./ParseRelation":23,"./arrayContainsObject":34,"./decode":36,"./encode":37,"./unique":42,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],20:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _ParseGeoPoint = _dereq_('./ParseGeoPoint');
var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Creates a new Polygon with any of the following forms:<br>
* <pre>
* new Polygon([[0,0],[0,1],[1,1],[1,0]])
* new Polygon([GeoPoint, GeoPoint, GeoPoint])
* </pre>
* @class Parse.GeoPoint
* @constructor
*
* <p>Represents a coordinates that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.</p>
*
* <p>Example:<pre>
* var polygon = new Parse.Polygon([[0,0],[0,1],[1,1],[1,0]]);
* var object = new Parse.Object("PlaceObject");
* object.set("area", polygon);
* object.save();</pre></p>
*/
var ParsePolygon = function () {
function ParsePolygon(arg1) {
(0, _classCallCheck3.default)(this, ParsePolygon);
this._coordinates = ParsePolygon._validate(arg1);
}
/**
* Coordinates value for this Polygon.
* Throws an exception if not valid type.
* @property coordinates
* @type Array
*/
(0, _createClass3.default)(ParsePolygon, [{
key: 'toJSON',
/**
* Returns a JSON representation of the GeoPoint, suitable for Parse.
* @method toJSON
* @return {Object}
*/
value: function () {
ParsePolygon._validate(this._coordinates);
return {
__type: 'Polygon',
coordinates: this._coordinates
};
}
}, {
key: 'equals',
value: function (other) {
if (!(other instanceof ParsePolygon) || this.coordinates.length !== other.coordinates.length) {
return false;
}
var isEqual = true;
for (var i = 1; i < this._coordinates.length; i += 1) {
if (this._coordinates[i][0] != other.coordinates[i][0] || this._coordinates[i][1] != other.coordinates[i][1]) {
isEqual = false;
break;
}
}
return isEqual;
}
}, {
key: 'containsPoint',
value: function (point) {
var minX = this._coordinates[0][0];
var maxX = this._coordinates[0][0];
var minY = this._coordinates[0][1];
var maxY = this._coordinates[0][1];
for (var i = 1; i < this._coordinates.length; i += 1) {
var p = this._coordinates[i];
minX = Math.min(p[0], minX);
maxX = Math.max(p[0], maxX);
minY = Math.min(p[1], minY);
maxY = Math.max(p[1], maxY);
}
var outside = point.latitude < minX || point.latitude > maxX || point.longitude < minY || point.longitude > maxY;
if (outside) {
return false;
}
var inside = false;
for (var _i = 0, j = this._coordinates.length - 1; _i < this._coordinates.length; j = _i++) {
var startX = this._coordinates[_i][0];
var startY = this._coordinates[_i][1];
var endX = this._coordinates[j][0];
var endY = this._coordinates[j][1];
var intersect = startY > point.longitude != endY > point.longitude && point.latitude < (endX - startX) * (point.longitude - startY) / (endY - startY) + startX;
if (intersect) {
inside = !inside;
}
}
return inside;
}
/**
* Throws an exception if the given lat-long is out of bounds.
* @return {Array}
*/
}, {
key: 'coordinates',
get: function () {
return this._coordinates;
},
set: function (coords) {
this._coordinates = ParsePolygon._validate(coords);
}
}], [{
key: '_validate',
value: function (coords) {
if (!Array.isArray(coords)) {
throw new TypeError('Coordinates must be an Array');
}
if (coords.length < 3) {
throw new TypeError('Polygon must have at least 3 GeoPoints or Points');
}
var points = [];
for (var i = 0; i < coords.length; i += 1) {
var coord = coords[i];
var geoPoint = void 0;
if (coord instanceof _ParseGeoPoint2.default) {
geoPoint = coord;
} else if (Array.isArray(coord) && coord.length === 2) {
geoPoint = new _ParseGeoPoint2.default(coord[0], coord[1]);
} else {
throw new TypeError('Coordinates must be an Array of GeoPoints or Points');
}
points.push([geoPoint.latitude, geoPoint.longitude]);
}
return points;
}
}]);
return ParsePolygon;
}(); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParsePolygon;
},{"./ParseGeoPoint":15,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],21:[function(_dereq_,module,exports){
(function (process){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getIterator2 = _dereq_('babel-runtime/core-js/get-iterator');
var _getIterator3 = _interopRequireDefault(_getIterator2);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
var _isPromisesAPlusCompliant = true;
/**
* A Promise is returned by async methods as a hook to provide callbacks to be
* called when the async task is fulfilled.
*
* <p>Typical usage would be like:<pre>
* query.find().then(function(results) {
* results[0].set("foo", "bar");
* return results[0].saveAsync();
* }).then(function(result) {
* console.log("Updated " + result.id);
* });
* </pre></p>
*
* @class Parse.Promise
* @constructor
*/
var ParsePromise = function () {
function ParsePromise(executor) {
(0, _classCallCheck3.default)(this, ParsePromise);
this._resolved = false;
this._rejected = false;
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
if (typeof executor === 'function') {
executor(this.resolve.bind(this), this.reject.bind(this));
}
}
/**
* Marks this promise as fulfilled, firing any callbacks waiting on it.
* @method resolve
* @param {Object} result the result to pass to the callbacks.
*/
(0, _createClass3.default)(ParsePromise, [{
key: 'resolve',
value: function () {
if (this._resolved || this._rejected) {
throw new Error('A promise was resolved even though it had already been ' + (this._resolved ? 'resolved' : 'rejected') + '.');
}
this._resolved = true;
for (var _len = arguments.length, results = Array(_len), _key = 0; _key < _len; _key++) {
results[_key] = arguments[_key];
}
this._result = results;
for (var i = 0; i < this._resolvedCallbacks.length; i++) {
this._resolvedCallbacks[i].apply(this, results);
}
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
}
/**
* Marks this promise as fulfilled, firing any callbacks waiting on it.
* @method reject
* @param {Object} error the error to pass to the callbacks.
*/
}, {
key: 'reject',
value: function (error) {
if (this._resolved || this._rejected) {
throw new Error('A promise was rejected even though it had already been ' + (this._resolved ? 'resolved' : 'rejected') + '.');
}
this._rejected = true;
this._error = error;
for (var i = 0; i < this._rejectedCallbacks.length; i++) {
this._rejectedCallbacks[i](error);
}
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
}
/**
* Adds callbacks to be called when this promise is fulfilled. Returns a new
* Promise that will be fulfilled when the callback is complete. It allows
* chaining. If the callback itself returns a Promise, then the one returned
* by "then" will not be fulfilled until that one returned by the callback
* is fulfilled.
* @method then
* @param {Function} resolvedCallback Function that is called when this
* Promise is resolved. Once the callback is complete, then the Promise
* returned by "then" will also be fulfilled.
* @param {Function} rejectedCallback Function that is called when this
* Promise is rejected with an error. Once the callback is complete, then
* the promise returned by "then" with be resolved successfully. If
* rejectedCallback is null, or it returns a rejected Promise, then the
* Promise returned by "then" will be rejected with that error.
* @return {Parse.Promise} A new Promise that will be fulfilled after this
* Promise is fulfilled and either callback has completed. If the callback
* returned a Promise, then this Promise will not be fulfilled until that
* one is.
*/
}, {
key: 'then',
value: function (resolvedCallback, rejectedCallback) {
var _this = this;
var promise = new ParsePromise();
var wrappedResolvedCallback = function () {
for (var _len2 = arguments.length, results = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
results[_key2] = arguments[_key2];
}
if (typeof resolvedCallback === 'function') {
if (_isPromisesAPlusCompliant) {
try {
results = [resolvedCallback.apply(this, results)];
} catch (e) {
results = [ParsePromise.error(e)];
}
} else {
results = [resolvedCallback.apply(this, results)];
}
}
if (results.length === 1 && ParsePromise.is(results[0])) {
results[0].then(function () {
promise.resolve.apply(promise, arguments);
}, function (error) {
promise.reject(error);
});
} else {
promise.resolve.apply(promise, results);
}
};
var wrappedRejectedCallback = function (error) {
var result = [];
if (typeof rejectedCallback === 'function') {
if (_isPromisesAPlusCompliant) {
try {
result = [rejectedCallback(error)];
} catch (e) {
result = [ParsePromise.error(e)];
}
} else {
result = [rejectedCallback(error)];
}
if (result.length === 1 && ParsePromise.is(result[0])) {
result[0].then(function () {
promise.resolve.apply(promise, arguments);
}, function (error) {
promise.reject(error);
});
} else {
if (_isPromisesAPlusCompliant) {
promise.resolve.apply(promise, result);
} else {
promise.reject(result[0]);
}
}
} else {
promise.reject(error);
}
};
var runLater = function (fn) {
fn.call();
};
if (_isPromisesAPlusCompliant) {
if (typeof process !== 'undefined' && typeof process.nextTick === 'function') {
runLater = function (fn) {
process.nextTick(fn);
};
} else if (typeof setTimeout === 'function') {
runLater = function (fn) {
setTimeout(fn, 0);
};
}
}
if (this._resolved) {
runLater(function () {
wrappedResolvedCallback.apply(_this, _this._result);
});
} else if (this._rejected) {
runLater(function () {
wrappedRejectedCallback(_this._error);
});
} else {
this._resolvedCallbacks.push(wrappedResolvedCallback);
this._rejectedCallbacks.push(wrappedRejectedCallback);
}
return promise;
}
/**
* Add handlers to be called when the promise
* is either resolved or rejected
* @method always
*/
}, {
key: 'always',
value: function (callback) {
return this.then(callback, callback);
}
/**
* Add handlers to be called when the Promise object is resolved
* @method done
*/
}, {
key: 'done',
value: function (callback) {
return this.then(callback);
}
/**
* Add handlers to be called when the Promise object is rejected
* Alias for catch().
* @method fail
*/
}, {
key: 'fail',
value: function (callback) {
return this.then(null, callback);
}
/**
* Add handlers to be called when the Promise object is rejected
* @method catch
*/
}, {
key: 'catch',
value: function (callback) {
return this.then(null, callback);
}
/**
* Run the given callbacks after this promise is fulfilled.
* @method _thenRunCallbacks
* @param optionsOrCallback {} A Backbone-style options callback, or a
* callback function. If this is an options object and contains a "model"
* attributes, that will be passed to error callbacks as the first argument.
* @param model {} If truthy, this will be passed as the first result of
* error callbacks. This is for Backbone-compatability.
* @return {Parse.Promise} A promise that will be resolved after the
* callbacks are run, with the same result as this.
*/
}, {
key: '_thenRunCallbacks',
value: function (optionsOrCallback, model) {
var options = {};
if (typeof optionsOrCallback === 'function') {
options.success = function (result) {
optionsOrCallback(result, null);
};
options.error = function (error) {
optionsOrCallback(null, error);
};
} else if ((typeof optionsOrCallback === 'undefined' ? 'undefined' : (0, _typeof3.default)(optionsOrCallback)) === 'object') {
if (typeof optionsOrCallback.success === 'function') {
options.success = optionsOrCallback.success;
}
if (typeof optionsOrCallback.error === 'function') {
options.error = optionsOrCallback.error;
}
}
return this.then(function () {
for (var _len3 = arguments.length, results = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
results[_key3] = arguments[_key3];
}
if (options.success) {
options.success.apply(this, results);
}
return ParsePromise.as.apply(ParsePromise, arguments);
}, function (error) {
if (options.error) {
if (typeof model !== 'undefined') {
options.error(model, error);
} else {
options.error(error);
}
}
// By explicitly returning a rejected Promise, this will work with
// either jQuery or Promises/A+ semantics.
return ParsePromise.error(error);
});
}
/**
* Adds a callback function that should be called regardless of whether
* this promise failed or succeeded. The callback will be given either the
* array of results for its first argument, or the error as its second,
* depending on whether this Promise was rejected or resolved. Returns a
* new Promise, like "then" would.
* @method _continueWith
* @param {Function} continuation the callback.
*/
}, {
key: '_continueWith',
value: function (continuation) {
return this.then(function () {
for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return continuation(args, null);
}, function (error) {
return continuation(null, error);
});
}
/**
* Returns true iff the given object fulfils the Promise interface.
* @method is
* @param {Object} promise The object to test
* @static
* @return {Boolean}
*/
}], [{
key: 'is',
value: function (promise) {
return promise != null && typeof promise.then === 'function';
}
/**
* Returns a new promise that is resolved with a given value.
* @method as
* @param value The value to resolve the promise with
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'as',
value: function () {
var promise = new ParsePromise();
for (var _len5 = arguments.length, values = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
values[_key5] = arguments[_key5];
}
promise.resolve.apply(promise, values);
return promise;
}
/**
* Returns a new promise that is resolved with a given value.
* If that value is a thenable Promise (has a .then() prototype
* method), the new promise will be chained to the end of the
* value.
* @method resolve
* @param value The value to resolve the promise with
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'resolve',
value: function (value) {
return new ParsePromise(function (resolve, reject) {
if (ParsePromise.is(value)) {
value.then(resolve, reject);
} else {
resolve(value);
}
});
}
/**
* Returns a new promise that is rejected with a given error.
* @method error
* @param error The error to reject the promise with
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'error',
value: function () {
var promise = new ParsePromise();
for (var _len6 = arguments.length, errors = Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
errors[_key6] = arguments[_key6];
}
promise.reject.apply(promise, errors);
return promise;
}
/**
* Returns a new promise that is rejected with a given error.
* This is an alias for Parse.Promise.error, for compliance with
* the ES6 implementation.
* @method reject
* @param error The error to reject the promise with
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'reject',
value: function () {
for (var _len7 = arguments.length, errors = Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
errors[_key7] = arguments[_key7];
}
return ParsePromise.error.apply(null, errors);
}
/**
* Returns a new promise that is fulfilled when all of the input promises
* are resolved. If any promise in the list fails, then the returned promise
* will be rejected with an array containing the error from each promise.
* If they all succeed, then the returned promise will succeed, with the
* results being the results of all the input
* promises. For example: <pre>
* var p1 = Parse.Promise.as(1);
* var p2 = Parse.Promise.as(2);
* var p3 = Parse.Promise.as(3);
*
* Parse.Promise.when(p1, p2, p3).then(function(r1, r2, r3) {
* console.log(r1); // prints 1
* console.log(r2); // prints 2
* console.log(r3); // prints 3
* });</pre>
*
* The input promises can also be specified as an array: <pre>
* var promises = [p1, p2, p3];
* Parse.Promise.when(promises).then(function(results) {
* console.log(results); // prints [1,2,3]
* });
* </pre>
* @method when
* @param {Array} promises a list of promises to wait for.
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'when',
value: function (promises) {
var objects;
var arrayArgument = Array.isArray(promises);
if (arrayArgument) {
objects = promises;
} else {
objects = arguments;
}
var total = objects.length;
var hadError = false;
var results = [];
var returnValue = arrayArgument ? [results] : results;
var errors = [];
results.length = objects.length;
errors.length = objects.length;
if (total === 0) {
return ParsePromise.as.apply(this, returnValue);
}
var promise = new ParsePromise();
var resolveOne = function () {
total--;
if (total <= 0) {
if (hadError) {
promise.reject(errors);
} else {
promise.resolve.apply(promise, returnValue);
}
}
};
var chain = function (object, index) {
if (ParsePromise.is(object)) {
object.then(function (result) {
results[index] = result;
resolveOne();
}, function (error) {
errors[index] = error;
hadError = true;
resolveOne();
});
} else {
results[i] = object;
resolveOne();
}
};
for (var i = 0; i < objects.length; i++) {
chain(objects[i], i);
}
return promise;
}
/**
* Returns a new promise that is fulfilled when all of the promises in the
* iterable argument are resolved. If any promise in the list fails, then
* the returned promise will be immediately rejected with the reason that
* single promise rejected. If they all succeed, then the returned promise
* will succeed, with the results being the results of all the input
* promises. If the iterable provided is empty, the returned promise will
* be immediately resolved.
*
* For example: <pre>
* var p1 = Parse.Promise.as(1);
* var p2 = Parse.Promise.as(2);
* var p3 = Parse.Promise.as(3);
*
* Parse.Promise.all([p1, p2, p3]).then(function([r1, r2, r3]) {
* console.log(r1); // prints 1
* console.log(r2); // prints 2
* console.log(r3); // prints 3
* });</pre>
*
* @method all
* @param {Iterable} promises an iterable of promises to wait for.
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'all',
value: function (promises) {
var total = 0;
var objects = [];
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = (0, _getIterator3.default)(promises), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var p = _step.value;
objects[total++] = p;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
if (total === 0) {
return ParsePromise.as([]);
}
var hadError = false;
var promise = new ParsePromise();
var resolved = 0;
var results = [];
objects.forEach(function (object, i) {
if (ParsePromise.is(object)) {
object.then(function (result) {
if (hadError) {
return false;
}
results[i] = result;
resolved++;
if (resolved >= total) {
promise.resolve(results);
}
}, function (error) {
// Reject immediately
promise.reject(error);
hadError = true;
});
} else {
results[i] = object;
resolved++;
if (!hadError && resolved >= total) {
promise.resolve(results);
}
}
});
return promise;
}
/**
* Returns a new promise that is immediately fulfilled when any of the
* promises in the iterable argument are resolved or rejected. If the
* first promise to complete is resolved, the returned promise will be
* resolved with the same value. Likewise, if the first promise to
* complete is rejected, the returned promise will be rejected with the
* same reason.
*
* @method race
* @param {Iterable} promises an iterable of promises to wait for.
* @static
* @return {Parse.Promise} the new promise.
*/
}, {
key: 'race',
value: function (promises) {
var completed = false;
var promise = new ParsePromise();
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = (0, _getIterator3.default)(promises), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var p = _step2.value;
if (ParsePromise.is(p)) {
p.then(function (result) {
if (completed) {
return;
}
completed = true;
promise.resolve(result);
}, function (error) {
if (completed) {
return;
}
completed = true;
promise.reject(error);
});
} else if (!completed) {
completed = true;
promise.resolve(p);
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
return promise;
}
/**
* Runs the given asyncFunction repeatedly, as long as the predicate
* function returns a truthy value. Stops repeating if asyncFunction returns
* a rejected promise.
* @method _continueWhile
* @param {Function} predicate should return false when ready to stop.
* @param {Function} asyncFunction should return a Promise.
* @static
*/
}, {
key: '_continueWhile',
value: function (predicate, asyncFunction) {
if (predicate()) {
return asyncFunction().then(function () {
return ParsePromise._continueWhile(predicate, asyncFunction);
});
}
return ParsePromise.as();
}
}, {
key: 'isPromisesAPlusCompliant',
value: function () {
return _isPromisesAPlusCompliant;
}
}, {
key: 'enableAPlusCompliant',
value: function () {
_isPromisesAPlusCompliant = true;
}
}, {
key: 'disableAPlusCompliant',
value: function () {
_isPromisesAPlusCompliant = false;
}
}]);
return ParsePromise;
}();
exports.default = ParsePromise;
}).call(this,_dereq_('_process'))
},{"_process":63,"babel-runtime/core-js/get-iterator":44,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],22:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _keys = _dereq_('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _encode = _dereq_('./encode');
var _encode2 = _interopRequireDefault(_encode);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParseGeoPoint = _dereq_('./ParseGeoPoint');
var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint);
var _ParsePolygon = _dereq_('./ParsePolygon');
var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape any \E's in
* the text separately.
*/
function quote(s) {
return '\\Q' + s.replace('\\E', '\\E\\\\E\\Q') + '\\E';
}
/**
* Handles pre-populating the result data of a query with select fields,
* making sure that the data object contains keys for all objects that have
* been requested with a select, so that our cached state updates correctly.
*/
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function handleSelectResult(data, select) {
var serverDataMask = {};
select.forEach(function (field) {
var hasSubObjectSelect = field.indexOf(".") !== -1;
if (!hasSubObjectSelect && !data.hasOwnProperty(field)) {
// this field was selected, but is missing from the retrieved data
data[field] = undefined;
} else if (hasSubObjectSelect) {
// this field references a sub-object,
// so we need to walk down the path components
var pathComponents = field.split(".");
var obj = data;
var serverMask = serverDataMask;
pathComponents.forEach(function (component, index, arr) {
// add keys if the expected data is missing
if (obj && !obj.hasOwnProperty(component)) {
obj[component] = undefined;
}
if (obj !== undefined) {
obj = obj[component];
}
//add this path component to the server mask so we can fill it in later if needed
if (index < arr.length - 1) {
if (!serverMask[component]) {
serverMask[component] = {};
}
serverMask = serverMask[component];
}
});
}
});
if ((0, _keys2.default)(serverDataMask).length > 0) {
var copyMissingDataWithMask = function copyMissingDataWithMask(src, dest, mask, copyThisLevel) {
//copy missing elements at this level
if (copyThisLevel) {
for (var key in src) {
if (src.hasOwnProperty(key) && !dest.hasOwnProperty(key)) {
dest[key] = src[key];
}
}
}
for (var key in mask) {
if (dest[key] !== undefined && dest[key] !== null && src !== undefined && src !== null) {
//traverse into objects as needed
copyMissingDataWithMask(src[key], dest[key], mask[key], true);
}
}
};
// When selecting from sub-objects, we don't want to blow away the missing
// information that we may have retrieved before. We've already added any
// missing selected keys to sub-objects, but we still need to add in the
// data for any previously retrieved sub-objects that were not selected.
var serverData = _CoreManager2.default.getObjectStateController().getServerData({ id: data.objectId, className: data.className });
copyMissingDataWithMask(serverData, data, serverDataMask, false);
}
}
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @class Parse.Query
* @constructor
* @param {} objectClass An instance of a subclass of Parse.Object, or a Parse className string.
*
* <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of Parse.Object.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of Parse.Object.
* },
*
* error: function(object, error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new Parse.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*/
var ParseQuery = function () {
function ParseQuery(objectClass) {
(0, _classCallCheck3.default)(this, ParseQuery);
if (typeof objectClass === 'string') {
if (objectClass === 'User' && _CoreManager2.default.get('PERFORM_USER_REWRITE')) {
this.className = '_User';
} else {
this.className = objectClass;
}
} else if (objectClass instanceof _ParseObject2.default) {
this.className = objectClass.className;
} else if (typeof objectClass === 'function') {
if (typeof objectClass.className === 'string') {
this.className = objectClass.className;
} else {
var obj = new objectClass();
this.className = obj.className;
}
} else {
throw new TypeError('A ParseQuery must be constructed with a ParseObject or class name.');
}
this._where = {};
this._include = [];
this._limit = -1; // negative limit is not sent in the server request
this._skip = 0;
this._extraOptions = {};
}
/**
* Adds constraint that at least one of the passed in queries matches.
* @method _orQuery
* @param {Array} queries
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
(0, _createClass3.default)(ParseQuery, [{
key: '_orQuery',
value: function (queries) {
var queryJSON = queries.map(function (q) {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
}
/**
* Helper for condition queries
*/
}, {
key: '_addCondition',
value: function (key, condition, value) {
if (!this._where[key] || typeof this._where[key] === 'string') {
this._where[key] = {};
}
this._where[key][condition] = (0, _encode2.default)(value, false, true);
return this;
}
/**
* Returns a JSON representation of this query.
* @method toJSON
* @return {Object} The JSON representation of the query.
*/
}, {
key: 'toJSON',
value: function () {
var params = {
where: this._where
};
if (this._include.length) {
params.include = this._include.join(',');
}
if (this._select) {
params.keys = this._select.join(',');
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order) {
params.order = this._order.join(',');
}
for (var key in this._extraOptions) {
params[key] = this._extraOptions[key];
}
return params;
}
/**
* Return a query with conditions from json, can be useful to send query from server side to client
* Not static, all query conditions was set before calling this method will be deleted.
* For example on the server side we have
* var query = new Parse.Query("className");
* query.equalTo(key: value);
* query.limit(100);
* ... (others queries)
* Create JSON representation of Query Object
* var jsonFromServer = query.fromJSON();
*
* On client side getting query:
* var query = new Parse.Query("className");
* query.fromJSON(jsonFromServer);
*
* and continue to query...
* query.skip(100).find().then(...);
* @method withJSON
* @param {QueryJSON} json from Parse.Query.toJSON() method
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withJSON',
value: function (json) {
if (json.where) {
this._where = json.where;
}
if (json.include) {
this._include = json.include.split(",");
}
if (json.keys) {
this._select = json.keys.split(",");
}
if (json.limit) {
this._limit = json.limit;
}
if (json.skip) {
this._skip = json.skip;
}
if (json.order) {
this._order = json.order.split(",");
}
for (var _key in json) {
if (json.hasOwnProperty(_key)) {
if (["where", "include", "keys", "limit", "skip", "order"].indexOf(_key) === -1) {
this._extraOptions[_key] = json[_key];
}
}
}return this;
}
/**
* Static method to restore Parse.Query by json representation
* Internally calling Parse.Query.withJSON
* @param {String} className
* @param {QueryJSON} json from Parse.Query.toJSON() method
* @returns {Parse.Query} new created query
*/
}, {
key: 'get',
/**
* Constructs a Parse.Object whose id is already known by fetching data from
* the server. Either options.success or options.error is called when the
* find completes.
*
* @method get
* @param {String} objectId The id of the object to be fetched.
* @param {Object} options A Backbone-style options object.
* Valid options are:<ul>
* <li>success: A Backbone-style success callback
* <li>error: An Backbone-style error callback.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the result when
* the query completes.
*/
value: function (objectId, options) {
this.equalTo('objectId', objectId);
var firstOptions = {};
if (options && options.hasOwnProperty('useMasterKey')) {
firstOptions.useMasterKey = options.useMasterKey;
}
if (options && options.hasOwnProperty('sessionToken')) {
firstOptions.sessionToken = options.sessionToken;
}
return this.first(firstOptions).then(function (response) {
if (response) {
return response;
}
var errorObject = new _ParseError2.default(_ParseError2.default.OBJECT_NOT_FOUND, 'Object not found.');
return _ParsePromise2.default.error(errorObject);
})._thenRunCallbacks(options, null);
}
/**
* Retrieves a list of ParseObjects that satisfy this query.
* Either options.success or options.error is called when the find
* completes.
*
* @method find
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the results when
* the query completes.
*/
}, {
key: 'find',
value: function (options) {
var _this = this;
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = _CoreManager2.default.getQueryController();
var select = this._select;
return controller.find(this.className, this.toJSON(), findOptions).then(function (response) {
return response.results.map(function (data) {
// In cases of relations, the server may send back a className
// on the top level of the payload
var override = response.className || _this.className;
if (!data.className) {
data.className = override;
}
// Make sure the data object contains keys for all objects that
// have been requested with a select, so that our cached state
// updates correctly.
if (select) {
handleSelectResult(data, select);
}
return _ParseObject2.default.fromJSON(data, !select);
});
})._thenRunCallbacks(options);
}
/**
* Counts the number of objects that match this query.
* Either options.success or options.error is called when the count
* completes.
*
* @method count
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the count completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the count when
* the query completes.
*/
}, {
key: 'count',
value: function (options) {
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = _CoreManager2.default.getQueryController();
var params = this.toJSON();
params.limit = 0;
params.count = 1;
return controller.find(this.className, params, findOptions).then(function (result) {
return result.count;
})._thenRunCallbacks(options);
}
/**
* Retrieves at most one Parse.Object that satisfies this query.
*
* Either options.success or options.error is called when it completes.
* success is passed the object if there is one. otherwise, undefined.
*
* @method first
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the find completes successfully.
* <li>error: Function to call when the find fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
*
* @return {Parse.Promise} A promise that is resolved with the object when
* the query completes.
*/
}, {
key: 'first',
value: function (options) {
var _this2 = this;
options = options || {};
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var controller = _CoreManager2.default.getQueryController();
var params = this.toJSON();
params.limit = 1;
var select = this._select;
return controller.find(this.className, params, findOptions).then(function (response) {
var objects = response.results;
if (!objects[0]) {
return undefined;
}
if (!objects[0].className) {
objects[0].className = _this2.className;
}
// Make sure the data object contains keys for all objects that
// have been requested with a select, so that our cached state
// updates correctly.
if (select) {
handleSelectResult(objects[0], select);
}
return _ParseObject2.default.fromJSON(objects[0], !select);
})._thenRunCallbacks(options);
}
/**
* Iterates over each result of a query, calling a callback for each one. If
* the callback returns a promise, the iteration will not continue until
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
* @method each
* @param {Function} callback Callback that will be called with each result
* of the query.
* @param {Object} options A Backbone-style options object. Valid options
* are:<ul>
* <li>success: Function to call when the iteration completes successfully.
* <li>error: Function to call when the iteration fails.
* <li>useMasterKey: In Cloud Code and Node only, causes the Master Key to
* be used for this request.
* <li>sessionToken: A valid session token, used for making a request on
* behalf of a specific user.
* </ul>
* @return {Parse.Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
}, {
key: 'each',
value: function (callback, options) {
options = options || {};
if (this._order || this._skip || this._limit >= 0) {
return _ParsePromise2.default.error('Cannot iterate on a query with sort, skip, or limit.')._thenRunCallbacks(options);
}
new _ParsePromise2.default();
var query = new ParseQuery(this.className);
// We can override the batch size from the options.
// This is undocumented, but useful for testing.
query._limit = options.batchSize || 100;
query._include = this._include.map(function (i) {
return i;
});
if (this._select) {
query._select = this._select.map(function (s) {
return s;
});
}
query._where = {};
for (var attr in this._where) {
var val = this._where[attr];
if (Array.isArray(val)) {
query._where[attr] = val.map(function (v) {
return v;
});
} else if (val && (typeof val === 'undefined' ? 'undefined' : (0, _typeof3.default)(val)) === 'object') {
var conditionMap = {};
query._where[attr] = conditionMap;
for (var cond in val) {
conditionMap[cond] = val[cond];
}
} else {
query._where[attr] = val;
}
}
query.ascending('objectId');
var findOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
findOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('sessionToken')) {
findOptions.sessionToken = options.sessionToken;
}
var finished = false;
return _ParsePromise2.default._continueWhile(function () {
return !finished;
}, function () {
return query.find(findOptions).then(function (results) {
var callbacksDone = _ParsePromise2.default.as();
results.forEach(function (result) {
callbacksDone = callbacksDone.then(function () {
return callback(result);
});
});
return callbacksDone.then(function () {
if (results.length >= query._limit) {
query.greaterThan('objectId', results[results.length - 1].id);
} else {
finished = true;
}
});
});
})._thenRunCallbacks(options);
}
/** Query Conditions **/
/**
* Adds a constraint to the query that requires a particular key's value to
* be equal to the provided value.
* @method equalTo
* @param {String} key The key to check.
* @param value The value that the Parse.Object must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'equalTo',
value: function (key, value) {
if (typeof value === 'undefined') {
return this.doesNotExist(key);
}
this._where[key] = (0, _encode2.default)(value, false, true);
return this;
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
* @method notEqualTo
* @param {String} key The key to check.
* @param value The value that must not be equalled.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'notEqualTo',
value: function (key, value) {
return this._addCondition(key, '$ne', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than the provided value.
* @method lessThan
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'lessThan',
value: function (key, value) {
return this._addCondition(key, '$lt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than the provided value.
* @method greaterThan
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'greaterThan',
value: function (key, value) {
return this._addCondition(key, '$gt', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
* @method lessThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'lessThanOrEqualTo',
value: function (key, value) {
return this._addCondition(key, '$lte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
* @method greaterThanOrEqualTo
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'greaterThanOrEqualTo',
value: function (key, value) {
return this._addCondition(key, '$gte', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
* @method containedIn
* @param {String} key The key to check.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'containedIn',
value: function (key, value) {
return this._addCondition(key, '$in', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
* @method notContainedIn
* @param {String} key The key to check.
* @param {Array} values The values that will not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'notContainedIn',
value: function (key, value) {
return this._addCondition(key, '$nin', value);
}
/**
* Adds a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
* @method containsAll
* @param {String} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'containsAll',
value: function (key, values) {
return this._addCondition(key, '$all', values);
}
/**
* Adds a constraint for finding objects that contain the given key.
* @method exists
* @param {String} key The key that should exist.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'exists',
value: function (key) {
return this._addCondition(key, '$exists', true);
}
/**
* Adds a constraint for finding objects that do not contain a given key.
* @method doesNotExist
* @param {String} key The key that should not exist
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'doesNotExist',
value: function (key) {
return this._addCondition(key, '$exists', false);
}
/**
* Adds a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
* @method matches
* @param {String} key The key that the string to match is stored in.
* @param {RegExp} regex The regular expression pattern to match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'matches',
value: function (key, regex, modifiers) {
this._addCondition(key, '$regex', regex);
if (!modifiers) {
modifiers = '';
}
if (regex.ignoreCase) {
modifiers += 'i';
}
if (regex.multiline) {
modifiers += 'm';
}
if (modifiers.length) {
this._addCondition(key, '$options', modifiers);
}
return this;
}
/**
* Adds a constraint that requires that a key's value matches a Parse.Query
* constraint.
* @method matchesQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'matchesQuery',
value: function (key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$inQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value not matches a
* Parse.Query constraint.
* @method doesNotMatchQuery
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'doesNotMatchQuery',
value: function (key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$notInQuery', queryJSON);
}
/**
* Adds a constraint that requires that a key's value matches a value in
* an object returned by a different Parse.Query.
* @method matchesKeyInQuery
* @param {String} key The key that contains the value that is being
* matched.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'matchesKeyInQuery',
value: function (key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$select', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint that requires that a key's value not match a value in
* an object returned by a different Parse.Query.
* @method doesNotMatchKeyInQuery
* @param {String} key The key that contains the value that is being
* excluded.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'doesNotMatchKeyInQuery',
value: function (key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
return this._addCondition(key, '$dontSelect', {
key: queryKey,
query: queryJSON
});
}
/**
* Adds a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
* @method contains
* @param {String} key The key that the string to match is stored in.
* @param {String} substring The substring that the value must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'contains',
value: function (key, value) {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value));
}
/**
* Adds a constraint for finding string values that start with a provided
* string. This query will use the backend index, so it will be fast even
* for large datasets.
* @method startsWith
* @param {String} key The key that the string to match is stored in.
* @param {String} prefix The substring that the value must start with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'startsWith',
value: function (key, value) {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', '^' + quote(value));
}
/**
* Adds a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
* @method endsWith
* @param {String} key The key that the string to match is stored in.
* @param {String} suffix The substring that the value must end with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'endsWith',
value: function (key, value) {
if (typeof value !== 'string') {
throw new Error('The value being searched for must be a string.');
}
return this._addCondition(key, '$regex', quote(value) + '$');
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given.
* @method near
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'near',
value: function (key, point) {
if (!(point instanceof _ParseGeoPoint2.default)) {
// Try to cast it as a GeoPoint
point = new _ParseGeoPoint2.default(point);
}
return this._addCondition(key, '$nearSphere', point);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* @method withinRadians
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in radians) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withinRadians',
value: function (key, point, distance) {
this.near(key, point);
return this._addCondition(key, '$maxDistance', distance);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 3958.8 miles.
* @method withinMiles
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in miles) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withinMiles',
value: function (key, point, distance) {
return this.withinRadians(key, point, distance / 3958.8);
}
/**
* Adds a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 6371.0 kilometers.
* @method withinKilometers
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in kilometers) of results
* to return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withinKilometers',
value: function (key, point, distance) {
return this.withinRadians(key, point, distance / 6371.0);
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
* @method withinGeoBox
* @param {String} key The key to be constrained.
* @param {Parse.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {Parse.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withinGeoBox',
value: function (key, southwest, northeast) {
if (!(southwest instanceof _ParseGeoPoint2.default)) {
southwest = new _ParseGeoPoint2.default(southwest);
}
if (!(northeast instanceof _ParseGeoPoint2.default)) {
northeast = new _ParseGeoPoint2.default(northeast);
}
this._addCondition(key, '$within', { '$box': [southwest, northeast] });
return this;
}
/**
* Adds a constraint to the query that requires a particular key's
* coordinates be contained within and on the bounds of a given polygon.
* Supports closed and open (last point is connected to first) paths
*
* Polygon must have at least 3 points
*
* @method withinPolygon
* @param {String} key The key to be constrained.
* @param {Array} array of geopoints
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'withinPolygon',
value: function (key, points) {
return this._addCondition(key, '$geoWithin', { '$polygon': points });
}
/**
* Add a constraint to the query that requires a particular key's
* coordinates that contains a ParseGeoPoint
*
* @method polygonContains
* @param {String} key The key to be constrained.
* @param {Parse.GeoPoint} GeoPoint
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'polygonContains',
value: function (key, point) {
return this._addCondition(key, '$geoIntersects', { '$point': point });
}
/** Query Orderings **/
/**
* Sorts the results in ascending order by the given key.
*
* @method ascending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'ascending',
value: function () {
this._order = [];
for (var _len = arguments.length, keys = Array(_len), _key2 = 0; _key2 < _len; _key2++) {
keys[_key2] = arguments[_key2];
}
return this.addAscending.apply(this, keys);
}
/**
* Sorts the results in ascending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addAscending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'addAscending',
value: function () {
var _this3 = this;
if (!this._order) {
this._order = [];
}
for (var _len2 = arguments.length, keys = Array(_len2), _key3 = 0; _key3 < _len2; _key3++) {
keys[_key3] = arguments[_key3];
}
keys.forEach(function (key) {
if (Array.isArray(key)) {
key = key.join();
}
_this3._order = _this3._order.concat(key.replace(/\s/g, '').split(','));
});
return this;
}
/**
* Sorts the results in descending order by the given key.
*
* @method descending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'descending',
value: function () {
this._order = [];
for (var _len3 = arguments.length, keys = Array(_len3), _key4 = 0; _key4 < _len3; _key4++) {
keys[_key4] = arguments[_key4];
}
return this.addDescending.apply(this, keys);
}
/**
* Sorts the results in descending order by the given key,
* but can also add secondary sort descriptors without overwriting _order.
*
* @method addDescending
* @param {(String|String[]|...String} key The key to order by, which is a
* string of comma separated values, or an Array of keys, or multiple keys.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'addDescending',
value: function () {
var _this4 = this;
if (!this._order) {
this._order = [];
}
for (var _len4 = arguments.length, keys = Array(_len4), _key5 = 0; _key5 < _len4; _key5++) {
keys[_key5] = arguments[_key5];
}
keys.forEach(function (key) {
if (Array.isArray(key)) {
key = key.join();
}
_this4._order = _this4._order.concat(key.replace(/\s/g, '').split(',').map(function (k) {
return '-' + k;
}));
});
return this;
}
/** Query Options **/
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
* @method skip
* @param {Number} n the number of results to skip.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'skip',
value: function (n) {
if (typeof n !== 'number' || n < 0) {
throw new Error('You can only skip by a positive number');
}
this._skip = n;
return this;
}
/**
* Sets the limit of the number of results to return. The default limit is
* 100, with a maximum of 1000 results being returned at a time.
* @method limit
* @param {Number} n the number of results to limit to.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'limit',
value: function (n) {
if (typeof n !== 'number') {
throw new Error('You can only set the limit to a numeric value');
}
this._limit = n;
return this;
}
/**
* Includes nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetched.
* @method include
* @param {String} key The name of the key to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'include',
value: function () {
var _this5 = this;
for (var _len5 = arguments.length, keys = Array(_len5), _key6 = 0; _key6 < _len5; _key6++) {
keys[_key6] = arguments[_key6];
}
keys.forEach(function (key) {
if (Array.isArray(key)) {
_this5._include = _this5._include.concat(key);
} else {
_this5._include.push(key);
}
});
return this;
}
/**
* Restricts the fields of the returned Parse.Objects to include only the
* provided keys. If this is called multiple times, then all of the keys
* specified in each of the calls will be included.
* @method select
* @param {Array} keys The names of the keys to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
}, {
key: 'select',
value: function () {
var _this6 = this;
if (!this._select) {
this._select = [];
}
for (var _len6 = arguments.length, keys = Array(_len6), _key7 = 0; _key7 < _len6; _key7++) {
keys[_key7] = arguments[_key7];
}
keys.forEach(function (key) {
if (Array.isArray(key)) {
_this6._select = _this6._select.concat(key);
} else {
_this6._select.push(key);
}
});
return this;
}
/**
* Subscribe this query to get liveQuery updates
* @method subscribe
* @return {LiveQuerySubscription} Returns the liveQuerySubscription, it's an event emitter
* which can be used to get liveQuery updates.
*/
}, {
key: 'subscribe',
value: function () {
var controller = _CoreManager2.default.getLiveQueryController();
return controller.subscribe(this);
}
/**
* Constructs a Parse.Query that is the OR of the passed in queries. For
* example:
* <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
*
* will create a compoundQuery that is an or of the query1, query2, and
* query3.
* @method or
* @param {...Parse.Query} var_args The list of queries to OR.
* @static
* @return {Parse.Query} The query that is the OR of the passed in queries.
*/
}], [{
key: 'fromJSON',
value: function (className, json) {
var query = new ParseQuery(className);
return query.withJSON(json);
}
}, {
key: 'or',
value: function () {
var className = null;
for (var _len7 = arguments.length, queries = Array(_len7), _key8 = 0; _key8 < _len7; _key8++) {
queries[_key8] = arguments[_key8];
}
queries.forEach(function (q) {
if (!className) {
className = q.className;
}
if (className !== q.className) {
throw new Error('All queries must be for the same class.');
}
});
var query = new ParseQuery(className);
query._orQuery(queries);
return query;
}
}]);
return ParseQuery;
}();
exports.default = ParseQuery;
var DefaultController = {
find: function (className, params, options) {
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('GET', 'classes/' + className, params, options);
}
};
_CoreManager2.default.setQueryController(DefaultController);
},{"./CoreManager":3,"./ParseError":13,"./ParseGeoPoint":15,"./ParseObject":18,"./ParsePolygon":20,"./ParsePromise":21,"./encode":37,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/typeof":62}],23:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _ParseOp = _dereq_('./ParseOp');
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseQuery = _dereq_('./ParseQuery');
var _ParseQuery2 = _interopRequireDefault(_ParseQuery);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Creates a new Relation for the given parent object and key. This
* constructor should rarely be used directly, but rather created by
* Parse.Object.relation.
* @class Parse.Relation
* @constructor
* @param {Parse.Object} parent The parent of this relation.
* @param {String} key The key for this relation on the parent.
*
* <p>
* A class that is used to access all of the children of a many-to-many
* relationship. Each instance of Parse.Relation is associated with a
* particular parent object and key.
* </p>
*/
var ParseRelation = function () {
function ParseRelation(parent, key) {
(0, _classCallCheck3.default)(this, ParseRelation);
this.parent = parent;
this.key = key;
this.targetClassName = null;
}
/**
* Makes sure that this relation has the right parent and key.
*/
(0, _createClass3.default)(ParseRelation, [{
key: '_ensureParentAndKey',
value: function (parent, key) {
this.key = this.key || key;
if (this.key !== key) {
throw new Error('Internal Error. Relation retrieved from two different keys.');
}
if (this.parent) {
if (this.parent.className !== parent.className) {
throw new Error('Internal Error. Relation retrieved from two different Objects.');
}
if (this.parent.id) {
if (this.parent.id !== parent.id) {
throw new Error('Internal Error. Relation retrieved from two different Objects.');
}
} else if (parent.id) {
this.parent = parent;
}
} else {
this.parent = parent;
}
}
/**
* Adds a Parse.Object or an array of Parse.Objects to the relation.
* @method add
* @param {} objects The item or items to add.
*/
}, {
key: 'add',
value: function (objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
var change = new _ParseOp.RelationOp(objects, []);
var parent = this.parent;
if (!parent) {
throw new Error('Cannot add to a Relation without a parent');
}
parent.set(this.key, change);
this.targetClassName = change._targetClassName;
return parent;
}
/**
* Removes a Parse.Object or an array of Parse.Objects from this relation.
* @method remove
* @param {} objects The item or items to remove.
*/
}, {
key: 'remove',
value: function (objects) {
if (!Array.isArray(objects)) {
objects = [objects];
}
var change = new _ParseOp.RelationOp([], objects);
if (!this.parent) {
throw new Error('Cannot remove from a Relation without a parent');
}
this.parent.set(this.key, change);
this.targetClassName = change._targetClassName;
}
/**
* Returns a JSON version of the object suitable for saving to disk.
* @method toJSON
* @return {Object}
*/
}, {
key: 'toJSON',
value: function () {
return {
__type: 'Relation',
className: this.targetClassName
};
}
/**
* Returns a Parse.Query that is limited to objects in this
* relation.
* @method query
* @return {Parse.Query}
*/
}, {
key: 'query',
value: function () {
var query;
var parent = this.parent;
if (!parent) {
throw new Error('Cannot construct a query for a Relation without a parent');
}
if (!this.targetClassName) {
query = new _ParseQuery2.default(parent.className);
query._extraOptions.redirectClassNameForKey = this.key;
} else {
query = new _ParseQuery2.default(this.targetClassName);
}
query._addCondition('$relatedTo', 'object', {
__type: 'Pointer',
className: parent.className,
objectId: parent.id
});
query._addCondition('$relatedTo', 'key', this.key);
return query;
}
}]);
return ParseRelation;
}(); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParseRelation;
},{"./ParseObject":18,"./ParseOp":19,"./ParseQuery":22,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],24:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = _dereq_('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _ParseACL = _dereq_('./ParseACL');
var _ParseACL2 = _interopRequireDefault(_ParseACL);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParseObject2 = _dereq_('./ParseObject');
var _ParseObject3 = _interopRequireDefault(_ParseObject2);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Represents a Role on the Parse server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* <p>Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.</p>
* @class Parse.Role
* @constructor
* @param {String} name The name of the Role to create.
* @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
* A Parse.Role is a local representation of a role persisted to the Parse
* cloud.
*/
var ParseRole = function (_ParseObject) {
(0, _inherits3.default)(ParseRole, _ParseObject);
function ParseRole(name, acl) {
(0, _classCallCheck3.default)(this, ParseRole);
var _this = (0, _possibleConstructorReturn3.default)(this, (ParseRole.__proto__ || (0, _getPrototypeOf2.default)(ParseRole)).call(this, '_Role'));
if (typeof name === 'string' && acl instanceof _ParseACL2.default) {
_this.setName(name);
_this.setACL(acl);
}
return _this;
}
/**
* Gets the name of the role. You can alternatively call role.get("name")
*
* @method getName
* @return {String} the name of the role.
*/
(0, _createClass3.default)(ParseRole, [{
key: 'getName',
value: function () {
var name = this.get('name');
if (name == null || typeof name === 'string') {
return name;
}
return '';
}
/**
* Sets the name for a role. This value must be set before the role has
* been saved to the server, and cannot be set once the role has been
* saved.
*
* <p>
* A role's name can only contain alphanumeric characters, _, -, and
* spaces.
* </p>
*
* <p>This is equivalent to calling role.set("name", name)</p>
*
* @method setName
* @param {String} name The name of the role.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
}, {
key: 'setName',
value: function (name, options) {
return this.set('name', name, options);
}
/**
* Gets the Parse.Relation for the Parse.Users that are direct
* children of this role. These users are granted any privileges that this
* role has been granted (e.g. read or write access through ACLs). You can
* add or remove users from the role through this relation.
*
* <p>This is equivalent to calling role.relation("users")</p>
*
* @method getUsers
* @return {Parse.Relation} the relation for the users belonging to this
* role.
*/
}, {
key: 'getUsers',
value: function () {
return this.relation('users');
}
/**
* Gets the Parse.Relation for the Parse.Roles that are direct
* children of this role. These roles' users are granted any privileges that
* this role has been granted (e.g. read or write access through ACLs). You
* can add or remove child roles from this role through this relation.
*
* <p>This is equivalent to calling role.relation("roles")</p>
*
* @method getRoles
* @return {Parse.Relation} the relation for the roles belonging to this
* role.
*/
}, {
key: 'getRoles',
value: function () {
return this.relation('roles');
}
}, {
key: 'validate',
value: function (attrs, options) {
var isInvalid = (0, _get3.default)(ParseRole.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseRole.prototype), 'validate', this).call(this, attrs, options);
if (isInvalid) {
return isInvalid;
}
if ('name' in attrs && attrs.name !== this.getName()) {
var newName = attrs.name;
if (this.id && this.id !== attrs.objectId) {
// Check to see if the objectId being set matches this.id
// This happens during a fetch -- the id is set before calling fetch
// Let the name be set in this case
return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name can only be set before it has been saved.');
}
if (typeof newName !== 'string') {
return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name must be a String.');
}
if (!/^[0-9a-zA-Z\-_ ]+$/.test(newName)) {
return new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'A role\'s name can be only contain alphanumeric characters, _, ' + '-, and spaces.');
}
}
return false;
}
}]);
return ParseRole;
}(_ParseObject3.default); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParseRole;
_ParseObject3.default.registerSubclass('_Role', ParseRole);
},{"./ParseACL":11,"./ParseError":13,"./ParseObject":18,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/get":59,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61}],25:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _isRevocableSession = _dereq_('./isRevocableSession');
var _isRevocableSession2 = _interopRequireDefault(_isRevocableSession);
var _ParseObject2 = _dereq_('./ParseObject');
var _ParseObject3 = _interopRequireDefault(_ParseObject2);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _ParseUser = _dereq_('./ParseUser');
var _ParseUser2 = _interopRequireDefault(_ParseUser);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* @class Parse.Session
* @constructor
*
* <p>A Parse.Session object is a local representation of a revocable session.
* This class is a subclass of a Parse.Object, and retains the same
* functionality of a Parse.Object.</p>
*/
var ParseSession = function (_ParseObject) {
(0, _inherits3.default)(ParseSession, _ParseObject);
function ParseSession(attributes) {
(0, _classCallCheck3.default)(this, ParseSession);
var _this = (0, _possibleConstructorReturn3.default)(this, (ParseSession.__proto__ || (0, _getPrototypeOf2.default)(ParseSession)).call(this, '_Session'));
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
if (!_this.set(attributes || {})) {
throw new Error('Can\'t create an invalid Session');
}
}
return _this;
}
/**
* Returns the session token string.
* @method getSessionToken
* @return {String}
*/
(0, _createClass3.default)(ParseSession, [{
key: 'getSessionToken',
value: function () {
var token = this.get('sessionToken');
if (typeof token === 'string') {
return token;
}
return '';
}
}], [{
key: 'readOnlyAttributes',
value: function () {
return ['createdWith', 'expiresAt', 'installationId', 'restricted', 'sessionToken', 'user'];
}
/**
* Retrieves the Session object for the currently logged in session.
* @method current
* @static
* @return {Parse.Promise} A promise that is resolved with the Parse.Session
* object after it has been fetched. If there is no current user, the
* promise will be rejected.
*/
}, {
key: 'current',
value: function (options) {
options = options || {};
var controller = _CoreManager2.default.getSessionController();
var sessionOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
sessionOptions.useMasterKey = options.useMasterKey;
}
return _ParseUser2.default.currentAsync().then(function (user) {
if (!user) {
return _ParsePromise2.default.error('There is no current user.');
}
user.getSessionToken();
sessionOptions.sessionToken = user.getSessionToken();
return controller.getSession(sessionOptions);
});
}
/**
* Determines whether the current session token is revocable.
* This method is useful for migrating Express.js or Node.js web apps to
* use revocable sessions. If you are migrating an app that uses the Parse
* SDK in the browser only, please use Parse.User.enableRevocableSession()
* instead, so that sessions can be automatically upgraded.
* @method isCurrentSessionRevocable
* @static
* @return {Boolean}
*/
}, {
key: 'isCurrentSessionRevocable',
value: function () {
var currentUser = _ParseUser2.default.current();
if (currentUser) {
return (0, _isRevocableSession2.default)(currentUser.getSessionToken() || '');
}
return false;
}
}]);
return ParseSession;
}(_ParseObject3.default); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
exports.default = ParseSession;
_ParseObject3.default.registerSubclass('_Session', ParseSession);
var DefaultController = {
getSession: function (options) {
var RESTController = _CoreManager2.default.getRESTController();
var session = new ParseSession();
return RESTController.request('GET', 'sessions/me', {}, options).then(function (sessionData) {
session._finishFetch(sessionData);
session._setExisted(true);
return session;
});
}
};
_CoreManager2.default.setSessionController(DefaultController);
},{"./CoreManager":3,"./ParseObject":18,"./ParsePromise":21,"./ParseUser":26,"./isRevocableSession":40,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],26:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _defineProperty = _dereq_('babel-runtime/core-js/object/define-property');
var _defineProperty2 = _interopRequireDefault(_defineProperty);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _getPrototypeOf = _dereq_('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = _dereq_('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _get2 = _dereq_('babel-runtime/helpers/get');
var _get3 = _interopRequireDefault(_get2);
var _inherits2 = _dereq_('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _isRevocableSession = _dereq_('./isRevocableSession');
var _isRevocableSession2 = _interopRequireDefault(_isRevocableSession);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParseObject2 = _dereq_('./ParseObject');
var _ParseObject3 = _interopRequireDefault(_ParseObject2);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _ParseSession = _dereq_('./ParseSession');
var _ParseSession2 = _interopRequireDefault(_ParseSession);
var _Storage = _dereq_('./Storage');
var _Storage2 = _interopRequireDefault(_Storage);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var CURRENT_USER_KEY = 'currentUser'; /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var canUseCurrentUser = !_CoreManager2.default.get('IS_NODE');
var currentUserCacheMatchesDisk = false;
var currentUserCache = null;
var authProviders = {};
/**
* @class Parse.User
* @constructor
*
* <p>A Parse.User object is a local representation of a user persisted to the
* Parse cloud. This class is a subclass of a Parse.Object, and retains the
* same functionality of a Parse.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.</p>
*/
var ParseUser = function (_ParseObject) {
(0, _inherits3.default)(ParseUser, _ParseObject);
function ParseUser(attributes) {
(0, _classCallCheck3.default)(this, ParseUser);
var _this = (0, _possibleConstructorReturn3.default)(this, (ParseUser.__proto__ || (0, _getPrototypeOf2.default)(ParseUser)).call(this, '_User'));
if (attributes && (typeof attributes === 'undefined' ? 'undefined' : (0, _typeof3.default)(attributes)) === 'object') {
if (!_this.set(attributes || {})) {
throw new Error('Can\'t create an invalid Parse User');
}
}
return _this;
}
/**
* Request a revocable session token to replace the older style of token.
* @method _upgradeToRevocableSession
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is resolved when the replacement
* token has been fetched.
*/
(0, _createClass3.default)(ParseUser, [{
key: '_upgradeToRevocableSession',
value: function (options) {
options = options || {};
var upgradeOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
upgradeOptions.useMasterKey = options.useMasterKey;
}
var controller = _CoreManager2.default.getUserController();
return controller.upgradeToRevocableSession(this, upgradeOptions)._thenRunCallbacks(options);
}
/**
* Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can
* call linkWith on the user (even if it doesn't exist yet on the server).
* @method _linkWith
*/
}, {
key: '_linkWith',
value: function (provider, options) {
var _this2 = this;
var authType;
if (typeof provider === 'string') {
authType = provider;
provider = authProviders[provider];
} else {
authType = provider.getAuthType();
}
if (options && options.hasOwnProperty('authData')) {
var authData = this.get('authData') || {};
if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
throw new Error('Invalid type: authData field should be an object');
}
authData[authType] = options.authData;
var controller = _CoreManager2.default.getUserController();
return controller.linkWith(this, authData)._thenRunCallbacks(options, this);
} else {
var promise = new _ParsePromise2.default();
provider.authenticate({
success: function (provider, result) {
var opts = {};
opts.authData = result;
if (options.success) {
opts.success = options.success;
}
if (options.error) {
opts.error = options.error;
}
_this2._linkWith(provider, opts).then(function () {
promise.resolve(_this2);
}, function (error) {
promise.reject(error);
});
},
error: function (provider, _error) {
if (typeof options.error === 'function') {
options.error(_this2, _error);
}
promise.reject(_error);
}
});
return promise;
}
}
/**
* Synchronizes auth data for a provider (e.g. puts the access token in the
* right place to be used by the Facebook SDK).
* @method _synchronizeAuthData
*/
}, {
key: '_synchronizeAuthData',
value: function (provider) {
if (!this.isCurrent() || !provider) {
return;
}
var authType;
if (typeof provider === 'string') {
authType = provider;
provider = authProviders[authType];
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData');
if (!provider || !authData || (typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
return;
}
var success = provider.restoreAuthentication(authData[authType]);
if (!success) {
this._unlinkFrom(provider);
}
}
/**
* Synchronizes authData for all providers.
* @method _synchronizeAllAuthData
*/
}, {
key: '_synchronizeAllAuthData',
value: function () {
var authData = this.get('authData');
if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
return;
}
for (var key in authData) {
this._synchronizeAuthData(key);
}
}
/**
* Removes null values from authData (which exist temporarily for
* unlinking)
* @method _cleanupAuthData
*/
}, {
key: '_cleanupAuthData',
value: function () {
if (!this.isCurrent()) {
return;
}
var authData = this.get('authData');
if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
return;
}
for (var key in authData) {
if (!authData[key]) {
delete authData[key];
}
}
}
/**
* Unlinks a user from a service.
* @method _unlinkFrom
*/
}, {
key: '_unlinkFrom',
value: function (provider, options) {
var _this3 = this;
if (typeof provider === 'string') {
provider = authProviders[provider];
} else {
provider.getAuthType();
}
return this._linkWith(provider, { authData: null }).then(function () {
_this3._synchronizeAuthData(provider);
return _ParsePromise2.default.as(_this3);
})._thenRunCallbacks(options);
}
/**
* Checks whether a user is linked to a service.
* @method _isLinked
*/
}, {
key: '_isLinked',
value: function (provider) {
var authType;
if (typeof provider === 'string') {
authType = provider;
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData') || {};
if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
return false;
}
return !!authData[authType];
}
/**
* Deauthenticates all providers.
* @method _logOutWithAll
*/
}, {
key: '_logOutWithAll',
value: function () {
var authData = this.get('authData');
if ((typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) !== 'object') {
return;
}
for (var key in authData) {
this._logOutWith(key);
}
}
/**
* Deauthenticates a single provider (e.g. removing access tokens from the
* Facebook SDK).
* @method _logOutWith
*/
}, {
key: '_logOutWith',
value: function (provider) {
if (!this.isCurrent()) {
return;
}
if (typeof provider === 'string') {
provider = authProviders[provider];
}
if (provider && provider.deauthenticate) {
provider.deauthenticate();
}
}
/**
* Class instance method used to maintain specific keys when a fetch occurs.
* Used to ensure that the session token is not lost.
*/
}, {
key: '_preserveFieldsOnFetch',
value: function () {
return {
sessionToken: this.get('sessionToken')
};
}
/**
* Returns true if <code>current</code> would return this user.
* @method isCurrent
* @return {Boolean}
*/
}, {
key: 'isCurrent',
value: function () {
var current = ParseUser.current();
return !!current && current.id === this.id;
}
/**
* Returns get("username").
* @method getUsername
* @return {String}
*/
}, {
key: 'getUsername',
value: function () {
var username = this.get('username');
if (username == null || typeof username === 'string') {
return username;
}
return '';
}
/**
* Calls set("username", username, options) and returns the result.
* @method setUsername
* @param {String} username
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
*/
}, {
key: 'setUsername',
value: function (username) {
// Strip anonymity, even we do not support anonymous user in js SDK, we may
// encounter anonymous user created by android/iOS in cloud code.
var authData = this.get('authData');
if (authData && (typeof authData === 'undefined' ? 'undefined' : (0, _typeof3.default)(authData)) === 'object' && authData.hasOwnProperty('anonymous')) {
// We need to set anonymous to null instead of deleting it in order to remove it from Parse.
authData.anonymous = null;
}
this.set('username', username);
}
/**
* Calls set("password", password, options) and returns the result.
* @method setPassword
* @param {String} password
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
*/
}, {
key: 'setPassword',
value: function (password) {
this.set('password', password);
}
/**
* Returns get("email").
* @method getEmail
* @return {String}
*/
}, {
key: 'getEmail',
value: function () {
var email = this.get('email');
if (email == null || typeof email === 'string') {
return email;
}
return '';
}
/**
* Calls set("email", email, options) and returns the result.
* @method setEmail
* @param {String} email
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
*/
}, {
key: 'setEmail',
value: function (email) {
this.set('email', email);
}
/**
* Returns the session token for this user, if the user has been logged in,
* or if it is the result of a query with the master key. Otherwise, returns
* undefined.
* @method getSessionToken
* @return {String} the session token, or undefined
*/
}, {
key: 'getSessionToken',
value: function () {
var token = this.get('sessionToken');
if (token == null || typeof token === 'string') {
return token;
}
return '';
}
/**
* Checks whether this user is the current user and has been authenticated.
* @method authenticated
* @return (Boolean) whether this user is the current user and is logged in.
*/
}, {
key: 'authenticated',
value: function () {
var current = ParseUser.current();
return !!this.get('sessionToken') && !!current && current.id === this.id;
}
/**
* Signs up a new user. You should call this instead of save for
* new Parse.Users. This will create a new Parse.User on the server, and
* also persist the session on disk so that you can access the user using
* <code>current</code>.
*
* <p>A username and password must be set before calling signUp.</p>
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method signUp
* @param {Object} attrs Extra fields to set on the new user, or null.
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is fulfilled when the signup
* finishes.
*/
}, {
key: 'signUp',
value: function (attrs, options) {
options = options || {};
var signupOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
signupOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
signupOptions.installationId = options.installationId;
}
var controller = _CoreManager2.default.getUserController();
return controller.signUp(this, attrs, signupOptions)._thenRunCallbacks(options, this);
}
/**
* Logs in a Parse.User. On success, this saves the session to disk,
* so you can retrieve the currently logged in user using
* <code>current</code>.
*
* <p>A username and password must be set before calling logIn.</p>
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method logIn
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the login is complete.
*/
}, {
key: 'logIn',
value: function (options) {
options = options || {};
var loginOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
loginOptions.useMasterKey = options.useMasterKey;
}
if (options.hasOwnProperty('installationId')) {
loginOptions.installationId = options.installationId;
}
var controller = _CoreManager2.default.getUserController();
return controller.logIn(this, loginOptions)._thenRunCallbacks(options, this);
}
/**
* Wrap the default save behavior with functionality to save to local
* storage if this is current user.
*/
}, {
key: 'save',
value: function () {
var _this4 = this;
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'save', this).apply(this, args).then(function () {
if (_this4.isCurrent()) {
return _CoreManager2.default.getUserController().updateUserOnDisk(_this4);
}
return _this4;
});
}
/**
* Wrap the default destroy behavior with functionality that logs out
* the current user when it is destroyed
*/
}, {
key: 'destroy',
value: function () {
var _this5 = this;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'destroy', this).apply(this, args).then(function () {
if (_this5.isCurrent()) {
return _CoreManager2.default.getUserController().removeUserFromDisk();
}
return _this5;
});
}
/**
* Wrap the default fetch behavior with functionality to save to local
* storage if this is current user.
*/
}, {
key: 'fetch',
value: function () {
var _this6 = this;
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return (0, _get3.default)(ParseUser.prototype.__proto__ || (0, _getPrototypeOf2.default)(ParseUser.prototype), 'fetch', this).apply(this, args).then(function () {
if (_this6.isCurrent()) {
return _CoreManager2.default.getUserController().updateUserOnDisk(_this6);
}
return _this6;
});
}
}], [{
key: 'readOnlyAttributes',
value: function () {
return ['sessionToken'];
}
/**
* Adds functionality to the existing Parse.User class
* @method extend
* @param {Object} protoProps A set of properties to add to the prototype
* @param {Object} classProps A set of static properties to add to the class
* @static
* @return {Class} The newly extended Parse.User class
*/
}, {
key: 'extend',
value: function (protoProps, classProps) {
if (protoProps) {
for (var prop in protoProps) {
if (prop !== 'className') {
(0, _defineProperty2.default)(ParseUser.prototype, prop, {
value: protoProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
if (classProps) {
for (var prop in classProps) {
if (prop !== 'className') {
(0, _defineProperty2.default)(ParseUser, prop, {
value: classProps[prop],
enumerable: false,
writable: true,
configurable: true
});
}
}
}
return ParseUser;
}
/**
* Retrieves the currently logged in ParseUser with a valid session,
* either from memory or localStorage, if necessary.
* @method current
* @static
* @return {Parse.Object} The currently logged in Parse.User.
*/
}, {
key: 'current',
value: function () {
if (!canUseCurrentUser) {
return null;
}
var controller = _CoreManager2.default.getUserController();
return controller.currentUser();
}
/**
* Retrieves the currently logged in ParseUser from asynchronous Storage.
* @method currentAsync
* @static
* @return {Parse.Promise} A Promise that is resolved with the currently
* logged in Parse User
*/
}, {
key: 'currentAsync',
value: function () {
if (!canUseCurrentUser) {
return _ParsePromise2.default.as(null);
}
var controller = _CoreManager2.default.getUserController();
return controller.currentUserAsync();
}
/**
* Signs up a new user with a username (or email) and password.
* This will create a new Parse.User on the server, and also persist the
* session in localStorage so that you can access the user using
* {@link #current}.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method signUp
* @param {String} username The username (or email) to sign up with.
* @param {String} password The password to sign up with.
* @param {Object} attrs Extra fields to set on the new user.
* @param {Object} options A Backbone-style options object.
* @static
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the signup completes.
*/
}, {
key: 'signUp',
value: function (username, password, attrs, options) {
attrs = attrs || {};
attrs.username = username;
attrs.password = password;
var user = new ParseUser(attrs);
return user.signUp({}, options);
}
/**
* Logs in a user with a username (or email) and password. On success, this
* saves the session to disk, so you can retrieve the currently logged in
* user using <code>current</code>.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method logIn
* @param {String} username The username (or email) to log in with.
* @param {String} password The password to log in with.
* @param {Object} options A Backbone-style options object.
* @static
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the login completes.
*/
}, {
key: 'logIn',
value: function (username, password, options) {
if (typeof username !== 'string') {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Username must be a string.'));
} else if (typeof password !== 'string') {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Password must be a string.'));
}
var user = new ParseUser();
user._finishFetch({ username: username, password: password });
return user.logIn(options);
}
/**
* Logs in a user with a session token. On success, this saves the session
* to disk, so you can retrieve the currently logged in user using
* <code>current</code>.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method become
* @param {String} sessionToken The sessionToken to log in with.
* @param {Object} options A Backbone-style options object.
* @static
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the login completes.
*/
}, {
key: 'become',
value: function (sessionToken, options) {
if (!canUseCurrentUser) {
throw new Error('It is not memory-safe to become a user in a server environment');
}
options = options || {};
var becomeOptions = {
sessionToken: sessionToken
};
if (options.hasOwnProperty('useMasterKey')) {
becomeOptions.useMasterKey = options.useMasterKey;
}
var controller = _CoreManager2.default.getUserController();
return controller.become(becomeOptions)._thenRunCallbacks(options);
}
}, {
key: 'logInWith',
value: function (provider, options) {
return ParseUser._logInWith(provider, options);
}
/**
* Logs out the currently logged in user session. This will remove the
* session from disk, log out of linked services, and future calls to
* <code>current</code> will return <code>null</code>.
* @method logOut
* @static
* @return {Parse.Promise} A promise that is resolved when the session is
* destroyed on the server.
*/
}, {
key: 'logOut',
value: function () {
if (!canUseCurrentUser) {
throw new Error('There is no current user on a node.js server environment.');
}
var controller = _CoreManager2.default.getUserController();
return controller.logOut();
}
/**
* Requests a password reset email to be sent to the specified email address
* associated with the user account. This email allows the user to securely
* reset their password on the Parse site.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @method requestPasswordReset
* @param {String} email The email address associated with the user that
* forgot their password.
* @param {Object} options A Backbone-style options object.
* @static
*/
}, {
key: 'requestPasswordReset',
value: function (email, options) {
options = options || {};
var requestOptions = {};
if (options.hasOwnProperty('useMasterKey')) {
requestOptions.useMasterKey = options.useMasterKey;
}
var controller = _CoreManager2.default.getUserController();
return controller.requestPasswordReset(email, requestOptions)._thenRunCallbacks(options);
}
/**
* Allow someone to define a custom User class without className
* being rewritten to _User. The default behavior is to rewrite
* User to _User for legacy reasons. This allows developers to
* override that behavior.
*
* @method allowCustomUserClass
* @param {Boolean} isAllowed Whether or not to allow custom User class
* @static
*/
}, {
key: 'allowCustomUserClass',
value: function (isAllowed) {
_CoreManager2.default.set('PERFORM_USER_REWRITE', !isAllowed);
}
/**
* Allows a legacy application to start using revocable sessions. If the
* current session token is not revocable, a request will be made for a new,
* revocable session.
* It is not necessary to call this method from cloud code unless you are
* handling user signup or login from the server side. In a cloud code call,
* this function will not attempt to upgrade the current token.
* @method enableRevocableSession
* @param {Object} options A Backbone-style options object.
* @static
* @return {Parse.Promise} A promise that is resolved when the process has
* completed. If a replacement session token is requested, the promise
* will be resolved after a new token has been fetched.
*/
}, {
key: 'enableRevocableSession',
value: function (options) {
options = options || {};
_CoreManager2.default.set('FORCE_REVOCABLE_SESSION', true);
if (canUseCurrentUser) {
var current = ParseUser.current();
if (current) {
return current._upgradeToRevocableSession(options);
}
}
return _ParsePromise2.default.as()._thenRunCallbacks(options);
}
/**
* Enables the use of become or the current user in a server
* environment. These features are disabled by default, since they depend on
* global objects that are not memory-safe for most servers.
* @method enableUnsafeCurrentUser
* @static
*/
}, {
key: 'enableUnsafeCurrentUser',
value: function () {
canUseCurrentUser = true;
}
/**
* Disables the use of become or the current user in any environment.
* These features are disabled on servers by default, since they depend on
* global objects that are not memory-safe for most servers.
* @method disableUnsafeCurrentUser
* @static
*/
}, {
key: 'disableUnsafeCurrentUser',
value: function () {
canUseCurrentUser = false;
}
}, {
key: '_registerAuthenticationProvider',
value: function (provider) {
authProviders[provider.getAuthType()] = provider;
// Synchronize the current user with the auth provider.
ParseUser.currentAsync().then(function (current) {
if (current) {
current._synchronizeAuthData(provider.getAuthType());
}
});
}
}, {
key: '_logInWith',
value: function (provider, options) {
var user = new ParseUser();
return user._linkWith(provider, options);
}
}, {
key: '_clearCache',
value: function () {
currentUserCache = null;
currentUserCacheMatchesDisk = false;
}
}, {
key: '_setCurrentUserCache',
value: function (user) {
currentUserCache = user;
}
}]);
return ParseUser;
}(_ParseObject3.default);
exports.default = ParseUser;
_ParseObject3.default.registerSubclass('_User', ParseUser);
var DefaultController = {
updateUserOnDisk: function (user) {
var path = _Storage2.default.generatePath(CURRENT_USER_KEY);
var json = user.toJSON();
json.className = '_User';
return _Storage2.default.setItemAsync(path, (0, _stringify2.default)(json)).then(function () {
return user;
});
},
removeUserFromDisk: function () {
var path = _Storage2.default.generatePath(CURRENT_USER_KEY);
currentUserCacheMatchesDisk = true;
currentUserCache = null;
return _Storage2.default.removeItemAsync(path);
},
setCurrentUser: function (user) {
currentUserCache = user;
user._cleanupAuthData();
user._synchronizeAllAuthData();
return DefaultController.updateUserOnDisk(user);
},
currentUser: function () {
if (currentUserCache) {
return currentUserCache;
}
if (currentUserCacheMatchesDisk) {
return null;
}
if (_Storage2.default.async()) {
throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.');
}
var path = _Storage2.default.generatePath(CURRENT_USER_KEY);
var userData = _Storage2.default.getItem(path);
currentUserCacheMatchesDisk = true;
if (!userData) {
currentUserCache = null;
return null;
}
userData = JSON.parse(userData);
if (!userData.className) {
userData.className = '_User';
}
if (userData._id) {
if (userData.objectId !== userData._id) {
userData.objectId = userData._id;
}
delete userData._id;
}
if (userData._sessionToken) {
userData.sessionToken = userData._sessionToken;
delete userData._sessionToken;
}
var current = _ParseObject3.default.fromJSON(userData);
currentUserCache = current;
current._synchronizeAllAuthData();
return current;
},
currentUserAsync: function () {
if (currentUserCache) {
return _ParsePromise2.default.as(currentUserCache);
}
if (currentUserCacheMatchesDisk) {
return _ParsePromise2.default.as(null);
}
var path = _Storage2.default.generatePath(CURRENT_USER_KEY);
return _Storage2.default.getItemAsync(path).then(function (userData) {
currentUserCacheMatchesDisk = true;
if (!userData) {
currentUserCache = null;
return _ParsePromise2.default.as(null);
}
userData = JSON.parse(userData);
if (!userData.className) {
userData.className = '_User';
}
if (userData._id) {
if (userData.objectId !== userData._id) {
userData.objectId = userData._id;
}
delete userData._id;
}
if (userData._sessionToken) {
userData.sessionToken = userData._sessionToken;
delete userData._sessionToken;
}
var current = _ParseObject3.default.fromJSON(userData);
currentUserCache = current;
current._synchronizeAllAuthData();
return _ParsePromise2.default.as(current);
});
},
signUp: function (user, attrs, options) {
var username = attrs && attrs.username || user.get('username');
var password = attrs && attrs.password || user.get('password');
if (!username || !username.length) {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Cannot sign up user with an empty name.'));
}
if (!password || !password.length) {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.'));
}
return user.save(attrs, options).then(function () {
// Clear the password field
user._finishFetch({ password: undefined });
if (canUseCurrentUser) {
return DefaultController.setCurrentUser(user);
}
return user;
});
},
logIn: function (user, options) {
var RESTController = _CoreManager2.default.getRESTController();
var stateController = _CoreManager2.default.getObjectStateController();
var auth = {
username: user.get('username'),
password: user.get('password')
};
return RESTController.request('GET', 'login', auth, options).then(function (response) {
user._migrateId(response.objectId);
user._setExisted(true);
stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined);
stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined);
response.password = undefined;
user._finishFetch(response);
if (!canUseCurrentUser) {
// We can't set the current user, so just return the one we logged in
return _ParsePromise2.default.as(user);
}
return DefaultController.setCurrentUser(user);
});
},
become: function (options) {
var user = new ParseUser();
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('GET', 'users/me', {}, options).then(function (response) {
user._finishFetch(response);
user._setExisted(true);
return DefaultController.setCurrentUser(user);
});
},
logOut: function () {
return DefaultController.currentUserAsync().then(function (currentUser) {
var path = _Storage2.default.generatePath(CURRENT_USER_KEY);
var promise = _Storage2.default.removeItemAsync(path);
var RESTController = _CoreManager2.default.getRESTController();
if (currentUser !== null) {
var currentSession = currentUser.getSessionToken();
if (currentSession && (0, _isRevocableSession2.default)(currentSession)) {
promise = promise.then(function () {
return RESTController.request('POST', 'logout', {}, { sessionToken: currentSession });
});
}
currentUser._logOutWithAll();
currentUser._finishFetch({ sessionToken: undefined });
}
currentUserCacheMatchesDisk = true;
currentUserCache = null;
return promise;
});
},
requestPasswordReset: function (email, options) {
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('POST', 'requestPasswordReset', { email: email }, options);
},
upgradeToRevocableSession: function (user, options) {
var token = user.getSessionToken();
if (!token) {
return _ParsePromise2.default.error(new _ParseError2.default(_ParseError2.default.SESSION_MISSING, 'Cannot upgrade a user with no session token'));
}
options.sessionToken = token;
var RESTController = _CoreManager2.default.getRESTController();
return RESTController.request('POST', 'upgradeToRevocableSession', {}, options).then(function (result) {
var session = new _ParseSession2.default();
session._finishFetch(result);
user._finishFetch({ sessionToken: session.getSessionToken() });
if (user.isCurrent()) {
return DefaultController.setCurrentUser(user);
}
return _ParsePromise2.default.as(user);
});
},
linkWith: function (user, authData) {
return user.save({ authData: authData }).then(function () {
if (canUseCurrentUser) {
return DefaultController.setCurrentUser(user);
}
return user;
});
}
};
_CoreManager2.default.setUserController(DefaultController);
},{"./CoreManager":3,"./ParseError":13,"./ParseObject":18,"./ParsePromise":21,"./ParseSession":25,"./Storage":30,"./isRevocableSession":40,"babel-runtime/core-js/json/stringify":45,"babel-runtime/core-js/object/define-property":48,"babel-runtime/core-js/object/get-prototype-of":51,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58,"babel-runtime/helpers/get":59,"babel-runtime/helpers/inherits":60,"babel-runtime/helpers/possibleConstructorReturn":61,"babel-runtime/helpers/typeof":62}],27:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.send = send;
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParseQuery = _dereq_('./ParseQuery');
var _ParseQuery2 = _interopRequireDefault(_ParseQuery);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Contains functions to deal with Push in Parse.
* @class Parse.Push
* @static
*/
/**
* Sends a push notification.
* @method send
* @param {Object} data - The data of the push notification. Valid fields
* are:
* <ol>
* <li>channels - An Array of channels to push to.</li>
* <li>push_time - A Date object for when to send the push.</li>
* <li>expiration_time - A Date object for when to expire
* the push.</li>
* <li>expiration_interval - The seconds from now to expire the push.</li>
* <li>where - A Parse.Query over Parse.Installation that is used to match
* a set of installations to push to.</li>
* <li>data - The data to send as part of the push</li>
* <ol>
* @param {Object} options An object that has an optional success function,
* that takes no arguments and will be called on a successful push, and
* an error function that takes a Parse.Error and will be called if the push
* failed.
* @return {Parse.Promise} A promise that is fulfilled when the push request
* completes.
*/
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function send(data, options) {
options = options || {};
if (data.where && data.where instanceof _ParseQuery2.default) {
data.where = data.where.toJSON().where;
}
if (data.push_time && (0, _typeof3.default)(data.push_time) === 'object') {
data.push_time = data.push_time.toJSON();
}
if (data.expiration_time && (0, _typeof3.default)(data.expiration_time) === 'object') {
data.expiration_time = data.expiration_time.toJSON();
}
if (data.expiration_time && data.expiration_interval) {
throw new Error('expiration_time and expiration_interval cannot both be set.');
}
return _CoreManager2.default.getPushController().send(data, {
useMasterKey: options.useMasterKey
})._thenRunCallbacks(options);
}
var DefaultController = {
send: function (data, options) {
var RESTController = _CoreManager2.default.getRESTController();
var request = RESTController.request('POST', 'push', data, { useMasterKey: !!options.useMasterKey });
return request._thenRunCallbacks(options);
}
};
_CoreManager2.default.setPushController(DefaultController);
},{"./CoreManager":3,"./ParseQuery":22,"babel-runtime/helpers/typeof":62}],28:[function(_dereq_,module,exports){
(function (process){
'use strict';
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _stringify = _dereq_('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParseError = _dereq_('./ParseError');
var _ParseError2 = _interopRequireDefault(_ParseError);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
var _Storage = _dereq_('./Storage');
var _Storage2 = _interopRequireDefault(_Storage);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var XHR = null;
if (typeof XMLHttpRequest !== 'undefined') {
XHR = XMLHttpRequest;
}
var useXDomainRequest = false;
if (typeof XDomainRequest !== 'undefined' && !('withCredentials' in new XMLHttpRequest())) {
useXDomainRequest = true;
}
function ajaxIE9(method, url, data) {
var promise = new _ParsePromise2.default();
var xdr = new XDomainRequest();
xdr.onload = function () {
var response;
try {
response = JSON.parse(xdr.responseText);
} catch (e) {
promise.reject(e);
}
if (response) {
promise.resolve(response);
}
};
xdr.onerror = xdr.ontimeout = function () {
// Let's fake a real error message.
var fakeResponse = {
responseText: (0, _stringify2.default)({
code: _ParseError2.default.X_DOMAIN_REQUEST,
error: 'IE\'s XDomainRequest does not supply error info.'
})
};
promise.reject(fakeResponse);
};
xdr.onprogress = function () {};
xdr.open(method, url);
xdr.send(data);
return promise;
}
var RESTController = {
ajax: function (method, url, data, headers) {
if (useXDomainRequest) {
return ajaxIE9(method, url, data, headers);
}
var promise = new _ParsePromise2.default();
var attempts = 0;
(function dispatch() {
if (XHR == null) {
throw new Error('Cannot make a request: No definition of XMLHttpRequest was found.');
}
var handled = false;
var xhr = new XHR();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4 || handled) {
return;
}
handled = true;
if (xhr.status >= 200 && xhr.status < 300) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
promise.reject(e.toString());
}
if (response) {
promise.resolve(response, xhr.status, xhr);
}
} else if (xhr.status >= 500 || xhr.status === 0) {
// retry on 5XX or node-xmlhttprequest error
if (++attempts < _CoreManager2.default.get('REQUEST_ATTEMPT_LIMIT')) {
// Exponentially-growing random delay
var delay = Math.round(Math.random() * 125 * Math.pow(2, attempts));
setTimeout(dispatch, delay);
} else if (xhr.status === 0) {
promise.reject('Unable to connect to the Parse API');
} else {
// After the retry limit is reached, fail
promise.reject(xhr);
}
} else {
promise.reject(xhr);
}
};
headers = headers || {};
if (typeof headers['Content-Type'] !== 'string') {
headers['Content-Type'] = 'text/plain'; // Avoid pre-flight
}
if (_CoreManager2.default.get('IS_NODE')) {
headers['User-Agent'] = 'Parse/' + _CoreManager2.default.get('VERSION') + ' (NodeJS ' + process.versions.node + ')';
}
xhr.open(method, url, true);
for (var h in headers) {
xhr.setRequestHeader(h, headers[h]);
}
xhr.send(data);
})();
return promise;
},
request: function (method, path, data, options) {
options = options || {};
var url = _CoreManager2.default.get('SERVER_URL');
if (url[url.length - 1] !== '/') {
url += '/';
}
url += path;
var payload = {};
if (data && (typeof data === 'undefined' ? 'undefined' : (0, _typeof3.default)(data)) === 'object') {
for (var k in data) {
payload[k] = data[k];
}
}
if (method !== 'POST') {
payload._method = method;
method = 'POST';
}
payload._ApplicationId = _CoreManager2.default.get('APPLICATION_ID');
var jsKey = _CoreManager2.default.get('JAVASCRIPT_KEY');
if (jsKey) {
payload._JavaScriptKey = jsKey;
}
payload._ClientVersion = _CoreManager2.default.get('VERSION');
var useMasterKey = options.useMasterKey;
if (typeof useMasterKey === 'undefined') {
useMasterKey = _CoreManager2.default.get('USE_MASTER_KEY');
}
if (useMasterKey) {
if (_CoreManager2.default.get('MASTER_KEY')) {
delete payload._JavaScriptKey;
payload._MasterKey = _CoreManager2.default.get('MASTER_KEY');
} else {
throw new Error('Cannot use the Master Key, it has not been provided.');
}
}
if (_CoreManager2.default.get('FORCE_REVOCABLE_SESSION')) {
payload._RevocableSession = '1';
}
var installationId = options.installationId;
var installationIdPromise;
if (installationId && typeof installationId === 'string') {
installationIdPromise = _ParsePromise2.default.as(installationId);
} else {
var installationController = _CoreManager2.default.getInstallationController();
installationIdPromise = installationController.currentInstallationId();
}
return installationIdPromise.then(function (iid) {
payload._InstallationId = iid;
var userController = _CoreManager2.default.getUserController();
if (options && typeof options.sessionToken === 'string') {
return _ParsePromise2.default.as(options.sessionToken);
} else if (userController) {
return userController.currentUserAsync().then(function (user) {
if (user) {
return _ParsePromise2.default.as(user.getSessionToken());
}
return _ParsePromise2.default.as(null);
});
}
return _ParsePromise2.default.as(null);
}).then(function (token) {
if (token) {
payload._SessionToken = token;
}
var payloadString = (0, _stringify2.default)(payload);
return RESTController.ajax(method, url, payloadString);
}).then(null, function (response) {
// Transform the error into an instance of ParseError by trying to parse
// the error string as JSON
var error;
if (response && response.responseText) {
try {
var errorJSON = JSON.parse(response.responseText);
error = new _ParseError2.default(errorJSON.code, errorJSON.error);
} catch (e) {
// If we fail to parse the error text, that's okay.
error = new _ParseError2.default(_ParseError2.default.INVALID_JSON, 'Received an error with invalid JSON from Parse: ' + response.responseText);
}
} else {
error = new _ParseError2.default(_ParseError2.default.CONNECTION_FAILED, 'XMLHttpRequest failed: ' + (0, _stringify2.default)(response));
}
return _ParsePromise2.default.error(error);
});
},
_setXHR: function (xhr) {
XHR = xhr;
}
};
module.exports = RESTController;
}).call(this,_dereq_('_process'))
},{"./CoreManager":3,"./ParseError":13,"./ParsePromise":21,"./Storage":30,"_process":63,"babel-runtime/core-js/json/stringify":45,"babel-runtime/helpers/typeof":62}],29:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getState = getState;
exports.initializeState = initializeState;
exports.removeState = removeState;
exports.getServerData = getServerData;
exports.setServerData = setServerData;
exports.getPendingOps = getPendingOps;
exports.setPendingOp = setPendingOp;
exports.pushPendingState = pushPendingState;
exports.popPendingState = popPendingState;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.getObjectCache = getObjectCache;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.commitServerChanges = commitServerChanges;
exports.enqueueTask = enqueueTask;
exports.clearAllState = clearAllState;
exports.duplicateState = duplicateState;
var _ObjectStateMutations = _dereq_('./ObjectStateMutations');
var ObjectStateMutations = _interopRequireWildcard(_ObjectStateMutations);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj.default = obj;return newObj;
}
}
var objectState = {}; /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function getState(obj) {
var classData = objectState[obj.className];
if (classData) {
return classData[obj.id] || null;
}
return null;
}
function initializeState(obj, initial) {
var state = getState(obj);
if (state) {
return state;
}
if (!objectState[obj.className]) {
objectState[obj.className] = {};
}
if (!initial) {
initial = ObjectStateMutations.defaultState();
}
state = objectState[obj.className][obj.id] = initial;
return state;
}
function removeState(obj) {
var state = getState(obj);
if (state === null) {
return null;
}
delete objectState[obj.className][obj.id];
return state;
}
function getServerData(obj) {
var state = getState(obj);
if (state) {
return state.serverData;
}
return {};
}
function setServerData(obj, attributes) {
var serverData = initializeState(obj).serverData;
ObjectStateMutations.setServerData(serverData, attributes);
}
function getPendingOps(obj) {
var state = getState(obj);
if (state) {
return state.pendingOps;
}
return [{}];
}
function setPendingOp(obj, attr, op) {
var pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.setPendingOp(pendingOps, attr, op);
}
function pushPendingState(obj) {
var pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.pushPendingState(pendingOps);
}
function popPendingState(obj) {
var pendingOps = initializeState(obj).pendingOps;
return ObjectStateMutations.popPendingState(pendingOps);
}
function mergeFirstPendingState(obj) {
var pendingOps = getPendingOps(obj);
ObjectStateMutations.mergeFirstPendingState(pendingOps);
}
function getObjectCache(obj) {
var state = getState(obj);
if (state) {
return state.objectCache;
}
return {};
}
function estimateAttribute(obj, attr) {
var serverData = getServerData(obj);
var pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
}
function estimateAttributes(obj) {
var serverData = getServerData(obj);
var pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
}
function commitServerChanges(obj, changes) {
var state = initializeState(obj);
ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
}
function enqueueTask(obj, task) {
var state = initializeState(obj);
return state.tasks.enqueue(task);
}
function clearAllState() {
objectState = {};
}
function duplicateState(source, dest) {
dest.id = source.id;
}
},{"./ObjectStateMutations":9}],30:[function(_dereq_,module,exports){
'use strict';
var _CoreManager = _dereq_('./CoreManager');
var _CoreManager2 = _interopRequireDefault(_CoreManager);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var Storage = {
async: function () {
var controller = _CoreManager2.default.getStorageController();
return !!controller.async;
},
getItem: function (path) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.getItem(path);
},
getItemAsync: function (path) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
return controller.getItemAsync(path);
}
return _ParsePromise2.default.as(controller.getItem(path));
},
setItem: function (path, value) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.setItem(path, value);
},
setItemAsync: function (path, value) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
return controller.setItemAsync(path, value);
}
return _ParsePromise2.default.as(controller.setItem(path, value));
},
removeItem: function (path) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
throw new Error('Synchronous storage is not supported by the current storage controller');
}
return controller.removeItem(path);
},
removeItemAsync: function (path) {
var controller = _CoreManager2.default.getStorageController();
if (controller.async === 1) {
return controller.removeItemAsync(path);
}
return _ParsePromise2.default.as(controller.removeItem(path));
},
generatePath: function (path) {
if (!_CoreManager2.default.get('APPLICATION_ID')) {
throw new Error('You need to call Parse.initialize before using Parse.');
}
if (typeof path !== 'string') {
throw new Error('Tried to get a Storage path that was not a String.');
}
if (path[0] === '/') {
path = path.substr(1);
}
return 'Parse/' + _CoreManager2.default.get('APPLICATION_ID') + '/' + path;
},
_clear: function () {
var controller = _CoreManager2.default.getStorageController();
if (controller.hasOwnProperty('clear')) {
controller.clear();
}
}
};
module.exports = Storage;
_CoreManager2.default.setStorageController(_dereq_('./StorageController.browser'));
},{"./CoreManager":3,"./ParsePromise":21,"./StorageController.browser":31}],31:[function(_dereq_,module,exports){
'use strict';
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var StorageController = {
async: 0,
getItem: function (path) {
return localStorage.getItem(path);
},
setItem: function (path, value) {
try {
localStorage.setItem(path, value);
} catch (e) {
// Quota exceeded, possibly due to Safari Private Browsing mode
}
},
removeItem: function (path) {
localStorage.removeItem(path);
},
clear: function () {
localStorage.clear();
}
}; /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
module.exports = StorageController;
},{"./ParsePromise":21}],32:[function(_dereq_,module,exports){
'use strict';
var _classCallCheck2 = _dereq_('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = _dereq_('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _ParsePromise = _dereq_('./ParsePromise');
var _ParsePromise2 = _interopRequireDefault(_ParsePromise);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var TaskQueue = function () {
function TaskQueue() {
(0, _classCallCheck3.default)(this, TaskQueue);
this.queue = [];
}
(0, _createClass3.default)(TaskQueue, [{
key: 'enqueue',
value: function (task) {
var _this = this;
var taskComplete = new _ParsePromise2.default();
this.queue.push({
task: task,
_completion: taskComplete
});
if (this.queue.length === 1) {
task().then(function () {
_this._dequeue();
taskComplete.resolve();
}, function (error) {
_this._dequeue();
taskComplete.reject(error);
});
}
return taskComplete;
}
}, {
key: '_dequeue',
value: function () {
var _this2 = this;
this.queue.shift();
if (this.queue.length) {
var next = this.queue[0];
next.task().then(function () {
_this2._dequeue();
next._completion.resolve();
}, function (error) {
_this2._dequeue();
next._completion.reject(error);
});
}
}
}]);
return TaskQueue;
}(); /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
module.exports = TaskQueue;
},{"./ParsePromise":21,"babel-runtime/helpers/classCallCheck":57,"babel-runtime/helpers/createClass":58}],33:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _weakMap = _dereq_('babel-runtime/core-js/weak-map');
var _weakMap2 = _interopRequireDefault(_weakMap);
exports.getState = getState;
exports.initializeState = initializeState;
exports.removeState = removeState;
exports.getServerData = getServerData;
exports.setServerData = setServerData;
exports.getPendingOps = getPendingOps;
exports.setPendingOp = setPendingOp;
exports.pushPendingState = pushPendingState;
exports.popPendingState = popPendingState;
exports.mergeFirstPendingState = mergeFirstPendingState;
exports.getObjectCache = getObjectCache;
exports.estimateAttribute = estimateAttribute;
exports.estimateAttributes = estimateAttributes;
exports.commitServerChanges = commitServerChanges;
exports.enqueueTask = enqueueTask;
exports.duplicateState = duplicateState;
exports.clearAllState = clearAllState;
var _ObjectStateMutations = _dereq_('./ObjectStateMutations');
var ObjectStateMutations = _interopRequireWildcard(_ObjectStateMutations);
var _TaskQueue = _dereq_('./TaskQueue');
var _TaskQueue2 = _interopRequireDefault(_TaskQueue);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj.default = obj;return newObj;
}
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var objectState = new _weakMap2.default();
function getState(obj) {
var classData = objectState.get(obj);
return classData || null;
}
function initializeState(obj, initial) {
var state = getState(obj);
if (state) {
return state;
}
if (!initial) {
initial = {
serverData: {},
pendingOps: [{}],
objectCache: {},
tasks: new _TaskQueue2.default(),
existed: false
};
}
state = initial;
objectState.set(obj, state);
return state;
}
function removeState(obj) {
var state = getState(obj);
if (state === null) {
return null;
}
objectState.delete(obj);
return state;
}
function getServerData(obj) {
var state = getState(obj);
if (state) {
return state.serverData;
}
return {};
}
function setServerData(obj, attributes) {
var serverData = initializeState(obj).serverData;
ObjectStateMutations.setServerData(serverData, attributes);
}
function getPendingOps(obj) {
var state = getState(obj);
if (state) {
return state.pendingOps;
}
return [{}];
}
function setPendingOp(obj, attr, op) {
var pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.setPendingOp(pendingOps, attr, op);
}
function pushPendingState(obj) {
var pendingOps = initializeState(obj).pendingOps;
ObjectStateMutations.pushPendingState(pendingOps);
}
function popPendingState(obj) {
var pendingOps = initializeState(obj).pendingOps;
return ObjectStateMutations.popPendingState(pendingOps);
}
function mergeFirstPendingState(obj) {
var pendingOps = getPendingOps(obj);
ObjectStateMutations.mergeFirstPendingState(pendingOps);
}
function getObjectCache(obj) {
var state = getState(obj);
if (state) {
return state.objectCache;
}
return {};
}
function estimateAttribute(obj, attr) {
var serverData = getServerData(obj);
var pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttribute(serverData, pendingOps, obj.className, obj.id, attr);
}
function estimateAttributes(obj) {
var serverData = getServerData(obj);
var pendingOps = getPendingOps(obj);
return ObjectStateMutations.estimateAttributes(serverData, pendingOps, obj.className, obj.id);
}
function commitServerChanges(obj, changes) {
var state = initializeState(obj);
ObjectStateMutations.commitServerChanges(state.serverData, state.objectCache, changes);
}
function enqueueTask(obj, task) {
var state = initializeState(obj);
return state.tasks.enqueue(task);
}
function duplicateState(source, dest) {
var oldState = initializeState(source);
var newState = initializeState(dest);
for (var key in oldState.serverData) {
newState.serverData[key] = oldState.serverData[key];
}
for (var index = 0; index < oldState.pendingOps.length; index++) {
for (var _key in oldState.pendingOps[index]) {
newState.pendingOps[index][_key] = oldState.pendingOps[index][_key];
}
}
for (var _key2 in oldState.objectCache) {
newState.objectCache[_key2] = oldState.objectCache[_key2];
}
newState.existed = oldState.existed;
}
function clearAllState() {
objectState = new _weakMap2.default();
}
},{"./ObjectStateMutations":9,"./TaskQueue":32,"babel-runtime/core-js/weak-map":56}],34:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = arrayContainsObject;
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function arrayContainsObject(array, object) {
if (array.indexOf(object) > -1) {
return true;
}
for (var i = 0; i < array.length; i++) {
if (array[i] instanceof _ParseObject2.default && array[i].className === object.className && array[i]._getId() === object._getId()) {
return true;
}
}
return false;
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
},{"./ParseObject":18}],35:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.default = canBeSerialized;
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function canBeSerialized(obj) {
if (!(obj instanceof _ParseObject2.default)) {
return true;
}
var attributes = obj.attributes;
for (var attr in attributes) {
var val = attributes[attr];
if (!canBeSerializedHelper(val)) {
return false;
}
}
return true;
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function canBeSerializedHelper(value) {
if ((typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) !== 'object') {
return true;
}
if (value instanceof _ParseRelation2.default) {
return true;
}
if (value instanceof _ParseObject2.default) {
return !!value.id;
}
if (value instanceof _ParseFile2.default) {
if (value.url()) {
return true;
}
return false;
}
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
if (!canBeSerializedHelper(value[i])) {
return false;
}
}
return true;
}
for (var k in value) {
if (!canBeSerializedHelper(value[k])) {
return false;
}
}
return true;
}
},{"./ParseFile":14,"./ParseObject":18,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],36:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.default = decode;
var _ParseACL = _dereq_('./ParseACL');
var _ParseACL2 = _interopRequireDefault(_ParseACL);
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseGeoPoint = _dereq_('./ParseGeoPoint');
var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint);
var _ParsePolygon = _dereq_('./ParsePolygon');
var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseOp = _dereq_('./ParseOp');
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
function decode(value) {
if (value === null || (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) !== 'object') {
return value;
}
if (Array.isArray(value)) {
var dup = [];
value.forEach(function (v, i) {
dup[i] = decode(v);
});
return dup;
}
if (typeof value.__op === 'string') {
return (0, _ParseOp.opFromJSON)(value);
}
if (value.__type === 'Pointer' && value.className) {
return _ParseObject2.default.fromJSON(value);
}
if (value.__type === 'Object' && value.className) {
return _ParseObject2.default.fromJSON(value);
}
if (value.__type === 'Relation') {
// The parent and key fields will be populated by the parent
var relation = new _ParseRelation2.default(null, null);
relation.targetClassName = value.className;
return relation;
}
if (value.__type === 'Date') {
return new Date(value.iso);
}
if (value.__type === 'File') {
return _ParseFile2.default.fromJSON(value);
}
if (value.__type === 'GeoPoint') {
return new _ParseGeoPoint2.default({
latitude: value.latitude,
longitude: value.longitude
});
}
if (value.__type === 'Polygon') {
return new _ParsePolygon2.default(value.coordinates);
}
var copy = {};
for (var k in value) {
copy[k] = decode(value[k]);
}
return copy;
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
},{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],37:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
var _keys = _dereq_('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
exports.default = function (value, disallowObjects, forcePointers, seen) {
return encode(value, !!disallowObjects, !!forcePointers, seen || []);
};
var _ParseACL = _dereq_('./ParseACL');
var _ParseACL2 = _interopRequireDefault(_ParseACL);
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseGeoPoint = _dereq_('./ParseGeoPoint');
var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint);
var _ParsePolygon = _dereq_('./ParsePolygon');
var _ParsePolygon2 = _interopRequireDefault(_ParsePolygon);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseOp = _dereq_('./ParseOp');
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
var toString = Object.prototype.toString; /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function encode(value, disallowObjects, forcePointers, seen) {
if (value instanceof _ParseObject2.default) {
if (disallowObjects) {
throw new Error('Parse Objects not allowed here');
}
var seenEntry = value.id ? value.className + ':' + value.id : value;
if (forcePointers || !seen || seen.indexOf(seenEntry) > -1 || value.dirty() || (0, _keys2.default)(value._getServerData()).length < 1) {
return value.toPointer();
}
seen = seen.concat(seenEntry);
return value._toFullJSON(seen);
}
if (value instanceof _ParseOp.Op || value instanceof _ParseACL2.default || value instanceof _ParseGeoPoint2.default || value instanceof _ParsePolygon2.default || value instanceof _ParseRelation2.default) {
return value.toJSON();
}
if (value instanceof _ParseFile2.default) {
if (!value.url()) {
throw new Error('Tried to encode an unsaved file.');
}
return value.toJSON();
}
if (toString.call(value) === '[object Date]') {
if (isNaN(value)) {
throw new Error('Tried to encode an invalid date.');
}
return { __type: 'Date', iso: value.toJSON() };
}
if (toString.call(value) === '[object RegExp]' && typeof value.source === 'string') {
return value.source;
}
if (Array.isArray(value)) {
return value.map(function (v) {
return encode(v, disallowObjects, forcePointers, seen);
});
}
if (value && (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object') {
var output = {};
for (var k in value) {
output[k] = encode(value[k], disallowObjects, forcePointers, seen);
}
return output;
}
return value;
}
},{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"./ParseOp":19,"./ParsePolygon":20,"./ParseRelation":23,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/typeof":62}],38:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _keys = _dereq_('babel-runtime/core-js/object/keys');
var _keys2 = _interopRequireDefault(_keys);
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.default = equals;
var _ParseACL = _dereq_('./ParseACL');
var _ParseACL2 = _interopRequireDefault(_ParseACL);
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseGeoPoint = _dereq_('./ParseGeoPoint');
var _ParseGeoPoint2 = _interopRequireDefault(_ParseGeoPoint);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
function equals(a, b) {
if ((typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) !== (typeof b === 'undefined' ? 'undefined' : (0, _typeof3.default)(b))) {
return false;
}
if (!a || (typeof a === 'undefined' ? 'undefined' : (0, _typeof3.default)(a)) !== 'object') {
// a is a primitive
return a === b;
}
if (Array.isArray(a) || Array.isArray(b)) {
if (!Array.isArray(a) || !Array.isArray(b)) {
return false;
}
if (a.length !== b.length) {
return false;
}
for (var i = a.length; i--;) {
if (!equals(a[i], b[i])) {
return false;
}
}
return true;
}
if (a instanceof _ParseACL2.default || a instanceof _ParseFile2.default || a instanceof _ParseGeoPoint2.default || a instanceof _ParseObject2.default) {
return a.equals(b);
}
if ((0, _keys2.default)(a).length !== (0, _keys2.default)(b).length) {
return false;
}
for (var k in a) {
if (!equals(a[k], b[k])) {
return false;
}
}
return true;
}
},{"./ParseACL":11,"./ParseFile":14,"./ParseGeoPoint":15,"./ParseObject":18,"babel-runtime/core-js/object/keys":52,"babel-runtime/helpers/typeof":62}],39:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = escape;
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
var encoded = {
'&': '&',
'<': '<',
'>': '>',
'/': '/',
'\'': ''',
'"': '"'
};
function escape(str) {
return str.replace(/[&<>\/'"]/g, function (char) {
return encoded[char];
});
}
},{}],40:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isRevocableSession;
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function isRevocableSession(token) {
return token.indexOf('r:') > -1;
}
},{}],41:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = parseDate;
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function parseDate(iso8601) {
var regexp = new RegExp('^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})' + 'T' + '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})' + '(.([0-9]+))?' + 'Z$');
var match = regexp.exec(iso8601);
if (!match) {
return null;
}
var year = match[1] || 0;
var month = (match[2] || 1) - 1;
var day = match[3] || 0;
var hour = match[4] || 0;
var minute = match[5] || 0;
var second = match[6] || 0;
var milli = match[8] || 0;
return new Date(Date.UTC(year, month, day, hour, minute, second, milli));
}
},{}],42:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = unique;
var _arrayContainsObject = _dereq_('./arrayContainsObject');
var _arrayContainsObject2 = _interopRequireDefault(_arrayContainsObject);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function unique(arr) {
var uniques = [];
arr.forEach(function (value) {
if (value instanceof _ParseObject2.default) {
if (!(0, _arrayContainsObject2.default)(uniques, value)) {
uniques.push(value);
}
} else {
if (uniques.indexOf(value) < 0) {
uniques.push(value);
}
}
});
return uniques;
}
},{"./ParseObject":18,"./arrayContainsObject":34}],43:[function(_dereq_,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof2 = _dereq_('babel-runtime/helpers/typeof');
var _typeof3 = _interopRequireDefault(_typeof2);
exports.default = unsavedChildren;
var _ParseFile = _dereq_('./ParseFile');
var _ParseFile2 = _interopRequireDefault(_ParseFile);
var _ParseObject = _dereq_('./ParseObject');
var _ParseObject2 = _interopRequireDefault(_ParseObject);
var _ParseRelation = _dereq_('./ParseRelation');
var _ParseRelation2 = _interopRequireDefault(_ParseRelation);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj };
}
/**
* Return an array of unsaved children, which are either Parse Objects or Files.
* If it encounters any dirty Objects without Ids, it will throw an exception.
*/
function unsavedChildren(obj, allowDeepUnsaved) {
var encountered = {
objects: {},
files: []
};
var identifier = obj.className + ':' + obj._getId();
encountered.objects[identifier] = obj.dirty() ? obj : true;
var attributes = obj.attributes;
for (var attr in attributes) {
if ((0, _typeof3.default)(attributes[attr]) === 'object') {
traverse(attributes[attr], encountered, false, !!allowDeepUnsaved);
}
}
var unsaved = [];
for (var id in encountered.objects) {
if (id !== identifier && encountered.objects[id] !== true) {
unsaved.push(encountered.objects[id]);
}
}
return unsaved.concat(encountered.files);
} /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/
function traverse(obj, encountered, shouldThrow, allowDeepUnsaved) {
if (obj instanceof _ParseObject2.default) {
if (!obj.id && shouldThrow) {
throw new Error('Cannot create a pointer to an unsaved Object.');
}
var identifier = obj.className + ':' + obj._getId();
if (!encountered.objects[identifier]) {
encountered.objects[identifier] = obj.dirty() ? obj : true;
var attributes = obj.attributes;
for (var attr in attributes) {
if ((0, _typeof3.default)(attributes[attr]) === 'object') {
traverse(attributes[attr], encountered, !allowDeepUnsaved, allowDeepUnsaved);
}
}
}
return;
}
if (obj instanceof _ParseFile2.default) {
if (!obj.url() && encountered.files.indexOf(obj) < 0) {
encountered.files.push(obj);
}
return;
}
if (obj instanceof _ParseRelation2.default) {
return;
}
if (Array.isArray(obj)) {
obj.forEach(function (el) {
if ((typeof el === 'undefined' ? 'undefined' : (0, _typeof3.default)(el)) === 'object') {
traverse(el, encountered, shouldThrow, allowDeepUnsaved);
}
});
}
for (var k in obj) {
if ((0, _typeof3.default)(obj[k]) === 'object') {
traverse(obj[k], encountered, shouldThrow, allowDeepUnsaved);
}
}
}
},{"./ParseFile":14,"./ParseObject":18,"./ParseRelation":23,"babel-runtime/helpers/typeof":62}],44:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/get-iterator"), __esModule: true };
},{"core-js/library/fn/get-iterator":64}],45:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/json/stringify"), __esModule: true };
},{"core-js/library/fn/json/stringify":65}],46:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/map"), __esModule: true };
},{"core-js/library/fn/map":66}],47:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/create"), __esModule: true };
},{"core-js/library/fn/object/create":67}],48:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":68}],49:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/freeze"), __esModule: true };
},{"core-js/library/fn/object/freeze":69}],50:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/get-own-property-descriptor"), __esModule: true };
},{"core-js/library/fn/object/get-own-property-descriptor":70}],51:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/get-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/get-prototype-of":71}],52:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/keys"), __esModule: true };
},{"core-js/library/fn/object/keys":72}],53:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/object/set-prototype-of"), __esModule: true };
},{"core-js/library/fn/object/set-prototype-of":73}],54:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/symbol"), __esModule: true };
},{"core-js/library/fn/symbol":74}],55:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/symbol/iterator"), __esModule: true };
},{"core-js/library/fn/symbol/iterator":75}],56:[function(_dereq_,module,exports){
module.exports = { "default": _dereq_("core-js/library/fn/weak-map"), __esModule: true };
},{"core-js/library/fn/weak-map":76}],57:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
exports.default = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
},{}],58:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
var _defineProperty = _dereq_("../core-js/object/define-property");
var _defineProperty2 = _interopRequireDefault(_defineProperty);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = 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;
(0, _defineProperty2.default)(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
},{"../core-js/object/define-property":48}],59:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
var _getPrototypeOf = _dereq_("../core-js/object/get-prototype-of");
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _getOwnPropertyDescriptor = _dereq_("../core-js/object/get-own-property-descriptor");
var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = (0, _getOwnPropertyDescriptor2.default)(object, property);
if (desc === undefined) {
var parent = (0, _getPrototypeOf2.default)(object);
if (parent === null) {
return undefined;
} else {
return get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
};
},{"../core-js/object/get-own-property-descriptor":50,"../core-js/object/get-prototype-of":51}],60:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
var _setPrototypeOf = _dereq_("../core-js/object/set-prototype-of");
var _setPrototypeOf2 = _interopRequireDefault(_setPrototypeOf);
var _create = _dereq_("../core-js/object/create");
var _create2 = _interopRequireDefault(_create);
var _typeof2 = _dereq_("../helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + (typeof superClass === "undefined" ? "undefined" : (0, _typeof3.default)(superClass)));
}
subClass.prototype = (0, _create2.default)(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf2.default ? (0, _setPrototypeOf2.default)(subClass, superClass) : subClass.__proto__ = superClass;
};
},{"../core-js/object/create":47,"../core-js/object/set-prototype-of":53,"../helpers/typeof":62}],61:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
var _typeof2 = _dereq_("../helpers/typeof");
var _typeof3 = _interopRequireDefault(_typeof2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && ((typeof call === "undefined" ? "undefined" : (0, _typeof3.default)(call)) === "object" || typeof call === "function") ? call : self;
};
},{"../helpers/typeof":62}],62:[function(_dereq_,module,exports){
"use strict";
exports.__esModule = true;
var _iterator = _dereq_("../core-js/symbol/iterator");
var _iterator2 = _interopRequireDefault(_iterator);
var _symbol = _dereq_("../core-js/symbol");
var _symbol2 = _interopRequireDefault(_symbol);
var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
return typeof obj === "undefined" ? "undefined" : _typeof(obj);
} : function (obj) {
return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
};
},{"../core-js/symbol":54,"../core-js/symbol/iterator":55}],63:[function(_dereq_,module,exports){
},{}],64:[function(_dereq_,module,exports){
_dereq_('../modules/web.dom.iterable');
_dereq_('../modules/es6.string.iterator');
module.exports = _dereq_('../modules/core.get-iterator');
},{"../modules/core.get-iterator":152,"../modules/es6.string.iterator":163,"../modules/web.dom.iterable":169}],65:[function(_dereq_,module,exports){
var core = _dereq_('../../modules/_core')
, $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify});
module.exports = function stringify(it){ // eslint-disable-line no-unused-vars
return $JSON.stringify.apply($JSON, arguments);
};
},{"../../modules/_core":92}],66:[function(_dereq_,module,exports){
_dereq_('../modules/es6.object.to-string');
_dereq_('../modules/es6.string.iterator');
_dereq_('../modules/web.dom.iterable');
_dereq_('../modules/es6.map');
_dereq_('../modules/es7.map.to-json');
module.exports = _dereq_('../modules/_core').Map;
},{"../modules/_core":92,"../modules/es6.map":154,"../modules/es6.object.to-string":162,"../modules/es6.string.iterator":163,"../modules/es7.map.to-json":166,"../modules/web.dom.iterable":169}],67:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.create');
var $Object = _dereq_('../../modules/_core').Object;
module.exports = function create(P, D){
return $Object.create(P, D);
};
},{"../../modules/_core":92,"../../modules/es6.object.create":155}],68:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.define-property');
var $Object = _dereq_('../../modules/_core').Object;
module.exports = function defineProperty(it, key, desc){
return $Object.defineProperty(it, key, desc);
};
},{"../../modules/_core":92,"../../modules/es6.object.define-property":156}],69:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.freeze');
module.exports = _dereq_('../../modules/_core').Object.freeze;
},{"../../modules/_core":92,"../../modules/es6.object.freeze":157}],70:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.get-own-property-descriptor');
var $Object = _dereq_('../../modules/_core').Object;
module.exports = function getOwnPropertyDescriptor(it, key){
return $Object.getOwnPropertyDescriptor(it, key);
};
},{"../../modules/_core":92,"../../modules/es6.object.get-own-property-descriptor":158}],71:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.get-prototype-of');
module.exports = _dereq_('../../modules/_core').Object.getPrototypeOf;
},{"../../modules/_core":92,"../../modules/es6.object.get-prototype-of":159}],72:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.keys');
module.exports = _dereq_('../../modules/_core').Object.keys;
},{"../../modules/_core":92,"../../modules/es6.object.keys":160}],73:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.object.set-prototype-of');
module.exports = _dereq_('../../modules/_core').Object.setPrototypeOf;
},{"../../modules/_core":92,"../../modules/es6.object.set-prototype-of":161}],74:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.symbol');
_dereq_('../../modules/es6.object.to-string');
_dereq_('../../modules/es7.symbol.async-iterator');
_dereq_('../../modules/es7.symbol.observable');
module.exports = _dereq_('../../modules/_core').Symbol;
},{"../../modules/_core":92,"../../modules/es6.object.to-string":162,"../../modules/es6.symbol":164,"../../modules/es7.symbol.async-iterator":167,"../../modules/es7.symbol.observable":168}],75:[function(_dereq_,module,exports){
_dereq_('../../modules/es6.string.iterator');
_dereq_('../../modules/web.dom.iterable');
module.exports = _dereq_('../../modules/_wks-ext').f('iterator');
},{"../../modules/_wks-ext":149,"../../modules/es6.string.iterator":163,"../../modules/web.dom.iterable":169}],76:[function(_dereq_,module,exports){
_dereq_('../modules/es6.object.to-string');
_dereq_('../modules/web.dom.iterable');
_dereq_('../modules/es6.weak-map');
module.exports = _dereq_('../modules/_core').WeakMap;
},{"../modules/_core":92,"../modules/es6.object.to-string":162,"../modules/es6.weak-map":165,"../modules/web.dom.iterable":169}],77:[function(_dereq_,module,exports){
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
},{}],78:[function(_dereq_,module,exports){
module.exports = function(){ /* empty */ };
},{}],79:[function(_dereq_,module,exports){
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
},{}],80:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object');
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
},{"./_is-object":110}],81:[function(_dereq_,module,exports){
var forOf = _dereq_('./_for-of');
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
},{"./_for-of":101}],82:[function(_dereq_,module,exports){
// false -> Array#indexOf
// true -> Array#includes
var toIObject = _dereq_('./_to-iobject')
, toLength = _dereq_('./_to-length')
, toIndex = _dereq_('./_to-index');
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
},{"./_to-index":141,"./_to-iobject":143,"./_to-length":144}],83:[function(_dereq_,module,exports){
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = _dereq_('./_ctx')
, IObject = _dereq_('./_iobject')
, toObject = _dereq_('./_to-object')
, toLength = _dereq_('./_to-length')
, asc = _dereq_('./_array-species-create');
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
},{"./_array-species-create":85,"./_ctx":93,"./_iobject":107,"./_to-length":144,"./_to-object":145}],84:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object')
, isArray = _dereq_('./_is-array')
, SPECIES = _dereq_('./_wks')('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
},{"./_is-array":109,"./_is-object":110,"./_wks":150}],85:[function(_dereq_,module,exports){
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = _dereq_('./_array-species-constructor');
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
},{"./_array-species-constructor":84}],86:[function(_dereq_,module,exports){
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = _dereq_('./_cof')
, TAG = _dereq_('./_wks')('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
},{"./_cof":87,"./_wks":150}],87:[function(_dereq_,module,exports){
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
},{}],88:[function(_dereq_,module,exports){
'use strict';
var dP = _dereq_('./_object-dp').f
, create = _dereq_('./_object-create')
, redefineAll = _dereq_('./_redefine-all')
, ctx = _dereq_('./_ctx')
, anInstance = _dereq_('./_an-instance')
, defined = _dereq_('./_defined')
, forOf = _dereq_('./_for-of')
, $iterDefine = _dereq_('./_iter-define')
, step = _dereq_('./_iter-step')
, setSpecies = _dereq_('./_set-species')
, DESCRIPTORS = _dereq_('./_descriptors')
, fastKey = _dereq_('./_meta').fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
},{"./_an-instance":79,"./_ctx":93,"./_defined":94,"./_descriptors":95,"./_for-of":101,"./_iter-define":113,"./_iter-step":114,"./_meta":118,"./_object-create":120,"./_object-dp":121,"./_redefine-all":133,"./_set-species":136}],89:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = _dereq_('./_classof')
, from = _dereq_('./_array-from-iterable');
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
},{"./_array-from-iterable":81,"./_classof":86}],90:[function(_dereq_,module,exports){
'use strict';
var redefineAll = _dereq_('./_redefine-all')
, getWeak = _dereq_('./_meta').getWeak
, anObject = _dereq_('./_an-object')
, isObject = _dereq_('./_is-object')
, anInstance = _dereq_('./_an-instance')
, forOf = _dereq_('./_for-of')
, createArrayMethod = _dereq_('./_array-methods')
, $has = _dereq_('./_has')
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
},{"./_an-instance":79,"./_an-object":80,"./_array-methods":83,"./_for-of":101,"./_has":103,"./_is-object":110,"./_meta":118,"./_redefine-all":133}],91:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_('./_global')
, $export = _dereq_('./_export')
, meta = _dereq_('./_meta')
, fails = _dereq_('./_fails')
, hide = _dereq_('./_hide')
, redefineAll = _dereq_('./_redefine-all')
, forOf = _dereq_('./_for-of')
, anInstance = _dereq_('./_an-instance')
, isObject = _dereq_('./_is-object')
, setToStringTag = _dereq_('./_set-to-string-tag')
, dP = _dereq_('./_object-dp').f
, each = _dereq_('./_array-methods')(0)
, DESCRIPTORS = _dereq_('./_descriptors');
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
C = wrapper(function(target, iterable){
anInstance(target, C, NAME, '_c');
target._c = new Base;
if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target);
});
each('add,clear,delete,forEach,get,has,set,keys,values,entries,toJSON'.split(','),function(KEY){
var IS_ADDER = KEY == 'add' || KEY == 'set';
if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){
anInstance(this, C, KEY);
if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false;
var result = this._c[KEY](a === 0 ? 0 : a, b);
return IS_ADDER ? this : result;
});
});
if('size' in proto)dP(C.prototype, 'size', {
get: function(){
return this._c.size;
}
});
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F, O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
},{"./_an-instance":79,"./_array-methods":83,"./_descriptors":95,"./_export":99,"./_fails":100,"./_for-of":101,"./_global":102,"./_hide":104,"./_is-object":110,"./_meta":118,"./_object-dp":121,"./_redefine-all":133,"./_set-to-string-tag":137}],92:[function(_dereq_,module,exports){
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
},{}],93:[function(_dereq_,module,exports){
// optional / simple context binding
var aFunction = _dereq_('./_a-function');
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
},{"./_a-function":77}],94:[function(_dereq_,module,exports){
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
},{}],95:[function(_dereq_,module,exports){
// Thank's IE8 for his funny defineProperty
module.exports = !_dereq_('./_fails')(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_fails":100}],96:[function(_dereq_,module,exports){
var isObject = _dereq_('./_is-object')
, document = _dereq_('./_global').document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
},{"./_global":102,"./_is-object":110}],97:[function(_dereq_,module,exports){
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
},{}],98:[function(_dereq_,module,exports){
// all enumerable object keys, includes symbols
var getKeys = _dereq_('./_object-keys')
, gOPS = _dereq_('./_object-gops')
, pIE = _dereq_('./_object-pie');
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
},{"./_object-gops":126,"./_object-keys":129,"./_object-pie":130}],99:[function(_dereq_,module,exports){
var global = _dereq_('./_global')
, core = _dereq_('./_core')
, ctx = _dereq_('./_ctx')
, hide = _dereq_('./_hide')
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, IS_WRAP = type & $export.W
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE]
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
, key, own, out;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
if(own && key in exports)continue;
// export native or passed
out = own ? target[key] : source[key];
// prevent global pollution for namespaces
exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
// bind timers to global for call from export context
: IS_BIND && own ? ctx(out, global)
// wrap global constructors for prevent change them in library
: IS_WRAP && target[key] == out ? (function(C){
var F = function(a, b, c){
if(this instanceof C){
switch(arguments.length){
case 0: return new C;
case 1: return new C(a);
case 2: return new C(a, b);
} return new C(a, b, c);
} return C.apply(this, arguments);
};
F[PROTOTYPE] = C[PROTOTYPE];
return F;
// make static versions for prototype methods
})(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
if(IS_PROTO){
(exports.virtual || (exports.virtual = {}))[key] = out;
// export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out);
}
}
};
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
},{"./_core":92,"./_ctx":93,"./_global":102,"./_hide":104}],100:[function(_dereq_,module,exports){
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
},{}],101:[function(_dereq_,module,exports){
var ctx = _dereq_('./_ctx')
, call = _dereq_('./_iter-call')
, isArrayIter = _dereq_('./_is-array-iter')
, anObject = _dereq_('./_an-object')
, toLength = _dereq_('./_to-length')
, getIterFn = _dereq_('./core.get-iterator-method')
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
},{"./_an-object":80,"./_ctx":93,"./_is-array-iter":108,"./_iter-call":111,"./_to-length":144,"./core.get-iterator-method":151}],102:[function(_dereq_,module,exports){
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
},{}],103:[function(_dereq_,module,exports){
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
},{}],104:[function(_dereq_,module,exports){
var dP = _dereq_('./_object-dp')
, createDesc = _dereq_('./_property-desc');
module.exports = _dereq_('./_descriptors') ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
},{"./_descriptors":95,"./_object-dp":121,"./_property-desc":132}],105:[function(_dereq_,module,exports){
module.exports = _dereq_('./_global').document && document.documentElement;
},{"./_global":102}],106:[function(_dereq_,module,exports){
module.exports = !_dereq_('./_descriptors') && !_dereq_('./_fails')(function(){
return Object.defineProperty(_dereq_('./_dom-create')('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
},{"./_descriptors":95,"./_dom-create":96,"./_fails":100}],107:[function(_dereq_,module,exports){
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = _dereq_('./_cof');
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
},{"./_cof":87}],108:[function(_dereq_,module,exports){
// check on default Array iterator
var Iterators = _dereq_('./_iterators')
, ITERATOR = _dereq_('./_wks')('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
},{"./_iterators":115,"./_wks":150}],109:[function(_dereq_,module,exports){
// 7.2.2 IsArray(argument)
var cof = _dereq_('./_cof');
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
},{"./_cof":87}],110:[function(_dereq_,module,exports){
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
},{}],111:[function(_dereq_,module,exports){
// call something on iterator step with safe closing on error
var anObject = _dereq_('./_an-object');
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
},{"./_an-object":80}],112:[function(_dereq_,module,exports){
'use strict';
var create = _dereq_('./_object-create')
, descriptor = _dereq_('./_property-desc')
, setToStringTag = _dereq_('./_set-to-string-tag')
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
_dereq_('./_hide')(IteratorPrototype, _dereq_('./_wks')('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
},{"./_hide":104,"./_object-create":120,"./_property-desc":132,"./_set-to-string-tag":137,"./_wks":150}],113:[function(_dereq_,module,exports){
'use strict';
var LIBRARY = _dereq_('./_library')
, $export = _dereq_('./_export')
, redefine = _dereq_('./_redefine')
, hide = _dereq_('./_hide')
, has = _dereq_('./_has')
, Iterators = _dereq_('./_iterators')
, $iterCreate = _dereq_('./_iter-create')
, setToStringTag = _dereq_('./_set-to-string-tag')
, getPrototypeOf = _dereq_('./_object-gpo')
, ITERATOR = _dereq_('./_wks')('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
},{"./_export":99,"./_has":103,"./_hide":104,"./_iter-create":112,"./_iterators":115,"./_library":117,"./_object-gpo":127,"./_redefine":134,"./_set-to-string-tag":137,"./_wks":150}],114:[function(_dereq_,module,exports){
module.exports = function(done, value){
return {value: value, done: !!done};
};
},{}],115:[function(_dereq_,module,exports){
module.exports = {};
},{}],116:[function(_dereq_,module,exports){
var getKeys = _dereq_('./_object-keys')
, toIObject = _dereq_('./_to-iobject');
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
},{"./_object-keys":129,"./_to-iobject":143}],117:[function(_dereq_,module,exports){
module.exports = true;
},{}],118:[function(_dereq_,module,exports){
var META = _dereq_('./_uid')('meta')
, isObject = _dereq_('./_is-object')
, has = _dereq_('./_has')
, setDesc = _dereq_('./_object-dp').f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !_dereq_('./_fails')(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
},{"./_fails":100,"./_has":103,"./_is-object":110,"./_object-dp":121,"./_uid":147}],119:[function(_dereq_,module,exports){
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = _dereq_('./_object-keys')
, gOPS = _dereq_('./_object-gops')
, pIE = _dereq_('./_object-pie')
, toObject = _dereq_('./_to-object')
, IObject = _dereq_('./_iobject')
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || _dereq_('./_fails')(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
},{"./_fails":100,"./_iobject":107,"./_object-gops":126,"./_object-keys":129,"./_object-pie":130,"./_to-object":145}],120:[function(_dereq_,module,exports){
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = _dereq_('./_an-object')
, dPs = _dereq_('./_object-dps')
, enumBugKeys = _dereq_('./_enum-bug-keys')
, IE_PROTO = _dereq_('./_shared-key')('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = _dereq_('./_dom-create')('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
_dereq_('./_html').appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
},{"./_an-object":80,"./_dom-create":96,"./_enum-bug-keys":97,"./_html":105,"./_object-dps":122,"./_shared-key":138}],121:[function(_dereq_,module,exports){
var anObject = _dereq_('./_an-object')
, IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define')
, toPrimitive = _dereq_('./_to-primitive')
, dP = Object.defineProperty;
exports.f = _dereq_('./_descriptors') ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
},{"./_an-object":80,"./_descriptors":95,"./_ie8-dom-define":106,"./_to-primitive":146}],122:[function(_dereq_,module,exports){
var dP = _dereq_('./_object-dp')
, anObject = _dereq_('./_an-object')
, getKeys = _dereq_('./_object-keys');
module.exports = _dereq_('./_descriptors') ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
},{"./_an-object":80,"./_descriptors":95,"./_object-dp":121,"./_object-keys":129}],123:[function(_dereq_,module,exports){
var pIE = _dereq_('./_object-pie')
, createDesc = _dereq_('./_property-desc')
, toIObject = _dereq_('./_to-iobject')
, toPrimitive = _dereq_('./_to-primitive')
, has = _dereq_('./_has')
, IE8_DOM_DEFINE = _dereq_('./_ie8-dom-define')
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = _dereq_('./_descriptors') ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
},{"./_descriptors":95,"./_has":103,"./_ie8-dom-define":106,"./_object-pie":130,"./_property-desc":132,"./_to-iobject":143,"./_to-primitive":146}],124:[function(_dereq_,module,exports){
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = _dereq_('./_to-iobject')
, gOPN = _dereq_('./_object-gopn').f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
},{"./_object-gopn":125,"./_to-iobject":143}],125:[function(_dereq_,module,exports){
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = _dereq_('./_object-keys-internal')
, hiddenKeys = _dereq_('./_enum-bug-keys').concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
},{"./_enum-bug-keys":97,"./_object-keys-internal":128}],126:[function(_dereq_,module,exports){
exports.f = Object.getOwnPropertySymbols;
},{}],127:[function(_dereq_,module,exports){
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = _dereq_('./_has')
, toObject = _dereq_('./_to-object')
, IE_PROTO = _dereq_('./_shared-key')('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
},{"./_has":103,"./_shared-key":138,"./_to-object":145}],128:[function(_dereq_,module,exports){
var has = _dereq_('./_has')
, toIObject = _dereq_('./_to-iobject')
, arrayIndexOf = _dereq_('./_array-includes')(false)
, IE_PROTO = _dereq_('./_shared-key')('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
},{"./_array-includes":82,"./_has":103,"./_shared-key":138,"./_to-iobject":143}],129:[function(_dereq_,module,exports){
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = _dereq_('./_object-keys-internal')
, enumBugKeys = _dereq_('./_enum-bug-keys');
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
},{"./_enum-bug-keys":97,"./_object-keys-internal":128}],130:[function(_dereq_,module,exports){
exports.f = {}.propertyIsEnumerable;
},{}],131:[function(_dereq_,module,exports){
// most Object methods by ES6 should accept primitives
var $export = _dereq_('./_export')
, core = _dereq_('./_core')
, fails = _dereq_('./_fails');
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
},{"./_core":92,"./_export":99,"./_fails":100}],132:[function(_dereq_,module,exports){
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
},{}],133:[function(_dereq_,module,exports){
var hide = _dereq_('./_hide');
module.exports = function(target, src, safe){
for(var key in src){
if(safe && target[key])target[key] = src[key];
else hide(target, key, src[key]);
} return target;
};
},{"./_hide":104}],134:[function(_dereq_,module,exports){
module.exports = _dereq_('./_hide');
},{"./_hide":104}],135:[function(_dereq_,module,exports){
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = _dereq_('./_is-object')
, anObject = _dereq_('./_an-object');
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = _dereq_('./_ctx')(Function.call, _dereq_('./_object-gopd').f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
},{"./_an-object":80,"./_ctx":93,"./_is-object":110,"./_object-gopd":123}],136:[function(_dereq_,module,exports){
'use strict';
var global = _dereq_('./_global')
, core = _dereq_('./_core')
, dP = _dereq_('./_object-dp')
, DESCRIPTORS = _dereq_('./_descriptors')
, SPECIES = _dereq_('./_wks')('species');
module.exports = function(KEY){
var C = typeof core[KEY] == 'function' ? core[KEY] : global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
},{"./_core":92,"./_descriptors":95,"./_global":102,"./_object-dp":121,"./_wks":150}],137:[function(_dereq_,module,exports){
var def = _dereq_('./_object-dp').f
, has = _dereq_('./_has')
, TAG = _dereq_('./_wks')('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
},{"./_has":103,"./_object-dp":121,"./_wks":150}],138:[function(_dereq_,module,exports){
var shared = _dereq_('./_shared')('keys')
, uid = _dereq_('./_uid');
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
},{"./_shared":139,"./_uid":147}],139:[function(_dereq_,module,exports){
var global = _dereq_('./_global')
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
},{"./_global":102}],140:[function(_dereq_,module,exports){
var toInteger = _dereq_('./_to-integer')
, defined = _dereq_('./_defined');
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
},{"./_defined":94,"./_to-integer":142}],141:[function(_dereq_,module,exports){
var toInteger = _dereq_('./_to-integer')
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
},{"./_to-integer":142}],142:[function(_dereq_,module,exports){
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
},{}],143:[function(_dereq_,module,exports){
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = _dereq_('./_iobject')
, defined = _dereq_('./_defined');
module.exports = function(it){
return IObject(defined(it));
};
},{"./_defined":94,"./_iobject":107}],144:[function(_dereq_,module,exports){
// 7.1.15 ToLength
var toInteger = _dereq_('./_to-integer')
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
},{"./_to-integer":142}],145:[function(_dereq_,module,exports){
// 7.1.13 ToObject(argument)
var defined = _dereq_('./_defined');
module.exports = function(it){
return Object(defined(it));
};
},{"./_defined":94}],146:[function(_dereq_,module,exports){
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = _dereq_('./_is-object');
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
},{"./_is-object":110}],147:[function(_dereq_,module,exports){
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
},{}],148:[function(_dereq_,module,exports){
var global = _dereq_('./_global')
, core = _dereq_('./_core')
, LIBRARY = _dereq_('./_library')
, wksExt = _dereq_('./_wks-ext')
, defineProperty = _dereq_('./_object-dp').f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
},{"./_core":92,"./_global":102,"./_library":117,"./_object-dp":121,"./_wks-ext":149}],149:[function(_dereq_,module,exports){
exports.f = _dereq_('./_wks');
},{"./_wks":150}],150:[function(_dereq_,module,exports){
var store = _dereq_('./_shared')('wks')
, uid = _dereq_('./_uid')
, Symbol = _dereq_('./_global').Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
},{"./_global":102,"./_shared":139,"./_uid":147}],151:[function(_dereq_,module,exports){
var classof = _dereq_('./_classof')
, ITERATOR = _dereq_('./_wks')('iterator')
, Iterators = _dereq_('./_iterators');
module.exports = _dereq_('./_core').getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
},{"./_classof":86,"./_core":92,"./_iterators":115,"./_wks":150}],152:[function(_dereq_,module,exports){
var anObject = _dereq_('./_an-object')
, get = _dereq_('./core.get-iterator-method');
module.exports = _dereq_('./_core').getIterator = function(it){
var iterFn = get(it);
if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!');
return anObject(iterFn.call(it));
};
},{"./_an-object":80,"./_core":92,"./core.get-iterator-method":151}],153:[function(_dereq_,module,exports){
'use strict';
var addToUnscopables = _dereq_('./_add-to-unscopables')
, step = _dereq_('./_iter-step')
, Iterators = _dereq_('./_iterators')
, toIObject = _dereq_('./_to-iobject');
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = _dereq_('./_iter-define')(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
},{"./_add-to-unscopables":78,"./_iter-define":113,"./_iter-step":114,"./_iterators":115,"./_to-iobject":143}],154:[function(_dereq_,module,exports){
'use strict';
var strong = _dereq_('./_collection-strong');
// 23.1 Map Objects
module.exports = _dereq_('./_collection')('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
},{"./_collection":91,"./_collection-strong":88}],155:[function(_dereq_,module,exports){
var $export = _dereq_('./_export')
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: _dereq_('./_object-create')});
},{"./_export":99,"./_object-create":120}],156:[function(_dereq_,module,exports){
var $export = _dereq_('./_export');
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !_dereq_('./_descriptors'), 'Object', {defineProperty: _dereq_('./_object-dp').f});
},{"./_descriptors":95,"./_export":99,"./_object-dp":121}],157:[function(_dereq_,module,exports){
// 19.1.2.5 Object.freeze(O)
var isObject = _dereq_('./_is-object')
, meta = _dereq_('./_meta').onFreeze;
_dereq_('./_object-sap')('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
},{"./_is-object":110,"./_meta":118,"./_object-sap":131}],158:[function(_dereq_,module,exports){
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = _dereq_('./_to-iobject')
, $getOwnPropertyDescriptor = _dereq_('./_object-gopd').f;
_dereq_('./_object-sap')('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
},{"./_object-gopd":123,"./_object-sap":131,"./_to-iobject":143}],159:[function(_dereq_,module,exports){
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = _dereq_('./_to-object')
, $getPrototypeOf = _dereq_('./_object-gpo');
_dereq_('./_object-sap')('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
},{"./_object-gpo":127,"./_object-sap":131,"./_to-object":145}],160:[function(_dereq_,module,exports){
// 19.1.2.14 Object.keys(O)
var toObject = _dereq_('./_to-object')
, $keys = _dereq_('./_object-keys');
_dereq_('./_object-sap')('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
},{"./_object-keys":129,"./_object-sap":131,"./_to-object":145}],161:[function(_dereq_,module,exports){
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = _dereq_('./_export');
$export($export.S, 'Object', {setPrototypeOf: _dereq_('./_set-proto').set});
},{"./_export":99,"./_set-proto":135}],162:[function(_dereq_,module,exports){
arguments[4][63][0].apply(exports,arguments)
},{"dup":63}],163:[function(_dereq_,module,exports){
'use strict';
var $at = _dereq_('./_string-at')(true);
// 21.1.3.27 String.prototype[@@iterator]()
_dereq_('./_iter-define')(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
},{"./_iter-define":113,"./_string-at":140}],164:[function(_dereq_,module,exports){
'use strict';
// ECMAScript 6 symbols shim
var global = _dereq_('./_global')
, has = _dereq_('./_has')
, DESCRIPTORS = _dereq_('./_descriptors')
, $export = _dereq_('./_export')
, redefine = _dereq_('./_redefine')
, META = _dereq_('./_meta').KEY
, $fails = _dereq_('./_fails')
, shared = _dereq_('./_shared')
, setToStringTag = _dereq_('./_set-to-string-tag')
, uid = _dereq_('./_uid')
, wks = _dereq_('./_wks')
, wksExt = _dereq_('./_wks-ext')
, wksDefine = _dereq_('./_wks-define')
, keyOf = _dereq_('./_keyof')
, enumKeys = _dereq_('./_enum-keys')
, isArray = _dereq_('./_is-array')
, anObject = _dereq_('./_an-object')
, toIObject = _dereq_('./_to-iobject')
, toPrimitive = _dereq_('./_to-primitive')
, createDesc = _dereq_('./_property-desc')
, _create = _dereq_('./_object-create')
, gOPNExt = _dereq_('./_object-gopn-ext')
, $GOPD = _dereq_('./_object-gopd')
, $DP = _dereq_('./_object-dp')
, $keys = _dereq_('./_object-keys')
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
_dereq_('./_object-gopn').f = gOPNExt.f = $getOwnPropertyNames;
_dereq_('./_object-pie').f = $propertyIsEnumerable;
_dereq_('./_object-gops').f = $getOwnPropertySymbols;
if(DESCRIPTORS && !_dereq_('./_library')){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || _dereq_('./_hide')($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
},{"./_an-object":80,"./_descriptors":95,"./_enum-keys":98,"./_export":99,"./_fails":100,"./_global":102,"./_has":103,"./_hide":104,"./_is-array":109,"./_keyof":116,"./_library":117,"./_meta":118,"./_object-create":120,"./_object-dp":121,"./_object-gopd":123,"./_object-gopn":125,"./_object-gopn-ext":124,"./_object-gops":126,"./_object-keys":129,"./_object-pie":130,"./_property-desc":132,"./_redefine":134,"./_set-to-string-tag":137,"./_shared":139,"./_to-iobject":143,"./_to-primitive":146,"./_uid":147,"./_wks":150,"./_wks-define":148,"./_wks-ext":149}],165:[function(_dereq_,module,exports){
'use strict';
var each = _dereq_('./_array-methods')(0)
, redefine = _dereq_('./_redefine')
, meta = _dereq_('./_meta')
, assign = _dereq_('./_object-assign')
, weak = _dereq_('./_collection-weak')
, isObject = _dereq_('./_is-object')
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = _dereq_('./_collection')('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
},{"./_array-methods":83,"./_collection":91,"./_collection-weak":90,"./_is-object":110,"./_meta":118,"./_object-assign":119,"./_redefine":134}],166:[function(_dereq_,module,exports){
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = _dereq_('./_export');
$export($export.P + $export.R, 'Map', {toJSON: _dereq_('./_collection-to-json')('Map')});
},{"./_collection-to-json":89,"./_export":99}],167:[function(_dereq_,module,exports){
_dereq_('./_wks-define')('asyncIterator');
},{"./_wks-define":148}],168:[function(_dereq_,module,exports){
_dereq_('./_wks-define')('observable');
},{"./_wks-define":148}],169:[function(_dereq_,module,exports){
_dereq_('./es6.array.iterator');
var global = _dereq_('./_global')
, hide = _dereq_('./_hide')
, Iterators = _dereq_('./_iterators')
, TO_STRING_TAG = _dereq_('./_wks')('toStringTag');
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype;
if(proto && !proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = Iterators.Array;
}
},{"./_global":102,"./_hide":104,"./_iterators":115,"./_wks":150,"./es6.array.iterator":153}],170:[function(_dereq_,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}]},{},[10])(10)
});
|
Meteor.publish('settings', function() {
var options = {};
if(!isAdminById(this.userId)){
options = _.extend(options, {
fields: {
mailChimpAPIKey: false,
mailChimpListId: false
}
});
}
return Settings.find({}, options);
});
Meteor.publish('invites', function(){
if(canViewById(this.userId)){
return Invites.find({invitingUserId:this.userId});
}
});
|
(function(){var d=window.AmCharts;d.AmRadarChart=d.Class({inherits:d.AmCoordinateChart,construct:function(a){this.type="radar";d.AmRadarChart.base.construct.call(this,a);this.cname="AmRadarChart";this.marginRight=this.marginBottom=this.marginTop=this.marginLeft=0;this.radius="35%";d.applyTheme(this,a,this.cname)},initChart:function(){d.AmRadarChart.base.initChart.call(this);if(this.dataChanged)this.parseData();else this.onDataUpdated()},onDataUpdated:function(){this.drawChart()},updateGraphs:function(){var a=
this.graphs,b;for(b=0;b<a.length;b++){var c=a[b];c.index=b;c.width=this.realRadius;c.height=this.realRadius;c.x=this.marginLeftReal;c.y=this.marginTopReal;c.data=this.chartData}},parseData:function(){d.AmRadarChart.base.parseData.call(this);this.parseSerialData(this.dataProvider)},updateValueAxes:function(){var a=this.valueAxes,b;for(b=0;b<a.length;b++){var c=a[b];c.axisRenderer=d.RadAxis;c.guideFillRenderer=d.RadarFill;c.axisItemRenderer=d.RadItem;c.autoGridCount=!1;c.rMultiplier=1;c.x=this.marginLeftReal;
c.y=this.marginTopReal;c.width=this.realRadius;c.height=this.realRadius;c.marginsChanged=!0;c.titleDY=c.y}},drawChart:function(){d.AmRadarChart.base.drawChart.call(this);var a=this.updateWidth(),b=this.updateHeight(),c=this.marginTop+this.getTitleHeight(),f=this.marginLeft,m=this.marginBottom,n=this.marginRight,e=b-c-m;this.marginLeftReal=f+(a-f-n)/2;this.marginTopReal=c+e/2;this.realRadius=d.toCoordinate(this.radius,Math.min(a-f-n,b-c-m),e);this.updateValueAxes();this.updateGraphs();a=this.chartData;
if(d.ifArray(a)){if(0<this.realWidth&&0<this.realHeight){a=a.length-1;c=this.valueAxes;for(b=0;b<c.length;b++)c[b].zoom(0,a);c=this.graphs;for(b=0;b<c.length;b++)c[b].zoom(0,a);(a=this.legend)&&a.invalidateSize()}}else this.cleanChart();this.dispDUpd();this.gridSet.toBack();this.axesSet.toBack();this.set.toBack()},formatString:function(a,b,c){var f=b.graph;-1!=a.indexOf("[[category]]")&&(a=a.replace(/\[\[category\]\]/g,String(b.serialDataItem.category)));f=f.numberFormatter;f||(f=this.nf);a=d.formatValue(a,
b.values,["value"],f,"",this.usePrefixes,this.prefixesOfSmallNumbers,this.prefixesOfBigNumbers);-1!=a.indexOf("[[")&&(a=d.formatDataContextValue(a,b.dataContext));return a=d.AmRadarChart.base.formatString.call(this,a,b,c)},cleanChart:function(){d.callMethod("destroy",[this.valueAxes,this.graphs])}})})();(function(){var d=window.AmCharts;d.RadAxis=d.Class({construct:function(a){var b=a.chart,c=a.axisThickness,f=a.axisColor,m=a.axisAlpha;this.set=b.container.set();this.set.translate(a.x,a.y);b.axesSet.push(this.set);var n=a.axisTitleOffset,e=a.radarCategoriesEnabled,r=a.chart.fontFamily,h=a.fontSize;void 0===h&&(h=a.chart.fontSize);var k=a.color;void 0===k&&(k=a.chart.color);if(b){this.axisWidth=a.height;var p=b.chartData,l=p.length,w,z=this.axisWidth;"middle"==a.pointPosition&&"circles"!=a.gridType&&
(a.rMultiplier=Math.cos(180/l*Math.PI/180),z*=a.rMultiplier);for(w=0;w<l;w+=a.axisFrequency){var q=180-360/l*w,g=q;"middle"==a.pointPosition&&(g-=180/l);var t=this.axisWidth*Math.sin(q/180*Math.PI),q=this.axisWidth*Math.cos(q/180*Math.PI);0<m&&(t=d.line(b.container,[0,t],[0,q],f,m,c),this.set.push(t),d.setCN(b,t,a.bcn+"line"));if(e){var x="start",t=(z+n)*Math.sin(g/180*Math.PI),q=(z+n)*Math.cos(g/180*Math.PI);if(180==g||0===g)x="middle",t-=5;0>g&&(x="end",t-=10);180==g&&(q-=5);0===g&&(q+=5);g=d.text(b.container,
p[w].category,k,r,h,x);g.translate(t+5,q);this.set.push(g);d.setCN(b,g,a.bcn+"title")}}}}})})();(function(){var d=window.AmCharts;d.RadItem=d.Class({construct:function(a,b,c,f,m,n,e,r){f=a.chart;void 0===c&&(c="");var h=a.chart.fontFamily,k=a.fontSize;void 0===k&&(k=a.chart.fontSize);var p=a.color;void 0===p&&(p=a.chart.color);var l=a.chart.container;this.set=m=l.set();var w=a.axisColor,z=a.axisAlpha,q=a.tickLength,g=a.gridAlpha,t=a.gridThickness,x=a.gridColor,D=a.dashLength,E=a.fillColor,B=a.fillAlpha,F=a.labelsEnabled;n=a.counter;var G=a.inside,H=a.gridType,u,J=a.labelOffset,A;b-=a.height;
var y;e?(F=!0,void 0!==e.id&&(A=f.classNamePrefix+"-guide-"+e.id),isNaN(e.tickLength)||(q=e.tickLength),void 0!=e.lineColor&&(x=e.lineColor),isNaN(e.lineAlpha)||(g=e.lineAlpha),isNaN(e.dashLength)||(D=e.dashLength),isNaN(e.lineThickness)||(t=e.lineThickness),!0===e.inside&&(G=!0),void 0!==e.boldLabel&&(r=e.boldLabel)):c||(g/=3,q/=2);var I="end",C=-1;G&&(I="start",C=1);var v;F&&(v=d.text(l,c,p,h,k,I,r),v.translate((q+3+J)*C,b),m.push(v),d.setCN(f,v,a.bcn+"label"),e&&d.setCN(f,v,"guide"),d.setCN(f,
v,A,!0),this.label=v,y=d.line(l,[0,q*C],[b,b],w,z,t),m.push(y),d.setCN(f,y,a.bcn+"tick"),e&&d.setCN(f,y,"guide"),d.setCN(f,y,A,!0));b=Math.abs(b);r=[];h=[];if(0<g){if("polygons"==H){u=a.data.length;for(k=0;k<u;k++)p=180-360/u*k,r.push(b*Math.sin(p/180*Math.PI)),h.push(b*Math.cos(p/180*Math.PI));r.push(r[0]);h.push(h[0]);g=d.line(l,r,h,x,g,t,D)}else g=d.circle(l,b,"#FFFFFF",0,t,x,g);m.push(g);d.setCN(f,g,a.bcn+"grid");d.setCN(f,g,A,!0);e&&d.setCN(f,g,"guide")}if(1==n&&0<B&&!e&&""!==c){e=a.previousCoord;
if("polygons"==H){for(k=u;0<=k;k--)p=180-360/u*k,r.push(e*Math.sin(p/180*Math.PI)),h.push(e*Math.cos(p/180*Math.PI));u=d.polygon(l,r,h,E,B)}else u=d.wedge(l,0,0,0,360,b,b,e,0,{fill:E,"fill-opacity":B,stroke:"#000","stroke-opacity":0,"stroke-width":1});m.push(u);d.setCN(f,u,a.bcn+"fill");d.setCN(f,u,A,!0)}!1===a.visible&&(y&&y.hide(),v&&v.hide());""!==c&&(a.counter=0===n?1:0,a.previousCoord=b)},graphics:function(){return this.set},getLabel:function(){return this.label}})})();(function(){var d=window.AmCharts;d.RadarFill=d.Class({construct:function(a,b,c,f){b-=a.axisWidth;c-=a.axisWidth;var m=Math.min(b,c);c=Math.max(b,c);b=a.chart;var n=b.container,e=f.fillAlpha,r=f.fillColor;c=Math.abs(c);var m=Math.abs(m),h=Math.min(c,m);c=Math.max(c,m);var m=h,h=f.angle+90,k=f.toAngle+90;isNaN(h)&&(h=0);isNaN(k)&&(k=360);this.set=n.set();void 0===r&&(r="#000000");isNaN(e)&&(e=0);if("polygons"==a.gridType){var k=[],p=[];a=a.data.length;var l;for(l=0;l<a;l++)h=180-360/a*l,k.push(c*Math.sin(h/
180*Math.PI)),p.push(c*Math.cos(h/180*Math.PI));k.push(k[0]);p.push(p[0]);for(l=a;0<=l;l--)h=180-360/a*l,k.push(m*Math.sin(h/180*Math.PI)),p.push(m*Math.cos(h/180*Math.PI));n=d.polygon(n,k,p,r,e)}else n=d.wedge(n,0,0,h,k-h,c,c,m,0,{fill:r,"fill-opacity":e,stroke:"#000","stroke-opacity":0,"stroke-width":1});d.setCN(b,n,"guide-fill");f.id&&d.setCN(b,n,"guide-fill-"+f.id);this.set.push(n);this.fill=n},graphics:function(){return this.set},getLabel:function(){}})})();
|
loadIonicon('<svg width="1em" height="1em" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M248.03 116.81l24.68-24.678 19.232 19.234-24.678 24.677zM176 125.7c-45.3 0-82.3 37-82.3 82.3 0 17.5 5.5 33.7 14.9 47 15.3-13 33.9-22.6 54.7-27.6l13.2-16.6c13.6-17.1 30.7-30.2 50.8-38.9 6.1-2.6 12.4-4.8 19-6.6-14.5-23.7-40.6-39.6-70.3-39.6zM162 64h28v41h-28zM32 194h41v28H32zM81.6 276.8l-.8-.8-24.7 24.7 19.2 19.2 24.7-24.7zM79.29 92.13l24.677 24.678-19.233 19.233-24.678-24.677zM405.6 288.6C394.7 233.4 346.2 192 288 192c-34 0-65.1 11.9-86.5 38.8 29.4 2.2 56.7 13 77.8 33.9 15.6 15.6 26.6 34.6 32.1 55.3h-28.7c-13.1-37.3-48-64-90.6-64-5.1 0-12.3.6-17.7 1.7C128.6 267.1 96 305 96 352c0 53 43 96 96 96h208c44.2 0 80-35.8 80-80 0-42.2-32.8-76.5-74.4-79.4z"/></svg>','md-partly-sunny');
|
/* globals ansispan:true */
ansispan = function(str) {
str = str.replace(/>/g, '>');
str = str.replace(/</g, '<');
Object.keys(ansispan.foregroundColors).forEach(function(ansi) {
var span = '<span style="color: ' + ansispan.foregroundColors[ansi] + '">';
//
// `\033[Xm` == `\033[0;Xm` sets foreground color to `X`.
//
str = str.replace(
new RegExp('\0o33\\[' + ansi + 'm', 'g'),
span
).replace(
new RegExp('\0o33\\[0;' + ansi + 'm', 'g'),
span
);
});
//
// `\033[1m` enables bold font, `\033[22m` disables it
//
str = str.replace(/\033\[1m/g, '<b>').replace(/\033\[22m/g, '</b>');
//
// `\033[3m` enables italics font, `\033[23m` disables it
//
str = str.replace(/\033\[3m/g, '<i>').replace(/\033\[23m/g, '</i>');
str = str.replace(/\033\[m/g, '</span>');
str = str.replace(/\033\[0m/g, '</span>');
return str.replace(/\033\[39m/g, '</span>');
};
ansispan.foregroundColors = {
'30': 'gray',
'31': 'red',
'32': 'lime',
'33': 'yellow',
'34': '#6B98FF',
'35': '#FF00FF',
'36': 'cyan',
'37': 'white'
};
|
const tabsInstance = (
<Tabs defaultActiveKey={2}>
<Tab eventKey={1} title="Tab 1">Tab 1 content</Tab>
<Tab eventKey={2} title="Tab 2">Tab 2 content</Tab>
<Tab eventKey={3} title="Tab 3" disabled>Tab 3 content</Tab>
</Tabs>
);
React.render(tabsInstance, mountNode);
|
// javascript 'shim' to trigger the click event of element(s)
// when the space key is pressed.
//
// Created since some Assistive Technologies (for example some Screenreaders)
// Will tell a user to press space on a 'button', so this functionality needs to be shimmed
// See https://github.com/alphagov/govuk_elements/pull/272#issuecomment-233028270
//
// Usage instructions:
// GOVUK.shimLinksWithButtonRole.init();
;(function (global) {
'use strict'
var $ = global.jQuery
var GOVUK = global.GOVUK || {}
GOVUK.shimLinksWithButtonRole = {
init: function init () {
// listen to 'document' for keydown event on the any elements that should be buttons.
$(document).on('keydown', '[role="button"]', function (event) {
// if the keyCode (which) is 32 it's a space, let's simulate a click.
if (event.which === 32) {
event.preventDefault()
// trigger the target's click event
event.target.click()
}
})
}
}
// hand back to global
global.GOVUK = GOVUK
})(window)
|
'use strict';
/**
* Module dependencies.
*/
var acl = require('acl');
// Using the memory backend
acl = new acl(new acl.memoryBackend());
/**
* Invoke Articles Permissions
*/
exports.invokeRolesPolicies = function() {
acl.allow([{
roles: ['admin'],
allows: [{
resources: '/api/articles',
permissions: '*'
}, {
resources: '/api/articles/:articleId',
permissions: '*'
}]
}, {
roles: ['user'],
allows: [{
resources: '/api/articles',
permissions: ['get', 'post']
}, {
resources: '/api/articles/:articleId',
permissions: ['get']
}]
}, {
roles: ['guest'],
allows: [{
resources: '/api/articles',
permissions: ['get']
}, {
resources: '/api/articles/:articleId',
permissions: ['get']
}]
}]);
};
/**
* Check If Articles Policy Allows
*/
exports.isAllowed = function(req, res, next) {
var roles = (req.user) ? req.user.roles : ['guest'];
// If an article is being processed and the current user created it then allow any manipulation
if (req.article && req.user && req.article.user.id === req.user.id) {
return next();
}
// Check for user roles
acl.areAnyRolesAllowed(roles, req.route.path, req.method.toLowerCase(), function(err, isAllowed) {
if (err) {
// An authorization error occurred.
return res.status(500).send('Unexpected authorization error');
} else {
if (isAllowed) {
// Access granted! Invoke next middleware
return next();
} else {
return res.status(403).json({
message: 'User is not authorized'
});
}
}
});
};
|
/**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
'use strict';
var test = require('tape');
var clone = require('../clone');
test('clone', function(t) {
t.equal(typeof clone, 'function', 'clone should be a function');
var flatObject = {a: {}, b: {}, c: {}};
t.deepEqual(clone(flatObject), flatObject, 'clone should clone flat object');
var nestedObject = {
test1: {
test1test1: {
test1test1test1: 3
},
test1test2: 3
},
test2: {},
test3: {}
};
t.deepEqual(clone(nestedObject), nestedObject, 'clone should deep clone nested object');
t.end();
});
|
import warning from 'warning';
const getName = (object) =>
object.displayName ? `${object.displayName} ` :
object.muiName ? `${object.muiName} ` : '';
function deprecatedExport(object, deprecatedPath, supportedPath) {
warning(false,
`Importing ${getName(object)}from '${deprecatedPath}' has been deprecated, use '${supportedPath}' instead.`);
return object;
}
export default deprecatedExport;
|
YUI.add('anim-base', function(Y) {
/**
* The Animation Utility provides an API for creating advanced transitions.
* @module anim
*/
/**
* Provides the base Anim class, for animating numeric properties.
*
* @module anim
* @submodule anim-base
*/
/**
* A class for constructing animation instances.
* @class Anim
* @for Anim
* @constructor
* @extends Base
*/
var RUNNING = 'running',
START_TIME = 'startTime',
ELAPSED_TIME = 'elapsedTime',
/**
* @for Anim
* @event start
* @description fires when an animation begins.
* @param {Event} ev The start event.
* @type Event.Custom
*/
START = 'start',
/**
* @event tween
* @description fires every frame of the animation.
* @param {Event} ev The tween event.
* @type Event.Custom
*/
TWEEN = 'tween',
/**
* @event end
* @description fires after the animation completes.
* @param {Event} ev The end event.
* @type Event.Custom
*/
END = 'end',
NODE = 'node',
PAUSED = 'paused',
REVERSE = 'reverse', // TODO: cleanup
ITERATION_COUNT = 'iterationCount',
NUM = Number;
var _running = {},
_timer;
Y.Anim = function() {
Y.Anim.superclass.constructor.apply(this, arguments);
Y.Anim._instances[Y.stamp(this)] = this;
};
Y.Anim.NAME = 'anim';
Y.Anim._instances = {};
/**
* Regex of properties that should use the default unit.
*
* @property RE_DEFAULT_UNIT
* @static
*/
Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i;
/**
* The default unit to use with properties that pass the RE_DEFAULT_UNIT test.
*
* @property DEFAULT_UNIT
* @static
*/
Y.Anim.DEFAULT_UNIT = 'px';
Y.Anim.DEFAULT_EASING = function (t, b, c, d) {
return c * t / d + b; // linear easing
};
/**
* Time in milliseconds passed to setInterval for frame processing
*
* @property intervalTime
* @default 20
* @static
*/
Y.Anim._intervalTime = 20;
/**
* Bucket for custom getters and setters
*
* @property behaviors
* @static
*/
Y.Anim.behaviors = {
left: {
get: function(anim, attr) {
return anim._getOffset(attr);
}
}
};
Y.Anim.behaviors.top = Y.Anim.behaviors.left;
/**
* The default setter to use when setting object properties.
*
* @property DEFAULT_SETTER
* @static
*/
Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) {
var node = anim._node,
domNode = node._node,
val = fn(elapsed, NUM(from), NUM(to) - NUM(from), duration);
if (domNode) {
if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) {
unit = unit || '';
node.setStyle(att, val + unit);
} else if ('attributes' in domNode && att in domNode.attributes) {
node.setAttribute(att, val);
} else if (att in domNode) {
domNode[att] = val;
}
} else if (node.set) {
node.set(att, val);
} else if (att in node) {
node[att] = val;
}
};
/**
* The default getter to use when getting object properties.
*
* @property DEFAULT_GETTER
* @static
*/
Y.Anim.DEFAULT_GETTER = function(anim, att) {
var node = anim._node,
domNode = node._node,
val = '';
if (domNode) {
if ('style' in domNode && (att in domNode.style || att in Y.DOM.CUSTOM_STYLES)) {
val = node.getComputedStyle(att);
} else if ('attributes' in domNode && att in domNode.attributes) {
val = node.getAttribute(att);
} else if (att in domNode) {
val = domNode[att];
}
} else if (node.get) {
val = node.get(att);
} else if (att in node) {
val = node[att];
}
return val;
};
Y.Anim.ATTRS = {
/**
* The object to be animated.
* @attribute node
* @type Node
*/
node: {
setter: function(node) {
if (node) {
if (typeof node == 'string' || node.nodeType) {
node = Y.one(node);
}
}
this._node = node;
if (!node) {
Y.log(node + ' is not a valid node', 'warn', 'Anim');
}
return node;
}
},
/**
* The length of the animation. Defaults to "1" (second).
* @attribute duration
* @type NUM
*/
duration: {
value: 1
},
/**
* The method that will provide values to the attribute(s) during the animation.
* Defaults to "Easing.easeNone".
* @attribute easing
* @type Function
*/
easing: {
value: Y.Anim.DEFAULT_EASING,
setter: function(val) {
if (typeof val === 'string' && Y.Easing) {
return Y.Easing[val];
}
}
},
/**
* The starting values for the animated properties.
*
* Fields may be strings, numbers, or functions.
* If a function is used, the return value becomes the from value.
* If no from value is specified, the DEFAULT_GETTER will be used.
* Supports any unit, provided it matches the "to" (or default)
* unit (e.g. `{width: '10em', color: 'rgb(0, 0, 0)', borderColor: '#ccc'}`).
*
* If using the default ('px' for length-based units), the unit may be omitted
* (e.g. `{width: 100}, borderColor: 'ccc'}`, which defaults to pixels
* and hex, respectively).
*
* @attribute from
* @type Object
*/
from: {},
/**
* The ending values for the animated properties.
*
* Fields may be strings, numbers, or functions.
* Supports any unit, provided it matches the "from" (or default)
* unit (e.g. `{width: '50%', color: 'red', borderColor: '#ccc'}`).
*
* If using the default ('px' for length-based units), the unit may be omitted
* (e.g. `{width: 100, borderColor: 'ccc'}`, which defaults to pixels
* and hex, respectively).
*
* @attribute to
* @type Object
*/
to: {},
/**
* Date stamp for the first frame of the animation.
* @attribute startTime
* @type Int
* @default 0
* @readOnly
*/
startTime: {
value: 0,
readOnly: true
},
/**
* Current time the animation has been running.
* @attribute elapsedTime
* @type Int
* @default 0
* @readOnly
*/
elapsedTime: {
value: 0,
readOnly: true
},
/**
* Whether or not the animation is currently running.
* @attribute running
* @type Boolean
* @default false
* @readOnly
*/
running: {
getter: function() {
return !!_running[Y.stamp(this)];
},
value: false,
readOnly: true
},
/**
* The number of times the animation should run
* @attribute iterations
* @type Int
* @default 1
*/
iterations: {
value: 1
},
/**
* The number of iterations that have occurred.
* Resets when an animation ends (reaches iteration count or stop() called).
* @attribute iterationCount
* @type Int
* @default 0
* @readOnly
*/
iterationCount: {
value: 0,
readOnly: true
},
/**
* How iterations of the animation should behave.
* Possible values are "normal" and "alternate".
* Normal will repeat the animation, alternate will reverse on every other pass.
*
* @attribute direction
* @type String
* @default "normal"
*/
direction: {
value: 'normal' // | alternate (fwd on odd, rev on even per spec)
},
/**
* Whether or not the animation is currently paused.
* @attribute paused
* @type Boolean
* @default false
* @readOnly
*/
paused: {
readOnly: true,
value: false
},
/**
* If true, animation begins from last frame
* @attribute reverse
* @type Boolean
* @default false
*/
reverse: {
value: false
}
};
/**
* Runs all animation instances.
* @method run
* @static
*/
Y.Anim.run = function() {
var instances = Y.Anim._instances;
for (var i in instances) {
if (instances[i].run) {
instances[i].run();
}
}
};
/**
* Pauses all animation instances.
* @method pause
* @static
*/
Y.Anim.pause = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].pause) {
_running[i].pause();
}
}
Y.Anim._stopTimer();
};
/**
* Stops all animation instances.
* @method stop
* @static
*/
Y.Anim.stop = function() {
for (var i in _running) { // stop timer if nothing running
if (_running[i].stop) {
_running[i].stop();
}
}
Y.Anim._stopTimer();
};
Y.Anim._startTimer = function() {
if (!_timer) {
_timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime);
}
};
Y.Anim._stopTimer = function() {
clearInterval(_timer);
_timer = 0;
};
/**
* Called per Interval to handle each animation frame.
* @method _runFrame
* @private
* @static
*/
Y.Anim._runFrame = function() {
var done = true;
for (var anim in _running) {
if (_running[anim]._runFrame) {
done = false;
_running[anim]._runFrame();
}
}
if (done) {
Y.Anim._stopTimer();
}
};
Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/;
var proto = {
/**
* Starts or resumes an animation.
* @method run
* @chainable
*/
run: function() {
if (this.get(PAUSED)) {
this._resume();
} else if (!this.get(RUNNING)) {
this._start();
}
return this;
},
/**
* Pauses the animation and
* freezes it in its current state and time.
* Calling run() will continue where it left off.
* @method pause
* @chainable
*/
pause: function() {
if (this.get(RUNNING)) {
this._pause();
}
return this;
},
/**
* Stops the animation and resets its time.
* @method stop
* @param {Boolean} finish If true, the animation will move to the last frame
* @chainable
*/
stop: function(finish) {
if (this.get(RUNNING) || this.get(PAUSED)) {
this._end(finish);
}
return this;
},
_added: false,
_start: function() {
this._set(START_TIME, new Date() - this.get(ELAPSED_TIME));
this._actualFrames = 0;
if (!this.get(PAUSED)) {
this._initAnimAttr();
}
_running[Y.stamp(this)] = this;
Y.Anim._startTimer();
this.fire(START);
},
_pause: function() {
this._set(START_TIME, null);
this._set(PAUSED, true);
delete _running[Y.stamp(this)];
/**
* @event pause
* @description fires when an animation is paused.
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('pause');
},
_resume: function() {
this._set(PAUSED, false);
_running[Y.stamp(this)] = this;
this._set(START_TIME, new Date() - this.get(ELAPSED_TIME));
Y.Anim._startTimer();
/**
* @event resume
* @description fires when an animation is resumed (run from pause).
* @param {Event} ev The pause event.
* @type Event.Custom
*/
this.fire('resume');
},
_end: function(finish) {
var duration = this.get('duration') * 1000;
if (finish) { // jump to last frame
this._runAttrs(duration, duration, this.get(REVERSE));
}
this._set(START_TIME, null);
this._set(ELAPSED_TIME, 0);
this._set(PAUSED, false);
delete _running[Y.stamp(this)];
this.fire(END, {elapsed: this.get(ELAPSED_TIME)});
},
_runFrame: function() {
var d = this._runtimeAttr.duration,
t = new Date() - this.get(START_TIME),
reverse = this.get(REVERSE),
done = (t >= d),
attribute,
setter;
this._runAttrs(t, d, reverse);
this._actualFrames += 1;
this._set(ELAPSED_TIME, t);
this.fire(TWEEN);
if (done) {
this._lastFrame();
}
},
_runAttrs: function(t, d, reverse) {
var attr = this._runtimeAttr,
customAttr = Y.Anim.behaviors,
easing = attr.easing,
lastFrame = d,
done = false,
attribute,
setter,
i;
if (t >= d) {
done = true;
}
if (reverse) {
t = d - t;
lastFrame = 0;
}
for (i in attr) {
if (attr[i].to) {
attribute = attr[i];
setter = (i in customAttr && 'set' in customAttr[i]) ?
customAttr[i].set : Y.Anim.DEFAULT_SETTER;
if (!done) {
setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit);
} else {
setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit);
}
}
}
},
_lastFrame: function() {
var iter = this.get('iterations'),
iterCount = this.get(ITERATION_COUNT);
iterCount += 1;
if (iter === 'infinite' || iterCount < iter) {
if (this.get('direction') === 'alternate') {
this.set(REVERSE, !this.get(REVERSE)); // flip it
}
/**
* @event iteration
* @description fires when an animation begins an iteration.
* @param {Event} ev The iteration event.
* @type Event.Custom
*/
this.fire('iteration');
} else {
iterCount = 0;
this._end();
}
this._set(START_TIME, new Date());
this._set(ITERATION_COUNT, iterCount);
},
_initAnimAttr: function() {
var from = this.get('from') || {},
to = this.get('to') || {},
attr = {
duration: this.get('duration') * 1000,
easing: this.get('easing')
},
customAttr = Y.Anim.behaviors,
node = this.get(NODE), // implicit attr init
unit, begin, end;
Y.each(to, function(val, name) {
if (typeof val === 'function') {
val = val.call(this, node);
}
begin = from[name];
if (begin === undefined) {
begin = (name in customAttr && 'get' in customAttr[name]) ?
customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name);
} else if (typeof begin === 'function') {
begin = begin.call(this, node);
}
var mFrom = Y.Anim.RE_UNITS.exec(begin);
var mTo = Y.Anim.RE_UNITS.exec(val);
begin = mFrom ? mFrom[1] : begin;
end = mTo ? mTo[1] : val;
unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units
if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) {
unit = Y.Anim.DEFAULT_UNIT;
}
if (!begin || !end) {
Y.error('invalid "from" or "to" for "' + name + '"', 'Anim');
return;
}
attr[name] = {
from: begin,
to: end,
unit: unit
};
}, this);
this._runtimeAttr = attr;
},
// TODO: move to computedStyle? (browsers dont agree on default computed offsets)
_getOffset: function(attr) {
var node = this._node,
val = node.getComputedStyle(attr),
get = (attr === 'left') ? 'getX': 'getY',
set = (attr === 'left') ? 'setX': 'setY';
if (val === 'auto') {
var position = node.getStyle('position');
if (position === 'absolute' || position === 'fixed') {
val = node[get]();
node[set](val);
} else {
val = 0;
}
}
return val;
},
destructor: function() {
delete Y.Anim._instances[Y.stamp(this)];
}
};
Y.extend(Y.Anim, Y.Base, proto);
}, '@VERSION@' ,{requires:['base-base', 'node-style']});
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom"));
else
root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _BootstrapTable = __webpack_require__(1);
var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable);
var _TableHeaderColumn = __webpack_require__(41);
var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn);
if (typeof window !== 'undefined') {
window.BootstrapTable = _BootstrapTable2['default'];
window.TableHeaderColumn = _TableHeaderColumn2['default'];
}
exports.BootstrapTable = _BootstrapTable2['default'];
exports.TableHeaderColumn = _TableHeaderColumn2['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-alert: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableHeader = __webpack_require__(4);
var _TableHeader2 = _interopRequireDefault(_TableHeader);
var _TableBody = __webpack_require__(8);
var _TableBody2 = _interopRequireDefault(_TableBody);
var _paginationPaginationList = __webpack_require__(29);
var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList);
var _toolbarToolBar = __webpack_require__(31);
var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar);
var _TableFilter = __webpack_require__(32);
var _TableFilter2 = _interopRequireDefault(_TableFilter);
var _storeTableDataStore = __webpack_require__(33);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _csv_export_util = __webpack_require__(35);
var _csv_export_util2 = _interopRequireDefault(_csv_export_util);
var _Filter = __webpack_require__(39);
var BootstrapTable = (function (_Component) {
_inherits(BootstrapTable, _Component);
function BootstrapTable(props) {
var _this = this;
_classCallCheck(this, BootstrapTable);
_get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props);
this.handleSort = function (order, sortField) {
if (_this.props.options.onSortChange) {
_this.props.options.onSortChange(sortField, order, _this.props);
}
var result = _this.store.sort(order, sortField).get();
_this.setState({
data: result
});
};
this.handlePaginationData = function (page, sizePerPage) {
var onPageChange = _this.props.options.onPageChange;
if (onPageChange) {
onPageChange(page, sizePerPage);
}
if (_this.isRemoteDataSource()) {
return;
}
var result = _this.store.page(page, sizePerPage).get();
_this.setState({
data: result,
currPage: page,
sizePerPage: sizePerPage
});
};
this.handleMouseLeave = function () {
if (_this.props.options.onMouseLeave) {
_this.props.options.onMouseLeave();
}
};
this.handleMouseEnter = function () {
if (_this.props.options.onMouseEnter) {
_this.props.options.onMouseEnter();
}
};
this.handleRowMouseOut = function (row, event) {
if (_this.props.options.onRowMouseOut) {
_this.props.options.onRowMouseOut(row, event);
}
};
this.handleRowMouseOver = function (row, event) {
if (_this.props.options.onRowMouseOver) {
_this.props.options.onRowMouseOver(row, event);
}
};
this.handleRowClick = function (row) {
if (_this.props.options.onRowClick) {
_this.props.options.onRowClick(row);
}
};
this.handleSelectAllRow = function (e) {
var isSelected = e.currentTarget.checked;
var selectedRowKeys = [];
var result = true;
if (_this.props.selectRow.onSelectAll) {
result = _this.props.selectRow.onSelectAll(isSelected, isSelected ? _this.store.get() : []);
}
if (typeof result === 'undefined' || result !== false) {
if (isSelected) {
selectedRowKeys = _this.store.getAllRowkey();
}
_this.store.setSelectedRowKey(selectedRowKeys);
_this.setState({ selectedRowKeys: selectedRowKeys });
}
};
this.handleShowOnlySelected = function () {
_this.store.ignoreNonSelected();
var result = undefined;
if (_this.props.pagination) {
result = _this.store.page(1, _this.state.sizePerPage).get();
} else {
result = _this.store.get();
}
_this.setState({
data: result,
currPage: 1
});
};
this.handleSelectRow = function (row, isSelected) {
var result = true;
var currSelected = _this.store.getSelectedRowKeys();
var rowKey = row[_this.store.getKeyField()];
var selectRow = _this.props.selectRow;
if (selectRow.onSelect) {
result = selectRow.onSelect(row, isSelected);
}
if (typeof result === 'undefined' || result !== false) {
if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {
currSelected = isSelected ? [rowKey] : [];
} else {
if (isSelected) {
currSelected.push(rowKey);
} else {
currSelected = currSelected.filter(function (key) {
return rowKey !== key;
});
}
}
_this.store.setSelectedRowKey(currSelected);
_this.setState({
selectedRowKeys: currSelected
});
}
};
this.handleAddRow = function (newObj) {
try {
_this.store.add(newObj);
} catch (e) {
return e;
}
_this._handleAfterAddingRow(newObj);
};
this.getPageByRowKey = function (rowKey) {
var sizePerPage = _this.state.sizePerPage;
var currentData = _this.store.getCurrentDisplayData();
var keyField = _this.store.getKeyField();
var result = currentData.findIndex(function (x) {
return x[keyField] === rowKey;
});
if (result > -1) {
return parseInt(result / sizePerPage, 10) + 1;
} else {
return result;
}
};
this.handleDropRow = function (rowKeys) {
var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys();
// add confirm before the delete action if that option is set.
if (dropRowKeys && dropRowKeys.length > 0) {
if (_this.props.options.handleConfirmDeleteRow) {
_this.props.options.handleConfirmDeleteRow(function () {
_this.deleteRow(dropRowKeys);
}, dropRowKeys);
} else if (confirm('Are you sure want delete?')) {
_this.deleteRow(dropRowKeys);
}
}
};
this.handleFilterData = function (filterObj) {
_this.store.filter(filterObj);
var sortObj = _this.store.getSortInfo();
if (sortObj) {
_this.store.sort(sortObj.order, sortObj.sortField);
}
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterColumnFilter) {
_this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result,
currPage: 1
});
};
this.handleExportCSV = function () {
var result = _this.store.getDataIgnoringPagination();
var keys = [];
_this.props.children.map(function (column) {
if (column.props.hidden === false) {
keys.push(column.props.dataField);
}
});
(0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName);
};
this.handleSearch = function (searchText) {
_this.store.search(searchText);
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterSearch) {
_this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result,
currPage: 1
});
};
this._scrollHeader = function (e) {
_this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft;
};
this._adjustTable = function () {
_this._adjustHeaderWidth();
_this._adjustHeight();
};
this._adjustHeaderWidth = function () {
var header = _this.refs.header.refs.header;
var headerContainer = _this.refs.header.refs.container;
var tbody = _this.refs.body.refs.tbody;
var firstRow = tbody.childNodes[0];
var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth;
var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0;
if (firstRow && _this.store.getDataNum()) {
var cells = firstRow.childNodes;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var computedStyle = getComputedStyle(cell);
var width = parseFloat(computedStyle.width.replace('px', ''));
if (_this.isIE) {
var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', ''));
var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', ''));
var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', ''));
var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', ''));
width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth;
}
var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0;
if (width <= 0) {
width = 120;
cell.width = width + lastPadding + 'px';
}
var result = width + lastPadding + 'px';
header.childNodes[i].style.width = result;
header.childNodes[i].style.minWidth = result;
}
}
};
this._adjustHeight = function () {
if (_this.props.height.indexOf('%') === -1) {
_this.refs.body.refs.container.style.height = parseFloat(_this.props.height, 10) - _this.refs.header.refs.container.offsetHeight + 'px';
}
};
this.isIE = false;
this._attachCellEditFunc();
if (_util2['default'].canUseDOM()) {
this.isIE = document.documentMode;
}
this.store = new _storeTableDataStore.TableDataStore(this.props.data.slice());
this.initTable(this.props);
if (this.filter) {
this.filter.on('onFilterChange', function (currentFilter) {
_this.handleFilterData(currentFilter);
});
}
if (this.props.selectRow && this.props.selectRow.selected) {
var copy = this.props.selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
}
this.state = {
data: this.getTableData(),
currPage: this.props.options.page || 1,
sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0],
selectedRowKeys: this.store.getSelectedRowKeys()
};
}
_createClass(BootstrapTable, [{
key: 'initTable',
value: function initTable(props) {
var _this2 = this;
var keyField = props.keyField;
var isKeyFieldDefined = typeof keyField === 'string' && keyField.length;
_react2['default'].Children.forEach(props.children, function (column) {
if (column.props.isKey) {
if (keyField) {
throw 'Error. Multiple key column be detected in TableHeaderColumn.';
}
keyField = column.props.dataField;
}
if (column.props.filter) {
// a column contains a filter
if (!_this2.filter) {
// first time create the filter on the BootstrapTable
_this2.filter = new _Filter.Filter();
}
// pass the filter to column with filter
column.props.filter.emitter = _this2.filter;
}
});
var colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) {
prev[curr.name] = curr;
return prev;
}, {});
if (!isKeyFieldDefined && !keyField) {
throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.';
}
this.store.setProps({
isPagination: props.pagination,
keyField: keyField,
colInfos: colInfos,
multiColumnSearch: props.multiColumnSearch,
remote: this.isRemoteDataSource()
});
}
}, {
key: 'getTableData',
value: function getTableData() {
var _props = this.props;
var options = _props.options;
var pagination = _props.pagination;
var result = [];
if (options.sortName && options.sortOrder) {
this.store.sort(options.sortOrder, options.sortName);
}
if (pagination) {
var page = undefined;
var sizePerPage = undefined;
if (this.store.isChangedPage()) {
sizePerPage = this.state.sizePerPage;
page = this.state.currPage;
} else {
sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0];
page = options.page || 1;
}
result = this.store.page(page, sizePerPage).get();
} else {
result = this.store.get();
}
return result;
}
}, {
key: 'getColumnsDescription',
value: function getColumnsDescription(_ref) {
var children = _ref.children;
return _react2['default'].Children.map(children, function (column, i) {
return {
name: column.props.dataField,
align: column.props.dataAlign,
sort: column.props.dataSort,
format: column.props.dataFormat,
formatExtraData: column.props.formatExtraData,
filterFormatted: column.props.filterFormatted,
editable: column.props.editable,
hidden: column.props.hidden,
searchable: column.props.searchable,
className: column.props.columnClassName,
width: column.props.width,
text: column.props.children,
sortFunc: column.props.sortFunc,
sortFuncExtraData: column.props.sortFuncExtraData,
index: i
};
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.initTable(nextProps);
var options = nextProps.options;
var selectRow = nextProps.selectRow;
this.store.setData(nextProps.data.slice());
var page = options.page || this.state.currPage;
var sizePerPage = options.sizePerPage || this.state.sizePerPage;
// #125
if (!options.page && page >= Math.ceil(nextProps.data.length / sizePerPage)) {
page = 1;
}
var sortInfo = this.store.getSortInfo();
var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined);
var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined);
if (sortField && sortOrder) this.store.sort(sortOrder, sortField);
var data = this.store.page(page, sizePerPage).get();
this.setState({
data: data,
currPage: page,
sizePerPage: sizePerPage
});
if (selectRow && selectRow.selected) {
// set default select rows to store.
var copy = selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
this.setState({
selectedRowKeys: copy
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this._adjustTable();
window.addEventListener('resize', this._adjustTable);
this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
window.removeEventListener('resize', this._adjustTable);
this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader);
if (this.filter) {
this.filter.removeAllListeners('onFilterChange');
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this._adjustTable();
this._attachCellEditFunc();
if (this.props.options.afterTableComplete) {
this.props.options.afterTableComplete();
}
}
}, {
key: '_attachCellEditFunc',
value: function _attachCellEditFunc() {
var cellEdit = this.props.cellEdit;
if (cellEdit) {
this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this);
if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) {
this.props.selectRow.clickToSelect = false;
}
}
}
/**
* Returns true if in the current configuration,
* the datagrid should load its data remotely.
*
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
}, {
key: 'isRemoteDataSource',
value: function isRemoteDataSource(props) {
return (props || this.props).remote;
}
}, {
key: 'render',
value: function render() {
var style = {
height: this.props.height,
maxHeight: this.props.maxHeight
};
var columns = this.getColumnsDescription(this.props);
var sortInfo = this.store.getSortInfo();
var pagination = this.renderPagination();
var toolBar = this.renderToolBar();
var tableFilter = this.renderTableFilter(columns);
var isSelectAll = this.isSelectAll();
var sortIndicator = this.props.options.sortIndicator;
if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-container' },
toolBar,
_react2['default'].createElement(
'div',
{ className: 'react-bs-table', ref: 'table', style: style,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave },
_react2['default'].createElement(
_TableHeader2['default'],
{
ref: 'header',
rowSelectType: this.props.selectRow.mode,
hideSelectColumn: this.props.selectRow.hideSelectColumn,
sortName: sortInfo ? sortInfo.sortField : undefined,
sortOrder: sortInfo ? sortInfo.order : undefined,
sortIndicator: sortIndicator,
onSort: this.handleSort,
onSelectAllRow: this.handleSelectAllRow,
bordered: this.props.bordered,
condensed: this.props.condensed,
isFiltered: this.filter ? true : false,
isSelectAll: isSelectAll },
this.props.children
),
_react2['default'].createElement(_TableBody2['default'], { ref: 'body',
style: style,
data: this.state.data,
columns: columns,
trClassName: this.props.trClassName,
striped: this.props.striped,
bordered: this.props.bordered,
hover: this.props.hover,
keyField: this.store.getKeyField(),
condensed: this.props.condensed,
selectRow: this.props.selectRow,
cellEdit: this.props.cellEdit,
selectedRowKeys: this.state.selectedRowKeys,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
noDataText: this.props.options.noDataText })
),
tableFilter,
pagination
);
}
}, {
key: 'isSelectAll',
value: function isSelectAll() {
var defaultSelectRowKeys = this.store.getSelectedRowKeys();
var allRowKeys = this.store.getAllRowkey();
if (defaultSelectRowKeys.length !== allRowKeys.length) {
return defaultSelectRowKeys.length === 0 ? false : 'indeterminate';
} else {
if (this.store.isEmpty()) {
return false;
}
return true;
}
}
}, {
key: 'cleanSelected',
value: function cleanSelected() {
this.store.setSelectedRowKey([]);
this.setState({
selectedRowKeys: []
});
}
}, {
key: 'handleEditCell',
value: function handleEditCell(newVal, rowIndex, colIndex) {
var _props$cellEdit = this.props.cellEdit;
var beforeSaveCell = _props$cellEdit.beforeSaveCell;
var afterSaveCell = _props$cellEdit.afterSaveCell;
var fieldName = undefined;
_react2['default'].Children.forEach(this.props.children, function (column, i) {
if (i === colIndex) {
fieldName = column.props.dataField;
return false;
}
});
if (beforeSaveCell) {
var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal);
if (!isValid && typeof isValid !== 'undefined') {
this.setState({
data: this.store.get()
});
return;
}
}
var result = this.store.edit(newVal, rowIndex, fieldName).get();
this.setState({
data: result
});
if (afterSaveCell) {
afterSaveCell(this.state.data[rowIndex], fieldName, newVal);
}
}
}, {
key: 'handleAddRowAtBegin',
value: function handleAddRowAtBegin(newObj) {
try {
this.store.addAtBegin(newObj);
} catch (e) {
return e;
}
this._handleAfterAddingRow(newObj);
}
}, {
key: 'getSizePerPage',
value: function getSizePerPage() {
return this.state.sizePerPage;
}
}, {
key: 'getCurrentPage',
value: function getCurrentPage() {
return this.state.currPage;
}
}, {
key: 'deleteRow',
value: function deleteRow(dropRowKeys) {
var result = undefined;
this.store.remove(dropRowKeys); // remove selected Row
this.store.setSelectedRowKey([]); // clear selected row key
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
var currPage = this.state.currPage;
if (currPage > currLastPage) currPage = currLastPage;
result = this.store.page(currPage, sizePerPage).get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys(),
currPage: currPage
});
} else {
result = this.store.get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys()
});
}
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
}
}, {
key: 'renderPagination',
value: function renderPagination() {
if (this.props.pagination) {
var dataSize = undefined;
if (this.isRemoteDataSource()) {
dataSize = this.props.fetchInfo.dataTotalSize;
} else {
dataSize = this.store.getDataNum();
}
var options = this.props.options;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-pagination' },
_react2['default'].createElement(_paginationPaginationList2['default'], {
ref: 'pagination',
currPage: this.state.currPage,
changePage: this.handlePaginationData,
sizePerPage: this.state.sizePerPage,
sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST,
paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE,
remote: this.isRemoteDataSource(),
dataSize: dataSize,
onSizePerPageList: options.onSizePerPageList,
prePage: options.prePage || _Const2['default'].PRE_PAGE,
nextPage: options.nextPage || _Const2['default'].NEXT_PAGE,
firstPage: options.firstPage || _Const2['default'].FIRST_PAGE,
lastPage: options.lastPage || _Const2['default'].LAST_PAGE })
);
}
return null;
}
}, {
key: 'renderToolBar',
value: function renderToolBar() {
var _props2 = this.props;
var selectRow = _props2.selectRow;
var insertRow = _props2.insertRow;
var deleteRow = _props2.deleteRow;
var search = _props2.search;
var children = _props2.children;
var enableShowOnlySelected = selectRow && selectRow.showOnlySelected;
if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) {
var columns = undefined;
if (Array.isArray(children)) {
columns = children.map(function (column) {
var props = column.props;
return {
name: props.children,
field: props.dataField,
// when you want same auto generate value and not allow edit, example ID field
autoValue: props.autoValue || false,
// for create editor, no params for column.editable() indicate that editor for new row
editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable,
format: props.dataFormat ? function (value) {
return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, '');
} : false
};
});
} else {
columns = [{
name: children.props.children,
field: children.props.dataField,
editable: children.props.editable
}];
}
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-tool-bar' },
_react2['default'].createElement(_toolbarToolBar2['default'], {
clearSearch: this.props.options.clearSearch,
searchDelayTime: this.props.options.searchDelayTime,
enableInsert: insertRow,
enableDelete: deleteRow,
enableSearch: search,
enableExportCSV: this.props.exportCSV,
enableShowOnlySelected: enableShowOnlySelected,
columns: columns,
searchPlaceholder: this.props.searchPlaceholder,
exportCSVText: this.props.options.exportCSVText,
ignoreEditable: this.props.options.ignoreEditable,
onAddRow: this.handleAddRow,
onDropRow: this.handleDropRow,
onSearch: this.handleSearch,
onExportCSV: this.handleExportCSV,
onShowOnlySelected: this.handleShowOnlySelected })
);
} else {
return null;
}
}
}, {
key: 'renderTableFilter',
value: function renderTableFilter(columns) {
if (this.props.columnFilter) {
return _react2['default'].createElement(_TableFilter2['default'], { columns: columns,
rowSelectType: this.props.selectRow.mode,
onFilter: this.handleFilterData });
} else {
return null;
}
}
}, {
key: '_handleAfterAddingRow',
value: function _handleAfterAddingRow(newObj) {
var result = undefined;
if (this.props.pagination) {
// if pagination is enabled and insert row be trigger, change to last page
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
result = this.store.page(currLastPage, sizePerPage).get();
this.setState({
data: result,
currPage: currLastPage
});
} else {
result = this.store.get();
this.setState({
data: result
});
}
if (this.props.options.afterInsertRow) {
this.props.options.afterInsertRow(newObj);
}
}
}]);
return BootstrapTable;
})(_react.Component);
BootstrapTable.propTypes = {
keyField: _react.PropTypes.string,
height: _react.PropTypes.string,
maxHeight: _react.PropTypes.string,
data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]),
remote: _react.PropTypes.bool, // remote data, default is false
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
pagination: _react.PropTypes.bool,
searchPlaceholder: _react.PropTypes.string,
selectRow: _react.PropTypes.shape({
mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]),
bgColor: _react.PropTypes.string,
selected: _react.PropTypes.array,
onSelect: _react.PropTypes.func,
onSelectAll: _react.PropTypes.func,
clickToSelect: _react.PropTypes.bool,
hideSelectColumn: _react.PropTypes.bool,
clickToSelectAndEditCell: _react.PropTypes.bool,
showOnlySelected: _react.PropTypes.bool
}),
cellEdit: _react.PropTypes.shape({
mode: _react.PropTypes.string,
blurToSave: _react.PropTypes.bool,
beforeSaveCell: _react.PropTypes.func,
afterSaveCell: _react.PropTypes.func
}),
insertRow: _react.PropTypes.bool,
deleteRow: _react.PropTypes.bool,
search: _react.PropTypes.bool,
columnFilter: _react.PropTypes.bool,
trClassName: _react.PropTypes.any,
options: _react.PropTypes.shape({
clearSearch: _react.PropTypes.bool,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
sortIndicator: _react.PropTypes.bool,
afterTableComplete: _react.PropTypes.func,
afterDeleteRow: _react.PropTypes.func,
afterInsertRow: _react.PropTypes.func,
afterSearch: _react.PropTypes.func,
afterColumnFilter: _react.PropTypes.func,
onRowClick: _react.PropTypes.func,
page: _react.PropTypes.number,
sizePerPageList: _react.PropTypes.array,
sizePerPage: _react.PropTypes.number,
paginationSize: _react.PropTypes.number,
onSortChange: _react.PropTypes.func,
onPageChange: _react.PropTypes.func,
onSizePerPageList: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
handleConfirmDeleteRow: _react.PropTypes.func,
prePage: _react.PropTypes.string,
nextPage: _react.PropTypes.string,
firstPage: _react.PropTypes.string,
lastPage: _react.PropTypes.string,
searchDelayTime: _react.PropTypes.number,
exportCSVText: _react.PropTypes.text,
ignoreEditable: _react.PropTypes.bool
}),
fetchInfo: _react.PropTypes.shape({
dataTotalSize: _react.PropTypes.number
}),
exportCSV: _react.PropTypes.bool,
csvFileName: _react.PropTypes.string
};
BootstrapTable.defaultProps = {
height: '100%',
maxHeight: undefined,
striped: false,
bordered: true,
hover: false,
condensed: false,
pagination: false,
searchPlaceholder: undefined,
selectRow: {
mode: _Const2['default'].ROW_SELECT_NONE,
bgColor: _Const2['default'].ROW_SELECT_BG_COLOR,
selected: [],
onSelect: undefined,
onSelectAll: undefined,
clickToSelect: false,
hideSelectColumn: false,
clickToSelectAndEditCell: false,
showOnlySelected: false
},
cellEdit: {
mode: _Const2['default'].CELL_EDIT_NONE,
blurToSave: false,
beforeSaveCell: undefined,
afterSaveCell: undefined
},
insertRow: false,
deleteRow: false,
search: false,
multiColumnSearch: false,
columnFilter: false,
trClassName: '',
options: {
clearSearch: false,
sortName: undefined,
sortOrder: undefined,
sortIndicator: true,
afterTableComplete: undefined,
afterDeleteRow: undefined,
afterInsertRow: undefined,
afterSearch: undefined,
afterColumnFilter: undefined,
onRowClick: undefined,
onMouseLeave: undefined,
onMouseEnter: undefined,
onRowMouseOut: undefined,
onRowMouseOver: undefined,
page: undefined,
sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST,
sizePerPage: undefined,
paginationSize: _Const2['default'].PAGINATION_SIZE,
onSizePerPageList: undefined,
noDataText: undefined,
handleConfirmDeleteRow: undefined,
prePage: _Const2['default'].PRE_PAGE,
nextPage: _Const2['default'].NEXT_PAGE,
firstPage: _Const2['default'].FIRST_PAGE,
lastPage: _Const2['default'].LAST_PAGE,
searchDelayTime: undefined,
exportCSVText: _Const2['default'].EXPORT_CSV_TEXT,
ignoreEditable: false
},
fetchInfo: {
dataTotalSize: 0
},
exportCSV: false,
csvFileName: undefined
};
exports['default'] = BootstrapTable;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = {
SORT_DESC: 'desc',
SORT_ASC: 'asc',
SIZE_PER_PAGE: 10,
NEXT_PAGE: '>',
LAST_PAGE: '>>',
PRE_PAGE: '<',
FIRST_PAGE: '<<',
ROW_SELECT_BG_COLOR: '',
ROW_SELECT_NONE: 'none',
ROW_SELECT_SINGLE: 'radio',
ROW_SELECT_MULTI: 'checkbox',
CELL_EDIT_NONE: 'none',
CELL_EDIT_CLICK: 'click',
CELL_EDIT_DBCLICK: 'dbclick',
SIZE_PER_PAGE_LIST: [10, 25, 30, 50],
PAGINATION_SIZE: 5,
NO_DATA_TEXT: 'There is no data to display',
SHOW_ONLY_SELECT: 'Show Selected Only',
SHOW_ALL: 'Show All',
EXPORT_CSV_TEXT: 'Export to CSV',
FILTER_DELAY: 500,
FILTER_TYPE: {
TEXT: 'TextFilter',
REGEX: 'RegexFilter',
SELECT: 'SelectFilter',
NUMBER: 'NumberFilter',
DATE: 'DateFilter',
CUSTOM: 'CustomFilter'
}
};
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _SelectRowHeaderColumn = __webpack_require__(7);
var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn);
var Checkbox = (function (_Component) {
_inherits(Checkbox, _Component);
function Checkbox() {
_classCallCheck(this, Checkbox);
_get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Checkbox, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.update(this.props.checked);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.update(props.checked);
}
}, {
key: 'update',
value: function update(checked) {
_reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate';
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('input', { className: 'react-bs-select-all',
type: 'checkbox',
checked: this.props.checked,
onChange: this.props.onChange });
}
}]);
return Checkbox;
})(_react.Component);
var TableHeader = (function (_Component2) {
_inherits(TableHeader, _Component2);
function TableHeader() {
_classCallCheck(this, TableHeader);
_get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(TableHeader, [{
key: 'render',
value: function render() {
var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper');
var tableClasses = (0, _classnames2['default'])('table', 'table-hover', {
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed
});
var selectRowHeaderCol = null;
if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader();
this._attachClearSortCaretFunc();
return _react2['default'].createElement(
'div',
{ ref: 'container', className: containerClasses },
_react2['default'].createElement(
'table',
{ className: tableClasses },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ ref: 'header' },
selectRowHeaderCol,
this.props.children
)
)
)
);
}
}, {
key: 'renderSelectRowHeader',
value: function renderSelectRowHeader() {
if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) {
return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null);
} else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
return _react2['default'].createElement(
_SelectRowHeaderColumn2['default'],
null,
_react2['default'].createElement(Checkbox, {
onChange: this.props.onSelectAllRow,
checked: this.props.isSelectAll })
);
} else {
return null;
}
}
}, {
key: '_attachClearSortCaretFunc',
value: function _attachClearSortCaretFunc() {
var _props = this.props;
var sortIndicator = _props.sortIndicator;
var children = _props.children;
var sortName = _props.sortName;
var sortOrder = _props.sortOrder;
var onSort = _props.onSort;
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var _children$i$props = children[i].props;
var dataField = _children$i$props.dataField;
var dataSort = _children$i$props.dataSort;
var sort = dataSort && dataField === sortName ? sortOrder : undefined;
this.props.children[i] = _react2['default'].cloneElement(children[i], { key: i, onSort: onSort, sort: sort, sortIndicator: sortIndicator });
}
} else {
var _children$props = children.props;
var dataField = _children$props.dataField;
var dataSort = _children$props.dataSort;
var sort = dataSort && dataField === sortName ? sortOrder : undefined;
this.props.children = _react2['default'].cloneElement(children, { key: 0, onSort: onSort, sort: sort, sortIndicator: sortIndicator });
}
}
}]);
return TableHeader;
})(_react.Component);
TableHeader.propTypes = {
rowSelectType: _react.PropTypes.string,
onSort: _react.PropTypes.func,
onSelectAllRow: _react.PropTypes.func,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
hideSelectColumn: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
isFiltered: _react.PropTypes.bool,
isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]),
sortIndicator: _react.PropTypes.bool
};
exports['default'] = TableHeader;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_5__;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var SelectRowHeaderColumn = (function (_Component) {
_inherits(SelectRowHeaderColumn, _Component);
function SelectRowHeaderColumn() {
_classCallCheck(this, SelectRowHeaderColumn);
_get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(SelectRowHeaderColumn, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(
'th',
{ style: { textAlign: 'center' } },
this.props.children
);
}
}]);
return SelectRowHeaderColumn;
})(_react.Component);
SelectRowHeaderColumn.propTypes = {
children: _react.PropTypes.node
};
exports['default'] = SelectRowHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableRow = __webpack_require__(9);
var _TableRow2 = _interopRequireDefault(_TableRow);
var _TableColumn = __webpack_require__(10);
var _TableColumn2 = _interopRequireDefault(_TableColumn);
var _TableEditColumn = __webpack_require__(11);
var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var isFun = function isFun(obj) {
return obj && typeof obj === 'function';
};
var TableBody = (function (_Component) {
_inherits(TableBody, _Component);
function TableBody(props) {
var _this = this;
_classCallCheck(this, TableBody);
_get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props);
this.handleRowMouseOut = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOut(targetRow, event);
};
this.handleRowMouseOver = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOver(targetRow, event);
};
this.handleRowClick = function (rowIndex) {
var selectedRow = undefined;
var _props = _this.props;
var data = _props.data;
var onRowClick = _props.onRowClick;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
}
});
onRowClick(selectedRow);
};
this.handleSelectRow = function (rowIndex, isSelected) {
var selectedRow = undefined;
var _props2 = _this.props;
var data = _props2.data;
var onSelectRow = _props2.onSelectRow;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
return false;
}
});
onSelectRow(selectedRow, isSelected);
};
this.handleSelectRowColumChange = function (e) {
if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) {
_this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked);
}
};
this.handleEditCell = function (rowIndex, columnIndex) {
_this.editing = true;
if (_this._isSelectRowDefined()) {
columnIndex--;
if (_this.props.selectRow.hideSelectColumn) columnIndex++;
}
rowIndex--;
var stateObj = {
currEditCell: {
rid: rowIndex,
cid: columnIndex
}
};
if (_this.props.selectRow.clickToSelectAndEditCell && _this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_DBCLICK) {
var selected = _this.props.selectedRowKeys.indexOf(_this.props.data[rowIndex][_this.props.keyField]) !== -1;
_this.handleSelectRow(rowIndex + 1, !selected);
}
_this.setState(stateObj);
};
this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) {
_this.setState({ currEditCell: null });
if (newVal !== null) {
_this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex);
}
};
this.state = {
currEditCell: null
};
this.editing = false;
}
_createClass(TableBody, [{
key: 'render',
value: function render() {
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-hover': this.props.hover,
'table-condensed': this.props.condensed
});
var isSelectRowDefined = this._isSelectRowDefined();
var tableHeader = this.renderTableHeader(isSelectRowDefined);
var tableRows = this.props.data.map(function (data, r) {
var tableColumns = this.props.columns.map(function (column, i) {
var fieldValue = data[column.name];
if (this.editing && column.name !== this.props.keyField && // Key field can't be edit
column.editable && // column is editable? default is true, user can set it false
this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) {
var editable = column.editable;
var format = column.format ? function (value) {
return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, '');
} : false;
if (isFun(column.editable)) {
editable = column.editable(fieldValue, data, r, i);
}
return _react2['default'].createElement(
_TableEditColumn2['default'],
{
completeEdit: this.handleCompleteEditCell,
// add by bluespring for column editor customize
editable: editable,
format: column.format ? format : false,
key: i,
blurToSave: this.props.cellEdit.blurToSave,
rowIndex: r,
colIndex: i },
fieldValue
);
} else {
// add by bluespring for className customize
var columnChild = fieldValue;
var tdClassName = column.className;
if (isFun(column.className)) {
tdClassName = column.className(fieldValue, data, r, i);
}
if (typeof column.format !== 'undefined') {
var formattedValue = column.format(fieldValue, data, column.formatExtraData);
if (!_react2['default'].isValidElement(formattedValue)) {
columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } });
} else {
columnChild = formattedValue;
}
}
return _react2['default'].createElement(
_TableColumn2['default'],
{ key: i,
dataAlign: column.align,
className: tdClassName,
cellEdit: this.props.cellEdit,
hidden: column.hidden,
onEdit: this.handleEditCell,
width: column.width },
columnChild
);
}
}, this);
var selected = this.props.selectedRowKeys.indexOf(data[this.props.keyField]) !== -1;
var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected) : null;
// add by bluespring for className customize
var trClassName = this.props.trClassName;
if (isFun(this.props.trClassName)) {
trClassName = this.props.trClassName(data, r);
}
return _react2['default'].createElement(
_TableRow2['default'],
{ isSelected: selected, key: r, className: trClassName,
selectRow: isSelectRowDefined ? this.props.selectRow : undefined,
enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow },
selectRowColumn,
tableColumns
);
}, this);
if (tableRows.length === 0) {
tableRows.push(_react2['default'].createElement(
_TableRow2['default'],
{ key: '##table-empty##' },
_react2['default'].createElement(
'td',
{ colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0),
className: 'react-bs-table-no-data' },
this.props.noDataText || _Const2['default'].NO_DATA_TEXT
)
));
}
this.editing = false;
return _react2['default'].createElement(
'div',
{ ref: 'container', className: 'react-bs-container-body', style: this.props.style },
_react2['default'].createElement(
'table',
{ className: tableClasses },
tableHeader,
_react2['default'].createElement(
'tbody',
{ ref: 'tbody' },
tableRows
)
)
);
}
}, {
key: 'renderTableHeader',
value: function renderTableHeader(isSelectRowDefined) {
var selectRowHeader = null;
if (isSelectRowDefined) {
var style = {
width: 30,
minWidth: 30
};
if (!this.props.selectRow.hideSelectColumn) {
selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 });
}
}
var theader = this.props.columns.map(function (column, i) {
var width = column.width === null ? column.width : parseInt(column.width, 10);
var style = {
display: column.hidden ? 'none' : null,
width: width,
minWidth: width
/** add min-wdth to fix user assign column width
not eq offsetWidth in large column table **/
};
return _react2['default'].createElement('col', { style: style, key: i, className: column.className });
});
return _react2['default'].createElement(
'colgroup',
{ ref: 'header' },
selectRowHeader,
theader
);
}
}, {
key: 'renderSelectRowColumn',
value: function renderSelectRowColumn(selected) {
if (this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {
return _react2['default'].createElement(
_TableColumn2['default'],
{ dataAlign: 'center' },
_react2['default'].createElement('input', { type: 'radio', checked: selected,
onChange: this.handleSelectRowColumChange })
);
} else {
return _react2['default'].createElement(
_TableColumn2['default'],
{ dataAlign: 'center' },
_react2['default'].createElement('input', { type: 'checkbox', checked: selected,
onChange: this.handleSelectRowColumChange })
);
}
}
}, {
key: '_isSelectRowDefined',
value: function _isSelectRowDefined() {
return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI;
}
}]);
return TableBody;
})(_react.Component);
TableBody.propTypes = {
data: _react.PropTypes.array,
columns: _react.PropTypes.array,
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
keyField: _react.PropTypes.string,
selectedRowKeys: _react.PropTypes.array,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
style: _react.PropTypes.object
};
exports['default'] = TableBody;
module.exports = exports['default'];
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var TableRow = (function (_Component) {
_inherits(TableRow, _Component);
function TableRow(props) {
var _this = this;
_classCallCheck(this, TableRow);
_get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props);
this.rowClick = function (e) {
if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') {
(function () {
var rowIndex = e.currentTarget.rowIndex + 1;
if (_this.props.selectRow) {
if (_this.props.selectRow.clickToSelect) {
_this.props.onSelectRow(rowIndex, !_this.props.isSelected);
} else if (_this.props.selectRow.clickToSelectAndEditCell) {
_this.clickNum++;
/** if clickToSelectAndEditCell is enabled,
* there should be a delay to prevent a selection changed when
* user dblick to edit cell on same row but different cell
**/
setTimeout(function () {
if (_this.clickNum === 1) {
_this.props.onSelectRow(rowIndex, !_this.props.isSelected);
}
_this.clickNum = 0;
}, 200);
}
}
if (_this.props.onRowClick) _this.props.onRowClick(rowIndex);
})();
}
};
this.rowMouseOut = function (e) {
if (_this.props.onRowMouseOut) {
_this.props.onRowMouseOut(e.currentTarget.rowIndex, e);
}
};
this.rowMouseOver = function (e) {
if (_this.props.onRowMouseOver) {
_this.props.onRowMouseOver(e.currentTarget.rowIndex, e);
}
};
this.clickNum = 0;
}
_createClass(TableRow, [{
key: 'render',
value: function render() {
this.clickNum = 0;
var trCss = {
style: {
backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null
},
className: (this.props.isSelected && this.props.selectRow.className ? this.props.selectRow.className : '') + (this.props.className || '')
};
if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) {
return _react2['default'].createElement(
'tr',
_extends({}, trCss, {
onMouseOver: this.rowMouseOver,
onMouseOut: this.rowMouseOut,
onClick: this.rowClick }),
this.props.children
);
} else {
return _react2['default'].createElement(
'tr',
trCss,
this.props.children
);
}
}
}]);
return TableRow;
})(_react.Component);
TableRow.propTypes = {
isSelected: _react.PropTypes.bool,
enableCellEdit: _react.PropTypes.bool,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
onRowMouseOut: _react.PropTypes.func,
onRowMouseOver: _react.PropTypes.func
};
TableRow.defaultProps = {
onRowClick: undefined
};
exports['default'] = TableRow;
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TableColumn = (function (_Component) {
_inherits(TableColumn, _Component);
function TableColumn(props) {
var _this = this;
_classCallCheck(this, TableColumn);
_get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props);
this.handleCellEdit = function (e) {
if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
if (document.selection && document.selection.empty) {
document.selection.empty();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
_this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex);
};
}
/* eslint no-unused-vars: [0, { "args": "after-used" }] */
_createClass(TableColumn, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var children = this.props.children;
var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString();
if (shouldUpdated) {
return shouldUpdated;
}
if (typeof children === 'object' && children !== null && children.props !== null) {
if (children.props.type === 'checkbox' || children.props.type === 'radio') {
shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked;
} else {
shouldUpdated = true;
}
} else {
shouldUpdated = shouldUpdated || children !== nextProps.children;
}
if (shouldUpdated) {
return shouldUpdated;
}
if (!(this.props.cellEdit && nextProps.cellEdit)) {
return false;
} else {
return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode;
}
}
}, {
key: 'render',
value: function render() {
var tdStyle = {
textAlign: this.props.dataAlign,
display: this.props.hidden ? 'none' : null
};
var opts = {};
if (this.props.cellEdit) {
if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) {
opts.onClick = this.handleCellEdit;
} else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
opts.onDoubleClick = this.handleCellEdit;
}
}
return _react2['default'].createElement(
'td',
_extends({ style: tdStyle, className: this.props.className }, opts),
this.props.children
);
}
}]);
return TableColumn;
})(_react.Component);
TableColumn.propTypes = {
dataAlign: _react.PropTypes.string,
hidden: _react.PropTypes.bool,
className: _react.PropTypes.string,
children: _react.PropTypes.node
};
TableColumn.defaultProps = {
dataAlign: 'left',
hidden: false,
className: ''
};
exports['default'] = TableColumn;
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableEditColumn = (function (_Component) {
_inherits(TableEditColumn, _Component);
function TableEditColumn(props) {
var _this = this;
_classCallCheck(this, TableEditColumn);
_get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props);
this.handleKeyPress = function (e) {
if (e.keyCode === 13) {
// Pressed ENTER
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
} else if (e.keyCode === 27) {
_this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex);
}
};
this.handleBlur = function (e) {
if (_this.props.blurToSave) {
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
}
};
this.timeouteClear = 0;
this.state = {
shakeEditor: false
};
}
_createClass(TableEditColumn, [{
key: 'validator',
value: function validator(value) {
var ts = this;
if (ts.props.editable.validator) {
var valid = ts.props.editable.validator(value);
if (!valid) {
ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel');
var input = ts.refs.inputRef;
// animate input
ts.clearTimeout();
ts.setState({ shakeEditor: true });
ts.timeouteClear = setTimeout(function () {
ts.setState({ shakeEditor: false });
}, 300);
input.focus();
return false;
}
}
return true;
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear !== 0) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs.inputRef.focus();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var editable = _props.editable;
var format = _props.format;
var children = _props.children;
var shakeEditor = this.state.shakeEditor;
var attr = {
ref: 'inputRef',
onKeyDown: this.handleKeyPress,
onBlur: this.handleBlur
};
// put placeholder if exist
editable.placeholder && (attr.placeholder = editable.placeholder);
var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor });
return _react2['default'].createElement(
'td',
{ ref: 'td', style: { position: 'relative' } },
(0, _Editor2['default'])(editable, attr, format, editorClass, children || ''),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' })
);
}
}, {
key: '_getCheckBoxValue',
value: function _getCheckBoxValue(e) {
var value = '';
var values = e.currentTarget.value.split(':');
value = e.currentTarget.checked ? values[0] : values[1];
return value;
}
}]);
return TableEditColumn;
})(_react.Component);
TableEditColumn.propTypes = {
completeEdit: _react.PropTypes.func,
rowIndex: _react.PropTypes.number,
colIndex: _react.PropTypes.number,
blurToSave: _react.PropTypes.bool,
editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
children: _react.PropTypes.node
};
exports['default'] = TableEditColumn;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) {
if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') {
// simple declare
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (!editable) {
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
disabled: 'disabled',
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable.type) {
// standard declare
// put style if exist
editable.style && (attr.style = editable.style);
// put class if exist
attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : '');
if (editable.type === 'select') {
// process select input
var options = [];
var values = editable.options.values;
if (Array.isArray(values)) {
(function () {
// only can use arrray data for options
var rowValue = undefined;
options = values.map(function (d, i) {
rowValue = format ? format(d) : d;
return _react2['default'].createElement(
'option',
{ key: 'option' + i, value: d },
rowValue
);
});
})();
}
return _react2['default'].createElement(
'select',
_extends({}, attr, { defaultValue: defaultValue }),
options
);
} else if (editable.type === 'textarea') {
var _ret2 = (function () {
// process textarea input
// put other if exist
editable.cols && (attr.cols = editable.cols);
editable.rows && (attr.rows = editable.rows);
var saveBtn = undefined;
var keyUpHandler = attr.onKeyDown;
if (keyUpHandler) {
attr.onKeyDown = function (e) {
if (e.keyCode !== 13) {
// not Pressed ENTER
keyUpHandler(e);
}
};
saveBtn = _react2['default'].createElement(
'button',
{
className: 'btn btn-info btn-xs textarea-save-btn',
onClick: keyUpHandler },
'save'
);
}
return {
v: _react2['default'].createElement(
'div',
null,
_react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })),
saveBtn
)
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
} else if (editable.type === 'checkbox') {
var values = 'true:false';
if (editable.options && editable.options.values) {
// values = editable.options.values.split(':');
values = editable.options.values;
}
attr.className = attr.className.replace('form-control', '');
attr.className += ' checkbox pull-right';
var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false;
return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox',
value: values, defaultChecked: checked }));
} else {
// process other input type. as password,url,email...
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue }));
}
}
// default return for other case of editable
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text',
className: (editorClass || '') + ' form-control editor edit-text' }));
};
exports['default'] = editor;
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactToastr = __webpack_require__(14);
var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation);
var Notification = (function (_Component) {
_inherits(Notification, _Component);
function Notification() {
_classCallCheck(this, Notification);
_get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Notification, [{
key: 'notice',
// allow type is success,info,warning,error
value: function notice(type, msg, title) {
this.refs.toastr[type](msg, title, {
mode: 'single',
timeOut: 5000,
extendedTimeOut: 1000,
showAnimation: 'animated bounceIn',
hideAnimation: 'animated bounceOut'
});
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr',
toastMessageFactory: ToastrMessageFactory,
id: 'toast-container',
className: 'toast-top-right' });
}
}]);
return Notification;
})(_react.Component);
exports['default'] = Notification;
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToastMessage = exports.ToastContainer = undefined;
var _ToastContainer = __webpack_require__(15);
var _ToastContainer2 = _interopRequireDefault(_ToastContainer);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.ToastContainer = _ToastContainer2.default;
exports.ToastMessage = _ToastMessage2.default;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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; }; }();
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ToastContainer = function (_Component) {
_inherits(ToastContainer, _Component);
function ToastContainer() {
var _Object$getPrototypeO;
var _temp, _this, _ret;
_classCallCheck(this, ToastContainer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
toasts: [],
toastId: 0,
previousMessage: null
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(ToastContainer, [{
key: "error",
value: function error(message, title, optionsOverride) {
this._notify(this.props.toastType.error, message, title, optionsOverride);
}
}, {
key: "info",
value: function info(message, title, optionsOverride) {
this._notify(this.props.toastType.info, message, title, optionsOverride);
}
}, {
key: "success",
value: function success(message, title, optionsOverride) {
this._notify(this.props.toastType.success, message, title, optionsOverride);
}
}, {
key: "warning",
value: function warning(message, title, optionsOverride) {
this._notify(this.props.toastType.warning, message, title, optionsOverride);
}
}, {
key: "clear",
value: function clear() {
var _this2 = this;
Object.keys(this.refs).forEach(function (key) {
_this2.refs[key].hideToast(false);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return _react2.default.createElement(
"div",
_extends({}, this.props, { "aria-live": "polite", role: "alert" }),
this.state.toasts.map(function (toast) {
return _this3.props.toastMessageFactory(toast);
})
);
}
}, {
key: "_notify",
value: function _notify(type, message, title) {
var _this4 = this;
var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
if (this.props.preventDuplicates) {
if (this.state.previousMessage === message) {
return;
}
}
var key = this.state.toastId++;
var toastId = key;
var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
$merge: {
type: type,
title: title,
message: message,
toastId: toastId,
key: key,
ref: "toasts__" + key,
handleOnClick: function handleOnClick(e) {
if ("function" === typeof optionsOverride.handleOnClick) {
optionsOverride.handleOnClick();
}
return _this4._handle_toast_on_click(e);
},
handleRemove: this._handle_toast_remove.bind(this)
}
});
var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);
var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
toasts: toastOperation,
previousMessage: { $set: message }
});
this.setState(nextState);
}
}, {
key: "_handle_toast_on_click",
value: function _handle_toast_on_click(event) {
this.props.onClick(event);
if (event.defaultPrevented) {
return;
}
event.preventDefault();
event.stopPropagation();
}
}, {
key: "_handle_toast_remove",
value: function _handle_toast_remove(toastId) {
var _this5 = this;
var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
this.state.toasts[operationName](function (found, toast, index) {
if (found || toast.toastId !== toastId) {
return false;
}
_this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {
toasts: { $splice: [[index, 1]] }
}));
return true;
}, false);
}
}]);
return ToastContainer;
}(_react.Component);
ToastContainer.defaultProps = {
toastType: {
error: "error",
info: "info",
success: "success",
warning: "warning"
},
id: "toast-container",
toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),
preventDuplicates: false,
newestOnTop: true,
onClick: function onClick() {}
};
exports.default = ToastContainer;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(17);
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var assign = __webpack_require__(19);
var keyOf = __webpack_require__(20);
var invariant = __webpack_require__(21);
var hasOwnProperty = ({}).hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({ $push: null });
var COMMAND_UNSHIFT = keyOf({ $unshift: null });
var COMMAND_SPLICE = keyOf({ $splice: null });
var COMMAND_SET = keyOf({ $set: null });
var COMMAND_MERGE = keyOf({ $merge: null });
var COMMAND_APPLY = keyOf({ $apply: null });
var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function (command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined;
var specValue = spec[command];
!Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined;
}
function update(value, spec) {
!(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined;
if (hasOwnProperty.call(spec, COMMAND_SET)) {
!(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined;
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
!(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined;
!(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined;
assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function (item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function (item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined;
!Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
spec[COMMAND_SPLICE].forEach(function (args) {
!Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
!(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined;
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 18 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
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');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 19 */
/***/ function(module, exports) {
/**
* Copyright 2014-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.jQuery = exports.animation = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _animationMixin = __webpack_require__(23);
var _animationMixin2 = _interopRequireDefault(_animationMixin);
var _jQueryMixin = __webpack_require__(28);
var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function noop() {}
var ToastMessageSpec = {
displayName: "ToastMessage",
getDefaultProps: function getDefaultProps() {
var iconClassNames = {
error: "toast-error",
info: "toast-info",
success: "toast-success",
warning: "toast-warning"
};
return {
className: "toast",
iconClassNames: iconClassNames,
titleClassName: "toast-title",
messageClassName: "toast-message",
tapToDismiss: true,
closeButton: false
};
},
handleOnClick: function handleOnClick(event) {
this.props.handleOnClick(event);
if (this.props.tapToDismiss) {
this.hideToast(true);
}
},
_handle_close_button_click: function _handle_close_button_click(event) {
event.stopPropagation();
this.hideToast(true);
},
_handle_remove: function _handle_remove() {
this.props.handleRemove(this.props.toastId);
},
_render_close_button: function _render_close_button() {
return this.props.closeButton ? _react2.default.createElement("button", {
className: "toast-close-button", role: "button",
onClick: this._handle_close_button_click,
dangerouslySetInnerHTML: { __html: "×" }
}) : false;
},
_render_title_element: function _render_title_element() {
return this.props.title ? _react2.default.createElement(
"div",
{ className: this.props.titleClassName },
this.props.title
) : false;
},
_render_message_element: function _render_message_element() {
return this.props.message ? _react2.default.createElement(
"div",
{ className: this.props.messageClassName },
this.props.message
) : false;
},
render: function render() {
var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type];
return _react2.default.createElement(
"div",
{
className: (0, _classnames2.default)(this.props.className, iconClassName),
style: this.props.style,
onClick: this.handleOnClick,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave
},
this._render_close_button(),
this._render_title_element(),
this._render_message_element()
);
}
};
var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.animation" },
mixins: { $set: [_animationMixin2.default] }
}));
var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.jQuery" },
mixins: { $set: [_jQueryMixin2.default] }
}));
/*
* assign default noop functions
*/
ToastMessageSpec.handleMouseEnter = noop;
ToastMessageSpec.handleMouseLeave = noop;
ToastMessageSpec.hideToast = noop;
var ToastMessage = _react2.default.createClass(ToastMessageSpec);
ToastMessage.animation = animation;
ToastMessage.jQuery = jQuery;
exports.default = ToastMessage;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CSSCore = __webpack_require__(24);
var _CSSCore2 = _interopRequireDefault(_CSSCore);
var _ReactTransitionEvents = __webpack_require__(26);
var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TICK = 17;
var toString = Object.prototype.toString;
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate)
showAnimation: "animated bounceIn", // or other animations from animate.css
hideAnimation: "animated bounceOut",
timeOut: 5000,
extendedTimeOut: 1000
};
},
componentWillMount: function componentWillMount() {
this.classNameQueue = [];
this.isHiding = false;
this.intervalId = null;
},
componentDidMount: function componentDidMount() {
var _this = this;
this._is_mounted = true;
this._show();
var node = _reactDom2.default.findDOMNode(this);
var onHideComplete = function onHideComplete() {
if (_this.isHiding) {
_this._set_is_hiding(false);
_ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete);
_this._handle_remove();
}
};
_ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
componentWillUnmount: function componentWillUnmount() {
this._is_mounted = false;
if (this.intervalId) {
clearTimeout(this.intervalId);
}
},
_set_transition: function _set_transition(hide) {
var animationType = hide ? "leave" : "enter";
var node = _reactDom2.default.findDOMNode(this);
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
_CSSCore2.default.addClass(node, className);
// Need to do this to actually trigger a transition.
this._queue_class(activeClassName);
},
_clear_transition: function _clear_transition(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animationType = hide ? "leave" : "enter";
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
},
_set_animation: function _set_animation(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animations = this._get_animation_classes(hide);
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
animations.forEach(function (anim) {
_CSSCore2.default.removeClass(node, anim);
});
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
animations.forEach(function (anim) {
_CSSCore2.default.addClass(node, anim);
});
},
_get_animation_classes: function _get_animation_classes(hide) {
var animations = hide ? this.props.hideAnimation : this.props.showAnimation;
if ("[object Array]" === toString.call(animations)) {
return animations;
} else if ("string" === typeof animations) {
return animations.split(" ");
}
},
_clear_animation: function _clear_animation(hide) {
var _this2 = this;
var animations = this._get_animation_classes(hide);
animations.forEach(function (animation) {
_CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation);
});
},
_queue_class: function _queue_class(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this._flush_class_name_queue, TICK);
}
},
_flush_class_name_queue: function _flush_class_name_queue() {
if (this._is_mounted) {
this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this)));
}
this.classNameQueue.length = 0;
this.timeout = null;
},
_show: function _show() {
if (this.props.transition) {
this._set_transition();
} else if (this.props.showAnimation) {
this._set_animation();
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.intervalId);
this._set_interval_id(null);
if (this.isHiding) {
this._set_is_hiding(false);
if (this.props.hideAnimation) {
this._clear_animation(true);
} else if (this.props.transition) {
this._clear_transition(true);
}
}
},
handleMouseLeave: function handleMouseLeave() {
if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.isHiding || this.intervalId === null && !override) {
return;
}
this._set_is_hiding(true);
if (this.props.transition) {
this._set_transition(true);
} else if (this.props.hideAnimation) {
this._set_animation(true);
} else {
this._handle_remove();
}
},
_set_interval_id: function _set_interval_id(intervalId) {
this.intervalId = intervalId;
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.isHiding = isHiding;
}
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CSSCore
* @typechecks
*/
'use strict';
var invariant = __webpack_require__(25);
/**
* The CSSCore module specifies the API (and implements most of the methods)
* that should be used when dealing with the display of elements (via their
* CSS classes and visibility on screen. It is an API focused on mutating the
* display and not reading it as no logical state should be encoded in the
* display of elements.
*/
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function (element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @return {boolean} true if the element has the class, false if not
*/
hasClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined;
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(27);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
/***/ },
/* 27 */
/***/ function(module, exports) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call_show_method($node, props) {
$node[props.showMethod]({
duration: props.showDuration,
easing: props.showEasing
});
}
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
style: {
display: "none" },
// effective $.hide()
showMethod: "fadeIn", // slideDown, and show are built into jQuery
showDuration: 300,
showEasing: "swing", // and linear are built into jQuery
hideMethod: "fadeOut",
hideDuration: 1000,
hideEasing: "swing",
//
timeOut: 5000,
extendedTimeOut: 1000
};
},
getInitialState: function getInitialState() {
return {
intervalId: null,
isHiding: false
};
},
componentDidMount: function componentDidMount() {
call_show_method(this._get_$_node(), this.props);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.state.intervalId);
this._set_interval_id(null);
this._set_is_hiding(false);
call_show_method(this._get_$_node().stop(true, true), this.props);
},
handleMouseLeave: function handleMouseLeave() {
if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.state.isHiding || this.state.intervalId === null && !override) {
return;
}
this.setState({ isHiding: true });
this._get_$_node()[this.props.hideMethod]({
duration: this.props.hideDuration,
easing: this.props.hideEasing,
complete: this._handle_remove
});
},
_get_$_node: function _get_$_node() {
/* eslint-disable no-undef */
return jQuery(_reactDom2.default.findDOMNode(this));
/* eslint-enable no-undef */
},
_set_interval_id: function _set_interval_id(intervalId) {
this.setState({
intervalId: intervalId
});
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.setState({
isHiding: isHiding
});
}
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _PageButtonJs = __webpack_require__(30);
var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var PaginationList = (function (_Component) {
_inherits(PaginationList, _Component);
function PaginationList() {
var _this = this;
_classCallCheck(this, PaginationList);
_get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments);
this.changePage = function (page) {
var _props = _this.props;
var prePage = _props.prePage;
var currPage = _props.currPage;
var nextPage = _props.nextPage;
var lastPage = _props.lastPage;
var firstPage = _props.firstPage;
var sizePerPage = _props.sizePerPage;
if (page === prePage) {
page = currPage - 1 < 1 ? 1 : currPage - 1;
} else if (page === nextPage) {
page = currPage + 1 > _this.totalPages ? _this.totalPages : currPage + 1;
} else if (page === lastPage) {
page = _this.totalPages;
} else if (page === firstPage) {
page = 1;
} else {
page = parseInt(page, 10);
}
if (page !== currPage) {
_this.props.changePage(page, sizePerPage);
}
};
this.changeSizePerPage = function (e) {
e.preventDefault();
var selectSize = parseInt(e.currentTarget.text, 10);
var currPage = _this.props.currPage;
if (selectSize !== _this.props.sizePerPage) {
_this.totalPages = Math.ceil(_this.props.dataSize / selectSize);
if (currPage > _this.totalPages) currPage = _this.totalPages;
_this.props.changePage(currPage, selectSize);
if (_this.props.onSizePerPageList) {
_this.props.onSizePerPageList(selectSize);
}
}
};
}
_createClass(PaginationList, [{
key: 'render',
value: function render() {
var _this2 = this;
var _props2 = this.props;
var dataSize = _props2.dataSize;
var sizePerPage = _props2.sizePerPage;
var sizePerPageList = _props2.sizePerPageList;
this.totalPages = Math.ceil(dataSize / sizePerPage);
var pageBtns = this.makePage();
var pageListStyle = {
float: 'right',
// override the margin-top defined in .pagination class in bootstrap.
marginTop: '0px'
};
var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) {
return _react2['default'].createElement(
'li',
{ key: _sizePerPage, role: 'presentation' },
_react2['default'].createElement(
'a',
{ role: 'menuitem',
tabIndex: '-1', href: '#',
onClick: _this2.changeSizePerPage },
_sizePerPage
)
);
});
return _react2['default'].createElement(
'div',
{ className: 'row', style: { marginTop: 15 } },
sizePerPageList.length > 1 ? _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'div',
{ className: 'dropdown' },
_react2['default'].createElement(
'button',
{ className: 'btn btn-default dropdown-toggle',
type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown',
'aria-expanded': 'true' },
sizePerPage,
_react2['default'].createElement(
'span',
null,
' ',
_react2['default'].createElement('span', { className: 'caret' })
)
),
_react2['default'].createElement(
'ul',
{ className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' },
sizePerPageOptions
)
)
),
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
) : _react2['default'].createElement(
'div',
{ className: 'col-md-12' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
);
}
}, {
key: 'makePage',
value: function makePage() {
var pages = this.getPages();
return pages.map(function (page) {
var isActive = page === this.props.currPage;
var disabled = false;
var hidden = false;
if (this.props.currPage === 1 && (page === this.props.firstPage || page === this.props.prePage)) {
disabled = true;
hidden = true;
}
if (this.props.currPage === this.totalPages && (page === this.props.nextPage || page === this.props.lastPage)) {
disabled = true;
hidden = true;
}
return _react2['default'].createElement(
_PageButtonJs2['default'],
{ key: page,
changePage: this.changePage,
active: isActive,
disable: disabled,
hidden: hidden },
page
);
}, this);
}
}, {
key: 'getPages',
value: function getPages() {
var pages = undefined;
var startPage = 1;
var endPage = this.totalPages;
startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), 1);
endPage = startPage + this.props.paginationSize - 1;
if (endPage > this.totalPages) {
endPage = this.totalPages;
startPage = endPage - this.props.paginationSize + 1;
}
if (startPage !== 1 && this.totalPages > this.props.paginationSize) {
pages = [this.props.firstPage, this.props.prePage];
} else if (this.totalPages > 1) {
pages = [this.props.prePage];
} else {
pages = [];
}
for (var i = startPage; i <= endPage; i++) {
if (i > 0) pages.push(i);
}
if (endPage !== this.totalPages) {
pages.push(this.props.nextPage);
pages.push(this.props.lastPage);
} else if (this.totalPages > 1) {
pages.push(this.props.nextPage);
}
return pages;
}
}]);
return PaginationList;
})(_react.Component);
PaginationList.propTypes = {
currPage: _react.PropTypes.number,
sizePerPage: _react.PropTypes.number,
dataSize: _react.PropTypes.number,
changePage: _react.PropTypes.func,
sizePerPageList: _react.PropTypes.array,
paginationSize: _react.PropTypes.number,
remote: _react.PropTypes.bool,
onSizePerPageList: _react.PropTypes.func,
prePage: _react.PropTypes.string
};
PaginationList.defaultProps = {
sizePerPage: _Const2['default'].SIZE_PER_PAGE
};
exports['default'] = PaginationList;
module.exports = exports['default'];
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var PageButton = (function (_Component) {
_inherits(PageButton, _Component);
function PageButton(props) {
var _this = this;
_classCallCheck(this, PageButton);
_get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props);
this.pageBtnClick = function (e) {
e.preventDefault();
_this.props.changePage(e.currentTarget.textContent);
};
}
_createClass(PageButton, [{
key: 'render',
value: function render() {
var classes = (0, _classnames2['default'])({
'active': this.props.active,
'disabled': this.props.disable,
'hidden': this.props.hidden
});
return _react2['default'].createElement(
'li',
{ className: classes },
_react2['default'].createElement(
'a',
{ href: '#', onClick: this.pageBtnClick },
this.props.children
)
);
}
}]);
return PageButton;
})(_react.Component);
PageButton.propTypes = {
changePage: _react.PropTypes.func,
active: _react.PropTypes.bool,
disable: _react.PropTypes.bool,
hidden: _react.PropTypes.bool,
children: _react.PropTypes.node
};
exports['default'] = PageButton;
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var ToolBar = (function (_Component) {
_inherits(ToolBar, _Component);
_createClass(ToolBar, null, [{
key: 'modalSeq',
value: 0,
enumerable: true
}]);
function ToolBar(props) {
var _this = this,
_arguments2 = arguments;
_classCallCheck(this, ToolBar);
_get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props);
this.handleSaveBtnClick = function () {
var newObj = _this.checkAndParseForm();
if (!newObj) {
// validate errors
return;
}
var msg = _this.props.onAddRow(newObj);
if (msg) {
_this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel');
_this.clearTimeout();
// shake form and hack prevent modal hide
_this.setState({
shakeEditor: true,
validateState: 'this is hack for prevent bootstrap modal hide'
});
// clear animate class
_this.timeouteClear = setTimeout(function () {
_this.setState({ shakeEditor: false });
}, 300);
} else {
// reset state and hide modal hide
_this.setState({
validateState: null,
shakeEditor: false
}, function () {
document.querySelector('.modal-backdrop').click();
document.querySelector('.' + _this.modalClassName).click();
});
// reset form
_this.refs.form.reset();
}
};
this.handleShowOnlyToggle = function () {
_this.setState({
showSelected: !_this.state.showSelected
});
_this.props.onShowOnlySelected();
};
this.handleDropRowBtnClick = function () {
_this.props.onDropRow();
};
this.handleDebounce = function (func, wait, immediate) {
var timeout = undefined;
return function () {
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(_this, _arguments2);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 0);
if (callNow) {
func.appy(_this, _arguments2);
}
};
};
this.handleKeyUp = function (event) {
event.persist();
_this.debounceCallback(event);
};
this.handleExportCSV = function () {
_this.props.onExportCSV();
};
this.handleClearBtnClick = function () {
_this.refs.seachInput.value = '';
_this.props.onSearch('');
};
this.timeouteClear = 0;
this.modalClassName;
this.state = {
isInsertRowTrigger: true,
validateState: null,
shakeEditor: false,
showSelected: false
};
}
_createClass(ToolBar, [{
key: 'componentWillMount',
value: function componentWillMount() {
var _this2 = this;
var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0;
this.debounceCallback = this.handleDebounce(function () {
_this2.props.onSearch(_this2.refs.seachInput.value);
}, delay);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'checkAndParseForm',
value: function checkAndParseForm() {
var _this3 = this;
var newObj = {};
var validateState = {};
var isValid = true;
var tempValue = undefined;
var tempMsg = undefined;
this.props.columns.forEach(function (column, i) {
if (column.autoValue) {
// when you want same auto generate value and not allow edit, example ID field
var time = new Date().getTime();
tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time;
} else {
var dom = this.refs[column.field + i];
tempValue = dom.value;
if (column.editable && column.editable.type === 'checkbox') {
var values = tempValue.split(':');
tempValue = dom.checked ? values[0] : values[1];
}
if (column.editable && column.editable.validator) {
// process validate
tempMsg = column.editable.validator(tempValue);
if (tempMsg !== true) {
isValid = false;
validateState[column.field] = tempMsg;
}
}
}
newObj[column.field] = tempValue;
}, this);
if (isValid) {
return newObj;
} else {
this.clearTimeout();
// show error in form and shake it
this.setState({ validateState: validateState, shakeEditor: true });
// notifier error
this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel');
// clear animate class
this.timeouteClear = setTimeout(function () {
_this3.setState({ shakeEditor: false });
}, 300);
return null;
}
}
}, {
key: 'handleCloseBtn',
value: function handleCloseBtn() {
this.refs.warning.style.display = 'none';
}
}, {
key: 'render',
value: function render() {
this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++;
var insertBtn = null;
var deleteBtn = null;
var exportCSV = null;
var showSelectedOnlyBtn = null;
if (this.props.enableInsert) {
insertBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info react-bs-table-add-btn',
'data-toggle': 'modal',
'data-target': '.' + this.modalClassName },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }),
' New'
);
}
if (this.props.enableDelete) {
deleteBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-warning react-bs-table-del-btn',
'data-toggle': 'tooltip',
'data-placement': 'right',
title: 'Drop selected row',
onClick: this.handleDropRowBtnClick },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }),
' Delete'
);
}
if (this.props.enableShowOnlySelected) {
showSelectedOnlyBtn = _react2['default'].createElement(
'button',
{ type: 'button',
onClick: this.handleShowOnlyToggle,
className: 'btn btn-primary',
'data-toggle': 'button',
'aria-pressed': 'false' },
this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT
);
}
if (this.props.enableExportCSV) {
exportCSV = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-success',
onClick: this.handleExportCSV },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }),
this.props.exportCSVText
);
}
var searchTextInput = this.renderSearchPanel();
var modal = this.props.enableInsert ? this.renderInsertRowModal() : null;
return _react2['default'].createElement(
'div',
{ className: 'row' },
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' },
_react2['default'].createElement(
'div',
{ className: 'btn-group btn-group-sm', role: 'group' },
exportCSV,
insertBtn,
deleteBtn,
showSelectedOnlyBtn
)
),
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' },
searchTextInput
),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }),
modal
);
}
}, {
key: 'renderSearchPanel',
value: function renderSearchPanel() {
if (this.props.enableSearch) {
var classNames = 'form-group form-group-sm react-bs-table-search-form';
var clearBtn = null;
if (this.props.clearSearch) {
clearBtn = _react2['default'].createElement(
'span',
{ className: 'input-group-btn' },
_react2['default'].createElement(
'button',
{
className: 'btn btn-default',
type: 'button',
onClick: this.handleClearBtnClick },
'Clear'
)
);
classNames += ' input-group input-group-sm';
}
return _react2['default'].createElement(
'div',
{ className: classNames },
_react2['default'].createElement('input', { ref: 'seachInput',
className: 'form-control',
type: 'text',
placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search',
onKeyUp: this.handleKeyUp }),
clearBtn
);
} else {
return null;
}
}
}, {
key: 'renderInsertRowModal',
value: function renderInsertRowModal() {
var _this4 = this;
var validateState = this.state.validateState || {};
var shakeEditor = this.state.shakeEditor;
var inputField = this.props.columns.map(function (column, i) {
var editable = column.editable;
var format = column.format;
var field = column.field;
var name = column.name;
var autoValue = column.autoValue;
var attr = {
ref: field + i,
placeholder: editable.placeholder ? editable.placeholder : name
};
if (autoValue) {
// when you want same auto generate value
// and not allow edit, for example ID field
return null;
}
var error = validateState[field] ? _react2['default'].createElement(
'span',
{ className: 'help-block bg-danger' },
validateState[field]
) : null;
// let editor = Editor(editable,attr,format);
// if(editor.props.type && editor.props.type == 'checkbox'){
return _react2['default'].createElement(
'div',
{ className: 'form-group', key: field },
_react2['default'].createElement(
'label',
null,
name
),
(0, _Editor2['default'])(editable, attr, format, '', undefined, _this4.props.ignoreEditable),
error
);
});
var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, {
// hack prevent bootstrap modal hide by reRender
'in': shakeEditor || this.state.validateState
});
var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', {
'animated': shakeEditor,
'shake': shakeEditor
});
return _react2['default'].createElement(
'div',
{ ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' },
_react2['default'].createElement(
'div',
{ className: dialogClass },
_react2['default'].createElement(
'div',
{ className: 'modal-content' },
_react2['default'].createElement(
'div',
{ className: 'modal-header' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'close',
'data-dismiss': 'modal',
'aria-label': 'Close' },
_react2['default'].createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
_react2['default'].createElement(
'h4',
{ className: 'modal-title' },
'New Record'
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-body' },
_react2['default'].createElement(
'form',
{ ref: 'form' },
inputField
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-footer' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-default',
'data-dismiss': 'modal' },
'Close'
),
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info',
onClick: this.handleSaveBtnClick },
'Save'
)
)
)
)
);
}
}]);
return ToolBar;
})(_react.Component);
ToolBar.propTypes = {
onAddRow: _react.PropTypes.func,
onDropRow: _react.PropTypes.func,
onShowOnlySelected: _react.PropTypes.func,
enableInsert: _react.PropTypes.bool,
enableDelete: _react.PropTypes.bool,
enableSearch: _react.PropTypes.bool,
enableShowOnlySelected: _react.PropTypes.bool,
columns: _react.PropTypes.array,
searchPlaceholder: _react.PropTypes.string,
exportCSVText: _react.PropTypes.string,
clearSearch: _react.PropTypes.bool,
ignoreEditable: _react.PropTypes.bool
};
ToolBar.defaultProps = {
enableInsert: false,
enableDelete: false,
enableSearch: false,
enableShowOnlySelected: false,
clearSearch: false,
ignoreEditable: false
};
exports['default'] = ToolBar;
module.exports = exports['default'];
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableFilter = (function (_Component) {
_inherits(TableFilter, _Component);
function TableFilter(props) {
var _this = this;
_classCallCheck(this, TableFilter);
_get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props);
this.handleKeyUp = function (e) {
var _e$currentTarget = e.currentTarget;
var value = _e$currentTarget.value;
var name = _e$currentTarget.name;
if (value.trim() === '') {
delete _this.filterObj[name];
} else {
_this.filterObj[name] = value;
}
_this.props.onFilter(_this.filterObj);
};
this.filterObj = {};
}
_createClass(TableFilter, [{
key: 'render',
value: function render() {
var _props = this.props;
var striped = _props.striped;
var condensed = _props.condensed;
var rowSelectType = _props.rowSelectType;
var columns = _props.columns;
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': striped,
'table-condensed': condensed
});
var selectRowHeader = null;
if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
var style = {
width: 35,
paddingLeft: 0,
paddingRight: 0
};
selectRowHeader = _react2['default'].createElement(
'th',
{ style: style, key: -1 },
'Filter'
);
}
var filterField = columns.map(function (column) {
var hidden = column.hidden;
var width = column.width;
var name = column.name;
var thStyle = {
display: hidden ? 'none' : null,
width: width
};
return _react2['default'].createElement(
'th',
{ key: name, style: thStyle },
_react2['default'].createElement(
'div',
{ className: 'th-inner table-header-column' },
_react2['default'].createElement('input', { size: '10', type: 'text',
placeholder: name, name: name, onKeyUp: this.handleKeyUp })
)
);
}, this);
return _react2['default'].createElement(
'table',
{ className: tableClasses, style: { marginTop: 5 } },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ style: { borderBottomStyle: 'hidden' } },
selectRowHeader,
filterField
)
)
);
}
}]);
return TableFilter;
})(_react.Component);
TableFilter.propTypes = {
columns: _react.PropTypes.array,
rowSelectType: _react.PropTypes.string,
onFilter: _react.PropTypes.func
};
exports['default'] = TableFilter;
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-nested-ternary: 0 */
/* eslint guard-for-in: 0 */
/* eslint no-console: 0 */
/* eslint eqeqeq: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
function _sort(arr, sortField, order, sortFunc, sortFuncExtraData) {
order = order.toLowerCase();
var isDesc = order === _Const2['default'].SORT_DESC;
arr.sort(function (a, b) {
if (sortFunc) {
return sortFunc(a, b, order, sortField, sortFuncExtraData);
} else {
if (isDesc) {
if (b[sortField] === null) return false;
if (a[sortField] === null) return true;
if (typeof b[sortField] === 'string') {
return b[sortField].localeCompare(a[sortField]);
} else {
return a[sortField] > b[sortField] ? -1 : a[sortField] < b[sortField] ? 1 : 0;
}
} else {
if (b[sortField] === null) return true;
if (a[sortField] === null) return false;
if (typeof a[sortField] === 'string') {
return a[sortField].localeCompare(b[sortField]);
} else {
return a[sortField] < b[sortField] ? -1 : a[sortField] > b[sortField] ? 1 : 0;
}
}
}
});
return arr;
}
var TableDataStore = (function () {
function TableDataStore(data) {
_classCallCheck(this, TableDataStore);
this.data = data;
this.colInfos = null;
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
this.searchText = null;
this.sortObj = null;
this.pageObj = {};
this.selected = [];
this.multiColumnSearch = false;
this.showOnlySelected = false;
this.remote = false; // remote data
}
_createClass(TableDataStore, [{
key: 'setProps',
value: function setProps(props) {
this.keyField = props.keyField;
this.enablePagination = props.isPagination;
this.colInfos = props.colInfos;
this.remote = props.remote;
this.multiColumnSearch = props.multiColumnSearch;
}
}, {
key: 'setData',
value: function setData(data) {
this.data = data;
this._refresh();
}
}, {
key: 'getSortInfo',
value: function getSortInfo() {
return this.sortObj;
}
}, {
key: 'setSelectedRowKey',
value: function setSelectedRowKey(selectedRowKeys) {
this.selected = selectedRowKeys;
}
}, {
key: 'getSelectedRowKeys',
value: function getSelectedRowKeys() {
return this.selected;
}
}, {
key: 'getCurrentDisplayData',
value: function getCurrentDisplayData() {
if (this.isOnFilter) return this.filteredData;else return this.data;
}
}, {
key: '_refresh',
value: function _refresh() {
if (this.isOnFilter) {
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
if (this.sortObj) {
this.sort(this.sortObj.order, this.sortObj.sortField);
}
}
}, {
key: 'ignoreNonSelected',
value: function ignoreNonSelected() {
var _this = this;
this.showOnlySelected = !this.showOnlySelected;
if (this.showOnlySelected) {
this.isOnFilter = true;
this.filteredData = this.data.filter(function (row) {
var result = _this.selected.find(function (x) {
return row[_this.keyField] === x;
});
return typeof result !== 'undefined' ? true : false;
});
} else {
this.isOnFilter = false;
}
}
}, {
key: 'sort',
value: function sort(order, sortField) {
this.sortObj = { order: order, sortField: sortField };
var currentDisplayData = this.getCurrentDisplayData();
if (!this.colInfos[sortField]) return this;
var _colInfos$sortField = this.colInfos[sortField];
var sortFunc = _colInfos$sortField.sortFunc;
var sortFuncExtraData = _colInfos$sortField.sortFuncExtraData;
currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc, sortFuncExtraData);
return this;
}
}, {
key: 'page',
value: function page(_page, sizePerPage) {
this.pageObj.end = _page * sizePerPage - 1;
this.pageObj.start = this.pageObj.end - (sizePerPage - 1);
return this;
}
}, {
key: 'edit',
value: function edit(newVal, rowIndex, fieldName) {
var currentDisplayData = this.getCurrentDisplayData();
var rowKeyCache = undefined;
if (!this.enablePagination) {
currentDisplayData[rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[rowIndex][this.keyField];
} else {
currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField];
}
if (this.isOnFilter) {
this.data.forEach(function (row) {
if (row[this.keyField] === rowKeyCache) {
row[fieldName] = newVal;
}
}, this);
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
return this;
}
}, {
key: 'addAtBegin',
value: function addAtBegin(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.unshift(newObj);
if (this.isOnFilter) {
this.data.unshift(newObj);
}
this._refresh();
}
}, {
key: 'add',
value: function add(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.push(newObj);
if (this.isOnFilter) {
this.data.push(newObj);
}
this._refresh();
}
}, {
key: 'remove',
value: function remove(rowKey) {
var _this2 = this;
var currentDisplayData = this.getCurrentDisplayData();
var result = currentDisplayData.filter(function (row) {
return rowKey.indexOf(row[_this2.keyField]) === -1;
});
if (this.isOnFilter) {
this.data = this.data.filter(function (row) {
return rowKey.indexOf(row[_this2.keyField]) === -1;
});
this.filteredData = result;
} else {
this.data = result;
}
}
}, {
key: 'filter',
value: function filter(filterObj) {
var _this3 = this;
if (Object.keys(filterObj).length === 0) {
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
if (this.searchText !== null) this.search(this.searchText);
} else {
this.filterObj = filterObj;
this.filteredData = this.data.filter(function (row) {
var valid = true;
var filterVal = undefined;
for (var key in filterObj) {
var targetVal = row[key];
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
filterVal = filterObj[key].value.number;
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
filterVal = filterObj[key].value;
break;
}
default:
{
filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
if (filterVal === undefined) {
// Support old filter
filterVal = filterObj[key].toLowerCase();
}
break;
}
}
if (_this3.colInfos[key]) {
var _colInfos$key = _this3.colInfos[key];
var format = _colInfos$key.format;
var filterFormatted = _colInfos$key.filterFormatted;
var formatExtraData = _colInfos$key.formatExtraData;
if (filterFormatted && format) {
targetVal = format(row[key], row, formatExtraData);
}
}
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
valid = _this3.filterNumber(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2['default'].FILTER_TYPE.DATE:
{
valid = _this3.filterDate(targetVal, filterVal);
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
valid = _this3.filterRegex(targetVal, filterVal);
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
valid = _this3.filterCustom(targetVal, filterVal, filterObj[key].value);
break;
}
default:
{
valid = _this3.filterText(targetVal, filterVal);
break;
}
}
if (!valid) {
break;
}
}
return valid;
});
this.isOnFilter = true;
}
}
}, {
key: 'filterNumber',
value: function filterNumber(targetVal, filterVal, comparator) {
var valid = true;
switch (comparator) {
case '=':
{
if (targetVal != filterVal) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
if (targetVal < filterVal) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetVal > filterVal) {
valid = false;
}
break;
}
case '!=':
{
if (targetVal == filterVal) {
valid = false;
}
break;
}
default:
{
console.error('Number comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterDate',
value: function filterDate(targetVal, filterVal) {
if (!targetVal) {
return false;
}
return targetVal.getDate() === filterVal.getDate() && targetVal.getMonth() === filterVal.getMonth() && targetVal.getFullYear() === filterVal.getFullYear();
}
}, {
key: 'filterRegex',
value: function filterRegex(targetVal, filterVal) {
try {
return new RegExp(filterVal, 'i').test(targetVal);
} catch (e) {
console.error('Invalid regular expression');
return true;
}
}
}, {
key: 'filterCustom',
value: function filterCustom(targetVal, filterVal, callbackInfo) {
if (callbackInfo !== null && typeof callbackInfo === 'object') {
return callbackInfo.callback(targetVal, callbackInfo.callbackParameters);
}
return this.filterText(targetVal, filterVal);
}
}, {
key: 'filterText',
value: function filterText(targetVal, filterVal) {
if (targetVal.toString().toLowerCase().indexOf(filterVal) === -1) {
return false;
}
return true;
}
/* General search function
* It will search for the text if the input includes that text;
*/
}, {
key: 'search',
value: function search(searchText) {
var _this4 = this;
if (searchText.trim() === '') {
this.filteredData = null;
this.isOnFilter = false;
this.searchText = null;
if (this.filterObj !== null) this.filter(this.filterObj);
} else {
(function () {
_this4.searchText = searchText;
var searchTextArray = [];
if (_this4.multiColumnSearch) {
searchTextArray = searchText.split(' ');
} else {
searchTextArray.push(searchText);
}
// Mark following code for fixing #363
// To avoid to search on a data which be searched or filtered
// But this solution have a poor performance, because I do a filter again
// const source = this.isOnFilter ? this.filteredData : this.data;
var source = _this4.filterObj !== null ? _this4.filter(_this4.filterObj) : _this4.data;
_this4.filteredData = source.filter(function (row) {
var keys = Object.keys(row);
var valid = false;
// for loops are ugly, but performance matters here.
// And you cant break from a forEach.
// http://jsperf.com/for-vs-foreach/66
for (var i = 0, keysLength = keys.length; i < keysLength; i++) {
var key = keys[i];
if (_this4.colInfos[key] && row[key]) {
var _colInfos$key2 = _this4.colInfos[key];
var format = _colInfos$key2.format;
var filterFormatted = _colInfos$key2.filterFormatted;
var formatExtraData = _colInfos$key2.formatExtraData;
var searchable = _colInfos$key2.searchable;
var targetVal = row[key];
if (searchable) {
if (filterFormatted && format) {
targetVal = format(targetVal, row, formatExtraData);
}
for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) {
var filterVal = searchTextArray[j].toLowerCase();
if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) {
valid = true;
break;
}
}
}
}
}
return valid;
});
_this4.isOnFilter = true;
})();
}
}
}, {
key: 'getDataIgnoringPagination',
value: function getDataIgnoringPagination() {
return this.getCurrentDisplayData();
}
}, {
key: 'get',
value: function get() {
var _data = this.getCurrentDisplayData();
if (_data.length === 0) return _data;
if (this.remote || !this.enablePagination) {
return _data;
} else {
var result = [];
for (var i = this.pageObj.start; i <= this.pageObj.end; i++) {
result.push(_data[i]);
if (i + 1 === _data.length) break;
}
return result;
}
}
}, {
key: 'getKeyField',
value: function getKeyField() {
return this.keyField;
}
}, {
key: 'getDataNum',
value: function getDataNum() {
return this.getCurrentDisplayData().length;
}
}, {
key: 'isChangedPage',
value: function isChangedPage() {
return this.pageObj.start && this.pageObj.end ? true : false;
}
}, {
key: 'isEmpty',
value: function isEmpty() {
return this.data.length === 0 || this.data === null || this.data === undefined;
}
}, {
key: 'getAllRowkey',
value: function getAllRowkey() {
var _this5 = this;
return this.data.map(function (row) {
return row[_this5.keyField];
});
}
}]);
return TableDataStore;
})();
exports.TableDataStore = TableDataStore;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
exports['default'] = {
renderReactSortCaret: function renderReactSortCaret(order) {
var orderClass = (0, _classnames2['default'])('order', {
'dropup': order === _Const2['default'].SORT_ASC
});
return _react2['default'].createElement(
'span',
{ className: orderClass },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '0px 5px' } })
);
},
getScrollBarWidth: function getScrollBarWidth() {
var inner = document.createElement('p');
inner.style.width = '100%';
inner.style.height = '200px';
var outer = document.createElement('div');
outer.style.position = 'absolute';
outer.style.top = '0px';
outer.style.left = '0px';
outer.style.visibility = 'hidden';
outer.style.width = '200px';
outer.style.height = '150px';
outer.style.overflow = 'hidden';
outer.appendChild(inner);
document.body.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 === w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return w1 - w2;
},
canUseDOM: function canUseDOM() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
}
};
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* eslint block-scoped-var: 0 */
/* eslint vars-on-top: 0 */
/* eslint no-var: 0 */
/* eslint no-unused-vars: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
if (_util2['default'].canUseDOM()) {
var filesaver = __webpack_require__(36);
var saveAs = filesaver.saveAs;
}
function toString(data, keys) {
var dataString = '';
if (data.length === 0) return dataString;
dataString += keys.join(',') + '\n';
data.map(function (row) {
keys.map(function (col, i) {
var cell = typeof row[col] !== 'undefined' ? '"' + row[col] + '"' : '';
dataString += cell;
if (i + 1 < keys.length) dataString += ',';
});
dataString += '\n';
});
return dataString;
}
var exportCSV = function exportCSV(data, keys, filename) {
var dataString = toString(data, keys);
if (typeof window !== 'undefined') {
saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename || 'spreadsheet.csv');
}
};
exports['default'] = exportCSV;
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20151003
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
"use strict";
var saveAs = saveAs || (function (view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var doc = view.document,
// only get URL when necessary in case Blob.js hasn't overridden it yet
get_URL = function get_URL() {
return view.URL || view.webkitURL || view;
},
save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
can_use_save_link = ("download" in save_link),
click = function click(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
},
is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent),
webkit_req_fs = view.webkitRequestFileSystem,
req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem,
throw_outside = function throw_outside(ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
},
force_saveable_type = "application/octet-stream",
fs_min_size = 0,
// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
// for the reasoning behind the timeout and revocation flow
arbitrary_revoke_timeout = 500,
// in ms
revoke = function revoke(file) {
var revoker = function revoker() {
if (typeof file === "string") {
// file is an object URL
get_URL().revokeObjectURL(file);
} else {
// file is a File
file.remove();
}
};
if (view.chrome) {
revoker();
} else {
setTimeout(revoker, arbitrary_revoke_timeout);
}
},
dispatch = function dispatch(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
},
auto_bom = function auto_bom(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob(["", blob], { type: blob.type });
}
return blob;
},
FileSaver = function FileSaver(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var filesaver = this,
type = blob.type,
blob_changed = false,
object_url,
target_view,
dispatch_all = function dispatch_all() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
},
// on any filesys errors revert to saving with object URLs
fs_error = function fs_error() {
if (target_view && is_safari && typeof FileReader !== "undefined") {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function () {
var base64Data = reader.result;
target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && is_safari) {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
},
abortable = function abortable(func) {
return function () {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
},
create_if_not_found = { create: true, exclusive: false },
slice;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
save_link.href = object_url;
save_link.download = name;
setTimeout(function () {
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
// Update: Google errantly closed 91158, I submitted it again:
// https://code.google.com/p/chromium/issues/detail?id=389642
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {
var save = function save() {
dir.getFile(name, create_if_not_found, abortable(function (file) {
file.createWriter(abortable(function (writer) {
writer.onwriteend = function (event) {
target_view.location.href = file.toURL();
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
revoke(file);
};
writer.onerror = function () {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function (event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function () {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, { create: false }, abortable(function (file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function (ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
},
FS_proto = FileSaver.prototype,
saveAs = function saveAs(blob, name, no_auto_bom) {
return new FileSaver(blob, name, no_auto_bom);
};
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function (blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name || "download");
};
}
FS_proto.abort = function () {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs;
})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ("function" !== "undefined" && __webpack_require__(37) !== null && __webpack_require__(38) != null) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return saveAs;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 37 */
/***/ function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ },
/* 38 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _events = __webpack_require__(40);
var Filter = (function (_EventEmitter) {
_inherits(Filter, _EventEmitter);
function Filter(data) {
_classCallCheck(this, Filter);
_get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data);
this.currentFilter = {};
}
_createClass(Filter, [{
key: 'handleFilter',
value: function handleFilter(dataField, value, type) {
var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM;
if (value !== null && typeof value === 'object') {
// value of the filter is an object
var hasValue = true;
for (var prop in value) {
if (!value[prop] || value[prop] === '') {
hasValue = false;
break;
}
}
// if one of the object properties is undefined or empty, we remove the filter
if (hasValue) {
this.currentFilter[dataField] = { value: value, type: filterType };
} else {
delete this.currentFilter[dataField];
}
} else if (!value || value.trim() === '') {
delete this.currentFilter[dataField];
} else {
this.currentFilter[dataField] = { value: value.trim(), type: filterType };
}
this.emit('onFilterChange', this.currentFilter);
}
}]);
return Filter;
})(_events.EventEmitter);
exports.Filter = Filter;
/***/ },
/* 40 */
/***/ function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/* eslint default-case: 0 */
/* eslint guard-for-in: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _filtersDate = __webpack_require__(42);
var _filtersDate2 = _interopRequireDefault(_filtersDate);
var _filtersText = __webpack_require__(43);
var _filtersText2 = _interopRequireDefault(_filtersText);
var _filtersRegex = __webpack_require__(44);
var _filtersRegex2 = _interopRequireDefault(_filtersRegex);
var _filtersSelect = __webpack_require__(45);
var _filtersSelect2 = _interopRequireDefault(_filtersSelect);
var _filtersNumber = __webpack_require__(46);
var _filtersNumber2 = _interopRequireDefault(_filtersNumber);
var TableHeaderColumn = (function (_Component) {
_inherits(TableHeaderColumn, _Component);
function TableHeaderColumn(props) {
var _this = this;
_classCallCheck(this, TableHeaderColumn);
_get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props);
this.handleColumnClick = function () {
if (!_this.props.dataSort) return;
var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC;
_this.props.onSort(order, _this.props.dataField);
};
this.handleFilter = this.handleFilter.bind(this);
}
_createClass(TableHeaderColumn, [{
key: 'handleFilter',
value: function handleFilter(value, type) {
this.props.filter.emitter.handleFilter(this.props.dataField, value, type);
}
}, {
key: 'getFilters',
value: function getFilters() {
switch (this.props.filter.type) {
case _Const2['default'].FILTER_TYPE.TEXT:
{
return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.SELECT:
{
return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.NUMBER:
{
return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.DATE:
{
return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters);
}
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs['header-col'].setAttribute('data-field', this.props.dataField);
}
}, {
key: 'render',
value: function render() {
var defaultCaret = undefined;
var thStyle = {
textAlign: this.props.dataAlign,
display: this.props.hidden ? 'none' : null
};
if (this.props.sortIndicator) {
defaultCaret = !this.props.dataSort ? null : _react2['default'].createElement(
'span',
{ className: 'order' },
_react2['default'].createElement(
'span',
{ className: 'dropdown' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } })
),
_react2['default'].createElement(
'span',
{ className: 'dropup' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } })
)
);
}
var sortCaret = this.props.sort ? _util2['default'].renderReactSortCaret(this.props.sort) : defaultCaret;
if (this.props.caretRender) {
sortCaret = this.props.caretRender(this.props.sort);
}
var classes = this.props.className + ' ' + (this.props.dataSort ? 'sort-column' : '');
var title = typeof this.props.children === 'string' ? { title: this.props.children } : null;
return _react2['default'].createElement(
'th',
_extends({ ref: 'header-col',
className: classes,
style: thStyle,
onClick: this.handleColumnClick
}, title),
this.props.children,
sortCaret,
_react2['default'].createElement(
'div',
{ onClick: function (e) {
return e.stopPropagation();
} },
this.props.filter ? this.getFilters() : null
)
);
}
}]);
return TableHeaderColumn;
})(_react.Component);
var filterTypeArray = [];
for (var key in _Const2['default'].FILTER_TYPE) {
filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]);
}
TableHeaderColumn.propTypes = {
dataField: _react.PropTypes.string,
dataAlign: _react.PropTypes.string,
dataSort: _react.PropTypes.bool,
onSort: _react.PropTypes.func,
dataFormat: _react.PropTypes.func,
isKey: _react.PropTypes.bool,
editable: _react.PropTypes.any,
hidden: _react.PropTypes.bool,
searchable: _react.PropTypes.bool,
className: _react.PropTypes.string,
width: _react.PropTypes.string,
sortFunc: _react.PropTypes.func,
sortFuncExtraData: _react.PropTypes.any,
columnClassName: _react.PropTypes.any,
filterFormatted: _react.PropTypes.bool,
sort: _react.PropTypes.string,
caretRender: _react.PropTypes.func,
formatExtraData: _react.PropTypes.any,
filter: _react.PropTypes.shape({
type: _react.PropTypes.oneOf(filterTypeArray),
delay: _react.PropTypes.number,
options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter
_react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter
]),
numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string),
emitter: _react.PropTypes.object,
placeholder: _react.PropTypes.string,
getElement: _react.PropTypes.func,
customFilterParameters: _react.PropTypes.object
}),
sortIndicator: _react.PropTypes.bool
};
TableHeaderColumn.defaultProps = {
dataAlign: 'left',
dataSort: false,
dataFormat: undefined,
isKey: false,
editable: true,
onSort: undefined,
hidden: false,
searchable: true,
className: '',
width: null,
sortFunc: undefined,
columnClassName: '',
filterFormatted: false,
sort: undefined,
formatExtraData: undefined,
sortFuncExtraData: undefined,
filter: undefined,
sortIndicator: true
};
exports['default'] = TableHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* eslint quotes: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var DateFilter = (function (_Component) {
_inherits(DateFilter, _Component);
function DateFilter(props) {
_classCallCheck(this, DateFilter);
_get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
}
_createClass(DateFilter, [{
key: 'setDefaultDate',
value: function setDefaultDate() {
var defaultDate = '';
if (this.props.defaultValue) {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
var defaultValue = new Date(this.props.defaultValue);
defaultDate = defaultValue.getFullYear() + '-' + ("0" + (defaultValue.getMonth() + 1)).slice(-2) + '-' + ("0" + defaultValue.getDate()).slice(-2);
}
return defaultDate;
}
}, {
key: 'filter',
value: function filter(event) {
var dateValue = event.target.value;
if (dateValue) {
this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);
} else {
this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var dateValue = this.refs.inputDate.defaultValue;
if (dateValue) {
this.props.filterHandler(new Date(dateValue), _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('input', { ref: 'inputDate',
className: 'filter date-filter form-control',
type: 'date',
onChange: this.filter,
defaultValue: this.setDefaultDate() });
}
}]);
return DateFilter;
})(_react.Component);
DateFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.object,
columnName: _react.PropTypes.string
};
exports['default'] = DateFilter;
module.exports = exports['default'];
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TextFilter = (function (_Component) {
_inherits(TextFilter, _Component);
function TextFilter(props) {
_classCallCheck(this, TextFilter);
_get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(TextFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var defaultValue = this.refs.inputText.defaultValue;
if (defaultValue) {
this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
var defaultValue = _props.defaultValue;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return TextFilter;
})(_react.Component);
TextFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
TextFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = TextFilter;
module.exports = exports['default'];
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var RegexFilter = (function (_Component) {
_inherits(RegexFilter, _Component);
function RegexFilter(props) {
_classCallCheck(this, RegexFilter);
_get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(RegexFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.inputText.defaultValue;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var defaultValue = _props.defaultValue;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter Regex for ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return RegexFilter;
})(_react.Component);
RegexFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
RegexFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = RegexFilter;
module.exports = exports['default'];
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var SelectFilter = (function (_Component) {
_inherits(SelectFilter, _Component);
function SelectFilter(props) {
_classCallCheck(this, SelectFilter);
_get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue)
};
}
_createClass(SelectFilter, [{
key: 'filter',
value: function filter(event) {
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}, {
key: 'getOptions',
value: function getOptions() {
var optionTags = [];
var _props = this.props;
var options = _props.options;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
placeholder || 'Select ' + columnName + '...'
));
Object.keys(options).map(function (key) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: key, value: key },
options[key]
));
});
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.selectInput.value;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'select',
{ ref: 'selectInput',
className: selectClass,
onChange: this.filter,
defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' },
this.getOptions()
);
}
}]);
return SelectFilter;
})(_react.Component);
SelectFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.object.isRequired,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
exports['default'] = SelectFilter;
module.exports = exports['default'];
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
var NumberFilter = (function (_Component) {
_inherits(NumberFilter, _Component);
function NumberFilter(props) {
_classCallCheck(this, NumberFilter);
_get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props);
this.numberComparators = this.props.numberComparators || legalComparators;
this.timeout = null;
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1
};
this.onChangeNumber = this.onChangeNumber.bind(this);
this.onChangeNumberSet = this.onChangeNumberSet.bind(this);
this.onChangeComparator = this.onChangeComparator.bind(this);
}
_createClass(NumberFilter, [{
key: 'onChangeNumber',
value: function onChangeNumber(event) {
var _this = this;
var comparator = this.refs.numberFilterComparator.value;
if (comparator === '') {
return;
}
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}, this.props.delay);
}
}, {
key: 'onChangeNumberSet',
value: function onChangeNumberSet(event) {
var comparator = this.refs.numberFilterComparator.value;
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
if (comparator === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var value = this.refs.numberFilter.value;
var comparator = event.target.value;
if (value === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2['default'].createElement('option', { key: '-1' }));
for (var i = 0; i < this.numberComparators.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: this.numberComparators[i] },
this.numberComparators[i]
));
}
return optionTags;
}
}, {
key: 'getNumberOptions',
value: function getNumberOptions() {
var optionTags = [];
var options = this.props.options;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
this.props.placeholder || 'Select ' + this.props.columnName + '...'
));
for (var i = 0; i < options.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: options[i] },
options[i]
));
}
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.numberFilterComparator.value;
var number = this.refs.numberFilter.value;
if (comparator && number) {
this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'div',
{ className: 'filter number-filter' },
_react2['default'].createElement(
'select',
{ ref: 'numberFilterComparator',
className: 'number-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' },
this.getComparatorOptions()
),
this.props.options ? _react2['default'].createElement(
'select',
{ ref: 'numberFilter',
className: selectClass,
onChange: this.onChangeNumberSet,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' },
this.getNumberOptions()
) : _react2['default'].createElement('input', { ref: 'numberFilter',
type: 'number',
className: 'number-filter-input form-control',
placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',
onChange: this.onChangeNumber,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' })
);
}
}]);
return NumberFilter;
})(_react.Component);
NumberFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.arrayOf(_react.PropTypes.number),
defaultValue: _react.PropTypes.shape({
number: _react.PropTypes.number,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
delay: _react.PropTypes.number,
/* eslint consistent-return: 0 */
numberComparators: function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
NumberFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = NumberFilter;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
//# sourceMappingURL=react-bootstrap-table.js.map
|
/* http://keith-wood.name/datepick.html
Urdu localisation for jQuery Datepicker.
Mansoor Munib -- mansoormunib@gmail.com <http://www.mansoor.co.nr/mansoor.html>
Thanks to Habib Ahmed, ObaidUllah Anwar. */
(function($) {
$.datepick.regionalOptions.ur = {
monthNames: ['جنوری','فروری','مارچ','اپریل','مئی','جون',
'جولائی','اگست','ستمبر','اکتوبر','نومبر','دسمبر'],
monthNamesShort: ['1','2','3','4','5','6',
'7','8','9','10','11','12'],
dayNames: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dayNamesShort: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dayNamesMin: ['اتوار','پير','منگل','بدھ','جمعرات','جمعہ','ہفتہ'],
dateFormat: 'dd/mm/yyyy', firstDay: 0,
renderer: $.datepick.defaultRenderer,
prevText: '<گذشتہ', prevStatus: 'ماه گذشتہ',
prevJumpText: '<<', prevJumpStatus: 'برس گذشتہ',
nextText: 'آئندہ>', nextStatus: 'ماه آئندہ',
nextJumpText: '>>', nextJumpStatus: 'برس آئندہ',
currentText: 'رواں', currentStatus: 'ماه رواں',
todayText: 'آج', todayStatus: 'آج',
clearText: 'حذف تاريخ', clearStatus: 'کریں حذف تاریخ',
closeText: 'کریں بند', closeStatus: 'کیلئے کرنے بند',
yearStatus: 'برس تبدیلی', monthStatus: 'ماه تبدیلی',
weekText: 'ہفتہ', weekStatus: 'ہفتہ',
dayStatus: 'انتخاب D, M d', defaultStatus: 'کریں منتخب تاريخ',
isRTL: true
};
$.datepick.setDefaults($.datepick.regionalOptions.ur);
})(jQuery);
|
/*!
* Inheritance.js (0.4.3)
*
* Copyright (c) 2015 Brandon Sara (http://bsara.github.io)
* Licensed under the CPOL-1.02 (https://github.com/bsara/inheritance.js/blob/master/LICENSE.md)
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.I = {};
root.I = factory();
}
}(this, function() {/**
* TODO: Add description
*
* @param {Object} obj - The object to mix into.
* NOTE: `undefined` and `null` are both VALID values for
* this parameter. If `obj` is `undefined` or `null`, then
* a new object will be created from the `mixins` given.
* @param {Array<Object>|Object} mixins - An array of objects whose properties should be mixed
* into the given `obj`.
* NOTE: The order of objects in this array does matter!
* If there are properties present in multiple mixin
* objects, then the mixin with the largest index value
* overwrite any values set by the lower index valued
* mixin objects.
*
* @returns {Object} The mixed version of `obj`.
*/
function mix(obj, mixins) {
var newObj = (obj || {});
if (!(mixins instanceof Array)) {
mixins = [ mixins ];
}
for (var i = 0; i < mixins.length; i++) {
var mixin = mixins[i];
if (!mixin) {
continue;
}
for (var propName in mixin) {
if (mixin.hasOwnProperty(propName)) {
newObj[propName] = mixin[propName];
}
}
}
return newObj;
}/**
* TODO: Add description
*
* @param {Object} obj - The object to deep mix into.
* NOTE: `undefined` and `null` are both VALID values for
* this parameter. If `obj` is `undefined` or `null`, then
* a new object will be created from the `mixins` given.
* @param {Array<Object>|Object} mixins - An array of objects whose properties should be deep
* mixed into the given `obj`.
* NOTE: The order of objects in this array does matter!
* If there are properties present in multiple mixin
* objects, then the mixin with the largest index value
* overwrite any values set by the lower index valued
* mixin objects.
*
* @returns {Object} The deep mixed version of `obj`.
*/
function mixDeep(obj, mixins) {
var newObj = (obj || {});
if (!(mixins instanceof Array)) {
mixins = [ mixins ];
}
for (var i = 0; i < mixins.length; i++) {
var mixin = mixins[i];
if (!mixin) {
continue;
}
for (var propName in mixin) {
if (!mixin.hasOwnProperty(propName)) {
continue;
}
if (typeof mixin[propName] === 'object') {
mixDeep(newObj[propName], mixin[propName]);
continue;
}
newObj[propName] = mixin[propName];
}
}
return newObj;
}/**
* Creates a new object definition based upon the given `objDefProps` that inherits the
* given `parent`.
*
* @param {Object} parent - The object to be inherited.
* @param {Object} [objDefProps] - An object containing all properties to be used in
* creating the new object definition that will inherit
* the given `parent` object. If this parameter is
* `undefined` or `null`, then a new child object
* definition is created.
* TODO: Add reference to the `objDefProps` spec
*
* @returns {Object} An object created from the given `objDefProps` that inherits
* `parent`.
*
* @requires makeInheritable, mixDeep
*/
function inheritance(parent, objDefProps) {
parent = (parent || Object);
objDefProps = (objDefProps || {});
var objDef;
var objCtor = (objDefProps.ctor || function() { return objDef.__super__.constructor.apply(this, arguments); });
var objDefName = objDefProps.__defName;
if (typeof objDefName === 'string' && objDefName.trim()) {
objDefName = objDefName.trim();
} else if (objCtor.name) {
objDefName = objCtor.name;
} else {
objDefName = undefined;
}
delete objDefProps.__defName; eval('objDef = function' + (objDefName ? (' ' + objDefName) : '') + '() { return objCtor.apply(this, arguments); };'); objDef.prototype = Object.create(parent.prototype);
_addOwnerIfFunction(objDef.prototype, objCtor);
Object.defineProperty(objDef.prototype, '__ctor__', {
value: objCtor,
configurable: false,
enumerable: false,
writable: false
});
makeInheritable(objDef);
_setupMixins(objDefProps);
_setupStaticProperties(objDef, objDefProps);
_setupPrivateProperties(objDef, objDefProps);
_setupSuperFunction(objDef);
_setupPublicProperties(objDef, objDefProps);
Object.defineProperty(objDef, '__super__', {
value: parent.prototype,
configurable: false,
enumerable: false,
writable: false
});
return objDef;
}
function _addOwnerIfFunction(owner, obj) {
if (typeof obj === 'function') {
obj.owner = owner;
}
return obj;
}
function _updatePrototypeWithMixDeep(prototype, props, propName) {
if (typeof props[propName] === 'object'
&& typeof props[propName] === typeof prototype[propName]
&& typeof props[propName].prototype === 'undefined'
&& typeof prototype[propName].prototype === 'undefined') {
mixDeep(prototype[propName], props[propName]);
return;
}
prototype[propName] = _addOwnerIfFunction(prototype, props[propName]);
}
function _setupMixins(props) {
var mixins = props.mixins;
if (mixins !== null && mixins instanceof Array) {
mixDeep(props, mixins);
}
}
function _setupStaticProperties(def, props) {
var propName;
var staticProps = props.static;
if (typeof staticProps !== 'undefined' && staticProps !== null) {
for (propName in staticProps) {
if (propName === 'consts'
|| propName === '__super__') {
continue;
}
def[propName] = _addOwnerIfFunction(def, staticProps[propName]);
}
var staticConstProps = staticProps.consts;
if (typeof staticConstProps !== 'undefined' && staticConstProps !== null) {
for (propName in staticConstProps) {
Object.defineProperty(def, propName, {
value: staticConstProps[propName],
configurable: false,
enumerable: true,
writable: false
});
}
}
}
}
function _setupPrivateProperties(def, props) {
var propName;
var privateProps = props.private;
if (typeof privateProps !== 'undefined' && privateProps !== null) {
for (propName in privateProps) {
if (propName === 'constructor'
|| propName === 'ctor'
|| propName === 'static'
|| propName === '_super'
|| propName === '__ctor__') {
continue;
}
Object.defineProperty(def.prototype, propName, {
value: _addOwnerIfFunction(def.prototype, privateProps[propName]),
configurable: true,
enumerable: false,
writable: true
});
}
var privateStaticProps = privateProps.static;
if (typeof privateStaticProps !== 'undefined' && privateStaticProps !== null) {
for (propName in privateStaticProps) {
Object.defineProperty(def, propName, {
value: _addOwnerIfFunction(def, privateStaticProps[propName]),
configurable: true,
enumerable: false,
writable: true
});
}
}
}
}
function _setupPublicProperties(def, props) {
def.prototype.constructor = _addOwnerIfFunction(def.prototype, def);
for (var propName in props) {
if (propName === 'constructor'
|| propName === 'ctor'
|| propName === 'mixins'
|| propName === 'private'
|| propName === 'static'
|| propName === '_super'
|| propName === '__ctor__') {
continue;
}
_updatePrototypeWithMixDeep(def.prototype, props, propName);
}
}
function _setupSuperFunction(def) {
Object.defineProperty(def.prototype, '_super', {
configurable: false,
enumerable: false,
writable: false,
value: function() {
var caller = arguments.callee.caller;
if (!caller) {
return;
}
var callerOwner = caller.owner;
var superType = callerOwner.constructor.__super__;
if (!superType) {
return;
}
if (caller === callerOwner.constructor || caller === callerOwner.__ctor__) {
return superType.constructor.apply(this, arguments);
}
var callerName = caller.name;
if (!callerName) {
var propNames = Object.getOwnPropertyNames(callerOwner);
for (var i = 0; i < propNames.length; i++) {
var propName = propNames[i];
if (callerOwner[propName] === caller) {
callerName = propName;
break;
}
}
}
if (!callerName) {
return;
}
var superFunc = superType[callerName];
if (typeof superFunc !== 'function' || superFunc === null) {
return;
}
return superFunc.apply(this, arguments);
}
});
}/**
* Makes an object inheritable by adding a function called `extend` as a "static"
* property of the object. (I.E. Calling this function passing `MyObject` as a
* parameter, creates `MyObject.extend`)
*
* @param {Object} obj - The object to make inheritable.
* @param {Boolean} [overwrite] - If `true`, then an existing `extend` property will be
* overwritten regardless of it's value.
* @param {Boolean} [ignoreOverwriteError] - If `true`, then no error will be thrown if
* `obj.extend` already exists and `overwrite`
* is not `true`.
*
* @returns {Object} The modified `obj` given.
*
* @throws {TypeError} If `obj` is `undefined` or `null`.
* @throws {TypeError} If `obj.extend` already exists and `overwrite` is NOT equal `true`.
*/
function makeInheritable(obj, overwrite, ignoreOverwriteError) {
if (typeof obj === 'undefined' || obj === null) {
throw new TypeError("`obj` cannot be undefined or null!");
}
if (overwrite !== true && typeof obj.extend !== 'undefined' && obj.extend !== null) {
if (ignoreOverwriteError === true) {
return obj;
}
throw new TypeError("`obj.extend` already exists! You're seeing this error to prevent the current extend function from being overwritten. See docs for how to override this functionality.");
}
/**
* Creates a new object definition based upon the given `objDefProps` properties and
* causes that new object definition to inherit this object.
*
* @param {Object} objDefProps - An object containing all properties to be used in
* creating the new object definition that will inherit
* this object. If this parameter is `undefined` or
* `null`, then a new child object definition is created.
* TODO: Add reference to the `objDefProps` spec
*
* @returns {Object} An object created from the given `objDefProps` that inherits this
* object.
*
* @throws {TypeError} If the object's definition has been sealed. @see {@link https://github.com/bsara/inheritance.js/blob/master/src/inherit/seal.js}
*
* @requires inheritance
*/
Object.defineProperty(obj, 'extend', {
value: function(objDefProps) { return inheritance(obj, objDefProps); },
configurable: true,
enumerable: false,
writable: true
});
return obj;
}/**
* Makes an object sealed by adding a function called `extend` as a "static" property
* of the object that throws an error if it is ever called. (I.E. Calling this function
* passing `MyObject` as a parameter, creates `MyObject.extend` and `MyObject.sealed`,
* where `MyObject.sealed` will always be `true`)
*
* @param {Object} obj - The object to seal.
* @param {Boolean} [overwrite] - If `true`, then an existing `extend` property will be
* overwritten regardless of it's value.
* @param {Boolean} [ignoreOverwriteError] - If `true`, then no error will be thrown if
* `obj.extend` already exists and `overwrite`
* is not `true`.
*
* @returns {Object} The modified `obj` given.
*
* @throws {TypeError} If `obj` is `undefined` or `null`.
* @throws {TypeError} If `obj.extend` already exists and `overwrite` is NOT equal `true`.
*/
function seal(obj, overwrite, ignoreOverwriteError) {
if (typeof obj === 'undefined' || obj === null) {
throw new TypeError("`obj` cannot be undefined or null!");
}
if (overwrite !== true && typeof obj.extend !== 'undefined' && obj.extend !== null) {
if (ignoreOverwriteError === true) {
return obj;
}
throw new TypeError("`obj.extend` already exists! You're seeing this error to prevent the current extend function from being overwritten. See docs for how to override this functionality.");
}
if (typeof obj.extend !== 'undefined' && obj.extend !== null) {
delete obj.extend;
}
Object.defineProperties(obj, {
sealed: {
configurable: false,
enumerable: false,
writable: false,
value: true
},
extend: {
configurable: false,
enumerable: false,
writable: false,
value: function() { throw new TypeError("The object definition you are trying to extend is sealed and cannot be inherited."); }
}
});
return obj;
}/** @namespace */
var ObjectDefinition = {
/**
* Creates a new object (I.E. "class") that can be inherited.
* NOTE: The new object inherits the native JavaScript `Object`.
*
* @param {Object} objDef - TODO: Add description
*
* @returns {Object} The newly created, inheritable, object that inherits `Object`.
*
* @requires inheritance
*/
create: function(objDef) {
return inheritance(Object, objDef);
},
/**
* Creates a new object (I.E. "class") that CANNOT be inherited.
* NOTE: The new object inherits the native JavaScript `Object`.
*
* @param {Object} objDef - TODO: Add description
*
* @returns {Object} The newly created, non-inheritable, object that inherits `Object`.
*
* @requires seal
*/
createSealed: function(objDef) {
return seal(inheritance(Object, objDef), true);
}
};
seal(ObjectDefinition, true);
return {
mix: mix,
mixDeep: mixDeep,
inheritance: inheritance,
makeInheritable: makeInheritable,
seal: seal,
ObjectDefinition: ObjectDefinition
};
}));
|
/*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
/*
The MIT License (MIT)
Copyright (c) 2007-2013 Einar Lielmanis and contributors.
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.
JS Beautifier
---------------
Written by Einar Lielmanis, <einar@jsbeautifier.org>
http://jsbeautifier.org/
Originally converted to javascript by Vital, <vital76@gmail.com>
"End braces on own line" added by Chris J. Shull, <chrisjshull@gmail.com>
Parsing improvements for brace-less statements by Liam Newman <bitwiseman@gmail.com>
Usage:
js_beautify(js_source_text);
js_beautify(js_source_text, options);
The options are:
indent_size (default 4) - indentation size,
indent_char (default space) - character to indent with,
preserve_newlines (default true) - whether existing line breaks should be preserved,
max_preserve_newlines (default unlimited) - maximum number of line breaks to be preserved in one chunk,
jslint_happy (default false) - if true, then jslint-stricter mode is enforced.
jslint_happy !jslint_happy
---------------------------------
function () function()
brace_style (default "collapse") - "collapse" | "expand" | "end-expand"
put braces on the same line as control statements (default), or put braces on own line (Allman / ANSI style), or just put end braces on own line.
space_before_conditional (default true) - should the space before conditional statement be added, "if(true)" vs "if (true)",
unescape_strings (default false) - should printable characters in strings encoded in \xNN notation be unescaped, "example" vs "\x65\x78\x61\x6d\x70\x6c\x65"
wrap_line_length (default unlimited) - lines should wrap at next opportunity after this number of characters.
NOTE: This is not a hard limit. Lines will continue until a point where a newline would
be preserved if it were present.
e.g
js_beautify(js_source_text, {
'indent_size': 1,
'indent_char': '\t'
});
*/
(function() {
function js_beautify(js_source_text, options) {
"use strict";
var beautifier = new Beautifier(js_source_text, options);
return beautifier.beautify();
}
function Beautifier(js_source_text, options) {
"use strict";
var input, output, token_text, token_type, last_type, last_last_text, indent_string;
var flags, previous_flags, flag_store;
var whitespace, wordchar, punct, parser_pos, line_starters, digits;
var prefix;
var input_wanted_newline;
var output_wrapped, output_space_before_token;
var input_length, n_newlines, whitespace_before_token;
var handlers, MODE, opt;
var preindent_string = '';
whitespace = "\n\r\t ".split('');
wordchar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_$'.split('');
digits = '0123456789'.split('');
punct = '+ - * / % & ++ -- = += -= *= /= %= == === != !== > < >= <= >> << >>> >>>= >>= <<= && &= | || ! !! , : ? ^ ^= |= ::';
punct += ' <%= <% %> <?= <? ?>'; // try to be a good boy and try not to break the markup language identifiers
punct = punct.split(' ');
// words which should always start on new line.
line_starters = 'continue,try,throw,return,var,if,switch,case,default,for,while,break,function'.split(',');
MODE = {
BlockStatement: 'BlockStatement', // 'BLOCK'
Statement: 'Statement', // 'STATEMENT'
ObjectLiteral: 'ObjectLiteral', // 'OBJECT',
ArrayLiteral: 'ArrayLiteral', //'[EXPRESSION]',
ForInitializer: 'ForInitializer', //'(FOR-EXPRESSION)',
Conditional: 'Conditional', //'(COND-EXPRESSION)',
Expression: 'Expression' //'(EXPRESSION)'
};
handlers = {
'TK_START_EXPR': handle_start_expr,
'TK_END_EXPR': handle_end_expr,
'TK_START_BLOCK': handle_start_block,
'TK_END_BLOCK': handle_end_block,
'TK_WORD': handle_word,
'TK_SEMICOLON': handle_semicolon,
'TK_STRING': handle_string,
'TK_EQUALS': handle_equals,
'TK_OPERATOR': handle_operator,
'TK_COMMA': handle_comma,
'TK_BLOCK_COMMENT': handle_block_comment,
'TK_INLINE_COMMENT': handle_inline_comment,
'TK_COMMENT': handle_comment,
'TK_DOT': handle_dot,
'TK_UNKNOWN': handle_unknown
};
function create_flags(flags_base, mode) {
return {
mode: mode,
last_text: flags_base ? flags_base.last_text : '', // last token text
last_word: flags_base ? flags_base.last_word : '', // last 'TK_WORD' passed
var_line: false,
var_line_tainted: false,
var_line_reindented: false,
in_html_comment: false,
multiline_array: false,
if_block: false,
do_block: false,
do_while: false,
in_case_statement: false, // switch(..){ INSIDE HERE }
in_case: false, // we're on the exact line with "case 0:"
case_body: false, // the indented case-action block
indentation_level: (flags_base ? flags_base.indentation_level + ((flags_base.var_line && flags_base.var_line_reindented) ? 1 : 0) : 0),
ternary_depth: 0
};
}
// Some interpreters have unexpected results with foo = baz || bar;
options = options ? options : {};
opt = {};
// compatibility
if (options.space_after_anon_function !== undefined && options.jslint_happy === undefined) {
options.jslint_happy = options.space_after_anon_function;
}
if (options.braces_on_own_line !== undefined) { //graceful handling of deprecated option
opt.brace_style = options.braces_on_own_line ? "expand" : "collapse";
}
opt.brace_style = options.brace_style ? options.brace_style : (opt.brace_style ? opt.brace_style : "collapse");
// graceful handling of deprecated option
if (opt.brace_style === "expand-strict") {
opt.brace_style = "expand";
}
opt.indent_size = options.indent_size ? parseInt(options.indent_size, 10) : 4;
opt.indent_char = options.indent_char ? options.indent_char : ' ';
opt.preserve_newlines = (options.preserve_newlines === undefined) ? true : options.preserve_newlines;
opt.break_chained_methods = (options.break_chained_methods === undefined) ? false : options.break_chained_methods;
opt.max_preserve_newlines = (options.max_preserve_newlines === undefined) ? 0 : parseInt(options.max_preserve_newlines, 10);
opt.space_in_paren = (options.space_in_paren === undefined) ? false : options.space_in_paren;
opt.jslint_happy = (options.jslint_happy === undefined) ? false : options.jslint_happy;
opt.keep_array_indentation = (options.keep_array_indentation === undefined) ? false : options.keep_array_indentation;
opt.space_before_conditional= (options.space_before_conditional === undefined) ? true : options.space_before_conditional;
opt.unescape_strings = (options.unescape_strings === undefined) ? false : options.unescape_strings;
opt.wrap_line_length = (options.wrap_line_length === undefined) ? 0 : parseInt(options.wrap_line_length, 10);
opt.e4x = (options.e4x === undefined) ? false : options.e4x;
//----------------------------------
indent_string = '';
while (opt.indent_size > 0) {
indent_string += opt.indent_char;
opt.indent_size -= 1;
}
while (js_source_text && (js_source_text.charAt(0) === ' ' || js_source_text.charAt(0) === '\t')) {
preindent_string += js_source_text.charAt(0);
js_source_text = js_source_text.substring(1);
}
input = js_source_text;
// cache the source's length.
input_length = js_source_text.length;
last_type = 'TK_START_BLOCK'; // last token type
last_last_text = ''; // pre-last token text
output = [];
output_wrapped = false;
output_space_before_token = false;
whitespace_before_token = [];
// Stack of parsing/formatting states, including MODE.
// We tokenize, parse, and output in an almost purely a forward-only stream of token input
// and formatted output. This makes the beautifier less accurate than full parsers
// but also far more tolerant of syntax errors.
//
// For example, the default mode is MODE.BlockStatement. If we see a '{' we push a new frame of type
// MODE.BlockStatement on the the stack, even though it could be object literal. If we later
// encounter a ":", we'll switch to to MODE.ObjectLiteral. If we then see a ";",
// most full parsers would die, but the beautifier gracefully falls back to
// MODE.BlockStatement and continues on.
flag_store = [];
set_mode(MODE.BlockStatement);
parser_pos = 0;
this.beautify = function () {
/*jshint onevar:true */
var t, i, keep_whitespace, sweet_code;
while (true) {
t = get_next_token();
token_text = t[0];
token_type = t[1];
if (token_type === 'TK_EOF') {
break;
}
keep_whitespace = opt.keep_array_indentation && is_array(flags.mode);
input_wanted_newline = n_newlines > 0;
if (keep_whitespace) {
for (i = 0; i < n_newlines; i += 1) {
print_newline(i > 0);
}
} else {
if (opt.max_preserve_newlines && n_newlines > opt.max_preserve_newlines) {
n_newlines = opt.max_preserve_newlines;
}
if (opt.preserve_newlines) {
if (n_newlines > 1) {
print_newline();
for (i = 1; i < n_newlines; i += 1) {
print_newline(true);
}
}
}
}
handlers[token_type]();
// The cleanest handling of inline comments is to treat them as though they aren't there.
// Just continue formatting and the behavior should be logical.
// Also ignore unknown tokens. Again, this should result in better behavior.
if (token_type !== 'TK_INLINE_COMMENT' && token_type !== 'TK_COMMENT' &&
token_type !== 'TK_UNKNOWN') {
last_last_text = flags.last_text;
last_type = token_type;
flags.last_text = token_text;
}
}
sweet_code = preindent_string + output.join('').replace(/[\r\n ]+$/, '');
return sweet_code;
};
function trim_output(eat_newlines) {
eat_newlines = (eat_newlines === undefined) ? false : eat_newlines;
while (output.length && (output[output.length - 1] === ' ' || output[output.length - 1] === indent_string || output[output.length - 1] === preindent_string || (eat_newlines && (output[output.length - 1] === '\n' || output[output.length - 1] === '\r')))) {
output.pop();
}
}
function trim(s) {
return s.replace(/^\s\s*|\s\s*$/, '');
}
// we could use just string.split, but
// IE doesn't like returning empty strings
function split_newlines(s) {
//return s.split(/\x0d\x0a|\x0a/);
s = s.replace(/\x0d/g, '');
var out = [],
idx = s.indexOf("\n");
while (idx !== -1) {
out.push(s.substring(0, idx));
s = s.substring(idx + 1);
idx = s.indexOf("\n");
}
if (s.length) {
out.push(s);
}
return out;
}
function just_added_newline() {
return output.length && output[output.length - 1] === "\n";
}
function just_added_blankline() {
return just_added_newline() && output.length - 1 > 0 && output[output.length - 2] === "\n";
}
function _last_index_of(arr, find) {
var i = arr.length - 1;
if (i < 0) {
i += arr.length;
}
if (i > arr.length - 1) {
i = arr.length - 1;
}
for (i++; i-- > 0;) {
if (i in arr && arr[i] === find) {
return i;
}
}
return -1;
}
function allow_wrap_or_preserved_newline(force_linewrap) {
force_linewrap = (force_linewrap === undefined) ? false : force_linewrap;
if (opt.wrap_line_length && !force_linewrap) {
var current_line = '';
var proposed_line_length = 0;
var start_line = _last_index_of(output, '\n') + 1;
// never wrap the first token of a line.
if (start_line < output.length) {
current_line = output.slice(start_line).join('');
proposed_line_length = current_line.length + token_text.length +
(output_space_before_token ? 1 : 0);
if (proposed_line_length >= opt.wrap_line_length) {
force_linewrap = true;
}
}
}
if (((opt.preserve_newlines && input_wanted_newline) || force_linewrap) && !just_added_newline()) {
print_newline(false, true);
// Expressions and array literals already indent their contents.
if(! (is_array(flags.mode) || is_expression(flags.mode))) {
output_wrapped = true;
}
}
}
function print_newline(force_newline, preserve_statement_flags) {
output_wrapped = false;
output_space_before_token = false;
if (!preserve_statement_flags) {
if (flags.last_text !== ';') {
while (flags.mode === MODE.Statement && !flags.if_block) {
restore_mode();
}
}
}
if (flags.mode === MODE.ArrayLiteral) {
flags.multiline_array = true;
}
if (!output.length) {
return; // no newline on start of file
}
if (force_newline || !just_added_newline()) {
output.push("\n");
}
}
function print_token_line_indentation() {
if (just_added_newline()) {
if (opt.keep_array_indentation && is_array(flags.mode) && input_wanted_newline) {
for (var i = 0; i < whitespace_before_token.length; i += 1) {
output.push(whitespace_before_token[i]);
}
} else {
if (preindent_string) {
output.push(preindent_string);
}
print_indent_string(flags.indentation_level);
print_indent_string(flags.var_line && flags.var_line_reindented);
print_indent_string(output_wrapped);
}
}
}
function print_indent_string(level) {
if (level === undefined) {
level = 1;
} else if (typeof level !== 'number') {
level = level ? 1 : 0;
}
// Never indent your first output indent at the start of the file
if (flags.last_text !== '') {
for (var i = 0; i < level; i += 1) {
output.push(indent_string);
}
}
}
function print_token_space_before() {
if (output_space_before_token && output.length) {
var last_output = output[output.length - 1];
if (!just_added_newline() && last_output !== ' ' && last_output !== indent_string) { // prevent occassional duplicate space
output.push(' ');
}
}
}
function print_token(printable_token) {
printable_token = printable_token || token_text;
print_token_line_indentation();
output_wrapped = false;
print_token_space_before();
output_space_before_token = false;
output.push(printable_token);
}
function indent() {
flags.indentation_level += 1;
}
function set_mode(mode) {
if (flags) {
flag_store.push(flags);
previous_flags = flags;
} else {
previous_flags = create_flags(null, mode);
}
flags = create_flags(previous_flags, mode);
}
function is_array(mode) {
return mode === MODE.ArrayLiteral;
}
function is_expression(mode) {
return in_array(mode, [MODE.Expression, MODE.ForInitializer, MODE.Conditional]);
}
function restore_mode() {
if (flag_store.length > 0) {
previous_flags = flags;
flags = flag_store.pop();
}
}
function start_of_statement() {
if (
(flags.last_text === 'do' ||
(flags.last_text === 'else' && token_text !== 'if') ||
(last_type === 'TK_END_EXPR' && (previous_flags.mode === MODE.ForInitializer || previous_flags.mode === MODE.Conditional)))) {
allow_wrap_or_preserved_newline();
set_mode(MODE.Statement);
indent();
output_wrapped = false;
return true;
}
return false;
}
function all_lines_start_with(lines, c) {
for (var i = 0; i < lines.length; i++) {
var line = trim(lines[i]);
if (line.charAt(0) !== c) {
return false;
}
}
return true;
}
function is_special_word(word) {
return in_array(word, ['case', 'return', 'do', 'if', 'throw', 'else']);
}
function in_array(what, arr) {
for (var i = 0; i < arr.length; i += 1) {
if (arr[i] === what) {
return true;
}
}
return false;
}
function unescape_string(s) {
var esc = false,
out = '',
pos = 0,
s_hex = '',
escaped = 0,
c;
while (esc || pos < s.length) {
c = s.charAt(pos);
pos++;
if (esc) {
esc = false;
if (c === 'x') {
// simple hex-escape \x24
s_hex = s.substr(pos, 2);
pos += 2;
} else if (c === 'u') {
// unicode-escape, \u2134
s_hex = s.substr(pos, 4);
pos += 4;
} else {
// some common escape, e.g \n
out += '\\' + c;
continue;
}
if (!s_hex.match(/^[0123456789abcdefABCDEF]+$/)) {
// some weird escaping, bail out,
// leaving whole string intact
return s;
}
escaped = parseInt(s_hex, 16);
if (escaped >= 0x00 && escaped < 0x20) {
// leave 0x00...0x1f escaped
if (c === 'x') {
out += '\\x' + s_hex;
} else {
out += '\\u' + s_hex;
}
continue;
} else if (escaped === 0x22 || escaped === 0x27 || escaped === 0x5c) {
// single-quote, apostrophe, backslash - escape these
out += '\\' + String.fromCharCode(escaped);
} else if (c === 'x' && escaped > 0x7e && escaped <= 0xff) {
// we bail out on \x7f..\xff,
// leaving whole string escaped,
// as it's probably completely binary
return s;
} else {
out += String.fromCharCode(escaped);
}
} else if (c === '\\') {
esc = true;
} else {
out += c;
}
}
return out;
}
function is_next(find) {
var local_pos = parser_pos;
var c = input.charAt(local_pos);
while (in_array(c, whitespace) && c !== find) {
local_pos++;
if (local_pos >= input_length) {
return false;
}
c = input.charAt(local_pos);
}
return c === find;
}
function get_next_token() {
var i, resulting_string;
n_newlines = 0;
if (parser_pos >= input_length) {
return ['', 'TK_EOF'];
}
input_wanted_newline = false;
whitespace_before_token = [];
var c = input.charAt(parser_pos);
parser_pos += 1;
while (in_array(c, whitespace)) {
if (c === '\n') {
n_newlines += 1;
whitespace_before_token = [];
} else if (n_newlines) {
if (c === indent_string) {
whitespace_before_token.push(indent_string);
} else if (c !== '\r') {
whitespace_before_token.push(' ');
}
}
if (parser_pos >= input_length) {
return ['', 'TK_EOF'];
}
c = input.charAt(parser_pos);
parser_pos += 1;
}
if (in_array(c, wordchar)) {
if (parser_pos < input_length) {
while (in_array(input.charAt(parser_pos), wordchar)) {
c += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos === input_length) {
break;
}
}
}
// small and surprisingly unugly hack for 1E-10 representation
if (parser_pos !== input_length && c.match(/^[0-9]+[Ee]$/) && (input.charAt(parser_pos) === '-' || input.charAt(parser_pos) === '+')) {
var sign = input.charAt(parser_pos);
parser_pos += 1;
var t = get_next_token();
c += sign + t[0];
return [c, 'TK_WORD'];
}
if (c === 'in') { // hack for 'in' operator
return [c, 'TK_OPERATOR'];
}
return [c, 'TK_WORD'];
}
if (c === '(' || c === '[') {
return [c, 'TK_START_EXPR'];
}
if (c === ')' || c === ']') {
return [c, 'TK_END_EXPR'];
}
if (c === '{') {
return [c, 'TK_START_BLOCK'];
}
if (c === '}') {
return [c, 'TK_END_BLOCK'];
}
if (c === ';') {
return [c, 'TK_SEMICOLON'];
}
if (c === '/') {
var comment = '';
// peek for comment /* ... */
var inline_comment = true;
if (input.charAt(parser_pos) === '*') {
parser_pos += 1;
if (parser_pos < input_length) {
while (parser_pos < input_length && !(input.charAt(parser_pos) === '*' && input.charAt(parser_pos + 1) && input.charAt(parser_pos + 1) === '/')) {
c = input.charAt(parser_pos);
comment += c;
if (c === "\n" || c === "\r") {
inline_comment = false;
}
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
}
parser_pos += 2;
if (inline_comment && n_newlines === 0) {
return ['/*' + comment + '*/', 'TK_INLINE_COMMENT'];
} else {
return ['/*' + comment + '*/', 'TK_BLOCK_COMMENT'];
}
}
// peek for comment // ...
if (input.charAt(parser_pos) === '/') {
comment = c;
while (input.charAt(parser_pos) !== '\r' && input.charAt(parser_pos) !== '\n') {
comment += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
return [comment, 'TK_COMMENT'];
}
}
if (c === "'" || c === '"' || // string
(
(c === '/') || // regexp
(opt.e4x && c ==="<" && input.slice(parser_pos - 1).match(/^<[a-zA-Z:0-9]+\s*([a-zA-Z:0-9]+="[^"]*"\s*)*\/?\s*>/)) // xml
) && ( // regex and xml can only appear in specific locations during parsing
(last_type === 'TK_WORD' && is_special_word (flags.last_text)) ||
(last_type === 'TK_END_EXPR' && in_array(previous_flags.mode, [MODE.Conditional, MODE.ForInitializer])) ||
(in_array(last_type, ['TK_COMMENT', 'TK_START_EXPR', 'TK_START_BLOCK',
'TK_END_BLOCK', 'TK_OPERATOR', 'TK_EQUALS', 'TK_EOF', 'TK_SEMICOLON', 'TK_COMMA']))
)) {
var sep = c,
esc = false,
has_char_escapes = false;
resulting_string = c;
if (parser_pos < input_length) {
if (sep === '/') {
//
// handle regexp
//
var in_char_class = false;
while (esc || in_char_class || input.charAt(parser_pos) !== sep) {
resulting_string += input.charAt(parser_pos);
if (!esc) {
esc = input.charAt(parser_pos) === '\\';
if (input.charAt(parser_pos) === '[') {
in_char_class = true;
} else if (input.charAt(parser_pos) === ']') {
in_char_class = false;
}
} else {
esc = false;
}
parser_pos += 1;
if (parser_pos >= input_length) {
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
return [resulting_string, 'TK_STRING'];
}
}
} else if (opt.e4x && sep === '<') {
//
// handle e4x xml literals
//
var xmlRegExp = /<(\/?)([a-zA-Z:0-9]+)\s*([a-zA-Z:0-9]+="[^"]*"\s*)*(\/?)\s*>/g;
var xmlStr = input.slice(parser_pos - 1);
var match = xmlRegExp.exec(xmlStr);
if (match && match.index === 0) {
var rootTag = match[2];
var depth = 0;
while (match) {
var isEndTag = !! match[1];
var tagName = match[2];
var isSingletonTag = !! match[match.length - 1];
if (tagName === rootTag && !isSingletonTag) {
if (isEndTag) {
--depth;
} else {
++depth;
}
}
if (depth <= 0) {
break;
}
match = xmlRegExp.exec(xmlStr);
}
var xmlLength = match ? match.index + match[0].length : xmlStr.length;
parser_pos += xmlLength - 1;
return [xmlStr.slice(0, xmlLength), "TK_STRING"];
}
} else {
//
// handle string
//
while (esc || input.charAt(parser_pos) !== sep) {
resulting_string += input.charAt(parser_pos);
if (esc) {
if (input.charAt(parser_pos) === 'x' || input.charAt(parser_pos) === 'u') {
has_char_escapes = true;
}
esc = false;
} else {
esc = input.charAt(parser_pos) === '\\';
}
parser_pos += 1;
if (parser_pos >= input_length) {
// incomplete string/rexp when end-of-file reached.
// bail out with what had been received so far.
return [resulting_string, 'TK_STRING'];
}
}
}
}
parser_pos += 1;
resulting_string += sep;
if (has_char_escapes && opt.unescape_strings) {
resulting_string = unescape_string(resulting_string);
}
if (sep === '/') {
// regexps may have modifiers /regexp/MOD , so fetch those, too
while (parser_pos < input_length && in_array(input.charAt(parser_pos), wordchar)) {
resulting_string += input.charAt(parser_pos);
parser_pos += 1;
}
}
return [resulting_string, 'TK_STRING'];
}
if (c === '#') {
if (output.length === 0 && input.charAt(parser_pos) === '!') {
// shebang
resulting_string = c;
while (parser_pos < input_length && c !== '\n') {
c = input.charAt(parser_pos);
resulting_string += c;
parser_pos += 1;
}
return [trim(resulting_string) + '\n', 'TK_UNKNOWN'];
}
// Spidermonkey-specific sharp variables for circular references
// https://developer.mozilla.org/En/Sharp_variables_in_JavaScript
// http://mxr.mozilla.org/mozilla-central/source/js/src/jsscan.cpp around line 1935
var sharp = '#';
if (parser_pos < input_length && in_array(input.charAt(parser_pos), digits)) {
do {
c = input.charAt(parser_pos);
sharp += c;
parser_pos += 1;
} while (parser_pos < input_length && c !== '#' && c !== '=');
if (c === '#') {
//
} else if (input.charAt(parser_pos) === '[' && input.charAt(parser_pos + 1) === ']') {
sharp += '[]';
parser_pos += 2;
} else if (input.charAt(parser_pos) === '{' && input.charAt(parser_pos + 1) === '}') {
sharp += '{}';
parser_pos += 2;
}
return [sharp, 'TK_WORD'];
}
}
if (c === '<' && input.substring(parser_pos - 1, parser_pos + 3) === '<!--') {
parser_pos += 3;
c = '<!--';
while (input.charAt(parser_pos) !== '\n' && parser_pos < input_length) {
c += input.charAt(parser_pos);
parser_pos++;
}
flags.in_html_comment = true;
return [c, 'TK_COMMENT'];
}
if (c === '-' && flags.in_html_comment && input.substring(parser_pos - 1, parser_pos + 2) === '-->') {
flags.in_html_comment = false;
parser_pos += 2;
return ['-->', 'TK_COMMENT'];
}
if (c === '.') {
return [c, 'TK_DOT'];
}
if (in_array(c, punct)) {
while (parser_pos < input_length && in_array(c + input.charAt(parser_pos), punct)) {
c += input.charAt(parser_pos);
parser_pos += 1;
if (parser_pos >= input_length) {
break;
}
}
if (c === ',') {
return [c, 'TK_COMMA'];
} else if (c === '=') {
return [c, 'TK_EQUALS'];
} else {
return [c, 'TK_OPERATOR'];
}
}
return [c, 'TK_UNKNOWN'];
}
function handle_start_expr() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
}
if (token_text === '[') {
if (last_type === 'TK_WORD' || flags.last_text === ')') {
// this is array index specifier, break immediately
// a[x], fn()[x]
if (in_array (flags.last_text, line_starters)) {
output_space_before_token = true;
}
set_mode(MODE.Expression);
print_token();
if (opt.space_in_paren) {
output_space_before_token = true;
}
return;
}
if (is_array(flags.mode)) {
if (flags.last_text === '[' ||
(flags.last_text === ',' && (last_last_text === ']' || last_last_text === '}'))) {
// ], [ goes to new line
// }, [ goes to new line
if (!opt.keep_array_indentation) {
print_newline();
}
}
}
} else {
if (flags.last_text === 'for') {
set_mode(MODE.ForInitializer);
} else if (in_array (flags.last_text, ['if', 'while'])) {
set_mode(MODE.Conditional);
} else {
set_mode(MODE.Expression);
}
}
if (flags.last_text === ';' || last_type === 'TK_START_BLOCK') {
print_newline();
} else if (last_type === 'TK_END_EXPR' || last_type === 'TK_START_EXPR' || last_type === 'TK_END_BLOCK' || flags.last_text === '.') {
if (input_wanted_newline) {
print_newline();
}
// do nothing on (( and )( and ][ and ]( and .(
} else if (last_type !== 'TK_WORD' && last_type !== 'TK_OPERATOR') {
output_space_before_token = true;
} else if (flags.last_word === 'function' || flags.last_word === 'typeof') {
// function() vs function ()
if (opt.jslint_happy) {
output_space_before_token = true;
}
} else if (in_array (flags.last_text, line_starters) || flags.last_text === 'catch') {
if (opt.space_before_conditional) {
output_space_before_token = true;
}
}
// Support of this kind of newline preservation.
// a = (b &&
// (c || d));
if (token_text === '(') {
if (last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (flags.mode !== MODE.ObjectLiteral) {
allow_wrap_or_preserved_newline();
}
}
}
if (token_text === '[') {
set_mode(MODE.ArrayLiteral);
}
print_token();
if (opt.space_in_paren) {
output_space_before_token = true;
}
// In all cases, if we newline while inside an expression it should be indented.
indent();
}
function handle_end_expr() {
// statements inside expressions are not valid syntax, but...
// statements must all be closed when their container closes
while (flags.mode === MODE.Statement) {
restore_mode();
}
if (token_text === ']' && is_array(flags.mode) && flags.multiline_array && !opt.keep_array_indentation) {
print_newline();
}
if (opt.space_in_paren) {
output_space_before_token = true;
}
if (token_text === ']' && opt.keep_array_indentation) {
print_token();
restore_mode();
} else {
restore_mode();
print_token();
}
// do {} while () // no statement required after
if (flags.do_while && previous_flags.mode === MODE.Conditional) {
previous_flags.mode = MODE.Expression;
flags.do_block = false;
flags.do_while = false;
}
}
function handle_start_block() {
set_mode(MODE.BlockStatement);
var empty_braces = is_next('}');
var empty_anonymous_function = empty_braces && flags.last_word === 'function' &&
last_type === 'TK_END_EXPR';
if (opt.brace_style === "expand") {
if (last_type !== 'TK_OPERATOR' &&
(empty_anonymous_function ||
last_type === 'TK_EQUALS' ||
(is_special_word (flags.last_text) && flags.last_text !== 'else'))) {
output_space_before_token = true;
} else {
print_newline();
}
} else { // collapse
if (last_type !== 'TK_OPERATOR' && last_type !== 'TK_START_EXPR') {
if (last_type === 'TK_START_BLOCK') {
print_newline();
} else {
output_space_before_token = true;
}
} else {
// if TK_OPERATOR or TK_START_EXPR
if (is_array(previous_flags.mode) && flags.last_text === ',') {
if (last_last_text === '}') {
// }, { in array context
output_space_before_token = true;
} else {
print_newline(); // [a, b, c, {
}
}
}
}
print_token();
indent();
}
function handle_end_block() {
// statements must all be closed when their container closes
while (flags.mode === MODE.Statement) {
restore_mode();
}
restore_mode();
var empty_braces = last_type === 'TK_START_BLOCK';
if (opt.brace_style === "expand") {
if (!empty_braces) {
print_newline();
}
} else {
// skip {}
if (!empty_braces) {
if (is_array(flags.mode) && opt.keep_array_indentation) {
// we REALLY need a newline here, but newliner would skip that
opt.keep_array_indentation = false;
print_newline();
opt.keep_array_indentation = true;
} else {
print_newline();
}
}
}
print_token();
}
function handle_word() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
} else if (input_wanted_newline && !is_expression(flags.mode) &&
(last_type !== 'TK_OPERATOR' || (flags.last_text === '--' || flags.last_text === '++')) &&
last_type !== 'TK_EQUALS' &&
(opt.preserve_newlines || flags.last_text !== 'var')) {
print_newline();
}
if (flags.do_block && !flags.do_while) {
if (token_text === 'while') {
// do {} ## while ()
output_space_before_token = true;
print_token();
output_space_before_token = true;
flags.do_while = true;
return;
} else {
// do {} should always have while as the next word.
// if we don't see the expected while, recover
print_newline();
flags.do_block = false;
}
}
// if may be followed by else, or not
// Bare/inline ifs are tricky
// Need to unwind the modes correctly: if (a) if (b) c(); else d(); else e();
if (flags.if_block) {
if (token_text !== 'else') {
while (flags.mode === MODE.Statement) {
restore_mode();
}
flags.if_block = false;
}
}
if (token_text === 'function') {
if (flags.var_line && last_type !== 'TK_EQUALS') {
flags.var_line_reindented = true;
}
if ((just_added_newline() || flags.last_text === ';' || flags.last_text === '}') &&
flags.last_text !== '{' && !is_array(flags.mode)) {
// make sure there is a nice clean space of at least one blank line
// before a new function definition, except in arrays
if(!just_added_newline()) {
print_newline(true);
}
if(!just_added_blankline()) {
print_newline(true);
}
}
if (last_type === 'TK_WORD') {
if (flags.last_text === 'get' || flags.last_text === 'set' || flags.last_text === 'new' || flags.last_text === 'return') {
output_space_before_token = true;
} else {
print_newline();
}
} else if (last_type === 'TK_OPERATOR' || flags.last_text === '=') {
// foo = function
output_space_before_token = true;
} else if (is_expression(flags.mode)) {
// (function
} else {
print_newline();
}
print_token();
flags.last_word = token_text;
return;
}
if (token_text === 'case' || (token_text === 'default' && flags.in_case_statement)) {
print_newline();
if (flags.case_body || opt.jslint_happy) {
// switch cases following one another
flags.indentation_level--;
flags.case_body = false;
}
print_token();
flags.in_case = true;
flags.in_case_statement = true;
return;
}
prefix = 'NONE';
if (last_type === 'TK_END_BLOCK') {
if (!in_array(token_text, ['else', 'catch', 'finally'])) {
prefix = 'NEWLINE';
} else {
if (opt.brace_style === "expand" || opt.brace_style === "end-expand") {
prefix = 'NEWLINE';
} else {
prefix = 'SPACE';
output_space_before_token = true;
}
}
} else if (last_type === 'TK_SEMICOLON' && flags.mode === MODE.BlockStatement) {
// TODO: Should this be for STATEMENT as well?
prefix = 'NEWLINE';
} else if (last_type === 'TK_SEMICOLON' && is_expression(flags.mode)) {
prefix = 'SPACE';
} else if (last_type === 'TK_STRING') {
prefix = 'NEWLINE';
} else if (last_type === 'TK_WORD') {
prefix = 'SPACE';
} else if (last_type === 'TK_START_BLOCK') {
prefix = 'NEWLINE';
} else if (last_type === 'TK_END_EXPR') {
output_space_before_token = true;
prefix = 'NEWLINE';
}
if (in_array(token_text, line_starters) && flags.last_text !== ')') {
if (flags.last_text === 'else') {
prefix = 'SPACE';
} else {
prefix = 'NEWLINE';
}
}
if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (flags.mode !== MODE.ObjectLiteral) {
allow_wrap_or_preserved_newline();
}
}
if (in_array(token_text, ['else', 'catch', 'finally'])) {
if (last_type !== 'TK_END_BLOCK' || opt.brace_style === "expand" || opt.brace_style === "end-expand") {
print_newline();
} else {
trim_output(true);
// If we trimmed and there's something other than a close block before us
// put a newline back in. Handles '} // comment' scenario.
if (output[output.length - 1] !== '}') {
print_newline();
}
output_space_before_token = true;
}
} else if (prefix === 'NEWLINE') {
if (is_special_word (flags.last_text)) {
// no newline between 'return nnn'
output_space_before_token = true;
} else if (last_type !== 'TK_END_EXPR') {
if ((last_type !== 'TK_START_EXPR' || token_text !== 'var') && flags.last_text !== ':') {
// no need to force newline on 'var': for (var x = 0...)
if (token_text === 'if' && flags.last_word === 'else' && flags.last_text !== '{') {
// no newline for } else if {
output_space_before_token = true;
} else {
flags.var_line = false;
flags.var_line_reindented = false;
print_newline();
}
}
} else if (in_array(token_text, line_starters) && flags.last_text !== ')') {
flags.var_line = false;
flags.var_line_reindented = false;
print_newline();
}
} else if (is_array(flags.mode) && flags.last_text === ',' && last_last_text === '}') {
print_newline(); // }, in lists get a newline treatment
} else if (prefix === 'SPACE') {
output_space_before_token = true;
}
print_token();
flags.last_word = token_text;
if (token_text === 'var') {
flags.var_line = true;
flags.var_line_reindented = false;
flags.var_line_tainted = false;
}
if (token_text === 'do') {
flags.do_block = true;
}
if (token_text === 'if') {
flags.if_block = true;
}
}
function handle_semicolon() {
while (flags.mode === MODE.Statement && !flags.if_block) {
restore_mode();
}
print_token();
flags.var_line = false;
flags.var_line_reindented = false;
if (flags.mode === MODE.ObjectLiteral) {
// if we're in OBJECT mode and see a semicolon, its invalid syntax
// recover back to treating this as a BLOCK
flags.mode = MODE.BlockStatement;
}
}
function handle_string() {
if (start_of_statement()) {
// The conditional starts the statement if appropriate.
// One difference - strings want at least a space before
output_space_before_token = true;
} else if (last_type === 'TK_WORD') {
output_space_before_token = true;
} else if (last_type === 'TK_COMMA' || last_type === 'TK_START_EXPR' || last_type === 'TK_EQUALS' || last_type === 'TK_OPERATOR') {
if (flags.mode !== MODE.ObjectLiteral) {
allow_wrap_or_preserved_newline();
}
} else {
print_newline();
}
print_token();
}
function handle_equals() {
if (flags.var_line) {
// just got an '=' in a var-line, different formatting/line-breaking, etc will now be done
flags.var_line_tainted = true;
}
output_space_before_token = true;
print_token();
output_space_before_token = true;
}
function handle_comma() {
if (flags.var_line) {
if (is_expression(flags.mode) || last_type === 'TK_END_BLOCK') {
// do not break on comma, for(var a = 1, b = 2)
flags.var_line_tainted = false;
}
if (flags.var_line) {
flags.var_line_reindented = true;
}
print_token();
if (flags.var_line_tainted) {
flags.var_line_tainted = false;
print_newline();
} else {
output_space_before_token = true;
}
return;
}
if (last_type === 'TK_END_BLOCK' && flags.mode !== MODE.Expression) {
print_token();
if (flags.mode === MODE.ObjectLiteral && flags.last_text === '}') {
print_newline();
} else {
output_space_before_token = true;
}
} else {
if (flags.mode === MODE.ObjectLiteral) {
print_token();
print_newline();
} else {
// EXPR or DO_BLOCK
print_token();
output_space_before_token = true;
}
}
}
function handle_operator() {
var space_before = true;
var space_after = true;
if (is_special_word (flags.last_text)) {
// "return" had a special handling in TK_WORD. Now we need to return the favor
output_space_before_token = true;
print_token();
return;
}
// hack for actionscript's import .*;
if (token_text === '*' && last_type === 'TK_DOT' && !last_last_text.match(/^\d+$/)) {
print_token();
return;
}
if (token_text === ':' && flags.in_case) {
flags.case_body = true;
indent();
print_token();
print_newline();
flags.in_case = false;
return;
}
if (token_text === '::') {
// no spaces around exotic namespacing syntax operator
print_token();
return;
}
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.9.1
// if there is a newline between -- or ++ and anything else we should preserve it.
if (input_wanted_newline && (token_text === '--' || token_text === '++')) {
print_newline();
}
if (in_array(token_text, ['--', '++', '!']) || (in_array(token_text, ['-', '+']) && (in_array(last_type, ['TK_START_BLOCK', 'TK_START_EXPR', 'TK_EQUALS', 'TK_OPERATOR']) || in_array (flags.last_text, line_starters) || flags.last_text === ','))) {
// unary operators (and binary +/- pretending to be unary) special cases
space_before = false;
space_after = false;
if (flags.last_text === ';' && is_expression(flags.mode)) {
// for (;; ++i)
// ^^^
space_before = true;
}
if (last_type === 'TK_WORD' && in_array (flags.last_text, line_starters)) {
space_before = true;
}
if ((flags.mode === MODE.BlockStatement || flags.mode === MODE.Statement) && (flags.last_text === '{' || flags.last_text === ';')) {
// { foo; --i }
// foo(); --bar;
print_newline();
}
} else if (token_text === ':') {
if (flags.ternary_depth === 0) {
if (flags.mode === MODE.BlockStatement) {
flags.mode = MODE.ObjectLiteral;
}
space_before = false;
} else {
flags.ternary_depth -= 1;
}
} else if (token_text === '?') {
flags.ternary_depth += 1;
}
output_space_before_token = output_space_before_token || space_before;
print_token();
output_space_before_token = space_after;
}
function handle_block_comment() {
var lines = split_newlines(token_text);
var j; // iterator for this case
var javadoc = false;
// block comment starts with a new line
print_newline(false, true);
if (lines.length > 1) {
if (all_lines_start_with(lines.slice(1), '*')) {
javadoc = true;
}
}
// first line always indented
print_token(lines[0]);
for (j = 1; j < lines.length; j++) {
print_newline(false, true);
if (javadoc) {
// javadoc: reformat and re-indent
print_token(' ' + trim(lines[j]));
} else {
// normal comments output raw
output.push(lines[j]);
}
}
// for comments of more than one line, make sure there's a new line after
print_newline(false, true);
}
function handle_inline_comment() {
output_space_before_token = true;
print_token();
output_space_before_token = true;
}
function handle_comment() {
if (input_wanted_newline) {
print_newline(false, true);
} else {
trim_output(true);
}
output_space_before_token = true;
print_token();
print_newline(false, true);
}
function handle_dot() {
if (is_special_word (flags.last_text)) {
output_space_before_token = true;
} else {
// allow preserved newlines before dots in general
// force newlines on dots after close paren when break_chained - for bar().baz()
allow_wrap_or_preserved_newline (flags.last_text === ')' && opt.break_chained_methods);
}
print_token();
}
function handle_unknown() {
print_token();
if (token_text[token_text.length - 1] === '\n') {
print_newline();
}
}
}
if (typeof define === "function") {
// Add support for require.js
define(function(require, exports, module) {
exports.js_beautify = js_beautify;
});
} else if (typeof exports !== "undefined") {
// Add support for CommonJS. Just put this file somewhere on your require.paths
// and you will be able to `var js_beautify = require("beautify").js_beautify`.
exports.js_beautify = js_beautify;
} else if (typeof window !== "undefined") {
// If we're running a web page and don't have either of the above, add our one global
window.js_beautify = js_beautify;
} else if (typeof global !== "undefined") {
// If we don't even have window, try global.
global.js_beautify = js_beautify;
}
}());
|
(function(L,O){"object"===typeof exports&&"undefined"!==typeof module?O(exports):"function"===typeof define&&define.amd?define(["exports"],O):L.async?O(L.neo_async=L.neo_async||{}):O(L.async=L.async||{})})(this,function(L){function O(a){var c=function(a){var d=J(arguments,1);setTimeout(function(){a.apply(null,d)})};Q="function"===typeof setImmediate?setImmediate:c;"object"===typeof process&&"function"===typeof process.nextTick?(C=/^v0.10/.test(process.version)?Q:process.nextTick,X=/^v0/.test(process.version)?
Q:process.nextTick):X=C=Q;!1===a&&(C=function(a){a()})}function E(a){for(var c=-1,b=a.length,d=Array(b);++c<b;)d[c]=a[c];return d}function J(a,c){var b=-1,d=a.length-c;if(0>=d)return[];for(var e=Array(d);++b<d;)e[b]=a[b+c];return e}function M(a){for(var c=D(a),b=c.length,d=-1,e={};++d<b;){var f=c[d];e[f]=a[f]}return e}function ia(a){for(var c=-1,b=a.length,d=[];++c<b;){var e=a[c];e&&(d[d.length]=e)}return d}function Ua(a){for(var c=-1,b=a.length,d=Array(b),e=b;++c<b;)d[--e]=a[c];return d}function Va(a,
c){for(var b=-1,d=a.length;++b<d;)if(a[b]===c)return!1;return!0}function R(a,c){for(var b=-1,d=a.length;++b<d;)c(a[b],b);return a}function S(a,c,b){for(var d=-1,e=b.length;++d<e;){var f=b[d];c(a[f],f)}return a}function K(a,c){for(var b=-1;++b<a;)c(b)}function Y(a,c){for(var b=-1,d=a.length,e=Array(d);++b<d;)e[b]=(a[b]||{})[c];return e}function Z(a,c){return a.criteria-c.criteria}function ja(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++d<e;)c(a[d],d,A(b));else for(;++d<e;)c(a[d],A(b))}function ka(a,
c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,A(b));else for(;++f<g;)c(a[d[f]],A(b))}function la(a,c,b){a=a[x]();var d=-1,e;if(3===c.length)for(;!1===(e=a.next()).done;)c(e.value,++d,b);else for(;!1===(e=a.next()).done;)c(e.value,b)}function ma(a,c,b){var d=-1,e=a.length;if(3===c.length)for(;++d<e;)c(a[d],d,b(d));else for(;++d<e;)c(a[d],b(d))}function $(a,c,b){var d,e=-1,f=a.length;if(3===c.length)for(;++e<f;)d=a[e],c(d,e,b(d));else for(;++e<f;)d=a[e],c(d,b(d))}function aa(a,
c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e,b(f));else for(;++g<l;)f=a[d[g]],c(f,b(f))}function ba(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(d));else for(;!1===(d=a.next()).done;)d=d.value,c(d,b(d))}function T(a,c,b){var d,e=-1,f=a.length;if(3===c.length)for(;++e<f;)d=a[e],c(d,e,b(e,d));else for(;++e<f;)d=a[e],c(d,b(e,d))}function na(a,c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e,
b(g,f));else for(;++g<l;)f=a[d[g]],c(f,b(g,f))}function oa(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(e,d));else for(;!1===(d=a.next()).done;)d=d.value,c(d,b(++e,d))}function pa(a,c,b,d){var e,f,g=-1,l=d.length;if(3===c.length)for(;++g<l;)e=d[g],f=a[e],c(f,e,b(e,f));else for(;++g<l;)e=d[g],f=a[e],c(f,b(e,f))}function qa(a,c,b){var d,e=-1;a=a[x]();if(3===c.length)for(;!1===(d=a.next()).done;)d=d.value,c(d,++e,b(e,d));else for(;!1===(d=a.next()).done;)d=
d.value,c(d,b(++e,d))}function A(a){return function(c,b){var d=a;a=z;d(c,b)}}function H(a){return function(c,b){var d=a;a=y;d(c,b)}}function ra(a,c,b,d){var e,f;d?(e=Array,f=E):(e=function(){return{}},f=M);return function(d,l,s){function q(a){return function(d,b){null===a&&z();d?(a=null,s=H(s),s(d,f(k))):(k[a]=b,a=null,++n===h&&s(null,k))}}s=s||y;var h,m,k,n=0;B(d)?(h=d.length,k=e(h),a(d,l,q)):d&&(x&&d[x]?(h=d.size,k=e(h),b(d,l,q)):"object"===typeof d&&(m=D(d),h=m.length,k=e(h),c(d,l,q,m)));h||s(null,
e())}}function sa(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&z();c?(a=null,g=H(g),g(c)):(!!e===d&&(h[a]=b),a=null,++m===s&&g(null,ia(h)))}}g=g||y;var s,q,h,m=0;B(e)?(s=e.length,h=Array(s),a(e,f,l)):e&&(x&&e[x]?(s=e.size,h=Array(s),b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,h=Array(s),c(e,f,l,q)));if(!s)return g(null,[])}}function ta(a){return function(c,b,d){function e(){n=c[u];b(n,h)}function f(){n=c[u];b(n,u,h)}function g(){n=p.next().value;b(n,h)}function l(){n=
p.next().value;b(n,u,h)}function s(){k=r[u];n=c[k];b(n,h)}function q(){k=r[u];n=c[k];b(n,k,h)}function h(b,c){b?d(b):(!!c===a&&(w[w.length]=n),++u===m?(t=z,d(null,w)):v?C(t):(v=!0,t()),v=!1)}d=A(d||y);var m,k,n,r,p,t,v=!1,u=0,w=[];B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null,[]);t()}}function ua(a){return function(c,b,d,e){function f(){n=I++;n<k&&(p=c[n],d(p,m(p,n)))}function g(){n=
I++;n<k&&(p=c[n],d(p,n,m(p,n)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p,I++)))}function s(){!1===(u=v.next()).done&&(p=u.value,d(p,I,m(p,I++)))}function q(){n=I++;n<k&&(p=c[t[n]],d(p,m(p,n)))}function h(){n=I++;n<k&&(r=t[n],p=c[r],d(p,r,m(p,n)))}function m(d,b){return function(c,f){null===b&&z();c?(b=null,w=y,e=H(e),e(c)):(!!f===a&&(G[b]=d),b=null,++E===k?(e=A(e),e(null,ia(G))):F?C(w):(F=!0,w()),F=!1)}}e=e||y;var k,n,r,p,t,v,u,w,G,F=!1,I=0,E=0;B(c)?(k=c.length,w=3===d.length?g:f):
c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q));if(!k||isNaN(b)||1>b)return e(null,[]);G=Array(k);K(b>k?k:b,w)}}function U(a,c,b){function d(){c(a[v],q)}function e(){c(a[v],v,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,v,q)}function l(){c(a[k[v]],q)}function s(){m=k[v];c(a[m],m,q)}function q(a,d){a?b(a):++v===h?(p=z,b(null)):!1===d?(p=z,b(null)):t?C(p):(t=!0,p());t=!1}b=A(b||y);var h,m,k,n,r,p,t=!1,v=0;B(a)?
(h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null);p()}function V(a,c,b,d){function e(){w<m&&b(a[w++],h)}function f(){k=w++;k<m&&b(a[k],k,h)}function g(){!1===(t=p.next()).done&&b(t.value,h)}function l(){!1===(t=p.next()).done&&b(t.value,w++,h)}function s(){w<m&&b(a[r[w++]],h)}function q(){k=w++;k<m&&(n=r[k],b(a[n],n,h))}function h(a,b){a?(v=y,d=H(d),d(a)):++G===m?(v=z,d=A(d),d(null)):
!1===b?(v=y,d=H(d),d(null)):u?C(v):(u=!0,v());u=!1}d=d||y;var m,k,n,r,p,t,v,u=!1,w=0,G=0;if(B(a))m=a.length,v=3===b.length?f:e;else if(a)if(x&&a[x])m=a.size,p=a[x](),v=3===b.length?l:g;else if("object"===typeof a)r=D(a),m=r.length,v=3===b.length?q:s;else return d(null);if(!m||isNaN(c)||1>c)return d(null);K(c>m?m:c,v)}function va(a,c,b){function d(){c(a[u],q)}function e(){c(a[u],u,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,u,q)}function l(){c(a[k[u]],q)}function s(){m=k[u];
c(a[m],m,q)}function q(a,d){a?(t=z,b=A(b),b(a,E(p))):(p[u]=d,++u===h?(t=z,b(null,p),b=z):v?C(t):(v=!0,t()),v=!1)}b=b||y;var h,m,k,n,r,p,t,v=!1,u=0;B(a)?(h=a.length,t=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),t=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,t=3===c.length?s:l));if(!h)return b(null,[]);p=Array(h);t()}function wa(a,c,b,d){return function(e,f,g){function l(a){var b=!1;return function(c,e){b&&z();b=!0;c?(g=H(g),g(c)):!!e===d?(g=H(g),g(null,a)):++h===s&&g(null)}}g=g||
y;var s,q,h=0;B(e)?(s=e.length,a(e,f,l)):e&&(x&&e[x]?(s=e.size,b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,c(e,f,l,q)));s||g(null)}}function xa(a){return function(c,b,d){function e(){n=c[u];b(n,h)}function f(){n=c[u];b(n,u,h)}function g(){n=p.next().value;b(n,h)}function l(){n=p.next().value;b(n,u,h)}function s(){n=c[r[u]];b(n,h)}function q(){k=r[u];n=c[k];b(n,k,h)}function h(b,c){b?d(b):!!c===a?(t=z,d(null,n)):++u===m?(t=z,d(null)):v?C(t):(v=!0,t());v=!1}d=A(d||y);var m,k,n,r,p,t,v=!1,u=0;
B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null);t()}}function ya(a){return function(c,b,d,e){function f(){n=F++;n<k&&(p=c[n],d(p,m(p)))}function g(){n=F++;n<k&&(p=c[n],d(p,n,m(p)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p)))}function s(){!1===(u=v.next()).done&&(p=u.value,d(p,F++,m(p)))}function q(){n=F++;n<k&&(p=c[t[n]],d(p,m(p)))}function h(){F<k&&(r=t[F++],p=
c[r],d(p,r,m(p)))}function m(b){var d=!1;return function(c,f){d&&z();d=!0;c?(w=y,e=H(e),e(c)):!!f===a?(w=y,e=H(e),e(null,b)):++I===k?e(null):G?C(w):(G=!0,w());G=!1}}e=e||y;var k,n,r,p,t,v,u,w,G=!1,F=0,I=0;B(c)?(k=c.length,w=3===d.length?g:f):c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q));if(!k||isNaN(b)||1>b)return e(null);K(b>k?k:b,w)}}function za(a,c,b,d){return function(e,f,g){function l(a,b){return function(c,e){null===a&&z();c?
(a=null,g=H(g),g(c,M(m))):(!!e===d&&(m[a]=b),a=null,++h===s&&g(null,m))}}g=g||y;var s,q,h=0,m={};B(e)?(s=e.length,a(e,f,l)):e&&(x&&e[x]?(s=e.size,b(e,f,l)):"object"===typeof e&&(q=D(e),s=q.length,c(e,f,l,q)));if(!s)return g(null,{})}}function Aa(a){return function(c,b,d){function e(){k=w;n=c[w];b(n,h)}function f(){k=w;n=c[w];b(n,w,h)}function g(){k=w;n=p.next().value;b(n,h)}function l(){k=w;n=p.next().value;b(n,k,h)}function s(){k=r[w];n=c[k];b(n,h)}function q(){k=r[w];n=c[k];b(n,k,h)}function h(b,
c){b?d(b,u):(!!c===a&&(u[k]=n),++w===m?(t=z,d(null,u)):v?C(t):(v=!0,t()),v=!1)}d=A(d||y);var m,k,n,r,p,t,v=!1,u={},w=0;B(c)?(m=c.length,t=3===b.length?f:e):c&&(x&&c[x]?(m=c.size,p=c[x](),t=3===b.length?l:g):"object"===typeof c&&(r=D(c),m=r.length,t=3===b.length?q:s));if(!m)return d(null,{});t()}}function Ba(a){return function(c,b,d,e){function f(){n=I++;n<k&&(p=c[n],d(p,m(p,n)))}function g(){n=I++;n<k&&(p=c[n],d(p,n,m(p,n)))}function l(){!1===(u=v.next()).done&&(p=u.value,d(p,m(p,I++)))}function s(){!1===
(u=v.next()).done&&(p=u.value,d(p,I,m(p,I++)))}function q(){I<k&&(r=t[I++],p=c[r],d(p,m(p,r)))}function h(){I<k&&(r=t[I++],p=c[r],d(p,r,m(p,r)))}function m(b,d){return function(c,f){null===d&&z();c?(d=null,w=y,e=H(e),e(c,M(F))):(!!f===a&&(F[d]=b),d=null,++E===k?(w=z,e=A(e),e(null,F)):G?C(w):(G=!0,w()),G=!1)}}e=e||y;var k,n,r,p,t,v,u,w,G=!1,F={},I=0,E=0;B(c)?(k=c.length,w=3===d.length?g:f):c&&(x&&c[x]?(k=c.size,v=c[x](),w=3===d.length?s:l):"object"===typeof c&&(t=D(c),k=t.length,w=3===d.length?h:q));
if(!k||isNaN(b)||1>b)return e(null,{});K(b>k?k:b,w)}}function W(a,c,b,d){function e(d){b(d,a[v],h)}function f(d){b(d,a[v],v,h)}function g(){b(c,r.next().value,h)}function l(){b(c,r.next().value,v,h)}function s(d){b(d,a[n[v]],h)}function q(d){k=n[v];b(d,a[k],k,h)}function h(a,c){a?d(a,c):++v===m?(b=z,d(null,c)):t?C(function(){p(c)}):(t=!0,p(c));t=!1}d=A(d||y);var m,k,n,r,p,t=!1,v=0;B(a)?(m=a.length,p=4===b.length?f:e):a&&(x&&a[x]?(m=a.size,r=a[x](),p=4===b.length?l:g):"object"===typeof a&&(n=D(a),
m=n.length,p=4===b.length?q:s));if(!m)return d(null,c);p(c)}function Ca(a,c,b,d){function e(d){b(d,a[--q],s)}function f(d){b(d,a[--q],q,s)}function g(d){b(d,a[k[--q]],s)}function l(d){m=k[--q];b(d,a[m],m,s)}function s(a,b){a?d(a,b):0===q?(t=z,d(null,b)):v?C(function(){t(b)}):(v=!0,t(b));v=!1}d=A(d||y);var q,h,m,k,n,r,p,t,v=!1;if(B(a))q=a.length,t=4===b.length?f:e;else if(a)if(x&&a[x]){q=a.size;p=Array(q);n=a[x]();for(h=-1;!1===(r=n.next()).done;)p[++h]=r.value;a=p;t=4===b.length?f:e}else"object"===
typeof a&&(k=D(a),q=k.length,t=4===b.length?l:g);if(!q)return d(null,c);t(c)}function Da(a,c,b){b=b||y;ca(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Ea(a,c,b){b=b||y;da(a,c,function(a,c){if(a)return b(a);b(null,!!c)})}function Fa(a,c,b,d){d=d||y;ea(a,c,b,function(a,b){if(a)return d(a);d(null,!!b)})}function Ga(a,c){return B(a)?0===a.length?(c(null),!1):!0:(c(Error("First argument to waterfall must be an array of functions")),!1)}function Ha(a,c){function b(b,h){if(b)s=z,c=A(c),c(b);
else if(++d===f){s=z;var m=c;c=z;2===arguments.length?m(b,h):m.apply(null,E(arguments))}else g=a[d],l=arguments,e?C(s):(e=!0,s()),e=!1}c=c||y;if(Ga(a,c)){var d=0,e=!1,f=a.length,g=a[d],l=[],s=function(){switch(g.length){case 0:try{b(null,g())}catch(a){b(a)}break;case 1:return g(b);case 2:return g(l[1],b);case 3:return g(l[1],l[2],b);case 4:return g(l[1],l[2],l[3],b);case 5:return g(l[1],l[2],l[3],l[4],b);default:return l=J(l,1),l[g.length-1]=b,g.apply(null,l)}};s()}}function Ia(){var a=E(arguments);
return function(){var c=this,b=E(arguments),d=b[b.length-1];"function"===typeof d?b.pop():d=y;W(a,b,function(a,b,d){a.push(function(a){var b=J(arguments,1);d(a,b)});b.apply(c,a)},function(a,b){b=B(b)?b:[b];b.unshift(a);d.apply(c,b)})}}function Ja(a){return function(c){var b=function(){var b=this,d=E(arguments),g=d.pop()||y;return a(c,function(a,c){a.apply(b,d.concat([c]))},g)};if(1<arguments.length){var d=J(arguments,1);return b.apply(this,d)}return b}}function N(){this.tail=this.head=null;this.length=
0}function fa(a,c,b,d){function e(a){a={data:a,callback:k};n?r._tasks.unshift(a):r._tasks.push(a);C(r.process)}function f(a,b,d){if(null==b)b=y;else if("function"!==typeof b)throw Error("task callback must be a function");r.started=!0;var c=B(a)?a:[a];void 0!==a&&c.length?(n=d,k=b,R(c,e)):r.idle()&&C(r.drain)}function g(a,b){var d=!1;return function(c,e){d&&z();d=!0;h--;for(var f,g=-1,k=m.length,l=-1,s=b.length,n=2<arguments.length,q=n&&E(arguments);++l<s;){for(f=b[l];++g<k;)m[g]===f&&(m.splice(g,
1),g=k,k--);g=-1;n?f.callback.apply(f,q):f.callback(c,e);c&&a.error(c,f.data)}h<=a.concurrency-a.buffer&&a.unsaturated();0===a._tasks.length+h&&a.drain();a.process()}}function l(){for(;!r.paused&&h<r.concurrency&&r._tasks.length;){var a=r._tasks.shift();0===r._tasks.length&&r.empty();h++;m.push(a);h===r.concurrency&&r.saturated();var b=g(r,[a]);c(a.data,b)}}function s(){for(;!r.paused&&h<r.concurrency&&r._tasks.length;){for(var a=r._tasks.splice(r.payload||r._tasks.length),b=-1,d=a.length,e=Array(d);++b<
d;)e[b]=a[b].data;0===r._tasks.length&&r.empty();h++;Array.prototype.push.apply(m,a);h===r.concurrency&&r.saturated();a=g(r,a);c(e,a)}}function q(){C(r.process)}if(void 0===b)b=1;else if(isNaN(b)||1>b)throw Error("Concurrency must not be zero");var h=0,m=[],k,n,r={_tasks:new N,concurrency:b,payload:d,saturated:y,unsaturated:y,buffer:b/4,empty:y,drain:y,error:y,started:!1,paused:!1,push:function(a,b){f(a,b)},kill:function(){r.drain=y;r._tasks.empty()},unshift:function(a,b){f(a,b,!0)},process:a?l:s,
length:function(){return r._tasks.length},running:function(){return h},workersList:function(){return m},idle:function(){return 0===r.length()+h},pause:function(){r.paused=!0},resume:function(){!1!==r.paused&&(r.paused=!1,K(r.concurrency<r._tasks.length?r.concurrency:r._tasks.length,q))},_worker:c};return r}function Ka(a,c,b){function d(){if(0===q.length&&0===s){if(0!==g)throw Error("async.auto task has cyclic dependencies");return b(null,l)}for(;q.length&&s<c&&b!==y;){s++;var a=q.shift();if(0===a[1])a[0](a[2]);
else a[0](l,a[2])}}function e(a){R(h[a]||[],function(a){a()});d()}"function"===typeof c&&(b=c,c=null);var f=D(a),g=f.length,l={};if(0===g)return b(null,l);var s=0,q=[],h={};b=A(b||y);c=c||g;S(a,function(a,d){function c(a,f){null===d&&z();s--;g--;f=2>=arguments.length?f:J(arguments,1);if(a){var h=M(l);h[d]=f;d=null;var m=b;b=y;m(a,h)}else l[d]=f,e(d),d=null}function r(){0===--v&&q.push([p,t,c])}var p,t;if(B(a)){var v=a.length-1;p=a[v];t=v;if(0===v)q.push([p,t,c]);else for(var u=-1;++u<v;){var w=a[u];
if(Va(f,w))throw u="async.auto task `"+w+"` has non-existent dependency in "+a.join(", "),Error(u);var x=h[w];x||(x=h[w]=[]);x.push(r)}}else p=a,t=0,q.push([p,t,c])},f);d()}function Wa(a){a=a.toString().replace(Xa,"");a=(a=a.match(Ya)[2].replace(" ",""))?a.split(Za):[];return a=a.map(function(a){return a.replace($a,"").trim()})}function ga(a,c,b){function d(a,e){if(++q===g||!a||s&&!s(a)){if(2>=arguments.length)return b(a,e);var f=E(arguments);return b.apply(null,f)}c(d)}function e(){c(f)}function f(a,
d){if(++q===g||!a||s&&!s(a)){if(2>=arguments.length)return b(a,d);var c=E(arguments);return b.apply(null,c)}setTimeout(e,l(q))}var g,l,s,q=0;if(3>arguments.length&&"function"===typeof a)b=c||y,c=a,a=null,g=5;else switch(b=b||y,typeof a){case "object":"function"===typeof a.errorFilter&&(s=a.errorFilter);var h=a.interval;switch(typeof h){case "function":l=h;break;case "string":case "number":l=(h=+h)?function(){return h}:function(){return 0}}g=+a.times||5;break;case "number":g=a||5;break;case "string":g=
+a||5;break;default:throw Error("Invalid arguments for async.retry");}if("function"!==typeof c)throw Error("Invalid arguments for async.retry");l?c(f):c(d)}function La(a){return function(){var c=E(arguments),b=c.pop(),d;try{d=a.apply(this,c)}catch(e){return b(e)}d&&"object"===typeof d&&"function"===typeof d.then?d.then(function(a){b(null,a)},function(a){b(a.message?a:Error(a))}):b(null,d)}}function Ma(a){return function(){function c(a,d){if(a)return b(null,{error:a});2<arguments.length&&(d=J(arguments,
1));b(null,{value:d})}var b;switch(arguments.length){case 1:return b=arguments[0],a(c);case 2:return b=arguments[1],a(arguments[0],c);default:var d=E(arguments),e=d.length-1;b=d[e];d[e]=c;a.apply(this,d)}}}function ha(a){function c(b){if("object"===typeof console)if(b)console.error&&console.error(b);else if(console[a]){var d=J(arguments,1);R(d,function(b){console[a](b)})}}return function(a){var d=J(arguments,1);d.push(c);a.apply(null,d)}}var y=function(){},z=function(){throw Error("Callback was already called.");
},B=Array.isArray,D=Object.keys,x="function"===typeof Symbol&&Symbol.iterator,C,X,Q;O();var P=function(a,c,b){return function(d,e,f){function g(a,b){a?(f=H(f),f(a)):++q===l?f(null):!1===b&&(f=H(f),f(null))}f=f||y;var l,s,q=0;B(d)?(l=d.length,a(d,e,g)):d&&(x&&d[x]?(l=d.size,b(d,e,g)):"object"===typeof d&&(s=D(d),l=s.length,c(d,e,g,s)));l||f(null)}}(ja,ka,la),Na=ra(ma,function(a,c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,b(f));else for(;++f<g;)c(a[d[f]],b(f))},function(a,
c,b){var d=-1,e=a.size,f=a[x]();if(3===c.length)for(;++d<e;)a=f.next().value,c(a,d,b(d));else for(;++d<e;)c(f.next().value,b(d))},!0),ab=ra(ma,function(a,c,b,d){var e,f=-1,g=d.length;if(3===c.length)for(;++f<g;)e=d[f],c(a[e],e,b(e));else for(;++f<g;)e=d[f],c(a[e],b(e))},function(a,c,b){var d=-1,e=a[x]();if(3===c.length)for(;!1===(a=e.next()).done;)c(a.value,++d,b(d));else for(;!1===(a=e.next()).done;)c(a.value,b(++d))},!1),Oa=sa(T,na,oa,!0),Pa=ta(!0),Qa=ua(!0),bb=sa(T,na,oa,!1),cb=ta(!1),db=ua(!1),
ca=wa($,aa,ba,!0),da=xa(!0),ea=ya(!0),Ra=function(a,c,b){var d=wa(a,c,b,!1);return function(a,b,c){c=c||y;d(a,b,function(a,b){if(a)return c(a);c(null,!b)})}}($,aa,ba),Sa=function(){var a=xa(!1);return function(c,b,d){d=d||y;a(c,b,function(a,b){if(a)return d(a);d(null,!b)})}}(),Ta=function(){var a=ya(!1);return function(c,b,d,e){e=e||y;a(c,b,d,function(a,b){if(a)return e(a);e(null,!b)})}}(),eb=za(T,pa,qa,!0),fb=Aa(!0),gb=Ba(!0),hb=za(T,pa,qa,!1),ib=Aa(!1),jb=Ba(!1),kb=function(a,c,b){return function(d,
e,f,g){function l(a,b){a?(g=H(g),g(a,B(h)?E(h):M(h))):++m===s?g(null,h):!1===b&&(g=H(g),g(null,B(h)?E(h):M(h)))}3===arguments.length&&(g=f,f=e,e=void 0);g=g||y;var s,q,h,m=0;B(d)?(s=d.length,h=void 0!==e?e:[],a(d,h,f,l)):d&&(x&&d[x]?(s=d.size,h=void 0!==e?e:{},b(d,h,f,l)):"object"===typeof d&&(q=D(d),s=q.length,h=void 0!==e?e:{},c(d,h,f,l,q)));s||g(null,void 0!==e?e:h||{})}}(function(a,c,b,d){var e=-1,f=a.length;if(4===b.length)for(;++e<f;)b(c,a[e],e,A(d));else for(;++e<f;)b(c,a[e],A(d))},function(a,
c,b,d,e){var f,g=-1,l=e.length;if(4===b.length)for(;++g<l;)f=e[g],b(c,a[f],f,A(d));else for(;++g<l;)b(c,a[e[g]],A(d))},function(a,c,b,d){var e=-1,f=a[x]();if(4===b.length)for(;!1===(a=f.next()).done;)b(c,a.value,++e,A(d));else for(;!1===(a=f.next()).done;)b(c,a.value,A(d))}),lb=function(a,c,b){return function(d,e,f){function g(a){var b=!1;return function(d,c){b&&z();b=!0;s[q]={value:a,criteria:c};d?(f=H(f),f(d)):++q===l&&(s.sort(Z),f(null,Y(s,"value")))}}f=f||y;var l,s,q=0;if(B(d))l=d.length,s=Array(l),
a(d,e,g);else if(d)if(x&&d[x])l=d.size,s=Array(l),b(d,e,g);else if("object"===typeof d){var h=D(d);l=h.length;s=Array(l);c(d,e,g,h)}l||f(null,[])}}($,aa,ba),mb=function(a,c,b){return function(d,e,f){function g(a,b){b&&Array.prototype.push.apply(q,B(b)?b:[b]);a?(f=H(f),f(a,E(q))):++s===l&&f(null,q)}f=f||y;var l,s=0,q=[];if(B(d))l=d.length,a(d,e,g);else if(d)if(x&&d[x])l=d.size,b(d,e,g);else if("object"===typeof d){var h=D(d);l=h.length;c(d,e,g,h)}l||f(null,q)}}(ja,ka,la),nb=function(a,c){return function(b,
d){function e(a){return function(b,c){null===a&&z();b?(a=null,d=H(d),d(b,l)):(l[a]=2>=arguments.length?c:J(arguments,1),a=null,++s===f&&d(null,l))}}d=d||y;var f,g,l,s=0;B(b)?(f=b.length,l=Array(f),a(b,e)):b&&"object"===typeof b&&(g=D(b),f=g.length,l={},c(b,e,g));f||d(null,l)}}(function(a,c){for(var b=-1,d=a.length;++b<d;)a[b](c(b))},function(a,c,b){for(var d,e=-1,f=b.length;++e<f;)d=b[e],a[d](c(d))}),ob=Ja(Na),pb=Ja(va),qb=ha("log"),rb=ha("dir"),P={VERSION:"2.0.1",each:P,eachSeries:U,eachLimit:V,
forEach:P,forEachSeries:U,forEachLimit:V,eachOf:P,eachOfSeries:U,eachOfLimit:V,forEachOf:P,forEachOfSeries:U,forEachOfLimit:V,map:Na,mapSeries:va,mapLimit:function(a,c,b,d){function e(){k=G++;k<m&&b(a[k],h(k))}function f(){k=G++;k<m&&b(a[k],k,h(k))}function g(){!1===(t=p.next()).done&&b(t.value,h(G++))}function l(){!1===(t=p.next()).done&&b(t.value,G,h(G++))}function s(){k=G++;k<m&&b(a[r[k]],h(k))}function q(){k=G++;k<m&&(n=r[k],b(a[n],n,h(k)))}function h(a){return function(b,c){null===a&&z();b?(a=
null,u=y,d=H(d),d(b,E(v))):(v[a]=c,a=null,++A===m?(u=z,d(null,v),d=z):w?C(u):(w=!0,u()),w=!1)}}d=d||y;var m,k,n,r,p,t,v,u,w=!1,G=0,A=0;B(a)?(m=a.length,u=3===b.length?f:e):a&&(x&&a[x]?(m=a.size,p=a[x](),u=3===b.length?l:g):"object"===typeof a&&(r=D(a),m=r.length,u=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,[]);v=Array(m);K(c>m?m:c,u)},mapValues:ab,mapValuesSeries:function(a,c,b){function d(){m=u;c(a[u],q)}function e(){m=u;c(a[u],u,q)}function f(){m=u;r=n.next().value;c(r,q)}function g(){m=
u;r=n.next().value;c(r,u,q)}function l(){m=k[u];c(a[m],q)}function s(){m=k[u];c(a[m],m,q)}function q(a,d){a?(p=z,b=A(b),b(a,M(v))):(v[m]=d,++u===h?(p=z,b(null,v),b=z):t?C(p):(t=!0,p()),t=!1)}b=b||y;var h,m,k,n,r,p,t=!1,v={},u=0;B(a)?(h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null,v);p()},mapValuesLimit:function(a,c,b,d){function e(){k=G++;k<m&&b(a[k],h(k))}function f(){k=G++;k<m&&b(a[k],
k,h(k))}function g(){!1===(t=p.next()).done&&b(t.value,h(G++))}function l(){!1===(t=p.next()).done&&b(t.value,G,h(G++))}function s(){k=G++;k<m&&(n=r[k],b(a[n],h(n)))}function q(){k=G++;k<m&&(n=r[k],b(a[n],n,h(n)))}function h(a){return function(b,c){null===a&&z();b?(a=null,v=y,d=H(d),d(b,M(w))):(w[a]=c,a=null,++A===m?d(null,w):u?C(v):(u=!0,v()),u=!1)}}d=d||y;var m,k,n,r,p,t,v,u=!1,w={},G=0,A=0;B(a)?(m=a.length,v=3===b.length?f:e):a&&(x&&a[x]?(m=a.size,p=a[x](),v=3===b.length?l:g):"object"===typeof a&&
(r=D(a),m=r.length,v=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,w);K(c>m?m:c,v)},filter:Oa,filterSeries:Pa,filterLimit:Qa,select:Oa,selectSeries:Pa,selectLimit:Qa,reject:bb,rejectSeries:cb,rejectLimit:db,detect:ca,detectSeries:da,detectLimit:ea,find:ca,findSeries:da,findLimit:ea,pick:eb,pickSeries:fb,pickLimit:gb,omit:hb,omitSeries:ib,omitLimit:jb,reduce:W,inject:W,foldl:W,reduceRight:Ca,foldr:Ca,transform:kb,transformSeries:function(a,c,b,d){function e(){b(t,a[u],h)}function f(){b(t,a[u],
u,h)}function g(){b(t,r.next().value,h)}function l(){b(t,r.next().value,u,h)}function s(){b(t,a[n[u]],h)}function q(){k=n[u];b(t,a[k],k,h)}function h(a,b){a?d(a,t):++u===m?(p=z,d(null,t)):!1===b?(p=z,d(null,t)):v?C(p):(v=!0,p());v=!1}3===arguments.length&&(d=b,b=c,c=void 0);d=A(d||y);var m,k,n,r,p,t,v=!1,u=0;B(a)?(m=a.length,t=void 0!==c?c:[],p=4===b.length?f:e):a&&(x&&a[x]?(m=a.size,r=a[x](),t=void 0!==c?c:{},p=4===b.length?l:g):"object"===typeof a&&(n=D(a),m=n.length,t=void 0!==c?c:{},p=4===b.length?
q:s));if(!m)return d(null,void 0!==c?c:t||{});p()},transformLimit:function(a,c,b,d,e){function f(){n=F++;n<k&&d(w,a[n],A(m))}function g(){n=F++;n<k&&d(w,a[n],n,A(m))}function l(){!1===(v=t.next()).done&&d(w,v.value,A(m))}function s(){!1===(v=t.next()).done&&d(w,v.value,F++,A(m))}function q(){n=F++;n<k&&d(w,a[p[n]],A(m))}function h(){n=F++;n<k&&(r=p[n],d(w,a[r],r,A(m)))}function m(a,b){a?(u=y,e(a,B(w)?E(w):M(w)),e=y):++I===k?e(null,w):!1===b?(u=y,e(null,B(w)?E(w):M(w)),e=y):z?C(u):(z=!0,u());z=!1}
4===arguments.length&&(e=d,d=b,b=void 0);e=e||y;var k,n,r,p,t,v,u,w,z=!1,F=0,I=0;B(a)?(k=a.length,w=void 0!==b?b:[],u=4===d.length?g:f):a&&(x&&a[x]?(k=a.size,t=a[x](),w=void 0!==b?b:{},u=4===d.length?s:l):"object"===typeof a&&(p=D(a),k=p.length,w=void 0!==b?b:{},u=4===d.length?h:q));if(!k||isNaN(c)||1>c)return e(null,void 0!==b?b:w||{});K(c>k?k:c,u)},sortBy:lb,sortBySeries:function(a,c,b){function d(){k=a[u];c(k,q)}function e(){k=a[u];c(k,u,q)}function f(){k=r.next().value;c(k,q)}function g(){k=r.next().value;
c(k,u,q)}function l(){k=a[n[u]];c(k,q)}function s(){m=n[u];k=a[m];c(k,m,q)}function q(a,d){p[u]={value:k,criteria:d};a?b(a):++u===h?(t=z,p.sort(Z),b(null,Y(p,"value"))):v?C(t):(v=!0,t());v=!1}b=A(b||y);var h,m,k,n,r,p,t,v=!1,u=0;B(a)?(h=a.length,t=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,r=a[x](),t=3===c.length?g:f):"object"===typeof a&&(n=D(a),h=n.length,t=3===c.length?s:l));if(!h)return b(null,[]);p=Array(h);t()},sortByLimit:function(a,c,b,d){function e(){F<m&&(r=a[F++],b(r,h(r)))}function f(){k=
F++;k<m&&(r=a[k],b(r,k,h(r)))}function g(){!1===(v=t.next()).done&&(r=v.value,b(r,h(r)))}function l(){!1===(v=t.next()).done&&(r=v.value,b(r,F++,h(r)))}function s(){F<m&&(r=a[p[F++]],b(r,h(r)))}function q(){F<m&&(n=p[F++],r=a[n],b(r,n,h(r)))}function h(a){var b=!1;return function(c,e){b&&z();b=!0;u[E]={value:a,criteria:e};c?(w=y,d(c),d=y):++E===m?(u.sort(Z),d(null,Y(u,"value"))):A?C(w):(A=!0,w());A=!1}}d=d||y;var m,k,n,r,p,t,v,u,w,A=!1,F=0,E=0;B(a)?(m=a.length,w=3===b.length?f:e):a&&(x&&a[x]?(m=a.size,
t=a[x](),w=3===b.length?l:g):"object"===typeof a&&(p=D(a),m=p.length,w=3===b.length?q:s));if(!m||isNaN(c)||1>c)return d(null,[]);u=Array(m);K(c>m?m:c,w)},some:Da,someSeries:Ea,someLimit:Fa,any:Da,anySeries:Ea,anyLimit:Fa,every:Ra,everySeries:Sa,everyLimit:Ta,all:Ra,allSeries:Sa,allLimit:Ta,concat:mb,concatSeries:function(a,c,b){function d(){c(a[u],q)}function e(){c(a[u],u,q)}function f(){c(n.next().value,q)}function g(){r=n.next().value;c(r,u,q)}function l(){c(a[k[u]],q)}function s(){m=k[u];c(a[m],
m,q)}function q(a,d){d&&Array.prototype.push.apply(v,B(d)?d:[d]);a?b(a,v):++u===h?(p=z,b(null,v)):t?C(p):(t=!0,p());t=!1}b=A(b||y);var h,m,k,n,r,p,t=!1,v=[],u=0;B(a)?(h=a.length,p=3===c.length?e:d):a&&(x&&a[x]?(h=a.size,n=a[x](),p=3===c.length?g:f):"object"===typeof a&&(k=D(a),h=k.length,p=3===c.length?s:l));if(!h)return b(null,v);p()},concatLimit:function(a,c,b,d){function e(){w<k&&b(a[w++],A(h))}function f(){n=w++;n<k&&b(a[n],n,A(h))}function g(){!1===(t=p.next()).done&&b(t.value,A(h))}function l(){!1===
(t=p.next()).done&&b(t.value,w++,A(h))}function s(){w<k&&b(a[F[w++]],A(h))}function q(){w<k&&(r=F[w++],b(a[r],r,A(h)))}function h(a,b){b&&Array.prototype.push.apply(m,B(b)?b:[b]);a?(v=y,d=H(d),d(a,m)):++E===k?(v=z,d=A(d),d(null,m)):u?C(v):(u=!0,v());u=!1}d=d||y;var m=[],k,n,r,p,t,v,u=!1,w=0,E=0;if(B(a))k=a.length,v=3===b.length?f:e;else if(a)if(x&&a[x])k=a.size,p=a[x](),v=3===b.length?l:g;else if("object"===typeof a){var F=D(a);k=F.length;v=3===b.length?q:s}if(!k||isNaN(c)||1>c)return d(null,m);K(c>
k?k:c,v)},parallel:nb,series:function(a,c){function b(){g=m;a[m](e)}function d(){g=l[m];a[g](e)}function e(a,b){a?(q=z,c=A(c),c(a,s)):(s[g]=2>=arguments.length?b:J(arguments,1),++m===f?(q=z,c(null,s)):h?C(q):(h=!0,q()),h=!1)}c=c||y;var f,g,l,s,q,h=!1,m=0;if(B(a))f=a.length,s=Array(f),q=b;else if(a&&"object"===typeof a)l=D(a),f=l.length,s={},q=d;else return c(null);if(!f)return c(null,s);q()},parallelLimit:function(a,c,b){function d(){l=n++;if(l<g)a[l](f(l))}function e(){n<g&&(s=q[n++],a[s](f(s)))}
function f(a){return function(d,c){null===a&&z();d?(a=null,m=y,b=H(b),b(d,h)):(h[a]=2>=arguments.length?c:J(arguments,1),a=null,++r===g?b(null,h):k?C(m):(k=!0,m()),k=!1)}}b=b||y;var g,l,s,q,h,m,k=!1,n=0,r=0;B(a)?(g=a.length,h=Array(g),m=d):a&&"object"===typeof a&&(q=D(a),g=q.length,h={},m=e);if(!g||isNaN(c)||1>c)return b(null,h);K(c>g?g:c,m)},waterfall:function(a,c){function b(){f=!1;switch(h.length){case 0:case 1:return q(d);case 2:return q(h[1],d);case 3:return q(h[1],h[2],d);case 4:return q(h[1],
h[2],h[3],d);case 5:return q(h[1],h[2],h[3],h[4],d);case 6:return q(h[1],h[2],h[3],h[4],h[5],d);default:return h=J(h,1),h.push(d),q.apply(null,h)}}function d(d,k){f&&z();f=!0;d?(e=c,c=z,e(d)):++l===s?(e=c,c=z,2>=arguments.length?e(d,k):e.apply(null,E(arguments))):(h=arguments,q=a[l]||z,g?C(b):(g=!0,b()),g=!1)}c=c||y;if(Ga(a,c)){var e,f,g,l=0,s=a.length,q=a[l],h=[];b()}},angelFall:Ha,angelfall:Ha,whilst:function(a,c,b){function d(){g?C(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);
2>=arguments.length?a(e)?d():b(null,e):(e=J(arguments,1),a.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||y;var g=!1;a()?d():b(null)},doWhilst:function(a,c,b){function d(){g?C(e):(g=!0,a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?d():b(null,e):(e=J(arguments,1),c.apply(null,e)?d():b.apply(null,[null].concat(e)))}b=b||y;var g=!1;e()},until:function(a,c,b){function d(){g?C(e):(g=!0,c(f));g=!1}function e(){c(f)}function f(c,e){if(c)return b(c);2>=arguments.length?
a(e)?b(null,e):d():(e=J(arguments,1),a.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||y;var g=!1;a()?b(null):d()},doUntil:function(a,c,b){function d(){g?C(e):(g=!0,a(f));g=!1}function e(){a(f)}function f(a,e){if(a)return b(a);2>=arguments.length?c(e)?b(null,e):d():(e=J(arguments,1),c.apply(null,e)?b.apply(null,[null].concat(e)):d())}b=b||y;var g=!1;e()},during:function(a,c,b){function d(a,d){if(a)return b(a);d?c(e):b(null)}function e(c){if(c)return b(c);a(d)}b=b||y;a(d)},doDuring:function(a,
c,b){function d(d,c){if(d)return b(d);c?a(e):b(null)}function e(a,e){if(a)return b(a);switch(arguments.length){case 0:case 1:c(d);break;case 2:c(e,d);break;default:var l=J(arguments,1);l.push(d);c.apply(null,l)}}b=b||y;d(null,!0)},forever:function(a,c){function b(){a(d)}function d(a){if(a){if(c)return c(a);throw a;}e?C(b):(e=!0,b());e=!1}var e=!1;b()},compose:function(){return Ia.apply(null,Ua(arguments))},seq:Ia,applyEach:ob,applyEachSeries:pb,queue:function(a,c){return fa(!0,a,c)},priorityQueue:function(a,
c){var b=fa(!0,a,c);b.push=function(a,c,f){b.started=!0;c=c||0;var g=B(a)?a:[a],l=g.length;if(void 0===a||0===l)b.idle()&&C(b.drain);else{f="function"===typeof f?f:y;for(a=b._tasks.head;a&&c>=a.priority;)a=a.next;for(;l--;){var s={data:g[l],priority:c,callback:f};a?b._tasks.insertBefore(a,s):b._tasks.push(s);C(b.process)}}};delete b.unshift;return b},cargo:function(a,c){return fa(!1,a,1,c)},auto:Ka,autoInject:function(a,c,b){var d={};S(a,function(a,b){var c,l=a.length;if(B(a)){if(0===l)throw Error("autoInject task functions require explicit parameters.");
c=E(a);l=c.length-1;a=c[l];if(0===l){d[b]=a;return}}else{if(1===l){d[b]=a;return}c=Wa(a);if(0===l&&0===c.length)throw Error("autoInject task functions require explicit parameters.");l=c.length-1}c[l]=function(b,d){switch(l){case 1:a(b[c[0]],d);break;case 2:a(b[c[0]],b[c[1]],d);break;case 3:a(b[c[0]],b[c[1]],b[c[2]],d);break;default:for(var f=-1;++f<l;)c[f]=b[c[f]];c[f]=d;a.apply(null,c)}};d[b]=c},D(a));Ka(d,c,b)},retry:ga,retryable:function(a,c){c||(c=a,a=null);return function(){function b(a){c(a)}
function d(a){c(g[0],a)}function e(a){c(g[0],g[1],a)}var f,g=E(arguments),l=g.length-1,s=g[l];switch(c.length){case 1:f=b;break;case 2:f=d;break;case 3:f=e;break;default:f=function(a){g[l]=a;c.apply(null,g)}}a?ga(a,f,s):ga(f,s)}},iterator:function(a){function c(e){var f=function(){b&&a[d[e]||e].apply(null,E(arguments));return f.next()};f.next=function(){return e<b-1?c(e+1):null};return f}var b=0,d=[];B(a)?b=a.length:(d=D(a),b=d.length);return c(0)},times:function(a,c,b){function d(c){return function(d,
l){null===c&&z();e[c]=l;c=null;d?(b(d),b=y):0===--a&&b(null,e)}}b=b||y;a=+a;if(isNaN(a)||1>a)return b(null,[]);var e=Array(a);K(a,function(a){c(a,d(a))})},timesSeries:function(a,c,b){function d(){c(l,e)}function e(c,e){f[l]=e;c?(b(c),b=z):++l>=a?(b(null,f),b=z):g?C(d):(g=!0,d());g=!1}b=b||y;a=+a;if(isNaN(a)||1>a)return b(null,[]);var f=Array(a),g=!1,l=0;d()},timesLimit:function(a,c,b,d){function e(){var c=s++;c<a&&b(c,f(c))}function f(b){return function(c,f){null===b&&z();g[b]=f;b=null;c?(d(c),d=
y):++q>=a?(d(null,g),d=z):l?C(e):(l=!0,e());l=!1}}d=d||y;a=+a;if(isNaN(a)||1>a||isNaN(c)||1>c)return d(null,[]);var g=Array(a),l=!1,s=0,q=0;K(c>a?a:c,e)},race:function(a,c){c=H(c||y);var b,d,e=-1;if(B(a))for(b=a.length;++e<b;)a[e](c);else if(a&&"object"===typeof a)for(d=D(a),b=d.length;++e<b;)a[d[e]](c);else return c(new TypeError("First argument to race must be a collection of functions"));b||c(null)},apply:function(a){switch(arguments.length){case 0:case 1:return a;case 2:return a.bind(null,arguments[1]);
case 3:return a.bind(null,arguments[1],arguments[2]);case 4:return a.bind(null,arguments[1],arguments[2],arguments[3]);case 5:return a.bind(null,arguments[1],arguments[2],arguments[3],arguments[4]);default:var c=arguments.length,b=0,d=Array(c);for(d[b]=null;++b<c;)d[b]=arguments[b];return a.bind.apply(a,d)}},nextTick:X,setImmediate:Q,memoize:function(a,c){c=c||function(a){return a};var b={},d={},e=function(){function e(){var a=E(arguments);b[s]=a;var c=d[s];delete d[s];for(var f=-1,g=c.length;++f<
g;)c[f].apply(null,a)}var g=E(arguments),l=g.pop(),s=c.apply(null,g);if(b.hasOwnProperty(s))C(function(){l.apply(null,b[s])});else{if(d.hasOwnProperty(s))return d[s].push(l);d[s]=[l];g.push(e);a.apply(null,g)}};e.memo=b;e.unmemoized=a;return e},unmemoize:function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},ensureAsync:function(a){return function(){var c=E(arguments),b=c.length-1,d=c[b],e=!0;c[b]=function(){var a=E(arguments);e?C(function(){d.apply(null,a)}):d.apply(null,a)};
a.apply(this,c);e=!1}},constant:function(){var a=[null].concat(E(arguments));return function(c){c=arguments[arguments.length-1];c.apply(this,a)}},asyncify:La,wrapSync:La,log:qb,dir:rb,reflect:Ma,reflectAll:function(a){function c(a,b){d[b]=Ma(a)}var b,d,e;B(a)?(b=a.length,d=Array(b),R(a,c)):a&&"object"===typeof a&&(e=D(a),b=e.length,d={},S(a,c,e));return d},timeout:function(a,c,b){function d(){var c=Error('Callback function "'+(a.name||"anonymous")+'" timed out.');c.code="ETIMEDOUT";b&&(c.info=b);
l=null;g(c)}function e(){null!==l&&(f(g,E(arguments)),clearTimeout(l))}function f(a,b){switch(b.length){case 0:a();break;case 1:a(b[0]);break;case 2:a(b[0],b[1]);break;default:a.apply(null,b)}}var g,l;return function(){l=setTimeout(d,c);var b=E(arguments),q=b.length-1;g=b[q];b[q]=e;f(a,b)}},createLogger:ha,safe:function(){O();return L},fast:function(){O(!1);return L}};L["default"]=P;S(P,function(a,c){L[c]=a},D(P));N.prototype._removeLink=function(a){(this.head=a.next)?a.next.prev=a.prev:this.tail=
a.prev;a.prev=null;a.next=null;this.length--;return a};N.prototype.empty=N;N.prototype._setInitial=function(a){this.length=1;this.head=this.tail=a};N.prototype.insertBefore=function(a,c){c.prev=a.prev;c.next=a;a.prev?a.prev.next=c:this.head=c;a.prev=c;this.length++};N.prototype.unshift=function(a){this.head?this.insertBefore(this.head,a):this._setInitial(a)};N.prototype.push=function(a){var c=this.tail;c?(a.prev=c,a.next=c.next,this.tail=a,c.next=a,this.length++):this._setInitial(a)};N.prototype.shift=
function(){return this.head&&this._removeLink(this.head)};N.prototype.splice=function(a){for(var c,b=[];a--&&(c=this.shift());)b.push(c);return b};var Ya=/^(function)?\s*[^\(]*\(\s*([^\)]*)\)/m,Za=/,/,$a=/(=.+)?(\s*)$/,Xa=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg});
|
/*
* Copyright (C) 2008 Apple Inc. All Rights Reserved.
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.Breakpoint = function(id, url, sourceID, lineNumber, columnNumber, condition, enabled)
{
this.id = id;
this.url = url;
this.sourceID = sourceID;
this.lineNumber = lineNumber;
this.columnNumber = columnNumber;
this.condition = condition;
this.enabled = enabled;
this.locations = [];
}
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v6.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
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 context_1 = require("./context/context");
var context_2 = require("./context/context");
var TemplateService = (function () {
function TemplateService() {
this.templateCache = {};
this.waitingCallbacks = {};
}
// returns the template if it is loaded, or null if it is not loaded
// but will call the callback when it is loaded
TemplateService.prototype.getTemplate = function (url, callback) {
var templateFromCache = this.templateCache[url];
if (templateFromCache) {
return templateFromCache;
}
var callbackList = this.waitingCallbacks[url];
var that = this;
if (!callbackList) {
// first time this was called, so need a new list for callbacks
callbackList = [];
this.waitingCallbacks[url] = callbackList;
// and also need to do the http request
var client = new XMLHttpRequest();
client.onload = function () {
that.handleHttpResult(this, url);
};
client.open("GET", url);
client.send();
}
// add this callback
if (callback) {
callbackList.push(callback);
}
// caller needs to wait for template to load, so return null
return null;
};
TemplateService.prototype.handleHttpResult = function (httpResult, url) {
if (httpResult.status !== 200 || httpResult.response === null) {
console.warn('Unable to get template error ' + httpResult.status + ' - ' + url);
return;
}
// response success, so process it
// in IE9 the response is in - responseText
this.templateCache[url] = httpResult.response || httpResult.responseText;
// inform all listeners that this is now in the cache
var callbacks = this.waitingCallbacks[url];
for (var i = 0; i < callbacks.length; i++) {
var callback = callbacks[i];
// we could pass the callback the response, however we know the client of this code
// is the cell renderer, and it passes the 'cellRefresh' method in as the callback
// which doesn't take any parameters.
callback();
}
if (this.$scope) {
var that = this;
setTimeout(function () {
that.$scope.$apply();
}, 0);
}
};
__decorate([
context_2.Autowired('$scope'),
__metadata('design:type', Object)
], TemplateService.prototype, "$scope", void 0);
TemplateService = __decorate([
context_1.Bean('templateService'),
__metadata('design:paramtypes', [])
], TemplateService);
return TemplateService;
})();
exports.TemplateService = TemplateService;
|
/*! jQuery UI - v1.11.1 - 2014-08-13
* http://jqueryui.com
* Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */
(function(t){"function"==typeof define&&define.amd?define(["jquery","./effect"],t):t(jQuery)})(function(t){return t.effects.effect.explode=function(e,i){function s(){b.push(this),b.length===u*d&&n()}function n(){p.css({visibility:"visible"}),t(b).remove(),g||p.hide(),i()}var o,a,r,h,l,c,u=e.pieces?Math.round(Math.sqrt(e.pieces)):3,d=u,p=t(this),f=t.effects.setMode(p,e.mode||"hide"),g="show"===f,m=p.show().css("visibility","hidden").offset(),v=Math.ceil(p.outerWidth()/d),_=Math.ceil(p.outerHeight()/u),b=[];for(o=0;u>o;o++)for(h=m.top+o*_,c=o-(u-1)/2,a=0;d>a;a++)r=m.left+a*v,l=a-(d-1)/2,p.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-a*v,top:-o*_}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:v,height:_,left:r+(g?l*v:0),top:h+(g?c*_:0),opacity:g?0:1}).animate({left:r+(g?0:l*v),top:h+(g?0:c*_),opacity:g?1:0},e.duration||500,e.easing,s)}});
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.0-alpha.4
* @link http://www.ag-grid.com/
* @license MIT
*/
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 utils_1 = require("../utils");
var context_1 = require("../context/context");
var cellRendererFactory_1 = require("./cellRendererFactory");
/** Class to use a cellRenderer. */
var CellRendererService = (function () {
function CellRendererService() {
}
/** Uses a cellRenderer, and returns the cellRenderer object if it is a class implementing ICellRenderer.
* @cellRendererKey: The cellRenderer to use. Can be: a) a class that we call 'new' on b) a function we call
* or c) a string that we use to look up the cellRenderer.
* @params: The params to pass to the cell renderer if it's a function or a class.
* @eTarget: The DOM element we will put the results of the html element into *
* @return: If options a, it returns the created class instance */
CellRendererService.prototype.useCellRenderer = function (cellRendererKey, eTarget, params) {
var cellRenderer = this.lookUpCellRenderer(cellRendererKey);
if (utils_1.Utils.missing(cellRenderer)) {
// this is a bug in users config, they specified a cellRenderer that doesn't exist,
// the factory already printed to console, so here we just skip
return;
}
var resultFromRenderer;
var iCellRendererInstance = null;
this.checkForDeprecatedItems(cellRenderer);
// we check if the class has the 'getGui' method to know if it's a component
var rendererIsAComponent = this.doesImplementICellRenderer(cellRenderer);
// if it's a component, we create and initialise it
if (rendererIsAComponent) {
var CellRendererClass = cellRenderer;
iCellRendererInstance = new CellRendererClass();
this.context.wireBean(iCellRendererInstance);
if (iCellRendererInstance.init) {
iCellRendererInstance.init(params);
}
resultFromRenderer = iCellRendererInstance.getGui();
}
else {
// otherwise it's a function, so we just use it
var cellRendererFunc = cellRenderer;
resultFromRenderer = cellRendererFunc(params);
}
if (resultFromRenderer === null || resultFromRenderer === '') {
return;
}
if (utils_1.Utils.isNodeOrElement(resultFromRenderer)) {
// a dom node or element was returned, so add child
eTarget.appendChild(resultFromRenderer);
}
else {
// otherwise assume it was html, so just insert
eTarget.innerHTML = resultFromRenderer;
}
return iCellRendererInstance;
};
CellRendererService.prototype.checkForDeprecatedItems = function (cellRenderer) {
if (cellRenderer && cellRenderer.renderer) {
console.warn('ag-grid: colDef.cellRenderer should not be an object, it should be a string, function or class. this ' +
'changed in v4.1.x, please check the documentation on Cell Rendering, or if you are doing grouping, look at the grouping examples.');
}
};
CellRendererService.prototype.doesImplementICellRenderer = function (cellRenderer) {
// see if the class has a prototype that defines a getGui method. this is very rough,
// but javascript doesn't have types, so is the only way!
return cellRenderer.prototype && 'getGui' in cellRenderer.prototype;
};
CellRendererService.prototype.lookUpCellRenderer = function (cellRendererKey) {
if (typeof cellRendererKey === 'string') {
return this.cellRendererFactory.getCellRenderer(cellRendererKey);
}
else {
return cellRendererKey;
}
};
__decorate([
context_1.Autowired('cellRendererFactory'),
__metadata('design:type', cellRendererFactory_1.CellRendererFactory)
], CellRendererService.prototype, "cellRendererFactory", void 0);
__decorate([
context_1.Autowired('context'),
__metadata('design:type', context_1.Context)
], CellRendererService.prototype, "context", void 0);
CellRendererService = __decorate([
context_1.Bean('cellRendererService'),
__metadata('design:paramtypes', [])
], CellRendererService);
return CellRendererService;
})();
exports.CellRendererService = CellRendererService;
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.2.2
* @link http://www.ag-grid.com/
* @license MIT
*/
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 context_1 = require("../../context/context");
var context_2 = require("../../context/context");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var filterManager_1 = require("../../filter/filterManager");
var FilterStage = (function () {
function FilterStage() {
}
FilterStage.prototype.execute = function (rowNode) {
var filterActive;
if (this.gridOptionsWrapper.isEnableServerSideFilter()) {
filterActive = false;
}
else {
filterActive = this.filterManager.isAnyFilterPresent();
}
this.recursivelyFilter(rowNode, filterActive);
};
FilterStage.prototype.recursivelyFilter = function (rowNode, filterActive) {
var _this = this;
// recursively get all children that are groups to also filter
rowNode.childrenAfterGroup.forEach(function (child) {
if (child.group) {
_this.recursivelyFilter(child, filterActive);
}
});
// result of filter for this node
var filterResult;
if (filterActive) {
filterResult = [];
rowNode.childrenAfterGroup.forEach(function (childNode) {
if (childNode.group) {
// a group is included in the result if it has any children of it's own.
// by this stage, the child groups are already filtered
if (childNode.childrenAfterFilter.length > 0) {
filterResult.push(childNode);
}
}
else {
// a leaf level node is included if it passes the filter
if (_this.filterManager.doesRowPassFilter(childNode)) {
filterResult.push(childNode);
}
}
});
}
else {
// if not filtering, the result is the original list
filterResult = rowNode.childrenAfterGroup;
}
rowNode.childrenAfterFilter = filterResult;
this.setAllChildrenCount(rowNode);
};
FilterStage.prototype.setAllChildrenCount = function (rowNode) {
var allChildrenCount = 0;
rowNode.childrenAfterFilter.forEach(function (child) {
if (child.group) {
allChildrenCount += child.allChildrenCount;
}
else {
allChildrenCount++;
}
});
rowNode.allChildrenCount = allChildrenCount;
};
__decorate([
context_2.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], FilterStage.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_2.Autowired('filterManager'),
__metadata('design:type', filterManager_1.FilterManager)
], FilterStage.prototype, "filterManager", void 0);
FilterStage = __decorate([
context_1.Bean('filterStage'),
__metadata('design:paramtypes', [])
], FilterStage);
return FilterStage;
})();
exports.FilterStage = FilterStage;
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.Dexie = factory();
}(this, function () { 'use strict';
// By default, debug will be true only if platform is a web platform and its page is served from localhost.
// When debug = true, error's stacks will contain asyncronic long stacks.
var debug = typeof location !== 'undefined' &&
// By default, use debug mode if served from localhost.
/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);
function setDebug(value, filter) {
debug = value;
libraryFilter = filter;
}
var libraryFilter = function () {
return true;
};
var NEEDS_THROW_FOR_STACK = !new Error("").stack;
function getErrorWithStack() {
"use strict";
if (NEEDS_THROW_FOR_STACK) try {
// Doing something naughty in strict mode here to trigger a specific error
// that can be explicitely ignored in debugger's exception settings.
// If we'd just throw new Error() here, IE's debugger's exception settings
// will just consider it as "exception thrown by javascript code" which is
// something you wouldn't want it to ignore.
getErrorWithStack.arguments;
throw new Error(); // Fallback if above line don't throw.
} catch (e) {
return e;
}
return new Error();
}
function prettyStack(exception, numIgnoredFrames) {
var stack = exception.stack;
if (!stack) return "";
numIgnoredFrames = numIgnoredFrames || 0;
if (stack.indexOf(exception.name) === 0) numIgnoredFrames += (exception.name + exception.message).split('\n').length;
return stack.split('\n').slice(numIgnoredFrames).filter(libraryFilter).map(function (frame) {
return "\n" + frame;
}).join('');
}
function nop() {}
function mirror(val) {
return val;
}
function pureFunctionChain(f1, f2) {
// Enables chained events that takes ONE argument and returns it to the next function in chain.
// This pattern is used in the hook("reading") event.
if (f1 == null || f1 === mirror) return f2;
return function (val) {
return f2(f1(val));
};
}
function callBoth(on1, on2) {
return function () {
on1.apply(this, arguments);
on2.apply(this, arguments);
};
}
function hookCreatingChain(f1, f2) {
// Enables chained events that takes several arguments and may modify first argument by making a modification and then returning the same instance.
// This pattern is used in the hook("creating") event.
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res !== undefined) arguments[0] = res;
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res2 !== undefined ? res2 : res;
};
}
function hookDeletingChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
f1.apply(this, arguments);
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = this.onerror = null;
f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
};
}
function hookUpdatingChain(f1, f2) {
if (f1 === nop) return f2;
return function (modifications) {
var res = f1.apply(this, arguments);
extend(modifications, res); // If f1 returns new modifications, extend caller's modifications with the result before calling next in chain.
var onsuccess = this.onsuccess,
// In case event listener has set this.onsuccess
onerror = this.onerror; // In case event listener has set this.onerror
this.onsuccess = null;
this.onerror = null;
var res2 = f2.apply(this, arguments);
if (onsuccess) this.onsuccess = this.onsuccess ? callBoth(onsuccess, this.onsuccess) : onsuccess;
if (onerror) this.onerror = this.onerror ? callBoth(onerror, this.onerror) : onerror;
return res === undefined ? res2 === undefined ? undefined : res2 : extend(res, res2);
};
}
function reverseStoppableEventChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
if (f2.apply(this, arguments) === false) return false;
return f1.apply(this, arguments);
};
}
function promisableChain(f1, f2) {
if (f1 === nop) return f2;
return function () {
var res = f1.apply(this, arguments);
if (res && typeof res.then === 'function') {
var thiz = this,
i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
}return res.then(function () {
return f2.apply(thiz, args);
});
}
return f2.apply(this, arguments);
};
}
var keys = Object.keys;
var isArray = Array.isArray;
var _global = typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;
function extend(obj, extension) {
if (typeof extension !== 'object') return obj;
keys(extension).forEach(function (key) {
obj[key] = extension[key];
});
return obj;
}
var getProto = Object.getPrototypeOf;
var _hasOwn = {}.hasOwnProperty;
function hasOwn(obj, prop) {
return _hasOwn.call(obj, prop);
}
function props(proto, extension) {
if (typeof extension === 'function') extension = extension(getProto(proto));
keys(extension).forEach(function (key) {
setProp(proto, key, extension[key]);
});
}
function setProp(obj, prop, functionOrGetSet, options) {
Object.defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ? { get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true } : { value: functionOrGetSet, configurable: true, writable: true }, options));
}
function derive(Child) {
return {
from: function (Parent) {
Child.prototype = Object.create(Parent.prototype);
setProp(Child.prototype, "constructor", Child);
return {
extend: props.bind(null, Child.prototype)
};
}
};
}
var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
function getPropertyDescriptor(obj, prop) {
var pd = getOwnPropertyDescriptor(obj, prop),
proto;
return pd || (proto = getProto(obj)) && getPropertyDescriptor(proto, prop);
}
var _slice = [].slice;
function slice(args, start, end) {
return _slice.call(args, start, end);
}
function override(origFunc, overridedFactory) {
return overridedFactory(origFunc);
}
function doFakeAutoComplete(fn) {
var to = setTimeout(fn, 1000);
clearTimeout(to);
}
function assert(b) {
if (!b) throw new exceptions.Internal("Assertion failed");
}
function asap(fn) {
if (_global.setImmediate) setImmediate(fn);else setTimeout(fn, 0);
}
/** Generate an object (hash map) based on given array.
* @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to
* instert on the resulting object for each item in the array. If this function returns a falsy value, the
* current item wont affect the resulting object.
*/
function arrayToObject(array, extractor) {
return array.reduce(function (result, item, i) {
var nameAndValue = extractor(item, i);
if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];
return result;
}, {});
}
function trycatcher(fn, reject) {
return function () {
try {
fn.apply(this, arguments);
} catch (e) {
reject(e);
}
};
}
function tryCatch(fn, onerror, args) {
try {
fn.apply(null, args);
} catch (ex) {
onerror && onerror(ex);
}
}
function rejection(err, uncaughtHandler) {
// Get the call stack and return a rejected promise.
var rv = Promise.reject(err);
return uncaughtHandler ? rv.uncaught(uncaughtHandler) : rv;
}
function getByKeyPath(obj, keyPath) {
// http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path
if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.
if (!keyPath) return obj;
if (typeof keyPath !== 'string') {
var rv = [];
for (var i = 0, l = keyPath.length; i < l; ++i) {
var val = getByKeyPath(obj, keyPath[i]);
rv.push(val);
}
return rv;
}
var period = keyPath.indexOf('.');
if (period !== -1) {
var innerObj = obj[keyPath.substr(0, period)];
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));
}
return undefined;
}
function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "") {
if (value === undefined) delete obj[currentKeyPath];else obj[currentKeyPath] = value;
} else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = obj[currentKeyPath] = {};
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) delete obj[keyPath];else obj[keyPath] = value;
}
}
}
function delByKeyPath(obj, keyPath) {
if (typeof keyPath === 'string') setByKeyPath(obj, keyPath, undefined);else if ('length' in keyPath) [].map.call(keyPath, function (kp) {
setByKeyPath(obj, kp, undefined);
});
}
function shallowClone(obj) {
var rv = {};
for (var m in obj) {
if (hasOwn(obj, m)) rv[m] = obj[m];
}
return rv;
}
function deepClone(any) {
if (!any || typeof any !== 'object') return any;
var rv;
if (isArray(any)) {
rv = [];
for (var i = 0, l = any.length; i < l; ++i) {
rv.push(deepClone(any[i]));
}
} else if (any instanceof Date) {
rv = new Date();
rv.setTime(any.getTime());
} else {
rv = any.constructor ? Object.create(any.constructor.prototype) : {};
for (var prop in any) {
if (hasOwn(any, prop)) {
rv[prop] = deepClone(any[prop]);
}
}
}
return rv;
}
function getObjectDiff(a, b, rv, prfx) {
// Compares objects a and b and produces a diff object.
rv = rv || {};
prfx = prfx || '';
for (var prop in a) {
if (hasOwn(a, prop)) {
if (!hasOwn(b, prop)) rv[prfx + prop] = undefined; // Property removed
else {
var ap = a[prop],
bp = b[prop];
if (typeof ap === 'object' && typeof bp === 'object') getObjectDiff(ap, bp, rv, prfx + prop + ".");else if (ap !== bp) rv[prfx + prop] = b[prop]; // Primitive value changed
}
}
}for (prop in b) {
if (hasOwn(b, prop) && !hasOwn(a, prop)) {
rv[prfx + prop] = b[prop]; // Property added
}
}return rv;
}
// If first argument is iterable or array-like, return it as an array
var iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;
var getIteratorOf = iteratorSymbol ? function (x) {
var i;
return x != null && (i = x[iteratorSymbol]) && i.apply(x);
} : function () {
return null;
};
var NO_CHAR_ARRAY = {};
// Takes one or several arguments and returns an array based on the following criteras:
// * If several arguments provided, return arguments converted to an array in a way that
// still allows javascript engine to optimize the code.
// * If single argument is an array, return a clone of it.
// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special
// case to the two bullets below.
// * If single argument is an iterable, convert it to an array and return the resulting array.
// * If single argument is array-like (has length of type number), convert it to an array.
function getArrayOf(arrayLike) {
var i, a, x, it;
if (arguments.length === 1) {
if (isArray(arrayLike)) return arrayLike.slice();
if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];
if (it = getIteratorOf(arrayLike)) {
a = [];
while (x = it.next(), !x.done) {
a.push(x.value);
}return a;
}
if (arrayLike == null) return [arrayLike];
i = arrayLike.length;
if (typeof i === 'number') {
a = new Array(i);
while (i--) {
a[i] = arrayLike[i];
}return a;
}
return [arrayLike];
}
i = arguments.length;
a = new Array(i);
while (i--) {
a[i] = arguments[i];
}return a;
}
var concat = [].concat;
function flatten(a) {
return concat.apply([], a);
}
var dexieErrorNames = ['Modify', 'Bulk', 'OpenFailed', 'VersionChange', 'Schema', 'Upgrade', 'InvalidTable', 'MissingAPI', 'NoSuchDatabase', 'InvalidArgument', 'SubTransaction', 'Unsupported', 'Internal', 'DatabaseClosed', 'IncompatiblePromise'];
var idbDomErrorNames = ['Unknown', 'Constraint', 'Data', 'TransactionInactive', 'ReadOnly', 'Version', 'NotFound', 'InvalidState', 'InvalidAccess', 'Abort', 'Timeout', 'QuotaExceeded', 'Syntax', 'DataClone'];
var errorList = dexieErrorNames.concat(idbDomErrorNames);
var defaultTexts = {
VersionChanged: "Database version changed by other database connection",
DatabaseClosed: "Database has been closed",
Abort: "Transaction aborted",
TransactionInactive: "Transaction has already completed or failed"
};
//
// DexieError - base class of all out exceptions.
//
function DexieError(name, msg) {
// Reason we don't use ES6 classes is because:
// 1. It bloats transpiled code and increases size of minified code.
// 2. It doesn't give us much in this case.
// 3. It would require sub classes to call super(), which
// is not needed when deriving from Error.
this._e = getErrorWithStack();
this.name = name;
this.message = msg;
}
derive(DexieError).from(Error).extend({
stack: {
get: function () {
return this._stack || (this._stack = this.name + ": " + this.message + prettyStack(this._e, 2));
}
},
toString: function () {
return this.name + ": " + this.message;
}
});
function getMultiErrorMessage(msg, failures) {
return msg + ". Errors: " + failures.map(function (f) {
return f.toString();
}).filter(function (v, i, s) {
return s.indexOf(v) === i;
}) // Only unique error strings
.join('\n');
}
//
// ModifyError - thrown in WriteableCollection.modify()
// Specific constructor because it contains members failures and failedKeys.
//
function ModifyError(msg, failures, successCount, failedKeys) {
this._e = getErrorWithStack();
this.failures = failures;
this.failedKeys = failedKeys;
this.successCount = successCount;
}
derive(ModifyError).from(DexieError);
function BulkError(msg, failures) {
this._e = getErrorWithStack();
this.name = "BulkError";
this.failures = failures;
this.message = getMultiErrorMessage(msg, failures);
}
derive(BulkError).from(DexieError);
//
//
// Dynamically generate error names and exception classes based
// on the names in errorList.
//
//
// Map of {ErrorName -> ErrorName + "Error"}
var errnames = errorList.reduce(function (obj, name) {
return obj[name] = name + "Error", obj;
}, {});
// Need an alias for DexieError because we're gonna create subclasses with the same name.
var BaseException = DexieError;
// Map of {ErrorName -> exception constructor}
var exceptions = errorList.reduce(function (obj, name) {
// Let the name be "DexieError" because this name may
// be shown in call stack and when debugging. DexieError is
// the most true name because it derives from DexieError,
// and we cannot change Function.name programatically without
// dynamically create a Function object, which would be considered
// 'eval-evil'.
var fullName = name + "Error";
function DexieError(msgOrInner, inner) {
this._e = getErrorWithStack();
this.name = fullName;
if (!msgOrInner) {
this.message = defaultTexts[name] || fullName;
this.inner = null;
} else if (typeof msgOrInner === 'string') {
this.message = msgOrInner;
this.inner = inner || null;
} else if (typeof msgOrInner === 'object') {
this.message = msgOrInner.name + ' ' + msgOrInner.message;
this.inner = msgOrInner;
}
}
derive(DexieError).from(BaseException);
obj[name] = DexieError;
return obj;
}, {});
// Use ECMASCRIPT standard exceptions where applicable:
exceptions.Syntax = SyntaxError;
exceptions.Type = TypeError;
exceptions.Range = RangeError;
var exceptionMap = idbDomErrorNames.reduce(function (obj, name) {
obj[name + "Error"] = exceptions[name];
return obj;
}, {});
function mapError(domError, message) {
if (!domError || domError instanceof DexieError || domError instanceof TypeError || domError instanceof SyntaxError || !domError.name || !exceptionMap[domError.name]) return domError;
var rv = new exceptionMap[domError.name](message || domError.message, domError);
if ("stack" in domError) {
// Derive stack from inner exception if it has a stack
setProp(rv, "stack", { get: function () {
return this.inner.stack;
} });
}
return rv;
}
var fullNameExceptions = errorList.reduce(function (obj, name) {
if (["Syntax", "Type", "Range"].indexOf(name) === -1) obj[name + "Error"] = exceptions[name];
return obj;
}, {});
fullNameExceptions.ModifyError = ModifyError;
fullNameExceptions.DexieError = DexieError;
fullNameExceptions.BulkError = BulkError;
function Events(ctx) {
var evs = {};
var rv = function (eventName, subscriber) {
if (subscriber) {
// Subscribe. If additional arguments than just the subscriber was provided, forward them as well.
var i = arguments.length,
args = new Array(i - 1);
while (--i) {
args[i - 1] = arguments[i];
}evs[eventName].subscribe.apply(null, args);
return ctx;
} else if (typeof eventName === 'string') {
// Return interface allowing to fire or unsubscribe from event
return evs[eventName];
}
};
rv.addEventType = add;
for (var i = 1, l = arguments.length; i < l; ++i) {
add(arguments[i]);
}
return rv;
function add(eventName, chainFunction, defaultFunction) {
if (typeof eventName === 'object') return addConfiguredEvents(eventName);
if (!chainFunction) chainFunction = reverseStoppableEventChain;
if (!defaultFunction) defaultFunction = nop;
var context = {
subscribers: [],
fire: defaultFunction,
subscribe: function (cb) {
if (context.subscribers.indexOf(cb) === -1) {
context.subscribers.push(cb);
context.fire = chainFunction(context.fire, cb);
}
},
unsubscribe: function (cb) {
context.subscribers = context.subscribers.filter(function (fn) {
return fn !== cb;
});
context.fire = context.subscribers.reduce(chainFunction, defaultFunction);
}
};
evs[eventName] = rv[eventName] = context;
return context;
}
function addConfiguredEvents(cfg) {
// events(this, {reading: [functionChain, nop]});
keys(cfg).forEach(function (eventName) {
var args = cfg[eventName];
if (isArray(args)) {
add(eventName, cfg[eventName][0], cfg[eventName][1]);
} else if (args === 'asap') {
// Rather than approaching event subscription using a functional approach, we here do it in a for-loop where subscriber is executed in its own stack
// enabling that any exception that occur wont disturb the initiator and also not nescessary be catched and forgotten.
var context = add(eventName, mirror, function fire() {
// Optimazation-safe cloning of arguments into args.
var i = arguments.length,
args = new Array(i);
while (i--) {
args[i] = arguments[i];
} // All each subscriber:
context.subscribers.forEach(function (fn) {
asap(function fireEvent() {
fn.apply(null, args);
});
});
});
} else throw new exceptions.InvalidArgument("Invalid event config");
});
}
}
//
// Promise Class for Dexie library
//
// I started out writing this Promise class by copying promise-light (https://github.com/taylorhakes/promise-light) by
// https://github.com/taylorhakes - an A+ and ECMASCRIPT 6 compliant Promise implementation.
//
// Modifications needed to be done to support indexedDB because it wont accept setTimeout()
// (See discussion: https://github.com/promises-aplus/promises-spec/issues/45) .
// This topic was also discussed in the following thread: https://github.com/promises-aplus/promises-spec/issues/45
//
// This implementation will not use setTimeout or setImmediate when it's not needed. The behavior is 100% Promise/A+ compliant since
// the caller of new Promise() can be certain that the promise wont be triggered the lines after constructing the promise.
//
// In previous versions this was fixed by not calling setTimeout when knowing that the resolve() or reject() came from another
// tick. In Dexie v1.4.0, I've rewritten the Promise class entirely. Just some fragments of promise-light is left. I use
// another strategy now that simplifies everything a lot: to always execute callbacks in a new tick, but have an own microTick
// engine that is used instead of setImmediate() or setTimeout().
// Promise class has also been optimized a lot with inspiration from bluebird - to avoid closures as much as possible.
// Also with inspiration from bluebird, asyncronic stacks in debug mode.
//
// Specific non-standard features of this Promise class:
// * Async static context support (Promise.PSD)
// * Promise.follow() method built upon PSD, that allows user to track all promises created from current stack frame
// and below + all promises that those promises creates or awaits.
// * Detect any unhandled promise in a PSD-scope (PSD.onunhandled).
//
// David Fahlander, https://github.com/dfahlander
//
// Just a pointer that only this module knows about.
// Used in Promise constructor to emulate a private constructor.
var INTERNAL = {};
// Async stacks (long stacks) must not grow infinitely.
var LONG_STACKS_CLIP_LIMIT = 100;
var MAX_LONG_STACKS = 20;
var stack_being_generated = false;
/* The default "nextTick" function used only for the very first promise in a promise chain.
As soon as then promise is resolved or rejected, all next tasks will be executed in micro ticks
emulated in this module. For indexedDB compatibility, this means that every method needs to
execute at least one promise before doing an indexedDB operation. Dexie will always call
db.ready().then() for every operation to make sure the indexedDB event is started in an
emulated micro tick.
*/
var schedulePhysicalTick = typeof setImmediate === 'undefined' ?
// No support for setImmediate. No worry, setTimeout is only called
// once time. Every tick that follows will be our emulated micro tick.
// Could have uses setTimeout.bind(null, 0, physicalTick) if it wasnt for that FF13 and below has a bug
function () {
setTimeout(physicalTick, 0);
} :
// setImmediate supported. Modern platform. Also supports Function.bind().
setImmediate.bind(null, physicalTick);
// Confifurable through Promise.scheduler.
// Don't export because it would be unsafe to let unknown
// code call it unless they do try..catch within their callback.
// This function can be retrieved through getter of Promise.scheduler though,
// but users must not do Promise.scheduler (myFuncThatThrows exception)!
var asap$1 = function (callback, args) {
microtickQueue.push([callback, args]);
if (needsNewPhysicalTick) {
schedulePhysicalTick();
needsNewPhysicalTick = false;
}
};
var isOutsideMicroTick = true;
var needsNewPhysicalTick = true;
var unhandledErrors = [];
var rejectingErrors = [];
var currentFulfiller = null;
var rejectionMapper = mirror;
// Remove in next major when removing error mapping of DOMErrors and DOMExceptions
var globalPSD = {
global: true,
ref: 0,
unhandleds: [],
onunhandled: globalError,
//env: null, // Will be set whenever leaving a scope using wrappers.snapshot()
finalize: function () {
this.unhandleds.forEach(function (uh) {
try {
globalError(uh[0], uh[1]);
} catch (e) {}
});
}
};
var PSD = globalPSD;
var microtickQueue = []; // Callbacks to call in this or next physical tick.
var numScheduledCalls = 0; // Number of listener-calls left to do in this physical tick.
var tickFinalizers = []; // Finalizers to call when there are no more async calls scheduled within current physical tick.
// Wrappers are not being used yet. Their framework is functioning and can be used
// to replace environment during a PSD scope (a.k.a. 'zone').
/* **KEEP** export var wrappers = (() => {
var wrappers = [];
return {
snapshot: () => {
var i = wrappers.length,
result = new Array(i);
while (i--) result[i] = wrappers[i].snapshot();
return result;
},
restore: values => {
var i = wrappers.length;
while (i--) wrappers[i].restore(values[i]);
},
wrap: () => wrappers.map(w => w.wrap()),
add: wrapper => {
wrappers.push(wrapper);
}
};
})();
*/
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
this._listeners = [];
this.onuncatched = nop; // Deprecate in next major. Not needed. Better to use global error handler.
// A library may set `promise._lib = true;` after promise is created to make resolve() or reject()
// execute the microtask engine implicitely within the call to resolve() or reject().
// To remain A+ compliant, a library must only set `_lib=true` if it can guarantee that the stack
// only contains library code when calling resolve() or reject().
// RULE OF THUMB: ONLY set _lib = true for promises explicitely resolving/rejecting directly from
// global scope (event handler, timer etc)!
this._lib = false;
// Current async scope
var psd = this._PSD = PSD;
if (debug) {
this._stackHolder = getErrorWithStack();
this._prev = null;
this._numPrev = 0; // Number of previous promises (for long stacks)
linkToPreviousPromise(this, currentFulfiller);
}
if (typeof fn !== 'function') {
if (fn !== INTERNAL) throw new TypeError('Not a function');
// Private constructor (INTERNAL, state, value).
// Used internally by Promise.resolve() and Promise.reject().
this._state = arguments[1];
this._value = arguments[2];
if (this._state === false) handleRejection(this, this._value); // Map error, set stack and addPossiblyUnhandledError().
return;
}
this._state = null; // null (=pending), false (=rejected) or true (=resolved)
this._value = null; // error or result
++psd.ref; // Refcounting current scope
executePromiseTask(this, fn);
}
props(Promise.prototype, {
then: function (onFulfilled, onRejected) {
var _this = this;
var rv = new Promise(function (resolve, reject) {
propagateToListener(_this, new Listener(onFulfilled, onRejected, resolve, reject));
});
debug && (!this._prev || this._state === null) && linkToPreviousPromise(rv, this);
return rv;
},
_then: function (onFulfilled, onRejected) {
// A little tinier version of then() that don't have to create a resulting promise.
propagateToListener(this, new Listener(null, null, onFulfilled, onRejected));
},
catch: function (onRejected) {
if (arguments.length === 1) return this.then(null, onRejected);
// First argument is the Error type to catch
var type = arguments[0],
handler = arguments[1];
return typeof type === 'function' ? this.then(null, function (err) {
return(
// Catching errors by its constructor type (similar to java / c++ / c#)
// Sample: promise.catch(TypeError, function (e) { ... });
err instanceof type ? handler(err) : PromiseReject(err)
);
}) : this.then(null, function (err) {
return(
// Catching errors by the error.name property. Makes sense for indexedDB where error type
// is always DOMError but where e.name tells the actual error type.
// Sample: promise.catch('ConstraintError', function (e) { ... });
err && err.name === type ? handler(err) : PromiseReject(err)
);
});
},
finally: function (onFinally) {
return this.then(function (value) {
onFinally();
return value;
}, function (err) {
onFinally();
return PromiseReject(err);
});
},
// Deprecate in next major. Needed only for db.on.error.
uncaught: function (uncaughtHandler) {
var _this2 = this;
// Be backward compatible and use "onuncatched" as the event name on this.
// Handle multiple subscribers through reverseStoppableEventChain(). If a handler returns `false`, bubbling stops.
this.onuncatched = reverseStoppableEventChain(this.onuncatched, uncaughtHandler);
// In case caller does this on an already rejected promise, assume caller wants to point out the error to this promise and not
// a previous promise. Reason: the prevous promise may lack onuncatched handler.
if (this._state === false && unhandledErrors.indexOf(this) === -1) {
// Replace unhandled error's destinaion promise with this one!
unhandledErrors.some(function (p, i, l) {
return p._value === _this2._value && (l[i] = _this2);
});
// Actually we do this shit because we need to support db.on.error() correctly during db.open(). If we deprecate db.on.error, we could
// take away this piece of code as well as the onuncatched and uncaught() method.
}
return this;
},
stack: {
get: function () {
if (this._stack) return this._stack;
try {
stack_being_generated = true;
var stacks = getStack(this, [], MAX_LONG_STACKS);
var stack = stacks.join("\nFrom previous: ");
if (this._state !== null) this._stack = stack; // Stack may be updated on reject.
return stack;
} finally {
stack_being_generated = false;
}
}
}
});
function Listener(onFulfilled, onRejected, resolve, reject) {
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
this.onRejected = typeof onRejected === 'function' ? onRejected : null;
this.resolve = resolve;
this.reject = reject;
this.psd = PSD;
}
// Promise Static Properties
props(Promise, {
all: function () {
var values = getArrayOf.apply(null, arguments); // Supports iterables, implicit arguments and array-like.
return new Promise(function (resolve, reject) {
if (values.length === 0) resolve([]);
var remaining = values.length;
values.forEach(function (a, i) {
return Promise.resolve(a).then(function (x) {
values[i] = x;
if (! --remaining) resolve(values);
}, reject);
});
});
},
resolve: function (value) {
if (value && typeof value.then === 'function') return value;
return new Promise(INTERNAL, true, value);
},
reject: PromiseReject,
race: function () {
var values = getArrayOf.apply(null, arguments);
return new Promise(function (resolve, reject) {
values.map(function (value) {
return Promise.resolve(value).then(resolve, reject);
});
});
},
PSD: {
get: function () {
return PSD;
},
set: function (value) {
return PSD = value;
}
},
newPSD: newScope,
usePSD: usePSD,
scheduler: {
get: function () {
return asap$1;
},
set: function (value) {
asap$1 = value;
}
},
rejectionMapper: {
get: function () {
return rejectionMapper;
},
set: function (value) {
rejectionMapper = value;
} // Map reject failures
},
follow: function (fn) {
return new Promise(function (resolve, reject) {
return newScope(function (resolve, reject) {
var psd = PSD;
psd.unhandleds = []; // For unhandled standard- or 3rd party Promises. Checked at psd.finalize()
psd.onunhandled = reject; // Triggered directly on unhandled promises of this library.
psd.finalize = callBoth(function () {
var _this3 = this;
// Unhandled standard or 3rd part promises are put in PSD.unhandleds and
// examined upon scope completion while unhandled rejections in this Promise
// will trigger directly through psd.onunhandled
run_at_end_of_this_or_next_physical_tick(function () {
_this3.unhandleds.length === 0 ? resolve() : reject(_this3.unhandleds[0]);
});
}, psd.finalize);
fn();
}, resolve, reject);
});
},
on: Events(null, { "error": [reverseStoppableEventChain, defaultErrorHandler] // Default to defaultErrorHandler
})
});
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function executePromiseTask(promise, fn) {
// Promise Resolution Procedure:
// https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
try {
fn(function (value) {
if (promise._state !== null) return;
if (value === promise) throw new TypeError('A promise cannot be resolved with itself.');
var shouldExecuteTick = promise._lib && beginMicroTickScope();
if (value && typeof value.then === 'function') {
executePromiseTask(promise, function (resolve, reject) {
value instanceof Promise ? value._then(resolve, reject) : value.then(resolve, reject);
});
} else {
promise._state = true;
promise._value = value;
propagateAllListeners(promise);
}
if (shouldExecuteTick) endMicroTickScope();
}, handleRejection.bind(null, promise)); // If Function.bind is not supported. Exception is handled in catch below
} catch (ex) {
handleRejection(promise, ex);
}
}
function handleRejection(promise, reason) {
rejectingErrors.push(reason);
if (promise._state !== null) return;
var shouldExecuteTick = promise._lib && beginMicroTickScope();
reason = rejectionMapper(reason);
promise._state = false;
promise._value = reason;
debug && reason !== null && !reason._promise && typeof reason === 'object' && tryCatch(function () {
var origProp = getPropertyDescriptor(reason, "stack");
reason._promise = promise;
setProp(reason, "stack", {
get: function () {
return stack_being_generated ? origProp && (origProp.get ? origProp.get.apply(reason) : origProp.value) : promise.stack;
}
});
});
// Add the failure to a list of possibly uncaught errors
addPossiblyUnhandledError(promise);
propagateAllListeners(promise);
if (shouldExecuteTick) endMicroTickScope();
}
function propagateAllListeners(promise) {
//debug && linkToPreviousPromise(promise);
var listeners = promise._listeners;
promise._listeners = [];
for (var i = 0, len = listeners.length; i < len; ++i) {
propagateToListener(promise, listeners[i]);
}
var psd = promise._PSD;
--psd.ref || psd.finalize(); // if psd.ref reaches zero, call psd.finalize();
if (numScheduledCalls === 0) {
// If numScheduledCalls is 0, it means that our stack is not in a callback of a scheduled call,
// and that no deferreds where listening to this rejection or success.
// Since there is a risk that our stack can contain application code that may
// do stuff after this code is finished that may generate new calls, we cannot
// call finalizers here.
++numScheduledCalls;
asap$1(function () {
if (--numScheduledCalls === 0) finalizePhysicalTick(); // Will detect unhandled errors
}, []);
}
}
function propagateToListener(promise, listener) {
if (promise._state === null) {
promise._listeners.push(listener);
return;
}
var cb = promise._state ? listener.onFulfilled : listener.onRejected;
if (cb === null) {
// This Listener doesnt have a listener for the event being triggered (onFulfilled or onReject) so lets forward the event to any eventual listeners on the Promise instance returned by then() or catch()
return (promise._state ? listener.resolve : listener.reject)(promise._value);
}
var psd = listener.psd;
++psd.ref;
++numScheduledCalls;
asap$1(callListener, [cb, promise, listener]);
}
function callListener(cb, promise, listener) {
var outerScope = PSD;
var psd = listener.psd;
try {
if (psd !== outerScope) {
// **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment.
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
// Set static variable currentFulfiller to the promise that is being fullfilled,
// so that we connect the chain of promises (for long stacks support)
currentFulfiller = promise;
// Call callback and resolve our listener with it's return value.
var value = promise._value,
ret;
if (promise._state) {
ret = cb(value);
} else {
if (rejectingErrors.length) rejectingErrors = [];
ret = cb(value);
if (rejectingErrors.indexOf(value) === -1) markErrorAsHandled(promise); // Callback didnt do Promise.reject(err) nor reject(err) onto another promise.
}
listener.resolve(ret);
} catch (e) {
// Exception thrown in callback. Reject our listener.
listener.reject(e);
} finally {
// Restore PSD, env and currentFulfiller.
if (psd !== outerScope) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment
}
currentFulfiller = null;
if (--numScheduledCalls === 0) finalizePhysicalTick();
--psd.ref || psd.finalize();
}
}
function getStack(promise, stacks, limit) {
if (stacks.length === limit) return stacks;
var stack = "";
if (promise._state === false) {
var failure = promise._value,
errorName,
message;
if (failure != null) {
errorName = failure.name || "Error";
message = failure.message || failure;
stack = prettyStack(failure, 0);
} else {
errorName = failure; // If error is undefined or null, show that.
message = "";
}
stacks.push(errorName + (message ? ": " + message : "") + stack);
}
if (debug) {
stack = prettyStack(promise._stackHolder, 2);
if (stack && stacks.indexOf(stack) === -1) stacks.push(stack);
if (promise._prev) getStack(promise._prev, stacks, limit);
}
return stacks;
}
function linkToPreviousPromise(promise, prev) {
// Support long stacks by linking to previous completed promise.
var numPrev = prev ? prev._numPrev + 1 : 0;
if (numPrev < LONG_STACKS_CLIP_LIMIT) {
// Prohibit infinite Promise loops to get an infinite long memory consuming "tail".
promise._prev = prev;
promise._numPrev = numPrev;
}
}
/* The callback to schedule with setImmediate() or setTimeout().
It runs a virtual microtick and executes any callback registered in microtickQueue.
*/
function physicalTick() {
beginMicroTickScope() && endMicroTickScope();
}
function beginMicroTickScope() {
var wasRootExec = isOutsideMicroTick;
isOutsideMicroTick = false;
needsNewPhysicalTick = false;
return wasRootExec;
}
/* Executes micro-ticks without doing try..catch.
This can be possible because we only use this internally and
the registered functions are exception-safe (they do try..catch
internally before calling any external method). If registering
functions in the microtickQueue that are not exception-safe, this
would destroy the framework and make it instable. So we don't export
our asap method.
*/
function endMicroTickScope() {
var callbacks, i, l;
do {
while (microtickQueue.length > 0) {
callbacks = microtickQueue;
microtickQueue = [];
l = callbacks.length;
for (i = 0; i < l; ++i) {
var item = callbacks[i];
item[0].apply(null, item[1]);
}
}
} while (microtickQueue.length > 0);
isOutsideMicroTick = true;
needsNewPhysicalTick = true;
}
function finalizePhysicalTick() {
var unhandledErrs = unhandledErrors;
unhandledErrors = [];
unhandledErrs.forEach(function (p) {
p._PSD.onunhandled.call(null, p._value, p);
});
var finalizers = tickFinalizers.slice(0); // Clone first because finalizer may remove itself from list.
var i = finalizers.length;
while (i) {
finalizers[--i]();
}
}
function run_at_end_of_this_or_next_physical_tick(fn) {
function finalizer() {
fn();
tickFinalizers.splice(tickFinalizers.indexOf(finalizer), 1);
}
tickFinalizers.push(finalizer);
++numScheduledCalls;
asap$1(function () {
if (--numScheduledCalls === 0) finalizePhysicalTick();
}, []);
}
function addPossiblyUnhandledError(promise) {
// Only add to unhandledErrors if not already there. The first one to add to this list
// will be upon the first rejection so that the root cause (first promise in the
// rejection chain) is the one listed.
if (!unhandledErrors.some(function (p) {
return p._value === promise._value;
})) unhandledErrors.push(promise);
}
function markErrorAsHandled(promise) {
// Called when a reject handled is actually being called.
// Search in unhandledErrors for any promise whos _value is this promise_value (list
// contains only rejected promises, and only one item per error)
var i = unhandledErrors.length;
while (i) {
if (unhandledErrors[--i]._value === promise._value) {
// Found a promise that failed with this same error object pointer,
// Remove that since there is a listener that actually takes care of it.
unhandledErrors.splice(i, 1);
return;
}
}
}
// By default, log uncaught errors to the console
function defaultErrorHandler(e) {
console.warn('Unhandled rejection: ' + (e.stack || e));
}
function PromiseReject(reason) {
return new Promise(INTERNAL, false, reason);
}
function wrap(fn, errorCatcher) {
var psd = PSD;
return function () {
var wasRootExec = beginMicroTickScope(),
outerScope = PSD;
try {
if (outerScope !== psd) {
// **KEEP** outerScope.env = wrappers.snapshot(); // Snapshot outerScope's environment
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
return fn.apply(this, arguments);
} catch (e) {
errorCatcher && errorCatcher(e);
} finally {
if (outerScope !== psd) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment
}
if (wasRootExec) endMicroTickScope();
}
};
}
function newScope(fn, a1, a2, a3) {
var parent = PSD,
psd = Object.create(parent);
psd.parent = parent;
psd.ref = 0;
psd.global = false;
// **KEEP** psd.env = wrappers.wrap(psd);
// unhandleds and onunhandled should not be specifically set here.
// Leave them on parent prototype.
// unhandleds.push(err) will push to parent's prototype
// onunhandled() will call parents onunhandled (with this scope's this-pointer though!)
++parent.ref;
psd.finalize = function () {
--this.parent.ref || this.parent.finalize();
};
var rv = usePSD(psd, fn, a1, a2, a3);
if (psd.ref === 0) psd.finalize();
return rv;
}
function usePSD(psd, fn, a1, a2, a3) {
var outerScope = PSD;
try {
if (psd !== outerScope) {
// **KEEP** outerScope.env = wrappers.snapshot(); // snapshot outerScope's environment.
PSD = psd;
// **KEEP** wrappers.restore(psd.env); // Restore PSD's environment.
}
return fn(a1, a2, a3);
} finally {
if (psd !== outerScope) {
PSD = outerScope;
// **KEEP** wrappers.restore(outerScope.env); // Restore outerScope's environment.
}
}
}
function globalError(err, promise) {
var rv;
try {
rv = promise.onuncatched(err);
} catch (e) {}
if (rv !== false) try {
Promise.on.error.fire(err, promise); // TODO: Deprecated and use same global handler as bluebird.
} catch (e) {}
}
/* **KEEP**
export function wrapPromise(PromiseClass) {
var proto = PromiseClass.prototype;
var origThen = proto.then;
wrappers.add({
snapshot: () => proto.then,
restore: value => {proto.then = value;},
wrap: () => patchedThen
});
function patchedThen (onFulfilled, onRejected) {
var promise = this;
var onFulfilledProxy = wrap(function(value){
var rv = value;
if (onFulfilled) {
rv = onFulfilled(rv);
if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.
}
--PSD.ref || PSD.finalize();
return rv;
});
var onRejectedProxy = wrap(function(err){
promise._$err = err;
var unhandleds = PSD.unhandleds;
var idx = unhandleds.length,
rv;
while (idx--) if (unhandleds[idx]._$err === err) break;
if (onRejected) {
if (idx !== -1) unhandleds.splice(idx, 1); // Mark as handled.
rv = onRejected(err);
if (rv && typeof rv.then === 'function') rv.then(); // Intercept that promise as well.
} else {
if (idx === -1) unhandleds.push(promise);
rv = PromiseClass.reject(err);
rv._$nointercept = true; // Prohibit eternal loop.
}
--PSD.ref || PSD.finalize();
return rv;
});
if (this._$nointercept) return origThen.apply(this, arguments);
++PSD.ref;
return origThen.call(this, onFulfilledProxy, onRejectedProxy);
}
}
// Global Promise wrapper
if (_global.Promise) wrapPromise(_global.Promise);
*/
doFakeAutoComplete(function () {
// Simplify the job for VS Intellisense. This piece of code is one of the keys to the new marvellous intellisense support in Dexie.
asap$1 = function (fn, args) {
setTimeout(function () {
fn.apply(null, args);
}, 0);
};
});
var maxString = String.fromCharCode(65535);
var maxKey = function () {
try {
IDBKeyRange.only([[]]);return [[]];
} catch (e) {
return maxString;
}
}();
var INVALID_KEY_ARGUMENT = "Invalid key provided. Keys must be of type string, number, Date or Array<string | number | Date>.";
var STRING_EXPECTED = "String expected.";
var connections = [];
var isIEOrEdge = typeof navigator !== 'undefined' && /(MSIE|Trident|Edge)/.test(navigator.userAgent);
var hasIEDeleteObjectStoreBug = isIEOrEdge;
var hangsOnDeleteLargeKeyRange = isIEOrEdge;
var dexieStackFrameFilter = function (frame) {
return !/(dexie\.js|dexie\.min\.js)/.test(frame);
};
setDebug(debug, dexieStackFrameFilter);
function Dexie(dbName, options) {
/// <param name="options" type="Object" optional="true">Specify only if you wich to control which addons that should run on this instance</param>
var deps = Dexie.dependencies;
var opts = extend({
// Default Options
addons: Dexie.addons, // Pick statically registered addons by default
autoOpen: true, // Don't require db.open() explicitely.
indexedDB: deps.indexedDB, // Backend IndexedDB api. Default to IDBShim or browser env.
IDBKeyRange: deps.IDBKeyRange // Backend IDBKeyRange api. Default to IDBShim or browser env.
}, options);
var addons = opts.addons,
autoOpen = opts.autoOpen,
indexedDB = opts.indexedDB,
IDBKeyRange = opts.IDBKeyRange;
var globalSchema = this._dbSchema = {};
var versions = [];
var dbStoreNames = [];
var allTables = {};
///<var type="IDBDatabase" />
var idbdb = null; // Instance of IDBDatabase
var dbOpenError = null;
var isBeingOpened = false;
var openComplete = false;
var READONLY = "readonly",
READWRITE = "readwrite";
var db = this;
var dbReadyResolve,
dbReadyPromise = new Promise(function (resolve) {
dbReadyResolve = resolve;
}),
cancelOpen,
openCanceller = new Promise(function (_, reject) {
cancelOpen = reject;
});
var autoSchema = true;
var hasNativeGetDatabaseNames = !!getNativeGetDatabaseNamesFn(indexedDB),
hasGetAll;
function init() {
// Default subscribers to "versionchange" and "blocked".
// Can be overridden by custom handlers. If custom handlers return false, these default
// behaviours will be prevented.
db.on("versionchange", function (ev) {
// Default behavior for versionchange event is to close database connection.
// Caller can override this behavior by doing db.on("versionchange", function(){ return false; });
// Let's not block the other window from making it's delete() or open() call.
// NOTE! This event is never fired in IE,Edge or Safari.
if (ev.newVersion > 0) console.warn('Another connection wants to upgrade database \'' + db.name + '\'. Closing db now to resume the upgrade.');else console.warn('Another connection wants to delete database \'' + db.name + '\'. Closing db now to resume the delete request.');
db.close();
// In many web applications, it would be recommended to force window.reload()
// when this event occurs. To do that, subscribe to the versionchange event
// and call window.location.reload(true) if ev.newVersion > 0 (not a deletion)
// The reason for this is that your current web app obviously has old schema code that needs
// to be updated. Another window got a newer version of the app and needs to upgrade DB but
// your window is blocking it unless we close it here.
});
db.on("blocked", function (ev) {
if (!ev.newVersion || ev.newVersion < ev.oldVersion) console.warn('Dexie.delete(\'' + db.name + '\') was blocked');else console.warn('Upgrade \'' + db.name + '\' blocked by other connection holding version ' + ev.oldVersion / 10);
});
}
//
//
//
// ------------------------- Versioning Framework---------------------------
//
//
//
this.version = function (versionNumber) {
/// <param name="versionNumber" type="Number"></param>
/// <returns type="Version"></returns>
if (idbdb || isBeingOpened) throw new exceptions.Schema("Cannot add version when database is open");
this.verno = Math.max(this.verno, versionNumber);
var versionInstance = versions.filter(function (v) {
return v._cfg.version === versionNumber;
})[0];
if (versionInstance) return versionInstance;
versionInstance = new Version(versionNumber);
versions.push(versionInstance);
versions.sort(lowerVersionFirst);
return versionInstance;
};
function Version(versionNumber) {
this._cfg = {
version: versionNumber,
storesSource: null,
dbschema: {},
tables: {},
contentUpgrade: null
};
this.stores({}); // Derive earlier schemas by default.
}
extend(Version.prototype, {
stores: function (stores) {
/// <summary>
/// Defines the schema for a particular version
/// </summary>
/// <param name="stores" type="Object">
/// Example: <br/>
/// {users: "id++,first,last,&username,*email", <br/>
/// passwords: "id++,&username"}<br/>
/// <br/>
/// Syntax: {Table: "[primaryKey][++],[&][*]index1,[&][*]index2,..."}<br/><br/>
/// Special characters:<br/>
/// "&" means unique key, <br/>
/// "*" means value is multiEntry, <br/>
/// "++" means auto-increment and only applicable for primary key <br/>
/// </param>
this._cfg.storesSource = this._cfg.storesSource ? extend(this._cfg.storesSource, stores) : stores;
// Derive stores from earlier versions if they are not explicitely specified as null or a new syntax.
var storesSpec = {};
versions.forEach(function (version) {
// 'versions' is always sorted by lowest version first.
extend(storesSpec, version._cfg.storesSource);
});
var dbschema = this._cfg.dbschema = {};
this._parseStoresSpec(storesSpec, dbschema);
// Update the latest schema to this version
// Update API
globalSchema = db._dbSchema = dbschema;
removeTablesApi([allTables, db, Transaction.prototype]);
setApiOnPlace([allTables, db, Transaction.prototype, this._cfg.tables], keys(dbschema), READWRITE, dbschema);
dbStoreNames = keys(dbschema);
return this;
},
upgrade: function (upgradeFunction) {
/// <param name="upgradeFunction" optional="true">Function that performs upgrading actions.</param>
var self = this;
fakeAutoComplete(function () {
upgradeFunction(db._createTransaction(READWRITE, keys(self._cfg.dbschema), self._cfg.dbschema)); // BUGBUG: No code completion for prev version's tables wont appear.
});
this._cfg.contentUpgrade = upgradeFunction;
return this;
},
_parseStoresSpec: function (stores, outSchema) {
keys(stores).forEach(function (tableName) {
if (stores[tableName] !== null) {
var instanceTemplate = {};
var indexes = parseIndexSyntax(stores[tableName]);
var primKey = indexes.shift();
if (primKey.multi) throw new exceptions.Schema("Primary key cannot be multi-valued");
if (primKey.keyPath) setByKeyPath(instanceTemplate, primKey.keyPath, primKey.auto ? 0 : primKey.keyPath);
indexes.forEach(function (idx) {
if (idx.auto) throw new exceptions.Schema("Only primary key can be marked as autoIncrement (++)");
if (!idx.keyPath) throw new exceptions.Schema("Index must have a name and cannot be an empty string");
setByKeyPath(instanceTemplate, idx.keyPath, idx.compound ? idx.keyPath.map(function () {
return "";
}) : "");
});
outSchema[tableName] = new TableSchema(tableName, primKey, indexes, instanceTemplate);
}
});
}
});
function runUpgraders(oldVersion, idbtrans, reject) {
var trans = db._createTransaction(READWRITE, dbStoreNames, globalSchema);
trans.create(idbtrans);
trans._completion.catch(reject);
var rejectTransaction = trans._reject.bind(trans);
newScope(function () {
PSD.trans = trans;
if (oldVersion === 0) {
// Create tables:
keys(globalSchema).forEach(function (tableName) {
createTable(idbtrans, tableName, globalSchema[tableName].primKey, globalSchema[tableName].indexes);
});
Promise.follow(function () {
return db.on.populate.fire(trans);
}).catch(rejectTransaction);
} else updateTablesAndIndexes(oldVersion, trans, idbtrans).catch(rejectTransaction);
});
}
function updateTablesAndIndexes(oldVersion, trans, idbtrans) {
// Upgrade version to version, step-by-step from oldest to newest version.
// Each transaction object will contain the table set that was current in that version (but also not-yet-deleted tables from its previous version)
var queue = [];
var oldVersionStruct = versions.filter(function (version) {
return version._cfg.version === oldVersion;
})[0];
if (!oldVersionStruct) throw new exceptions.Upgrade("Dexie specification of currently installed DB version is missing");
globalSchema = db._dbSchema = oldVersionStruct._cfg.dbschema;
var anyContentUpgraderHasRun = false;
var versToRun = versions.filter(function (v) {
return v._cfg.version > oldVersion;
});
versToRun.forEach(function (version) {
/// <param name="version" type="Version"></param>
queue.push(function () {
var oldSchema = globalSchema;
var newSchema = version._cfg.dbschema;
adjustToExistingIndexNames(oldSchema, idbtrans);
adjustToExistingIndexNames(newSchema, idbtrans);
globalSchema = db._dbSchema = newSchema;
var diff = getSchemaDiff(oldSchema, newSchema);
// Add tables
diff.add.forEach(function (tuple) {
createTable(idbtrans, tuple[0], tuple[1].primKey, tuple[1].indexes);
});
// Change tables
diff.change.forEach(function (change) {
if (change.recreate) {
throw new exceptions.Upgrade("Not yet support for changing primary key");
} else {
var store = idbtrans.objectStore(change.name);
// Add indexes
change.add.forEach(function (idx) {
addIndex(store, idx);
});
// Update indexes
change.change.forEach(function (idx) {
store.deleteIndex(idx.name);
addIndex(store, idx);
});
// Delete indexes
change.del.forEach(function (idxName) {
store.deleteIndex(idxName);
});
}
});
if (version._cfg.contentUpgrade) {
anyContentUpgraderHasRun = true;
return Promise.follow(function () {
version._cfg.contentUpgrade(trans);
});
}
});
queue.push(function (idbtrans) {
if (anyContentUpgraderHasRun && !hasIEDeleteObjectStoreBug) {
// Dont delete old tables if ieBug is present and a content upgrader has run. Let tables be left in DB so far. This needs to be taken care of.
var newSchema = version._cfg.dbschema;
// Delete old tables
deleteRemovedTables(newSchema, idbtrans);
}
});
});
// Now, create a queue execution engine
function runQueue() {
return queue.length ? Promise.resolve(queue.shift()(trans.idbtrans)).then(runQueue) : Promise.resolve();
}
return runQueue().then(function () {
createMissingTables(globalSchema, idbtrans); // At last, make sure to create any missing tables. (Needed by addons that add stores to DB without specifying version)
});
}
function getSchemaDiff(oldSchema, newSchema) {
var diff = {
del: [], // Array of table names
add: [], // Array of [tableName, newDefinition]
change: [] // Array of {name: tableName, recreate: newDefinition, del: delIndexNames, add: newIndexDefs, change: changedIndexDefs}
};
for (var table in oldSchema) {
if (!newSchema[table]) diff.del.push(table);
}
for (table in newSchema) {
var oldDef = oldSchema[table],
newDef = newSchema[table];
if (!oldDef) {
diff.add.push([table, newDef]);
} else {
var change = {
name: table,
def: newDef,
recreate: false,
del: [],
add: [],
change: []
};
if (oldDef.primKey.src !== newDef.primKey.src) {
// Primary key has changed. Remove and re-add table.
change.recreate = true;
diff.change.push(change);
} else {
// Same primary key. Just find out what differs:
var oldIndexes = oldDef.idxByName;
var newIndexes = newDef.idxByName;
for (var idxName in oldIndexes) {
if (!newIndexes[idxName]) change.del.push(idxName);
}
for (idxName in newIndexes) {
var oldIdx = oldIndexes[idxName],
newIdx = newIndexes[idxName];
if (!oldIdx) change.add.push(newIdx);else if (oldIdx.src !== newIdx.src) change.change.push(newIdx);
}
if (change.del.length > 0 || change.add.length > 0 || change.change.length > 0) {
diff.change.push(change);
}
}
}
}
return diff;
}
function createTable(idbtrans, tableName, primKey, indexes) {
/// <param name="idbtrans" type="IDBTransaction"></param>
var store = idbtrans.db.createObjectStore(tableName, primKey.keyPath ? { keyPath: primKey.keyPath, autoIncrement: primKey.auto } : { autoIncrement: primKey.auto });
indexes.forEach(function (idx) {
addIndex(store, idx);
});
return store;
}
function createMissingTables(newSchema, idbtrans) {
keys(newSchema).forEach(function (tableName) {
if (!idbtrans.db.objectStoreNames.contains(tableName)) {
createTable(idbtrans, tableName, newSchema[tableName].primKey, newSchema[tableName].indexes);
}
});
}
function deleteRemovedTables(newSchema, idbtrans) {
for (var i = 0; i < idbtrans.db.objectStoreNames.length; ++i) {
var storeName = idbtrans.db.objectStoreNames[i];
if (newSchema[storeName] == null) {
idbtrans.db.deleteObjectStore(storeName);
}
}
}
function addIndex(store, idx) {
store.createIndex(idx.name, idx.keyPath, { unique: idx.unique, multiEntry: idx.multi });
}
function dbUncaught(err) {
return db.on.error.fire(err);
}
//
//
// Dexie Protected API
//
//
this._allTables = allTables;
this._tableFactory = function createTable(mode, tableSchema) {
/// <param name="tableSchema" type="TableSchema"></param>
if (mode === READONLY) return new Table(tableSchema.name, tableSchema, Collection);else return new WriteableTable(tableSchema.name, tableSchema);
};
this._createTransaction = function (mode, storeNames, dbschema, parentTransaction) {
return new Transaction(mode, storeNames, dbschema, parentTransaction);
};
/* Generate a temporary transaction when db operations are done outside a transactino scope.
*/
function tempTransaction(mode, storeNames, fn) {
// Last argument is "writeLocked". But this doesnt apply to oneshot direct db operations, so we ignore it.
if (!openComplete && !PSD.letThrough) {
if (!isBeingOpened) {
if (!autoOpen) return rejection(new exceptions.DatabaseClosed(), dbUncaught);
db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.
}
return dbReadyPromise.then(function () {
return tempTransaction(mode, storeNames, fn);
});
} else {
var trans = db._createTransaction(mode, storeNames, globalSchema);
return trans._promise(mode, function (resolve, reject) {
newScope(function () {
// OPTIMIZATION POSSIBLE? newScope() not needed because it's already done in _promise.
PSD.trans = trans;
fn(resolve, reject, trans);
});
}).then(function (result) {
// Instead of resolving value directly, wait with resolving it until transaction has completed.
// Otherwise the data would not be in the DB if requesting it in the then() operation.
// Specifically, to ensure that the following expression will work:
//
// db.friends.put({name: "Arne"}).then(function () {
// db.friends.where("name").equals("Arne").count(function(count) {
// assert (count === 1);
// });
// });
//
return trans._completion.then(function () {
return result;
});
}); /*.catch(err => { // Don't do this as of now. If would affect bulk- and modify methods in a way that could be more intuitive. But wait! Maybe change in next major.
trans._reject(err);
return rejection(err);
});*/
}
}
this._whenReady = function (fn) {
return new Promise(fake || openComplete || PSD.letThrough ? fn : function (resolve, reject) {
if (!isBeingOpened) {
if (!autoOpen) {
reject(new exceptions.DatabaseClosed());
return;
}
db.open().catch(nop); // Open in background. If if fails, it will be catched by the final promise anyway.
}
dbReadyPromise.then(function () {
fn(resolve, reject);
});
}).uncaught(dbUncaught);
};
//
//
//
//
// Dexie API
//
//
//
this.verno = 0;
this.open = function () {
if (isBeingOpened || idbdb) return dbReadyPromise.then(function () {
return dbOpenError ? rejection(dbOpenError, dbUncaught) : db;
});
debug && (openCanceller._stackHolder = getErrorWithStack()); // Let stacks point to when open() was called rather than where new Dexie() was called.
isBeingOpened = true;
dbOpenError = null;
openComplete = false;
// Function pointers to call when the core opening process completes.
var resolveDbReady = dbReadyResolve,
// upgradeTransaction to abort on failure.
upgradeTransaction = null;
return Promise.race([openCanceller, new Promise(function (resolve, reject) {
doFakeAutoComplete(function () {
return resolve();
});
// Make sure caller has specified at least one version
if (versions.length > 0) autoSchema = false;
// Multiply db.verno with 10 will be needed to workaround upgrading bug in IE:
// IE fails when deleting objectStore after reading from it.
// A future version of Dexie.js will stopover an intermediate version to workaround this.
// At that point, we want to be backward compatible. Could have been multiplied with 2, but by using 10, it is easier to map the number to the real version number.
// If no API, throw!
if (!indexedDB) throw new exceptions.MissingAPI("indexedDB API not found. If using IE10+, make sure to run your code on a server URL " + "(not locally). If using old Safari versions, make sure to include indexedDB polyfill.");
var req = autoSchema ? indexedDB.open(dbName) : indexedDB.open(dbName, Math.round(db.verno * 10));
if (!req) throw new exceptions.MissingAPI("IndexedDB API not available"); // May happen in Safari private mode, see https://github.com/dfahlander/Dexie.js/issues/134
req.onerror = wrap(eventRejectHandler(reject));
req.onblocked = wrap(fireOnBlocked);
req.onupgradeneeded = wrap(function (e) {
upgradeTransaction = req.transaction;
if (autoSchema && !db._allowEmptyDB) {
// Unless an addon has specified db._allowEmptyDB, lets make the call fail.
// Caller did not specify a version or schema. Doing that is only acceptable for opening alread existing databases.
// If onupgradeneeded is called it means database did not exist. Reject the open() promise and make sure that we
// do not create a new database by accident here.
req.onerror = preventDefault; // Prohibit onabort error from firing before we're done!
upgradeTransaction.abort(); // Abort transaction (would hope that this would make DB disappear but it doesnt.)
// Close database and delete it.
req.result.close();
var delreq = indexedDB.deleteDatabase(dbName); // The upgrade transaction is atomic, and javascript is single threaded - meaning that there is no risk that we delete someone elses database here!
delreq.onsuccess = delreq.onerror = wrap(function () {
reject(new exceptions.NoSuchDatabase('Database ' + dbName + ' doesnt exist'));
});
} else {
upgradeTransaction.onerror = wrap(eventRejectHandler(reject));
var oldVer = e.oldVersion > Math.pow(2, 62) ? 0 : e.oldVersion; // Safari 8 fix.
runUpgraders(oldVer / 10, upgradeTransaction, reject, req);
}
}, reject);
req.onsuccess = wrap(function () {
// Core opening procedure complete. Now let's just record some stuff.
upgradeTransaction = null;
idbdb = req.result;
connections.push(db); // Used for emulating versionchange event on IE/Edge/Safari.
if (autoSchema) readGlobalSchema();else if (idbdb.objectStoreNames.length > 0) {
try {
adjustToExistingIndexNames(globalSchema, idbdb.transaction(safariMultiStoreFix(idbdb.objectStoreNames), READONLY));
} catch (e) {
// Safari may bail out if > 1 store names. However, this shouldnt be a showstopper. Issue #120.
}
}
idbdb.onversionchange = wrap(function (ev) {
db._vcFired = true; // detect implementations that not support versionchange (IE/Edge/Safari)
db.on("versionchange").fire(ev);
});
if (!hasNativeGetDatabaseNames) {
// Update localStorage with list of database names
globalDatabaseList(function (databaseNames) {
if (databaseNames.indexOf(dbName) === -1) return databaseNames.push(dbName);
});
}
resolve();
}, reject);
})]).then(function () {
// Before finally resolving the dbReadyPromise and this promise,
// call and await all on('ready') subscribers:
// Dexie.vip() makes subscribers able to use the database while being opened.
// This is a must since these subscribers take part of the opening procedure.
return Dexie.vip(db.on.ready.fire);
}).then(function () {
// Resolve the db.open() with the db instance.
isBeingOpened = false;
return db;
}).catch(function (err) {
try {
// Did we fail within onupgradeneeded? Make sure to abort the upgrade transaction so it doesnt commit.
upgradeTransaction && upgradeTransaction.abort();
} catch (e) {}
isBeingOpened = false; // Set before calling db.close() so that it doesnt reject openCanceller again (leads to unhandled rejection event).
db.close(); // Closes and resets idbdb, removes connections, resets dbReadyPromise and openCanceller so that a later db.open() is fresh.
// A call to db.close() may have made on-ready subscribers fail. Use dbOpenError if set, since err could be a follow-up error on that.
dbOpenError = err; // Record the error. It will be used to reject further promises of db operations.
return rejection(dbOpenError, dbUncaught); // dbUncaught will make sure any error that happened in any operation before will now bubble to db.on.error() thanks to the special handling in Promise.uncaught().
}).finally(function () {
openComplete = true;
resolveDbReady(); // dbReadyPromise is resolved no matter if open() rejects or resolved. It's just to wake up waiters.
});
};
this.close = function () {
var idx = connections.indexOf(db);
if (idx >= 0) connections.splice(idx, 1);
if (idbdb) {
try {
idbdb.close();
} catch (e) {}
idbdb = null;
}
autoOpen = false;
dbOpenError = new exceptions.DatabaseClosed();
if (isBeingOpened) cancelOpen(dbOpenError);
// Reset dbReadyPromise promise:
dbReadyPromise = new Promise(function (resolve) {
dbReadyResolve = resolve;
});
openCanceller = new Promise(function (_, reject) {
cancelOpen = reject;
});
};
this.delete = function () {
var hasArguments = arguments.length > 0;
return new Promise(function (resolve, reject) {
if (hasArguments) throw new exceptions.InvalidArgument("Arguments not allowed in db.delete()");
if (isBeingOpened) {
dbReadyPromise.then(doDelete);
} else {
doDelete();
}
function doDelete() {
db.close();
var req = indexedDB.deleteDatabase(dbName);
req.onsuccess = wrap(function () {
if (!hasNativeGetDatabaseNames) {
globalDatabaseList(function (databaseNames) {
var pos = databaseNames.indexOf(dbName);
if (pos >= 0) return databaseNames.splice(pos, 1);
});
}
resolve();
});
req.onerror = wrap(eventRejectHandler(reject));
req.onblocked = fireOnBlocked;
}
}).uncaught(dbUncaught);
};
this.backendDB = function () {
return idbdb;
};
this.isOpen = function () {
return idbdb !== null;
};
this.hasFailed = function () {
return dbOpenError !== null;
};
this.dynamicallyOpened = function () {
return autoSchema;
};
//
// Properties
//
this.name = dbName;
// db.tables - an array of all Table instances.
setProp(this, "tables", {
get: function () {
/// <returns type="Array" elementType="WriteableTable" />
return keys(allTables).map(function (name) {
return allTables[name];
});
}
});
//
// Events
//
this.on = Events(this, "error", "populate", "blocked", "versionchange", { ready: [promisableChain, nop] });
this.on.ready.subscribe = override(this.on.ready.subscribe, function (subscribe) {
return function (subscriber, bSticky) {
Dexie.vip(function () {
subscribe(subscriber);
if (!bSticky) subscribe(function unsubscribe() {
db.on.ready.unsubscribe(subscriber);
db.on.ready.unsubscribe(unsubscribe);
});
});
};
});
fakeAutoComplete(function () {
db.on("populate").fire(db._createTransaction(READWRITE, dbStoreNames, globalSchema));
db.on("error").fire(new Error());
});
this.transaction = function (mode, tableInstances, scopeFunc) {
/// <summary>
///
/// </summary>
/// <param name="mode" type="String">"r" for readonly, or "rw" for readwrite</param>
/// <param name="tableInstances">Table instance, Array of Table instances, String or String Array of object stores to include in the transaction</param>
/// <param name="scopeFunc" type="Function">Function to execute with transaction</param>
// Let table arguments be all arguments between mode and last argument.
var i = arguments.length;
if (i < 2) throw new exceptions.InvalidArgument("Too few arguments");
// Prevent optimzation killer (https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments)
// and clone arguments except the first one into local var 'args'.
var args = new Array(i - 1);
while (--i) {
args[i - 1] = arguments[i];
} // Let scopeFunc be the last argument and pop it so that args now only contain the table arguments.
scopeFunc = args.pop();
var tables = flatten(args); // Support using array as middle argument, or a mix of arrays and non-arrays.
var parentTransaction = PSD.trans;
// Check if parent transactions is bound to this db instance, and if caller wants to reuse it
if (!parentTransaction || parentTransaction.db !== db || mode.indexOf('!') !== -1) parentTransaction = null;
var onlyIfCompatible = mode.indexOf('?') !== -1;
mode = mode.replace('!', '').replace('?', ''); // Ok. Will change arguments[0] as well but we wont touch arguments henceforth.
try {
//
// Get storeNames from arguments. Either through given table instances, or through given table names.
//
var storeNames = tables.map(function (table) {
var storeName = table instanceof Table ? table.name : table;
if (typeof storeName !== 'string') throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");
return storeName;
});
//
// Resolve mode. Allow shortcuts "r" and "rw".
//
if (mode == "r" || mode == READONLY) mode = READONLY;else if (mode == "rw" || mode == READWRITE) mode = READWRITE;else throw new exceptions.InvalidArgument("Invalid transaction mode: " + mode);
if (parentTransaction) {
// Basic checks
if (parentTransaction.mode === READONLY && mode === READWRITE) {
if (onlyIfCompatible) {
// Spawn new transaction instead.
parentTransaction = null;
} else throw new exceptions.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");
}
if (parentTransaction) {
storeNames.forEach(function (storeName) {
if (!hasOwn(parentTransaction.tables, storeName)) {
if (onlyIfCompatible) {
// Spawn new transaction instead.
parentTransaction = null;
} else throw new exceptions.SubTransaction("Table " + storeName + " not included in parent transaction.");
}
});
}
}
} catch (e) {
return parentTransaction ? parentTransaction._promise(null, function (_, reject) {
reject(e);
}) : rejection(e, dbUncaught);
}
// If this is a sub-transaction, lock the parent and then launch the sub-transaction.
return parentTransaction ? parentTransaction._promise(mode, enterTransactionScope, "lock") : db._whenReady(enterTransactionScope);
function enterTransactionScope(resolve) {
var parentPSD = PSD;
resolve(Promise.resolve().then(function () {
return newScope(function () {
// Keep a pointer to last non-transactional PSD to use if someone calls Dexie.ignoreTransaction().
PSD.transless = PSD.transless || parentPSD;
// Our transaction.
//return new Promise((resolve, reject) => {
var trans = db._createTransaction(mode, storeNames, globalSchema, parentTransaction);
// Let the transaction instance be part of a Promise-specific data (PSD) value.
PSD.trans = trans;
if (parentTransaction) {
// Emulate transaction commit awareness for inner transaction (must 'commit' when the inner transaction has no more operations ongoing)
trans.idbtrans = parentTransaction.idbtrans;
} else {
trans.create(); // Create the backend transaction so that complete() or error() will trigger even if no operation is made upon it.
}
// Provide arguments to the scope function (for backward compatibility)
var tableArgs = storeNames.map(function (name) {
return trans.tables[name];
});
tableArgs.push(trans);
var returnValue;
return Promise.follow(function () {
// Finally, call the scope function with our table and transaction arguments.
returnValue = scopeFunc.apply(trans, tableArgs); // NOTE: returnValue is used in trans.on.complete() not as a returnValue to this func.
if (returnValue) {
if (typeof returnValue.next === 'function' && typeof returnValue.throw === 'function') {
// scopeFunc returned an iterator with throw-support. Handle yield as await.
returnValue = awaitIterator(returnValue);
} else if (typeof returnValue.then === 'function' && !hasOwn(returnValue, '_PSD')) {
throw new exceptions.IncompatiblePromise("Incompatible Promise returned from transaction scope (read more at http://tinyurl.com/znyqjqc). Transaction scope: " + scopeFunc.toString());
}
}
}).uncaught(dbUncaught).then(function () {
if (parentTransaction) trans._resolve(); // sub transactions don't react to idbtrans.oncomplete. We must trigger a acompletion.
return trans._completion; // Even if WE believe everything is fine. Await IDBTransaction's oncomplete or onerror as well.
}).then(function () {
return returnValue;
}).catch(function (e) {
//reject(e);
trans._reject(e); // Yes, above then-handler were maybe not called because of an unhandled rejection in scopeFunc!
return rejection(e);
});
//});
});
}));
}
};
this.table = function (tableName) {
/// <returns type="WriteableTable"></returns>
if (fake && autoSchema) return new WriteableTable(tableName);
if (!hasOwn(allTables, tableName)) {
throw new exceptions.InvalidTable('Table ' + tableName + ' does not exist');
}
return allTables[tableName];
};
//
//
//
// Table Class
//
//
//
function Table(name, tableSchema, collClass) {
/// <param name="name" type="String"></param>
this.name = name;
this.schema = tableSchema;
this.hook = allTables[name] ? allTables[name].hook : Events(null, {
"creating": [hookCreatingChain, nop],
"reading": [pureFunctionChain, mirror],
"updating": [hookUpdatingChain, nop],
"deleting": [hookDeletingChain, nop]
});
this._collClass = collClass || Collection;
}
props(Table.prototype, {
//
// Table Protected Methods
//
_trans: function getTransaction(mode, fn, writeLocked) {
var trans = PSD.trans;
return trans && trans.db === db ? trans._promise(mode, fn, writeLocked) : tempTransaction(mode, [this.name], fn);
},
_idbstore: function getIDBObjectStore(mode, fn, writeLocked) {
if (fake) return new Promise(fn); // Simplify the work for Intellisense/Code completion.
var trans = PSD.trans,
tableName = this.name;
function supplyIdbStore(resolve, reject, trans) {
fn(resolve, reject, trans.idbtrans.objectStore(tableName), trans);
}
return trans && trans.db === db ? trans._promise(mode, supplyIdbStore, writeLocked) : tempTransaction(mode, [this.name], supplyIdbStore);
},
//
// Table Public Methods
//
get: function (key, cb) {
var self = this;
return this._idbstore(READONLY, function (resolve, reject, idbstore) {
fake && resolve(self.schema.instanceTemplate);
var req = idbstore.get(key);
req.onerror = eventRejectHandler(reject);
req.onsuccess = function () {
resolve(self.hook.reading.fire(req.result));
};
}).then(cb);
},
where: function (indexName) {
return new WhereClause(this, indexName);
},
count: function (cb) {
return this.toCollection().count(cb);
},
offset: function (offset) {
return this.toCollection().offset(offset);
},
limit: function (numRows) {
return this.toCollection().limit(numRows);
},
reverse: function () {
return this.toCollection().reverse();
},
filter: function (filterFunction) {
return this.toCollection().and(filterFunction);
},
each: function (fn) {
return this.toCollection().each(fn);
},
toArray: function (cb) {
return this.toCollection().toArray(cb);
},
orderBy: function (index) {
return new this._collClass(new WhereClause(this, index));
},
toCollection: function () {
return new this._collClass(new WhereClause(this));
},
mapToClass: function (constructor, structure) {
/// <summary>
/// Map table to a javascript constructor function. Objects returned from the database will be instances of this class, making
/// it possible to the instanceOf operator as well as extending the class using constructor.prototype.method = function(){...}.
/// </summary>
/// <param name="constructor">Constructor function representing the class.</param>
/// <param name="structure" optional="true">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], password}</param>
this.schema.mappedClass = constructor;
var instanceTemplate = Object.create(constructor.prototype);
if (structure) {
// structure and instanceTemplate is for IDE code competion only while constructor.prototype is for actual inheritance.
applyStructure(instanceTemplate, structure);
}
this.schema.instanceTemplate = instanceTemplate;
// Now, subscribe to the when("reading") event to make all objects that come out from this table inherit from given class
// no matter which method to use for reading (Table.get() or Table.where(...)... )
var readHook = function (obj) {
if (!obj) return obj; // No valid object. (Value is null). Return as is.
// Create a new object that derives from constructor:
var res = Object.create(constructor.prototype);
// Clone members:
for (var m in obj) {
if (hasOwn(obj, m)) res[m] = obj[m];
}return res;
};
if (this.schema.readHook) {
this.hook.reading.unsubscribe(this.schema.readHook);
}
this.schema.readHook = readHook;
this.hook("reading", readHook);
return constructor;
},
defineClass: function (structure) {
/// <summary>
/// Define all members of the class that represents the table. This will help code completion of when objects are read from the database
/// as well as making it possible to extend the prototype of the returned constructor function.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
return this.mapToClass(Dexie.defineClass(structure), structure);
}
});
//
//
//
// WriteableTable Class (extends Table)
//
//
//
function WriteableTable(name, tableSchema, collClass) {
Table.call(this, name, tableSchema, collClass || WriteableCollection);
}
function BulkErrorHandlerCatchAll(errorList, done, supportHooks) {
return (supportHooks ? hookedEventRejectHandler : eventRejectHandler)(function (e) {
errorList.push(e);
done && done();
});
}
function bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook) {
// If hasDeleteHook, keysOrTuples must be an array of tuples: [[key1, value2],[key2,value2],...],
// else keysOrTuples must be just an array of keys: [key1, key2, ...].
return new Promise(function (resolve, reject) {
var len = keysOrTuples.length,
lastItem = len - 1;
if (len === 0) return resolve();
if (!hasDeleteHook) {
for (var i = 0; i < len; ++i) {
var req = idbstore.delete(keysOrTuples[i]);
req.onerror = wrap(eventRejectHandler(reject));
if (i === lastItem) req.onsuccess = wrap(function () {
return resolve();
});
}
} else {
var hookCtx,
errorHandler = hookedEventRejectHandler(reject),
successHandler = hookedEventSuccessHandler(null);
tryCatch(function () {
for (var i = 0; i < len; ++i) {
hookCtx = { onsuccess: null, onerror: null };
var tuple = keysOrTuples[i];
deletingHook.call(hookCtx, tuple[0], tuple[1], trans);
var req = idbstore.delete(tuple[0]);
req._hookCtx = hookCtx;
req.onerror = errorHandler;
if (i === lastItem) req.onsuccess = hookedEventSuccessHandler(resolve);else req.onsuccess = successHandler;
}
}, function (err) {
hookCtx.onerror && hookCtx.onerror(err);
throw err;
});
}
}).uncaught(dbUncaught);
}
derive(WriteableTable).from(Table).extend({
bulkDelete: function (keys) {
if (this.hook.deleting.fire === nop) {
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
resolve(bulkDelete(idbstore, trans, keys, false, nop));
});
} else {
return this.where(':id').anyOf(keys).delete().then(function () {}); // Resolve with undefined.
}
},
bulkPut: function (objects, keys) {
var _this = this;
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
if (!idbstore.keyPath && !_this.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument("bulkPut() with non-inbound keys requires keys array in second argument");
if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument("bulkPut(): keys argument invalid on tables with inbound keys");
if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
if (objects.length === 0) return resolve(); // Caller provided empty list.
var done = function (result) {
if (errorList.length === 0) resolve(result);else reject(new BulkError(_this.name + '.bulkPut(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));
};
var req,
errorList = [],
errorHandler,
numObjs = objects.length,
table = _this;
if (_this.hook.creating.fire === nop && _this.hook.updating.fire === nop) {
//
// Standard Bulk (no 'creating' or 'updating' hooks to care about)
//
errorHandler = BulkErrorHandlerCatchAll(errorList);
for (var i = 0, l = objects.length; i < l; ++i) {
req = keys ? idbstore.put(objects[i], keys[i]) : idbstore.put(objects[i]);
req.onerror = errorHandler;
}
// Only need to catch success or error on the last operation
// according to the IDB spec.
req.onerror = BulkErrorHandlerCatchAll(errorList, done);
req.onsuccess = eventSuccessHandler(done);
} else {
var effectiveKeys = keys || idbstore.keyPath && objects.map(function (o) {
return getByKeyPath(o, idbstore.keyPath);
});
// Generate map of {[key]: object}
var objectLookup = effectiveKeys && arrayToObject(effectiveKeys, function (key, i) {
return key != null && [key, objects[i]];
});
var promise = !effectiveKeys ?
// Auto-incremented key-less objects only without any keys argument.
table.bulkAdd(objects) :
// Keys provided. Either as inbound in provided objects, or as a keys argument.
// Begin with updating those that exists in DB:
table.where(':id').anyOf(effectiveKeys.filter(function (key) {
return key != null;
})).modify(function () {
this.value = objectLookup[this.primKey];
objectLookup[this.primKey] = null; // Mark as "don't add this"
}).catch(ModifyError, function (e) {
errorList = e.failures; // No need to concat here. These are the first errors added.
}).then(function () {
// Now, let's examine which items didnt exist so we can add them:
var objsToAdd = [],
keysToAdd = keys && [];
// Iterate backwards. Why? Because if same key was used twice, just add the last one.
for (var i = effectiveKeys.length - 1; i >= 0; --i) {
var key = effectiveKeys[i];
if (key == null || objectLookup[key]) {
objsToAdd.push(objects[i]);
keys && keysToAdd.push(key);
if (key != null) objectLookup[key] = null; // Mark as "dont add again"
}
}
// The items are in reverse order so reverse them before adding.
// Could be important in order to get auto-incremented keys the way the caller
// would expect. Could have used unshift instead of push()/reverse(),
// but: http://jsperf.com/unshift-vs-reverse
objsToAdd.reverse();
keys && keysToAdd.reverse();
return table.bulkAdd(objsToAdd, keysToAdd);
}).then(function (lastAddedKey) {
// Resolve with key of the last object in given arguments to bulkPut():
var lastEffectiveKey = effectiveKeys[effectiveKeys.length - 1]; // Key was provided.
return lastEffectiveKey != null ? lastEffectiveKey : lastAddedKey;
});
promise.then(done).catch(BulkError, function (e) {
// Concat failure from ModifyError and reject using our 'done' method.
errorList = errorList.concat(e.failures);
done();
}).catch(reject);
}
}, "locked"); // If called from transaction scope, lock transaction til all steps are done.
},
bulkAdd: function (objects, keys) {
var self = this,
creatingHook = this.hook.creating.fire;
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
if (!idbstore.keyPath && !self.schema.primKey.auto && !keys) throw new exceptions.InvalidArgument("bulkAdd() with non-inbound keys requires keys array in second argument");
if (idbstore.keyPath && keys) throw new exceptions.InvalidArgument("bulkAdd(): keys argument invalid on tables with inbound keys");
if (keys && keys.length !== objects.length) throw new exceptions.InvalidArgument("Arguments objects and keys must have the same length");
if (objects.length === 0) return resolve(); // Caller provided empty list.
function done(result) {
if (errorList.length === 0) resolve(result);else reject(new BulkError(self.name + '.bulkAdd(): ' + errorList.length + ' of ' + numObjs + ' operations failed', errorList));
}
var req,
errorList = [],
errorHandler,
successHandler,
numObjs = objects.length;
if (creatingHook !== nop) {
//
// There are subscribers to hook('creating')
// Must behave as documented.
//
var keyPath = idbstore.keyPath,
hookCtx;
errorHandler = BulkErrorHandlerCatchAll(errorList, null, true);
successHandler = hookedEventSuccessHandler(null);
tryCatch(function () {
for (var i = 0, l = objects.length; i < l; ++i) {
hookCtx = { onerror: null, onsuccess: null };
var key = keys && keys[i];
var obj = objects[i],
effectiveKey = keys ? key : keyPath ? getByKeyPath(obj, keyPath) : undefined,
keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans);
if (effectiveKey == null && keyToUse != null) {
if (keyPath) {
obj = deepClone(obj);
setByKeyPath(obj, keyPath, keyToUse);
} else {
key = keyToUse;
}
}
req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);
req._hookCtx = hookCtx;
if (i < l - 1) {
req.onerror = errorHandler;
if (hookCtx.onsuccess) req.onsuccess = successHandler;
}
}
}, function (err) {
hookCtx.onerror && hookCtx.onerror(err);
throw err;
});
req.onerror = BulkErrorHandlerCatchAll(errorList, done, true);
req.onsuccess = hookedEventSuccessHandler(done);
} else {
//
// Standard Bulk (no 'creating' hook to care about)
//
errorHandler = BulkErrorHandlerCatchAll(errorList);
for (var i = 0, l = objects.length; i < l; ++i) {
req = keys ? idbstore.add(objects[i], keys[i]) : idbstore.add(objects[i]);
req.onerror = errorHandler;
}
// Only need to catch success or error on the last operation
// according to the IDB spec.
req.onerror = BulkErrorHandlerCatchAll(errorList, done);
req.onsuccess = eventSuccessHandler(done);
}
});
},
add: function (obj, key) {
/// <summary>
/// Add an object to the database. In case an object with same primary key already exists, the object will not be added.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert</param>
/// <param name="key" optional="true">Primary key</param>
var creatingHook = this.hook.creating.fire;
return this._idbstore(READWRITE, function (resolve, reject, idbstore, trans) {
var hookCtx = { onsuccess: null, onerror: null };
if (creatingHook !== nop) {
var effectiveKey = key != null ? key : idbstore.keyPath ? getByKeyPath(obj, idbstore.keyPath) : undefined;
var keyToUse = creatingHook.call(hookCtx, effectiveKey, obj, trans); // Allow subscribers to when("creating") to generate the key.
if (effectiveKey == null && keyToUse != null) {
// Using "==" and "!=" to check for either null or undefined!
if (idbstore.keyPath) setByKeyPath(obj, idbstore.keyPath, keyToUse);else key = keyToUse;
}
}
try {
var req = key != null ? idbstore.add(obj, key) : idbstore.add(obj);
req._hookCtx = hookCtx;
req.onerror = hookedEventRejectHandler(reject);
req.onsuccess = hookedEventSuccessHandler(function (result) {
// TODO: Remove these two lines in next major release (2.0?)
// It's no good practice to have side effects on provided parameters
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, result);
resolve(result);
});
} catch (e) {
if (hookCtx.onerror) hookCtx.onerror(e);
throw e;
}
});
},
put: function (obj, key) {
/// <summary>
/// Add an object to the database but in case an object with same primary key alread exists, the existing one will get updated.
/// </summary>
/// <param name="obj" type="Object">A javascript object to insert or update</param>
/// <param name="key" optional="true">Primary key</param>
var self = this,
creatingHook = this.hook.creating.fire,
updatingHook = this.hook.updating.fire;
if (creatingHook !== nop || updatingHook !== nop) {
//
// People listens to when("creating") or when("updating") events!
// We must know whether the put operation results in an CREATE or UPDATE.
//
return this._trans(READWRITE, function (resolve, reject, trans) {
// Since key is optional, make sure we get it from obj if not provided
var effectiveKey = key !== undefined ? key : self.schema.primKey.keyPath && getByKeyPath(obj, self.schema.primKey.keyPath);
if (effectiveKey == null) {
// "== null" means checking for either null or undefined.
// No primary key. Must use add().
trans.tables[self.name].add(obj).then(resolve, reject);
} else {
// Primary key exist. Lock transaction and try modifying existing. If nothing modified, call add().
trans._lock(); // Needed because operation is splitted into modify() and add().
// clone obj before this async call. If caller modifies obj the line after put(), the IDB spec requires that it should not affect operation.
obj = deepClone(obj);
trans.tables[self.name].where(":id").equals(effectiveKey).modify(function () {
// Replace extisting value with our object
// CRUD event firing handled in WriteableCollection.modify()
this.value = obj;
}).then(function (count) {
if (count === 0) {
// Object's key was not found. Add the object instead.
// CRUD event firing will be done in add()
return trans.tables[self.name].add(obj, key); // Resolving with another Promise. Returned Promise will then resolve with the new key.
} else {
return effectiveKey; // Resolve with the provided key.
}
}).finally(function () {
trans._unlock();
}).then(resolve, reject);
}
});
} else {
// Use the standard IDB put() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = key !== undefined ? idbstore.put(obj, key) : idbstore.put(obj);
req.onerror = eventRejectHandler(reject);
req.onsuccess = function (ev) {
var keyPath = idbstore.keyPath;
if (keyPath) setByKeyPath(obj, keyPath, ev.target.result);
resolve(req.result);
};
});
}
},
'delete': function (key) {
/// <param name="key">Primary key of the object to delete</param>
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will know whether an object was actually deleted.
return this.where(":id").equals(key).delete();
} else {
// No one listens. Use standard IDB delete() method.
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.delete(key);
req.onerror = eventRejectHandler(reject);
req.onsuccess = function () {
resolve(req.result);
};
});
}
},
clear: function () {
if (this.hook.deleting.subscribers.length) {
// People listens to when("deleting") event. Must implement delete using WriteableCollection.delete() that will
// call the CRUD event. Only WriteableCollection.delete() will knows which objects that are actually deleted.
return this.toCollection().delete();
} else {
return this._idbstore(READWRITE, function (resolve, reject, idbstore) {
var req = idbstore.clear();
req.onerror = eventRejectHandler(reject);
req.onsuccess = function () {
resolve(req.result);
};
});
}
},
update: function (keyOrObject, modifications) {
if (typeof modifications !== 'object' || isArray(modifications)) throw new exceptions.InvalidArgument("Modifications must be an object.");
if (typeof keyOrObject === 'object' && !isArray(keyOrObject)) {
// object to modify. Also modify given object with the modifications:
keys(modifications).forEach(function (keyPath) {
setByKeyPath(keyOrObject, keyPath, modifications[keyPath]);
});
var key = getByKeyPath(keyOrObject, this.schema.primKey.keyPath);
if (key === undefined) return rejection(new exceptions.InvalidArgument("Given object does not contain its primary key"), dbUncaught);
return this.where(":id").equals(key).modify(modifications);
} else {
// key to modify
return this.where(":id").equals(keyOrObject).modify(modifications);
}
}
});
//
//
//
// Transaction Class
//
//
//
function Transaction(mode, storeNames, dbschema, parent) {
var _this2 = this;
/// <summary>
/// Transaction class. Represents a database transaction. All operations on db goes through a Transaction.
/// </summary>
/// <param name="mode" type="String">Any of "readwrite" or "readonly"</param>
/// <param name="storeNames" type="Array">Array of table names to operate on</param>
this.db = db;
this.mode = mode;
this.storeNames = storeNames;
this.idbtrans = null;
this.on = Events(this, "complete", "error", "abort");
this.parent = parent || null;
this.active = true;
this._tables = null;
this._reculock = 0;
this._blockedFuncs = [];
this._psd = null;
this._dbschema = dbschema;
this._resolve = null;
this._reject = null;
this._completion = new Promise(function (resolve, reject) {
_this2._resolve = resolve;
_this2._reject = reject;
}).uncaught(dbUncaught);
this._completion.then(function () {
_this2.on.complete.fire();
}, function (e) {
_this2.on.error.fire(e);
_this2.parent ? _this2.parent._reject(e) : _this2.active && _this2.idbtrans && _this2.idbtrans.abort();
_this2.active = false;
return rejection(e); // Indicate we actually DO NOT catch this error.
});
}
props(Transaction.prototype, {
//
// Transaction Protected Methods (not required by API users, but needed internally and eventually by dexie extensions)
//
_lock: function () {
assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.
// Temporary set all requests into a pending queue if they are called before database is ready.
++this._reculock; // Recursive read/write lock pattern using PSD (Promise Specific Data) instead of TLS (Thread Local Storage)
if (this._reculock === 1 && !PSD.global) PSD.lockOwnerFor = this;
return this;
},
_unlock: function () {
assert(!PSD.global); // Locking and unlocking reuires to be within a PSD scope.
if (--this._reculock === 0) {
if (!PSD.global) PSD.lockOwnerFor = null;
while (this._blockedFuncs.length > 0 && !this._locked()) {
var fn = this._blockedFuncs.shift();
try {
fn();
} catch (e) {}
}
}
return this;
},
_locked: function () {
// Checks if any write-lock is applied on this transaction.
// To simplify the Dexie API for extension implementations, we support recursive locks.
// This is accomplished by using "Promise Specific Data" (PSD).
// PSD data is bound to a Promise and any child Promise emitted through then() or resolve( new Promise() ).
// PSD is local to code executing on top of the call stacks of any of any code executed by Promise():
// * callback given to the Promise() constructor (function (resolve, reject){...})
// * callbacks given to then()/catch()/finally() methods (function (value){...})
// If creating a new independant Promise instance from within a Promise call stack, the new Promise will derive the PSD from the call stack of the parent Promise.
// Derivation is done so that the inner PSD __proto__ points to the outer PSD.
// PSD.lockOwnerFor will point to current transaction object if the currently executing PSD scope owns the lock.
return this._reculock && PSD.lockOwnerFor !== this;
},
create: function (idbtrans) {
var _this3 = this;
assert(!this.idbtrans);
if (!idbtrans && !idbdb) {
switch (dbOpenError && dbOpenError.name) {
case "DatabaseClosedError":
// Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()
throw new exceptions.DatabaseClosed(dbOpenError);
case "MissingAPIError":
// Errors where it is no difference whether it was caused by the user operation or an earlier call to db.open()
throw new exceptions.MissingAPI(dbOpenError.message, dbOpenError);
default:
// Make it clear that the user operation was not what caused the error - the error had occurred earlier on db.open()!
throw new exceptions.OpenFailed(dbOpenError);
}
}
if (!this.active) throw new exceptions.TransactionInactive();
assert(this._completion._state === null);
idbtrans = this.idbtrans = idbtrans || idbdb.transaction(safariMultiStoreFix(this.storeNames), this.mode);
idbtrans.onerror = wrap(function (ev) {
preventDefault(ev); // Prohibit default bubbling to window.error
_this3._reject(idbtrans.error);
});
idbtrans.onabort = wrap(function (ev) {
preventDefault(ev);
_this3.active && _this3._reject(new exceptions.Abort());
_this3.active = false;
_this3.on("abort").fire(ev);
});
idbtrans.oncomplete = wrap(function () {
_this3.active = false;
_this3._resolve();
});
return this;
},
_promise: function (mode, fn, bWriteLock) {
var self = this;
return newScope(function () {
var p;
// Read lock always
if (!self._locked()) {
p = self.active ? new Promise(function (resolve, reject) {
if (mode === READWRITE && self.mode !== READWRITE) throw new exceptions.ReadOnly("Transaction is readonly");
if (!self.idbtrans && mode) self.create();
if (bWriteLock) self._lock(); // Write lock if write operation is requested
fn(resolve, reject, self);
}) : rejection(new exceptions.TransactionInactive());
if (self.active && bWriteLock) p.finally(function () {
self._unlock();
});
} else {
// Transaction is write-locked. Wait for mutex.
p = new Promise(function (resolve, reject) {
self._blockedFuncs.push(function () {
self._promise(mode, fn, bWriteLock).then(resolve, reject);
});
});
}
p._lib = true;
return p.uncaught(dbUncaught);
});
},
//
// Transaction Public Properties and Methods
//
abort: function () {
this.active && this._reject(new exceptions.Abort());
this.active = false;
},
// Deprecate:
tables: {
get: function () {
if (this._tables) return this._tables;
return this._tables = arrayToObject(this.storeNames, function (name) {
return [name, allTables[name]];
});
}
},
// Deprecate:
complete: function (cb) {
return this.on("complete", cb);
},
// Deprecate:
error: function (cb) {
return this.on("error", cb);
},
// Deprecate
table: function (name) {
if (this.storeNames.indexOf(name) === -1) throw new exceptions.InvalidTable("Table " + name + " not in transaction");
return allTables[name];
}
});
//
//
//
// WhereClause
//
//
//
function WhereClause(table, index, orCollection) {
/// <param name="table" type="Table"></param>
/// <param name="index" type="String" optional="true"></param>
/// <param name="orCollection" type="Collection" optional="true"></param>
this._ctx = {
table: table,
index: index === ":id" ? null : index,
collClass: table._collClass,
or: orCollection
};
}
props(WhereClause.prototype, function () {
// WhereClause private methods
function fail(collectionOrWhereClause, err, T) {
var collection = collectionOrWhereClause instanceof WhereClause ? new collectionOrWhereClause._ctx.collClass(collectionOrWhereClause) : collectionOrWhereClause;
collection._ctx.error = T ? new T(err) : new TypeError(err);
return collection;
}
function emptyCollection(whereClause) {
return new whereClause._ctx.collClass(whereClause, function () {
return IDBKeyRange.only("");
}).limit(0);
}
function upperFactory(dir) {
return dir === "next" ? function (s) {
return s.toUpperCase();
} : function (s) {
return s.toLowerCase();
};
}
function lowerFactory(dir) {
return dir === "next" ? function (s) {
return s.toLowerCase();
} : function (s) {
return s.toUpperCase();
};
}
function nextCasing(key, lowerKey, upperNeedle, lowerNeedle, cmp, dir) {
var length = Math.min(key.length, lowerNeedle.length);
var llp = -1;
for (var i = 0; i < length; ++i) {
var lwrKeyChar = lowerKey[i];
if (lwrKeyChar !== lowerNeedle[i]) {
if (cmp(key[i], upperNeedle[i]) < 0) return key.substr(0, i) + upperNeedle[i] + upperNeedle.substr(i + 1);
if (cmp(key[i], lowerNeedle[i]) < 0) return key.substr(0, i) + lowerNeedle[i] + upperNeedle.substr(i + 1);
if (llp >= 0) return key.substr(0, llp) + lowerKey[llp] + upperNeedle.substr(llp + 1);
return null;
}
if (cmp(key[i], lwrKeyChar) < 0) llp = i;
}
if (length < lowerNeedle.length && dir === "next") return key + upperNeedle.substr(key.length);
if (length < key.length && dir === "prev") return key.substr(0, upperNeedle.length);
return llp < 0 ? null : key.substr(0, llp) + lowerNeedle[llp] + upperNeedle.substr(llp + 1);
}
function addIgnoreCaseAlgorithm(whereClause, match, needles, suffix) {
/// <param name="needles" type="Array" elementType="String"></param>
var upper,
lower,
compare,
upperNeedles,
lowerNeedles,
direction,
nextKeySuffix,
needlesLen = needles.length;
if (!needles.every(function (s) {
return typeof s === 'string';
})) {
return fail(whereClause, STRING_EXPECTED);
}
function initDirection(dir) {
upper = upperFactory(dir);
lower = lowerFactory(dir);
compare = dir === "next" ? simpleCompare : simpleCompareReverse;
var needleBounds = needles.map(function (needle) {
return { lower: lower(needle), upper: upper(needle) };
}).sort(function (a, b) {
return compare(a.lower, b.lower);
});
upperNeedles = needleBounds.map(function (nb) {
return nb.upper;
});
lowerNeedles = needleBounds.map(function (nb) {
return nb.lower;
});
direction = dir;
nextKeySuffix = dir === "next" ? "" : suffix;
}
initDirection("next");
var c = new whereClause._ctx.collClass(whereClause, function () {
return IDBKeyRange.bound(upperNeedles[0], lowerNeedles[needlesLen - 1] + suffix);
});
c._ondirectionchange = function (direction) {
// This event onlys occur before filter is called the first time.
initDirection(direction);
};
var firstPossibleNeedle = 0;
c._addAlgorithm(function (cursor, advance, resolve) {
/// <param name="cursor" type="IDBCursor"></param>
/// <param name="advance" type="Function"></param>
/// <param name="resolve" type="Function"></param>
var key = cursor.key;
if (typeof key !== 'string') return false;
var lowerKey = lower(key);
if (match(lowerKey, lowerNeedles, firstPossibleNeedle)) {
return true;
} else {
var lowestPossibleCasing = null;
for (var i = firstPossibleNeedle; i < needlesLen; ++i) {
var casing = nextCasing(key, lowerKey, upperNeedles[i], lowerNeedles[i], compare, direction);
if (casing === null && lowestPossibleCasing === null) firstPossibleNeedle = i + 1;else if (lowestPossibleCasing === null || compare(lowestPossibleCasing, casing) > 0) {
lowestPossibleCasing = casing;
}
}
if (lowestPossibleCasing !== null) {
advance(function () {
cursor.continue(lowestPossibleCasing + nextKeySuffix);
});
} else {
advance(resolve);
}
return false;
}
});
return c;
}
//
// WhereClause public methods
//
return {
between: function (lower, upper, includeLower, includeUpper) {
/// <summary>
/// Filter out records whose where-field lays between given lower and upper values. Applies to Strings, Numbers and Dates.
/// </summary>
/// <param name="lower"></param>
/// <param name="upper"></param>
/// <param name="includeLower" optional="true">Whether items that equals lower should be included. Default true.</param>
/// <param name="includeUpper" optional="true">Whether items that equals upper should be included. Default false.</param>
/// <returns type="Collection"></returns>
includeLower = includeLower !== false; // Default to true
includeUpper = includeUpper === true; // Default to false
try {
if (cmp(lower, upper) > 0 || cmp(lower, upper) === 0 && (includeLower || includeUpper) && !(includeLower && includeUpper)) return emptyCollection(this); // Workaround for idiotic W3C Specification that DataError must be thrown if lower > upper. The natural result would be to return an empty collection.
return new this._ctx.collClass(this, function () {
return IDBKeyRange.bound(lower, upper, !includeLower, !includeUpper);
});
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
},
equals: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.only(value);
});
},
above: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.lowerBound(value, true);
});
},
aboveOrEqual: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.lowerBound(value);
});
},
below: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.upperBound(value, true);
});
},
belowOrEqual: function (value) {
return new this._ctx.collClass(this, function () {
return IDBKeyRange.upperBound(value);
});
},
startsWith: function (str) {
/// <param name="str" type="String"></param>
if (typeof str !== 'string') return fail(this, STRING_EXPECTED);
return this.between(str, str + maxString, true, true);
},
startsWithIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
if (str === "") return this.startsWith(str);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return x.indexOf(a[0]) === 0;
}, [str], maxString);
},
equalsIgnoreCase: function (str) {
/// <param name="str" type="String"></param>
return addIgnoreCaseAlgorithm(this, function (x, a) {
return x === a[0];
}, [str], "");
},
anyOfIgnoreCase: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return emptyCollection(this);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return a.indexOf(x) !== -1;
}, set, "");
},
startsWithAnyOfIgnoreCase: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return emptyCollection(this);
return addIgnoreCaseAlgorithm(this, function (x, a) {
return a.some(function (n) {
return x.indexOf(n) === 0;
});
}, set, maxString);
},
anyOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
var compare = ascending;
try {
set.sort(compare);
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
if (set.length === 0) return emptyCollection(this);
var c = new this._ctx.collClass(this, function () {
return IDBKeyRange.bound(set[0], set[set.length - 1]);
});
c._ondirectionchange = function (direction) {
compare = direction === "next" ? ascending : descending;
set.sort(compare);
};
var i = 0;
c._addAlgorithm(function (cursor, advance, resolve) {
var key = cursor.key;
while (compare(key, set[i]) > 0) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === set.length) {
// There is no next. Stop searching.
advance(resolve);
return false;
}
}
if (compare(key, set[i]) === 0) {
// The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.
return true;
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
advance(function () {
cursor.continue(set[i]);
});
return false;
}
});
return c;
},
notEqual: function (value) {
return this.inAnyRange([[-Infinity, value], [value, maxKey]], { includeLowers: false, includeUppers: false });
},
noneOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (set.length === 0) return new this._ctx.collClass(this); // Return entire collection.
try {
set.sort(ascending);
} catch (e) {
return fail(this, INVALID_KEY_ARGUMENT);
}
// Transform ["a","b","c"] to a set of ranges for between/above/below: [[-Infinity,"a"], ["a","b"], ["b","c"], ["c",maxKey]]
var ranges = set.reduce(function (res, val) {
return res ? res.concat([[res[res.length - 1][1], val]]) : [[-Infinity, val]];
}, null);
ranges.push([set[set.length - 1], maxKey]);
return this.inAnyRange(ranges, { includeLowers: false, includeUppers: false });
},
/** Filter out values withing given set of ranges.
* Example, give children and elders a rebate of 50%:
*
* db.friends.where('age').inAnyRange([[0,18],[65,Infinity]]).modify({Rebate: 1/2});
*
* @param {(string|number|Date|Array)[][]} ranges
* @param {{includeLowers: boolean, includeUppers: boolean}} options
*/
inAnyRange: function (ranges, options) {
var ctx = this._ctx;
if (ranges.length === 0) return emptyCollection(this);
if (!ranges.every(function (range) {
return range[0] !== undefined && range[1] !== undefined && ascending(range[0], range[1]) <= 0;
})) {
return fail(this, "First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower", exceptions.InvalidArgument);
}
var includeLowers = !options || options.includeLowers !== false; // Default to true
var includeUppers = options && options.includeUppers === true; // Default to false
function addRange(ranges, newRange) {
for (var i = 0, l = ranges.length; i < l; ++i) {
var range = ranges[i];
if (cmp(newRange[0], range[1]) < 0 && cmp(newRange[1], range[0]) > 0) {
range[0] = min(range[0], newRange[0]);
range[1] = max(range[1], newRange[1]);
break;
}
}
if (i === l) ranges.push(newRange);
return ranges;
}
var sortDirection = ascending;
function rangeSorter(a, b) {
return sortDirection(a[0], b[0]);
}
// Join overlapping ranges
var set;
try {
set = ranges.reduce(addRange, []);
set.sort(rangeSorter);
} catch (ex) {
return fail(this, INVALID_KEY_ARGUMENT);
}
var i = 0;
var keyIsBeyondCurrentEntry = includeUppers ? function (key) {
return ascending(key, set[i][1]) > 0;
} : function (key) {
return ascending(key, set[i][1]) >= 0;
};
var keyIsBeforeCurrentEntry = includeLowers ? function (key) {
return descending(key, set[i][0]) > 0;
} : function (key) {
return descending(key, set[i][0]) >= 0;
};
function keyWithinCurrentRange(key) {
return !keyIsBeyondCurrentEntry(key) && !keyIsBeforeCurrentEntry(key);
}
var checkKey = keyIsBeyondCurrentEntry;
var c = new ctx.collClass(this, function () {
return IDBKeyRange.bound(set[0][0], set[set.length - 1][1], !includeLowers, !includeUppers);
});
c._ondirectionchange = function (direction) {
if (direction === "next") {
checkKey = keyIsBeyondCurrentEntry;
sortDirection = ascending;
} else {
checkKey = keyIsBeforeCurrentEntry;
sortDirection = descending;
}
set.sort(rangeSorter);
};
c._addAlgorithm(function (cursor, advance, resolve) {
var key = cursor.key;
while (checkKey(key)) {
// The cursor has passed beyond this key. Check next.
++i;
if (i === set.length) {
// There is no next. Stop searching.
advance(resolve);
return false;
}
}
if (keyWithinCurrentRange(key)) {
// The current cursor value should be included and we should continue a single step in case next item has the same key or possibly our next key in set.
return true;
} else if (cmp(key, set[i][1]) === 0 || cmp(key, set[i][0]) === 0) {
// includeUpper or includeLower is false so keyWithinCurrentRange() returns false even though we are at range border.
// Continue to next key but don't include this one.
return false;
} else {
// cursor.key not yet at set[i]. Forward cursor to the next key to hunt for.
advance(function () {
if (sortDirection === ascending) cursor.continue(set[i][0]);else cursor.continue(set[i][1]);
});
return false;
}
});
return c;
},
startsWithAnyOf: function () {
var set = getArrayOf.apply(NO_CHAR_ARRAY, arguments);
if (!set.every(function (s) {
return typeof s === 'string';
})) {
return fail(this, "startsWithAnyOf() only works with strings");
}
if (set.length === 0) return emptyCollection(this);
return this.inAnyRange(set.map(function (str) {
return [str, str + maxString];
}));
}
};
});
//
//
//
// Collection Class
//
//
//
function Collection(whereClause, keyRangeGenerator) {
/// <summary>
///
/// </summary>
/// <param name="whereClause" type="WhereClause">Where clause instance</param>
/// <param name="keyRangeGenerator" value="function(){ return IDBKeyRange.bound(0,1);}" optional="true"></param>
var keyRange = null,
error = null;
if (keyRangeGenerator) try {
keyRange = keyRangeGenerator();
} catch (ex) {
error = ex;
}
var whereCtx = whereClause._ctx,
table = whereCtx.table;
this._ctx = {
table: table,
index: whereCtx.index,
isPrimKey: !whereCtx.index || table.schema.primKey.keyPath && whereCtx.index === table.schema.primKey.name,
range: keyRange,
keysOnly: false,
dir: "next",
unique: "",
algorithm: null,
filter: null,
replayFilter: null,
justLimit: true, // True if a replayFilter is just a filter that performs a "limit" operation (or none at all)
isMatch: null,
offset: 0,
limit: Infinity,
error: error, // If set, any promise must be rejected with this error
or: whereCtx.or,
valueMapper: table.hook.reading.fire
};
}
function isPlainKeyRange(ctx, ignoreLimitFilter) {
return !(ctx.filter || ctx.algorithm || ctx.or) && (ignoreLimitFilter ? ctx.justLimit : !ctx.replayFilter);
}
props(Collection.prototype, function () {
//
// Collection Private Functions
//
function addFilter(ctx, fn) {
ctx.filter = combine(ctx.filter, fn);
}
function addReplayFilter(ctx, factory, isLimitFilter) {
var curr = ctx.replayFilter;
ctx.replayFilter = curr ? function () {
return combine(curr(), factory());
} : factory;
ctx.justLimit = isLimitFilter && !curr;
}
function addMatchFilter(ctx, fn) {
ctx.isMatch = combine(ctx.isMatch, fn);
}
/** @param ctx {
* isPrimKey: boolean,
* table: Table,
* index: string
* }
* @param store IDBObjectStore
**/
function getIndexOrStore(ctx, store) {
if (ctx.isPrimKey) return store;
var indexSpec = ctx.table.schema.idxByName[ctx.index];
if (!indexSpec) throw new exceptions.Schema("KeyPath " + ctx.index + " on object store " + store.name + " is not indexed");
return store.index(indexSpec.name);
}
/** @param ctx {
* isPrimKey: boolean,
* table: Table,
* index: string,
* keysOnly: boolean,
* range?: IDBKeyRange,
* dir: "next" | "prev"
* }
*/
function openCursor(ctx, store) {
var idxOrStore = getIndexOrStore(ctx, store);
return ctx.keysOnly && 'openKeyCursor' in idxOrStore ? idxOrStore.openKeyCursor(ctx.range || null, ctx.dir + ctx.unique) : idxOrStore.openCursor(ctx.range || null, ctx.dir + ctx.unique);
}
function iter(ctx, fn, resolve, reject, idbstore) {
var filter = ctx.replayFilter ? combine(ctx.filter, ctx.replayFilter()) : ctx.filter;
if (!ctx.or) {
iterate(openCursor(ctx, idbstore), combine(ctx.algorithm, filter), fn, resolve, reject, !ctx.keysOnly && ctx.valueMapper);
} else (function () {
var set = {};
var resolved = 0;
function resolveboth() {
if (++resolved === 2) resolve(); // Seems like we just support or btwn max 2 expressions, but there are no limit because we do recursion.
}
function union(item, cursor, advance) {
if (!filter || filter(cursor, advance, resolveboth, reject)) {
var key = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
if (!hasOwn(set, key)) {
set[key] = true;
fn(item, cursor, advance);
}
}
}
ctx.or._iterate(union, resolveboth, reject, idbstore);
iterate(openCursor(ctx, idbstore), ctx.algorithm, union, resolveboth, reject, !ctx.keysOnly && ctx.valueMapper);
})();
}
function getInstanceTemplate(ctx) {
return ctx.table.schema.instanceTemplate;
}
return {
//
// Collection Protected Functions
//
_read: function (fn, cb) {
var ctx = this._ctx;
if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {
reject(ctx.error);
});else return ctx.table._idbstore(READONLY, fn).then(cb);
},
_write: function (fn) {
var ctx = this._ctx;
if (ctx.error) return ctx.table._trans(null, function rejector(resolve, reject) {
reject(ctx.error);
});else return ctx.table._idbstore(READWRITE, fn, "locked"); // When doing write operations on collections, always lock the operation so that upcoming operations gets queued.
},
_addAlgorithm: function (fn) {
var ctx = this._ctx;
ctx.algorithm = combine(ctx.algorithm, fn);
},
_iterate: function (fn, resolve, reject, idbstore) {
return iter(this._ctx, fn, resolve, reject, idbstore);
},
clone: function (props) {
var rv = Object.create(this.constructor.prototype),
ctx = Object.create(this._ctx);
if (props) extend(ctx, props);
rv._ctx = ctx;
return rv;
},
raw: function () {
this._ctx.valueMapper = null;
return this;
},
//
// Collection Public methods
//
each: function (fn) {
var ctx = this._ctx;
if (fake) {
var item = getInstanceTemplate(ctx),
primKeyPath = ctx.table.schema.primKey.keyPath,
key = getByKeyPath(item, ctx.index ? ctx.table.schema.idxByName[ctx.index].keyPath : primKeyPath),
primaryKey = getByKeyPath(item, primKeyPath);
fn(item, { key: key, primaryKey: primaryKey });
}
return this._read(function (resolve, reject, idbstore) {
iter(ctx, fn, resolve, reject, idbstore);
});
},
count: function (cb) {
if (fake) return Promise.resolve(0).then(cb);
var ctx = this._ctx;
if (isPlainKeyRange(ctx, true)) {
// This is a plain key range. We can use the count() method if the index.
return this._read(function (resolve, reject, idbstore) {
var idx = getIndexOrStore(ctx, idbstore);
var req = ctx.range ? idx.count(ctx.range) : idx.count();
req.onerror = eventRejectHandler(reject);
req.onsuccess = function (e) {
resolve(Math.min(e.target.result, ctx.limit));
};
}, cb);
} else {
// Algorithms, filters or expressions are applied. Need to count manually.
var count = 0;
return this._read(function (resolve, reject, idbstore) {
iter(ctx, function () {
++count;return false;
}, function () {
resolve(count);
}, reject, idbstore);
}, cb);
}
},
sortBy: function (keyPath, cb) {
/// <param name="keyPath" type="String"></param>
var parts = keyPath.split('.').reverse(),
lastPart = parts[0],
lastIndex = parts.length - 1;
function getval(obj, i) {
if (i) return getval(obj[parts[i]], i - 1);
return obj[lastPart];
}
var order = this._ctx.dir === "next" ? 1 : -1;
function sorter(a, b) {
var aVal = getval(a, lastIndex),
bVal = getval(b, lastIndex);
return aVal < bVal ? -order : aVal > bVal ? order : 0;
}
return this.toArray(function (a) {
return a.sort(sorter);
}).then(cb);
},
toArray: function (cb) {
var ctx = this._ctx;
return this._read(function (resolve, reject, idbstore) {
fake && resolve([getInstanceTemplate(ctx)]);
if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {
// Special optimation if we could use IDBObjectStore.getAll() or
// IDBKeyRange.getAll():
var readingHook = ctx.table.hook.reading.fire;
var idxOrStore = getIndexOrStore(ctx, idbstore);
var req = ctx.limit < Infinity ? idxOrStore.getAll(ctx.range, ctx.limit) : idxOrStore.getAll(ctx.range);
req.onerror = eventRejectHandler(reject);
req.onsuccess = readingHook === mirror ? eventSuccessHandler(resolve) : wrap(eventSuccessHandler(function (res) {
resolve(res.map(readingHook));
}));
} else {
// Getting array through a cursor.
var a = [];
iter(ctx, function (item) {
a.push(item);
}, function arrayComplete() {
resolve(a);
}, reject, idbstore);
}
}, cb);
},
offset: function (offset) {
var ctx = this._ctx;
if (offset <= 0) return this;
ctx.offset += offset; // For count()
if (isPlainKeyRange(ctx)) {
addReplayFilter(ctx, function () {
var offsetLeft = offset;
return function (cursor, advance) {
if (offsetLeft === 0) return true;
if (offsetLeft === 1) {
--offsetLeft;return false;
}
advance(function () {
cursor.advance(offsetLeft);
offsetLeft = 0;
});
return false;
};
});
} else {
addReplayFilter(ctx, function () {
var offsetLeft = offset;
return function () {
return --offsetLeft < 0;
};
});
}
return this;
},
limit: function (numRows) {
this._ctx.limit = Math.min(this._ctx.limit, numRows); // For count()
addReplayFilter(this._ctx, function () {
var rowsLeft = numRows;
return function (cursor, advance, resolve) {
if (--rowsLeft <= 0) advance(resolve); // Stop after this item has been included
return rowsLeft >= 0; // If numRows is already below 0, return false because then 0 was passed to numRows initially. Otherwise we wouldnt come here.
};
}, true);
return this;
},
until: function (filterFunction, bIncludeStopEntry) {
var ctx = this._ctx;
fake && filterFunction(getInstanceTemplate(ctx));
addFilter(this._ctx, function (cursor, advance, resolve) {
if (filterFunction(cursor.value)) {
advance(resolve);
return bIncludeStopEntry;
} else {
return true;
}
});
return this;
},
first: function (cb) {
return this.limit(1).toArray(function (a) {
return a[0];
}).then(cb);
},
last: function (cb) {
return this.reverse().first(cb);
},
filter: function (filterFunction) {
/// <param name="jsFunctionFilter" type="Function">function(val){return true/false}</param>
fake && filterFunction(getInstanceTemplate(this._ctx));
addFilter(this._ctx, function (cursor) {
return filterFunction(cursor.value);
});
// match filters not used in Dexie.js but can be used by 3rd part libraries to test a
// collection for a match without querying DB. Used by Dexie.Observable.
addMatchFilter(this._ctx, filterFunction);
return this;
},
and: function (filterFunction) {
return this.filter(filterFunction);
},
or: function (indexName) {
return new WhereClause(this._ctx.table, indexName, this);
},
reverse: function () {
this._ctx.dir = this._ctx.dir === "prev" ? "next" : "prev";
if (this._ondirectionchange) this._ondirectionchange(this._ctx.dir);
return this;
},
desc: function () {
return this.reverse();
},
eachKey: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
return this.each(function (val, cursor) {
cb(cursor.key, cursor);
});
},
eachUniqueKey: function (cb) {
this._ctx.unique = "unique";
return this.eachKey(cb);
},
eachPrimaryKey: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
return this.each(function (val, cursor) {
cb(cursor.primaryKey, cursor);
});
},
keys: function (cb) {
var ctx = this._ctx;
ctx.keysOnly = !ctx.isMatch;
var a = [];
return this.each(function (item, cursor) {
a.push(cursor.key);
}).then(function () {
return a;
}).then(cb);
},
primaryKeys: function (cb) {
var ctx = this._ctx;
if (hasGetAll && ctx.dir === 'next' && isPlainKeyRange(ctx, true) && ctx.limit > 0) {
// Special optimation if we could use IDBObjectStore.getAllKeys() or
// IDBKeyRange.getAllKeys():
return this._read(function (resolve, reject, idbstore) {
var idxOrStore = getIndexOrStore(ctx, idbstore);
var req = ctx.limit < Infinity ? idxOrStore.getAllKeys(ctx.range, ctx.limit) : idxOrStore.getAllKeys(ctx.range);
req.onerror = eventRejectHandler(reject);
req.onsuccess = eventSuccessHandler(resolve);
}).then(cb);
}
ctx.keysOnly = !ctx.isMatch;
var a = [];
return this.each(function (item, cursor) {
a.push(cursor.primaryKey);
}).then(function () {
return a;
}).then(cb);
},
uniqueKeys: function (cb) {
this._ctx.unique = "unique";
return this.keys(cb);
},
firstKey: function (cb) {
return this.limit(1).keys(function (a) {
return a[0];
}).then(cb);
},
lastKey: function (cb) {
return this.reverse().firstKey(cb);
},
distinct: function () {
var ctx = this._ctx,
idx = ctx.index && ctx.table.schema.idxByName[ctx.index];
if (!idx || !idx.multi) return this; // distinct() only makes differencies on multiEntry indexes.
var set = {};
addFilter(this._ctx, function (cursor) {
var strKey = cursor.primaryKey.toString(); // Converts any Date to String, String to String, Number to String and Array to comma-separated string
var found = hasOwn(set, strKey);
set[strKey] = true;
return !found;
});
return this;
}
};
});
//
//
// WriteableCollection Class
//
//
function WriteableCollection() {
Collection.apply(this, arguments);
}
derive(WriteableCollection).from(Collection).extend({
//
// WriteableCollection Public Methods
//
modify: function (changes) {
var self = this,
ctx = this._ctx,
hook = ctx.table.hook,
updatingHook = hook.updating.fire,
deletingHook = hook.deleting.fire;
fake && typeof changes === 'function' && changes.call({ value: ctx.table.schema.instanceTemplate }, ctx.table.schema.instanceTemplate);
return this._write(function (resolve, reject, idbstore, trans) {
var modifyer;
if (typeof changes === 'function') {
// Changes is a function that may update, add or delete propterties or even require a deletion the object itself (delete this.item)
if (updatingHook === nop && deletingHook === nop) {
// Noone cares about what is being changed. Just let the modifier function be the given argument as is.
modifyer = changes;
} else {
// People want to know exactly what is being modified or deleted.
// Let modifyer be a proxy function that finds out what changes the caller is actually doing
// and call the hooks accordingly!
modifyer = function (item) {
var origItem = deepClone(item); // Clone the item first so we can compare laters.
if (changes.call(this, item, this) === false) return false; // Call the real modifyer function (If it returns false explicitely, it means it dont want to modify anyting on this object)
if (!hasOwn(this, "value")) {
// The real modifyer function requests a deletion of the object. Inform the deletingHook that a deletion is taking place.
deletingHook.call(this, this.primKey, item, trans);
} else {
// No deletion. Check what was changed
var objectDiff = getObjectDiff(origItem, this.value);
var additionalChanges = updatingHook.call(this, objectDiff, this.primKey, origItem, trans);
if (additionalChanges) {
// Hook want to apply additional modifications. Make sure to fullfill the will of the hook.
item = this.value;
keys(additionalChanges).forEach(function (keyPath) {
setByKeyPath(item, keyPath, additionalChanges[keyPath]); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
});
}
}
};
}
} else if (updatingHook === nop) {
// changes is a set of {keyPath: value} and no one is listening to the updating hook.
var keyPaths = keys(changes);
var numKeys = keyPaths.length;
modifyer = function (item) {
var anythingModified = false;
for (var i = 0; i < numKeys; ++i) {
var keyPath = keyPaths[i],
val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, val); // Adding {keyPath: undefined} means that the keyPath should be deleted. Handled by setByKeyPath
anythingModified = true;
}
}
return anythingModified;
};
} else {
// changes is a set of {keyPath: value} and people are listening to the updating hook so we need to call it and
// allow it to add additional modifications to make.
var origChanges = changes;
changes = shallowClone(origChanges); // Let's work with a clone of the changes keyPath/value set so that we can restore it in case a hook extends it.
modifyer = function (item) {
var anythingModified = false;
var additionalChanges = updatingHook.call(this, changes, this.primKey, deepClone(item), trans);
if (additionalChanges) extend(changes, additionalChanges);
keys(changes).forEach(function (keyPath) {
var val = changes[keyPath];
if (getByKeyPath(item, keyPath) !== val) {
setByKeyPath(item, keyPath, val);
anythingModified = true;
}
});
if (additionalChanges) changes = shallowClone(origChanges); // Restore original changes for next iteration
return anythingModified;
};
}
var count = 0;
var successCount = 0;
var iterationComplete = false;
var failures = [];
var failKeys = [];
var currentKey = null;
function modifyItem(item, cursor) {
currentKey = cursor.primaryKey;
var thisContext = {
primKey: cursor.primaryKey,
value: item,
onsuccess: null,
onerror: null
};
function onerror(e) {
failures.push(e);
failKeys.push(thisContext.primKey);
checkFinished();
return true; // Catch these errors and let a final rejection decide whether or not to abort entire transaction
}
if (modifyer.call(thisContext, item, thisContext) !== false) {
// If a callback explicitely returns false, do not perform the update!
var bDelete = !hasOwn(thisContext, "value");
++count;
tryCatch(function () {
var req = bDelete ? cursor.delete() : cursor.update(thisContext.value);
req._hookCtx = thisContext;
req.onerror = hookedEventRejectHandler(onerror);
req.onsuccess = hookedEventSuccessHandler(function () {
++successCount;
checkFinished();
});
}, onerror);
} else if (thisContext.onsuccess) {
// Hook will expect either onerror or onsuccess to always be called!
thisContext.onsuccess(thisContext.value);
}
}
function doReject(e) {
if (e) {
failures.push(e);
failKeys.push(currentKey);
}
return reject(new ModifyError("Error modifying one or more objects", failures, successCount, failKeys));
}
function checkFinished() {
if (iterationComplete && successCount + failures.length === count) {
if (failures.length > 0) doReject();else resolve(successCount);
}
}
self.clone().raw()._iterate(modifyItem, function () {
iterationComplete = true;
checkFinished();
}, doReject, idbstore);
});
},
'delete': function () {
var _this4 = this;
var ctx = this._ctx,
range = ctx.range,
deletingHook = ctx.table.hook.deleting.fire,
hasDeleteHook = deletingHook !== nop;
if (!hasDeleteHook && isPlainKeyRange(ctx) && (ctx.isPrimKey && !hangsOnDeleteLargeKeyRange || !range)) // if no range, we'll use clear().
{
// May use IDBObjectStore.delete(IDBKeyRange) in this case (Issue #208)
// For chromium, this is the way most optimized version.
// For IE/Edge, this could hang the indexedDB engine and make operating system instable
// (https://gist.github.com/dfahlander/5a39328f029de18222cf2125d56c38f7)
return this._write(function (resolve, reject, idbstore) {
// Our API contract is to return a count of deleted items, so we have to count() before delete().
var onerror = eventRejectHandler(reject),
countReq = range ? idbstore.count(range) : idbstore.count();
countReq.onerror = onerror;
countReq.onsuccess = function () {
var count = countReq.result;
tryCatch(function () {
var delReq = range ? idbstore.delete(range) : idbstore.clear();
delReq.onerror = onerror;
delReq.onsuccess = function () {
return resolve(count);
};
}, function (err) {
return reject(err);
});
};
});
}
// Default version to use when collection is not a vanilla IDBKeyRange on the primary key.
// Divide into chunks to not starve RAM.
// If has delete hook, we will have to collect not just keys but also objects, so it will use
// more memory and need lower chunk size.
var CHUNKSIZE = hasDeleteHook ? 2000 : 10000;
return this._write(function (resolve, reject, idbstore, trans) {
var totalCount = 0;
// Clone collection and change its table and set a limit of CHUNKSIZE on the cloned Collection instance.
var collection = _this4.clone({
keysOnly: !ctx.isMatch && !hasDeleteHook }) // load just keys (unless filter() or and() or deleteHook has subscribers)
.distinct() // In case multiEntry is used, never delete same key twice because resulting count
// would become larger than actual delete count.
.limit(CHUNKSIZE).raw(); // Don't filter through reading-hooks (like mapped classes etc)
var keysOrTuples = [];
// We're gonna do things on as many chunks that are needed.
// Use recursion of nextChunk function:
var nextChunk = function () {
return collection.each(hasDeleteHook ? function (val, cursor) {
// Somebody subscribes to hook('deleting'). Collect all primary keys and their values,
// so that the hook can be called with its values in bulkDelete().
keysOrTuples.push([cursor.primaryKey, cursor.value]);
} : function (val, cursor) {
// No one subscribes to hook('deleting'). Collect only primary keys:
keysOrTuples.push(cursor.primaryKey);
}).then(function () {
// Chromium deletes faster when doing it in sort order.
hasDeleteHook ? keysOrTuples.sort(function (a, b) {
return ascending(a[0], b[0]);
}) : keysOrTuples.sort(ascending);
return bulkDelete(idbstore, trans, keysOrTuples, hasDeleteHook, deletingHook);
}).then(function () {
var count = keysOrTuples.length;
totalCount += count;
keysOrTuples = [];
return count < CHUNKSIZE ? totalCount : nextChunk();
});
};
resolve(nextChunk());
});
}
});
//
//
//
// ------------------------- Help functions ---------------------------
//
//
//
function lowerVersionFirst(a, b) {
return a._cfg.version - b._cfg.version;
}
function setApiOnPlace(objs, tableNames, mode, dbschema) {
tableNames.forEach(function (tableName) {
var tableInstance = db._tableFactory(mode, dbschema[tableName]);
objs.forEach(function (obj) {
tableName in obj || (obj[tableName] = tableInstance);
});
});
}
function removeTablesApi(objs) {
objs.forEach(function (obj) {
for (var key in obj) {
if (obj[key] instanceof Table) delete obj[key];
}
});
}
function iterate(req, filter, fn, resolve, reject, valueMapper) {
// Apply valueMapper (hook('reading') or mappped class)
var mappedFn = valueMapper ? function (x, c, a) {
return fn(valueMapper(x), c, a);
} : fn;
// Wrap fn with PSD and microtick stuff from Promise.
var wrappedFn = wrap(mappedFn, reject);
if (!req.onerror) req.onerror = eventRejectHandler(reject);
if (filter) {
req.onsuccess = trycatcher(function filter_record() {
var cursor = req.result;
if (cursor) {
var c = function () {
cursor.continue();
};
if (filter(cursor, function (advancer) {
c = advancer;
}, resolve, reject)) wrappedFn(cursor.value, cursor, function (advancer) {
c = advancer;
});
c();
} else {
resolve();
}
}, reject);
} else {
req.onsuccess = trycatcher(function filter_record() {
var cursor = req.result;
if (cursor) {
var c = function () {
cursor.continue();
};
wrappedFn(cursor.value, cursor, function (advancer) {
c = advancer;
});
c();
} else {
resolve();
}
}, reject);
}
}
function parseIndexSyntax(indexes) {
/// <param name="indexes" type="String"></param>
/// <returns type="Array" elementType="IndexSpec"></returns>
var rv = [];
indexes.split(',').forEach(function (index) {
index = index.trim();
var name = index.replace(/([&*]|\+\+)/g, ""); // Remove "&", "++" and "*"
// Let keyPath of "[a+b]" be ["a","b"]:
var keyPath = /^\[/.test(name) ? name.match(/^\[(.*)\]$/)[1].split('+') : name;
rv.push(new IndexSpec(name, keyPath || null, /\&/.test(index), /\*/.test(index), /\+\+/.test(index), isArray(keyPath), /\./.test(index)));
});
return rv;
}
function cmp(key1, key2) {
return indexedDB.cmp(key1, key2);
}
function min(a, b) {
return cmp(a, b) < 0 ? a : b;
}
function max(a, b) {
return cmp(a, b) > 0 ? a : b;
}
function ascending(a, b) {
return indexedDB.cmp(a, b);
}
function descending(a, b) {
return indexedDB.cmp(b, a);
}
function simpleCompare(a, b) {
return a < b ? -1 : a === b ? 0 : 1;
}
function simpleCompareReverse(a, b) {
return a > b ? -1 : a === b ? 0 : 1;
}
function combine(filter1, filter2) {
return filter1 ? filter2 ? function () {
return filter1.apply(this, arguments) && filter2.apply(this, arguments);
} : filter1 : filter2;
}
function readGlobalSchema() {
db.verno = idbdb.version / 10;
db._dbSchema = globalSchema = {};
dbStoreNames = slice(idbdb.objectStoreNames, 0);
if (dbStoreNames.length === 0) return; // Database contains no stores.
var trans = idbdb.transaction(safariMultiStoreFix(dbStoreNames), 'readonly');
dbStoreNames.forEach(function (storeName) {
var store = trans.objectStore(storeName),
keyPath = store.keyPath,
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var primKey = new IndexSpec(keyPath, keyPath || "", false, false, !!store.autoIncrement, keyPath && typeof keyPath !== 'string', dotted);
var indexes = [];
for (var j = 0; j < store.indexNames.length; ++j) {
var idbindex = store.index(store.indexNames[j]);
keyPath = idbindex.keyPath;
dotted = keyPath && typeof keyPath === 'string' && keyPath.indexOf('.') !== -1;
var index = new IndexSpec(idbindex.name, keyPath, !!idbindex.unique, !!idbindex.multiEntry, false, keyPath && typeof keyPath !== 'string', dotted);
indexes.push(index);
}
globalSchema[storeName] = new TableSchema(storeName, primKey, indexes, {});
});
setApiOnPlace([allTables, Transaction.prototype], keys(globalSchema), READWRITE, globalSchema);
}
function adjustToExistingIndexNames(schema, idbtrans) {
/// <summary>
/// Issue #30 Problem with existing db - adjust to existing index names when migrating from non-dexie db
/// </summary>
/// <param name="schema" type="Object">Map between name and TableSchema</param>
/// <param name="idbtrans" type="IDBTransaction"></param>
var storeNames = idbtrans.db.objectStoreNames;
for (var i = 0; i < storeNames.length; ++i) {
var storeName = storeNames[i];
var store = idbtrans.objectStore(storeName);
hasGetAll = 'getAll' in store;
for (var j = 0; j < store.indexNames.length; ++j) {
var indexName = store.indexNames[j];
var keyPath = store.index(indexName).keyPath;
var dexieName = typeof keyPath === 'string' ? keyPath : "[" + slice(keyPath).join('+') + "]";
if (schema[storeName]) {
var indexSpec = schema[storeName].idxByName[dexieName];
if (indexSpec) indexSpec.name = indexName;
}
}
}
}
function fireOnBlocked(ev) {
db.on("blocked").fire(ev);
// Workaround (not fully*) for missing "versionchange" event in IE,Edge and Safari:
connections.filter(function (c) {
return c.name === db.name && c !== db && !c._vcFired;
}).map(function (c) {
return c.on("versionchange").fire(ev);
});
}
extend(this, {
Collection: Collection,
Table: Table,
Transaction: Transaction,
Version: Version,
WhereClause: WhereClause,
WriteableCollection: WriteableCollection,
WriteableTable: WriteableTable
});
init();
addons.forEach(function (fn) {
fn(db);
});
}
var fakeAutoComplete = function () {}; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())
var fake = false; // Will never be changed. We just fake for the IDE that we change it (see doFakeAutoComplete())
function parseType(type) {
if (typeof type === 'function') {
return new type();
} else if (isArray(type)) {
return [parseType(type[0])];
} else if (type && typeof type === 'object') {
var rv = {};
applyStructure(rv, type);
return rv;
} else {
return type;
}
}
function applyStructure(obj, structure) {
keys(structure).forEach(function (member) {
var value = parseType(structure[member]);
obj[member] = value;
});
return obj;
}
function eventSuccessHandler(done) {
return function (ev) {
done(ev.target.result);
};
}
function hookedEventSuccessHandler(resolve) {
// wrap() is needed when calling hooks because the rare scenario of:
// * hook does a db operation that fails immediately (IDB throws exception)
// For calling db operations on correct transaction, wrap makes sure to set PSD correctly.
// wrap() will also execute in a virtual tick.
// * If not wrapped in a virtual tick, direct exception will launch a new physical tick.
// * If this was the last event in the bulk, the promise will resolve after a physical tick
// and the transaction will have committed already.
// If no hook, the virtual tick will be executed in the reject()/resolve of the final promise,
// because it is always marked with _lib = true when created using Transaction._promise().
return wrap(function (event) {
var req = event.target,
result = req.result,
ctx = req._hookCtx,
// Contains the hook error handler. Put here instead of closure to boost performance.
hookSuccessHandler = ctx && ctx.onsuccess;
hookSuccessHandler && hookSuccessHandler(result);
resolve && resolve(result);
}, resolve);
}
function eventRejectHandler(reject) {
return function (event) {
preventDefault(event);
reject(event.target.error);
return false;
};
}
function hookedEventRejectHandler(reject) {
return wrap(function (event) {
// See comment on hookedEventSuccessHandler() why wrap() is needed only when supporting hooks.
var req = event.target,
err = req.error,
ctx = req._hookCtx,
// Contains the hook error handler. Put here instead of closure to boost performance.
hookErrorHandler = ctx && ctx.onerror;
hookErrorHandler && hookErrorHandler(err);
preventDefault(event);
reject(err);
return false;
});
}
function preventDefault(event) {
if (event.stopPropagation) // IndexedDBShim doesnt support this on Safari 8 and below.
event.stopPropagation();
if (event.preventDefault) // IndexedDBShim doesnt support this on Safari 8 and below.
event.preventDefault();
}
function globalDatabaseList(cb) {
var val,
localStorage = Dexie.dependencies.localStorage;
if (!localStorage) return cb([]); // Envs without localStorage support
try {
val = JSON.parse(localStorage.getItem('Dexie.DatabaseNames') || "[]");
} catch (e) {
val = [];
}
if (cb(val)) {
localStorage.setItem('Dexie.DatabaseNames', JSON.stringify(val));
}
}
function awaitIterator(iterator) {
var callNext = function (result) {
return iterator.next(result);
},
doThrow = function (error) {
return iterator.throw(error);
},
onSuccess = step(callNext),
onError = step(doThrow);
function step(getNext) {
return function (val) {
var next = getNext(val),
value = next.value;
return next.done ? value : !value || typeof value.then !== 'function' ? isArray(value) ? Promise.all(value).then(onSuccess, onError) : onSuccess(value) : value.then(onSuccess, onError);
};
}
return step(callNext)();
}
//
// IndexSpec struct
//
function IndexSpec(name, keyPath, unique, multi, auto, compound, dotted) {
/// <param name="name" type="String"></param>
/// <param name="keyPath" type="String"></param>
/// <param name="unique" type="Boolean"></param>
/// <param name="multi" type="Boolean"></param>
/// <param name="auto" type="Boolean"></param>
/// <param name="compound" type="Boolean"></param>
/// <param name="dotted" type="Boolean"></param>
this.name = name;
this.keyPath = keyPath;
this.unique = unique;
this.multi = multi;
this.auto = auto;
this.compound = compound;
this.dotted = dotted;
var keyPathSrc = typeof keyPath === 'string' ? keyPath : keyPath && '[' + [].join.call(keyPath, '+') + ']';
this.src = (unique ? '&' : '') + (multi ? '*' : '') + (auto ? "++" : "") + keyPathSrc;
}
//
// TableSchema struct
//
function TableSchema(name, primKey, indexes, instanceTemplate) {
/// <param name="name" type="String"></param>
/// <param name="primKey" type="IndexSpec"></param>
/// <param name="indexes" type="Array" elementType="IndexSpec"></param>
/// <param name="instanceTemplate" type="Object"></param>
this.name = name;
this.primKey = primKey || new IndexSpec();
this.indexes = indexes || [new IndexSpec()];
this.instanceTemplate = instanceTemplate;
this.mappedClass = null;
this.idxByName = arrayToObject(indexes, function (index) {
return [index.name, index];
});
}
//
// Static delete() method.
//
Dexie.delete = function (databaseName) {
var db = new Dexie(databaseName),
promise = db.delete();
promise.onblocked = function (fn) {
db.on("blocked", fn);
return this;
};
return promise;
};
//
// Static exists() method.
//
Dexie.exists = function (name) {
return new Dexie(name).open().then(function (db) {
db.close();
return true;
}).catch(Dexie.NoSuchDatabaseError, function () {
return false;
});
};
//
// Static method for retrieving a list of all existing databases at current host.
//
Dexie.getDatabaseNames = function (cb) {
return new Promise(function (resolve, reject) {
var getDatabaseNames = getNativeGetDatabaseNamesFn(indexedDB);
if (getDatabaseNames) {
// In case getDatabaseNames() becomes standard, let's prepare to support it:
var req = getDatabaseNames();
req.onsuccess = function (event) {
resolve(slice(event.target.result, 0)); // Converst DOMStringList to Array<String>
};
req.onerror = eventRejectHandler(reject);
} else {
globalDatabaseList(function (val) {
resolve(val);
return false;
});
}
}).then(cb);
};
Dexie.defineClass = function (structure) {
/// <summary>
/// Create a javascript constructor based on given template for which properties to expect in the class.
/// Any property that is a constructor function will act as a type. So {name: String} will be equal to {name: new String()}.
/// </summary>
/// <param name="structure">Helps IDE code completion by knowing the members that objects contain and not just the indexes. Also
/// know what type each member has. Example: {name: String, emailAddresses: [String], properties: {shoeSize: Number}}</param>
// Default constructor able to copy given properties into this object.
function Class(properties) {
/// <param name="properties" type="Object" optional="true">Properties to initialize object with.
/// </param>
properties ? extend(this, properties) : fake && applyStructure(this, structure);
}
return Class;
};
Dexie.applyStructure = applyStructure;
Dexie.ignoreTransaction = function (scopeFunc) {
// In case caller is within a transaction but needs to create a separate transaction.
// Example of usage:
//
// Let's say we have a logger function in our app. Other application-logic should be unaware of the
// logger function and not need to include the 'logentries' table in all transaction it performs.
// The logging should always be done in a separate transaction and not be dependant on the current
// running transaction context. Then you could use Dexie.ignoreTransaction() to run code that starts a new transaction.
//
// Dexie.ignoreTransaction(function() {
// db.logentries.add(newLogEntry);
// });
//
// Unless using Dexie.ignoreTransaction(), the above example would try to reuse the current transaction
// in current Promise-scope.
//
// An alternative to Dexie.ignoreTransaction() would be setImmediate() or setTimeout(). The reason we still provide an
// API for this because
// 1) The intention of writing the statement could be unclear if using setImmediate() or setTimeout().
// 2) setTimeout() would wait unnescessary until firing. This is however not the case with setImmediate().
// 3) setImmediate() is not supported in the ES standard.
// 4) You might want to keep other PSD state that was set in a parent PSD, such as PSD.letThrough.
return PSD.trans ? usePSD(PSD.transless, scopeFunc) : // Use the closest parent that was non-transactional.
scopeFunc(); // No need to change scope because there is no ongoing transaction.
};
Dexie.vip = function (fn) {
// To be used by subscribers to the on('ready') event.
// This will let caller through to access DB even when it is blocked while the db.ready() subscribers are firing.
// This would have worked automatically if we were certain that the Provider was using Dexie.Promise for all asyncronic operations. The promise PSD
// from the provider.connect() call would then be derived all the way to when provider would call localDatabase.applyChanges(). But since
// the provider more likely is using non-promise async APIs or other thenable implementations, we cannot assume that.
// Note that this method is only useful for on('ready') subscribers that is returning a Promise from the event. If not using vip()
// the database could deadlock since it wont open until the returned Promise is resolved, and any non-VIPed operation started by
// the caller will not resolve until database is opened.
return newScope(function () {
PSD.letThrough = true; // Make sure we are let through if still blocking db due to onready is firing.
return fn();
});
};
Dexie.async = function (generatorFn) {
return function () {
try {
var rv = awaitIterator(generatorFn.apply(this, arguments));
if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);
return rv;
} catch (e) {
return rejection(e);
}
};
};
Dexie.spawn = function (generatorFn, args, thiz) {
try {
var rv = awaitIterator(generatorFn.apply(thiz, args || []));
if (!rv || typeof rv.then !== 'function') return Promise.resolve(rv);
return rv;
} catch (e) {
return rejection(e);
}
};
// Dexie.currentTransaction property. Only applicable for transactions entered using the new "transact()" method.
setProp(Dexie, "currentTransaction", {
get: function () {
/// <returns type="Transaction"></returns>
return PSD.trans || null;
}
});
function safariMultiStoreFix(storeNames) {
return storeNames.length === 1 ? storeNames[0] : storeNames;
}
// Export our Promise implementation since it can be handy as a standalone Promise implementation
Dexie.Promise = Promise;
// Dexie.debug proptery:
// Dexie.debug = false
// Dexie.debug = true
// Dexie.debug = "dexie" - don't hide dexie's stack frames.
setProp(Dexie, "debug", {
get: function () {
return debug;
},
set: function (value) {
setDebug(value, value === 'dexie' ? function () {
return true;
} : dexieStackFrameFilter);
}
});
Promise.rejectionMapper = mapError;
// Export our derive/extend/override methodology
Dexie.derive = derive;
Dexie.extend = extend;
Dexie.props = props;
Dexie.override = override;
// Export our Events() function - can be handy as a toolkit
Dexie.Events = Dexie.events = Events; // Backward compatible lowercase version.
// Utilities
Dexie.getByKeyPath = getByKeyPath;
Dexie.setByKeyPath = setByKeyPath;
Dexie.delByKeyPath = delByKeyPath;
Dexie.shallowClone = shallowClone;
Dexie.deepClone = deepClone;
Dexie.addons = [];
Dexie.fakeAutoComplete = fakeAutoComplete;
Dexie.asap = asap;
Dexie.maxKey = maxKey;
Dexie.connections = connections;
// Export Error classes
extend(Dexie, fullNameExceptions); // Dexie.XXXError = class XXXError {...};
Dexie.MultiModifyError = Dexie.ModifyError; // Backward compatibility 0.9.8
Dexie.errnames = errnames;
// Export other static classes
Dexie.IndexSpec = IndexSpec;
Dexie.TableSchema = TableSchema;
//
// Dependencies
//
// These will automatically work in browsers with indexedDB support, or where an indexedDB polyfill has been included.
//
// In node.js, however, these properties must be set "manually" before instansiating a new Dexie(). For node.js, you need to require indexeddb-js or similar and then set these deps.
//
var idbshim = _global.idbModules && _global.idbModules.shimIndexedDB ? _global.idbModules : {};
Dexie.dependencies = {
// Required:
indexedDB: idbshim.shimIndexedDB || _global.indexedDB || _global.mozIndexedDB || _global.webkitIndexedDB || _global.msIndexedDB,
IDBKeyRange: idbshim.IDBKeyRange || _global.IDBKeyRange || _global.webkitIDBKeyRange
};
tryCatch(function () {
// Optional dependencies
// localStorage
Dexie.dependencies.localStorage = (typeof chrome !== "undefined" && chrome !== null ? chrome.storage : void 0) != null ? null : _global.localStorage;
});
// API Version Number: Type Number, make sure to always set a version number that can be comparable correctly. Example: 0.9, 0.91, 0.92, 1.0, 1.01, 1.1, 1.2, 1.21, etc.
Dexie.semVer = "1.4.0-beta2";
Dexie.version = Dexie.semVer.split('.').map(function (n) {
return parseInt(n);
}).reduce(function (p, c, i) {
return p + c / Math.pow(10, i * 2);
});
function getNativeGetDatabaseNamesFn(indexedDB) {
var fn = indexedDB && (indexedDB.getDatabaseNames || indexedDB.webkitGetDatabaseNames);
return fn && fn.bind(indexedDB);
}
// Fool IDE to improve autocomplete. Tested with Visual Studio 2013 and 2015.
doFakeAutoComplete(function () {
Dexie.fakeAutoComplete = fakeAutoComplete = doFakeAutoComplete;
Dexie.fake = fake = true;
});
// https://github.com/dfahlander/Dexie.js/issues/186
// typescript compiler tsc in mode ts-->es5 & commonJS, will expect require() to return
// x.default. Workaround: Set Dexie.default = Dexie.
Dexie.default = Dexie;
return Dexie;
}));
//# sourceMappingURL=dexie.js.map
|
/**
* angular-permission-ng
* Extension module of angular-permission for access control within angular-route
* @version v3.1.0 - 2016-05-15
* @link https://github.com/Narzerus/angular-permission
* @author Rafael Vidaurre <narzerus@gmail.com> (http://www.rafaelvidaurre.com), Blazej Krysiak
* <blazej.krysiak@gmail.com>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (module) {
'use strict';
/**
* @namespace permission.ng
*/
run.$inject = ['$rootScope', '$location', 'TransitionProperties', 'TransitionEvents', 'Authorization', 'PermissionMap'];
function run($rootScope, $location, TransitionProperties, TransitionEvents, Authorization, PermissionMap) {
'ngInject';
/**
* State transition interceptor
*/
$rootScope.$on('$routeChangeStart', function (event, next, current) {
if (areSetRoutePermissions() && !TransitionEvents.areEventsDefaultPrevented()) {
setTransitionProperties();
TransitionEvents.broadcastPermissionStartEvent();
var permissionMap = new PermissionMap({
only: next.$$route.data.permissions.only,
except: next.$$route.data.permissions.except,
redirectTo: next.$$route.data.permissions.redirectTo
});
Authorization
.authorize(permissionMap)
.then(function () {
handleAuthorizedState();
})
.catch(function (rejectedPermission) {
event.preventDefault();
handleUnauthorizedState(rejectedPermission, permissionMap);
});
}
/**
* Checks if route has set permissions restrictions
* @method
* @private
*
* @returns {boolean}
*/
function areSetRoutePermissions() {
return angular.isDefined(next.$$route.data) && angular.isDefined(next.$$route.data.permissions);
}
/**
* Updates values of `TransitionProperties` holder object
* @method
* @private
*/
function setTransitionProperties() {
TransitionProperties.next = next;
TransitionProperties.current = current;
}
/**
* Handles redirection for authorized access
* @method
* @private
*/
function handleAuthorizedState() {
TransitionEvents.broadcastPermissionAcceptedEvent();
}
/**
* Handles redirection for unauthorized access
* @method
* @private
*
* @param rejectedPermission {String} Rejected access right
* @param permissionMap {permission.PermissionMap} State permission map
*/
function handleUnauthorizedState(rejectedPermission, permissionMap) {
TransitionEvents.broadcastPermissionDeniedEvent();
permissionMap
.resolveRedirectState(rejectedPermission)
.then(function (redirect) {
$location.path(redirect.state).replace();
});
}
});
}
var ngPermission = angular
.module('permission.ng', ['permission', 'ngRoute'])
.run(run).name;
module.exports = ngPermission.name;
}(module || {}));
(function () {
'use strict';
/**
* Service responsible for managing and emitting events
* @name permission.ng.TransitionEvents
*
* @extends {permission.TransitionEvents}
*
* @param $delegate {Object} Parent instance being extended
* @param $rootScope {Object} Top-level angular scope
* @param TransitionProperties {permission.TransitionProperties} Helper storing transition parameters
* @param TransitionEventNames {permission.ng.TransitionEventNames} Constant storing event names
*/
TransitionEvents.$inject = ['$delegate', '$rootScope', 'TransitionProperties', 'TransitionEventNames'];
function TransitionEvents($delegate, $rootScope, TransitionProperties, TransitionEventNames) {
'ngInject';
$delegate.areEventsDefaultPrevented = areEventsDefaultPrevented;
$delegate.broadcastPermissionStartEvent = broadcastPermissionStartEvent;
$delegate.broadcastPermissionAcceptedEvent = broadcastPermissionAcceptedEvent;
$delegate.broadcastPermissionDeniedEvent = broadcastPermissionDeniedEvent;
/**
* Checks if state events are not prevented by default
* @methodOf permission.ng.TransitionEvents
*
* @returns {boolean}
*/
function areEventsDefaultPrevented() {
return isRouteChangePermissionStartDefaultPrevented();
}
/**
* Broadcasts "$routeChangePermissionStart" event from $rootScope
* @methodOf permission.ng.TransitionEvents
*/
function broadcastPermissionStartEvent() {
$rootScope.$broadcast(TransitionEventNames.permissionStart, TransitionProperties.next);
}
/**
* Broadcasts "$routeChangePermissionAccepted" event from $rootScope
* @methodOf permission.ng.TransitionEvents
*/
function broadcastPermissionAcceptedEvent() {
$rootScope.$broadcast(TransitionEventNames.permissionAccepted, TransitionProperties.next);
}
/**
* Broadcasts "$routeChangePermissionDenied" event from $rootScope
* @methodOf permission.ng.TransitionEvents
*/
function broadcastPermissionDeniedEvent() {
$rootScope.$broadcast(TransitionEventNames.permissionDenied, TransitionProperties.next);
}
/**
* Checks if event $routeChangePermissionStart hasn't been disabled by default
* @methodOf permission.ng.TransitionEvents
* @private
*
* @returns {boolean}
*/
function isRouteChangePermissionStartDefaultPrevented() {
return $rootScope.$broadcast(TransitionEventNames.permissionStart, TransitionProperties.next).defaultPrevented;
}
return $delegate;
}
angular
.module('permission.ng')
.decorator('TransitionEvents', TransitionEvents);
}());
(function () {
'use strict';
/**
* Constant storing event names for ng-route
* @name permission.ng.TransitionEventNames
*
* @type {Object.<String,Object>}
*
* @property permissionStart {String} Event name called when started checking for permissions
* @property permissionAccepted {String} Event name called when authorized
* @property permissionDenied {String} Event name called when unauthorized
*/
var TransitionEventNames = {
permissionStart: '$routeChangePermissionStart',
permissionAccepted: '$routeChangePermissionAccepted',
permissionDenied: '$routeChangePermissionDenied'
};
angular
.module('permission.ng')
.value('TransitionEventNames', TransitionEventNames);
}());
|
/*!
* numbro.js
* version : 1.8.1
* author : Företagsplatsen AB
* license : MIT
* http://www.foretagsplatsen.se
*/
(function () {
'use strict';
/************************************
Constants
************************************/
var numbro,
VERSION = '1.8.1',
binarySuffixes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
decimalSuffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
bytes = {
general: { scale: 1024, suffixes: decimalSuffixes, marker: 'bd' },
binary: { scale: 1024, suffixes: binarySuffixes, marker: 'b' },
decimal: { scale: 1000, suffixes: decimalSuffixes, marker: 'd' }
},
// general must be before the others because it reuses their characters!
byteFormatOrder = [ bytes.general, bytes.binary, bytes.decimal ],
// internal storage for culture config files
cultures = {},
// Todo: Remove in 2.0.0
languages = cultures,
currentCulture = 'en-US',
zeroFormat = null,
defaultFormat = '0,0',
defaultCurrencyFormat = '0$',
// check for nodeJS
hasModule = (typeof module !== 'undefined' && module.exports),
// default culture
enUS = {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function(number) {
var b = number % 10;
return (~~(number % 100 / 10) === 1) ? 'th' :
(b === 1) ? 'st' :
(b === 2) ? 'nd' :
(b === 3) ? 'rd' : 'th';
},
currency: {
symbol: '$',
position: 'prefix'
},
defaults: {
currencyFormat: ',0000 a'
},
formats: {
fourDigits: '0000 a',
fullWithTwoDecimals: '$ ,0.00',
fullWithTwoDecimalsNoCurrency: ',0.00'
}
};
/************************************
Constructors
************************************/
// Numbro prototype object
function Numbro(number) {
this._value = number;
}
function zeroes(count) {
var i, ret = '';
for (i = 0; i < count; i++) {
ret += '0';
}
return ret;
}
/**
* Implementation of toFixed() for numbers with exponents
* This function may return negative representations for zero values e.g. "-0.0"
*/
function toFixedLargeSmall(value, precision) {
var mantissa,
beforeDec,
afterDec,
exponent,
prefix,
endStr,
zerosStr,
str;
str = value.toString();
mantissa = str.split('e')[0];
exponent = str.split('e')[1];
beforeDec = mantissa.split('.')[0];
afterDec = mantissa.split('.')[1] || '';
if (+exponent > 0) {
// exponent is positive - add zeros after the numbers
str = beforeDec + afterDec + zeroes(exponent - afterDec.length);
} else {
// exponent is negative
if (+beforeDec < 0) {
prefix = '-0';
} else {
prefix = '0';
}
// tack on the decimal point if needed
if (precision > 0) {
prefix += '.';
}
zerosStr = zeroes((-1 * exponent) - 1);
// substring off the end to satisfy the precision
endStr = (zerosStr + Math.abs(beforeDec) + afterDec).substr(0, precision);
str = prefix + endStr;
}
// only add percision 0's if the exponent is positive
if (+exponent > 0 && precision > 0) {
str += '.' + zeroes(precision);
}
return str;
}
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*
* Also removes negative signs for zero-formatted numbers. e.g. -0.01 w/ precision 1 -> 0.0
*/
function toFixed(value, precision, roundingFunction, optionals) {
var power = Math.pow(10, precision),
optionalsRegExp,
output;
if (value.toString().indexOf('e') > -1) {
// toFixed returns scientific notation for numbers above 1e21 and below 1e-7
output = toFixedLargeSmall(value, precision);
// remove the leading negative sign if it exists and should not be present (e.g. -0.00)
if (output.charAt(0) === '-' && +output >= 0) {
output = output.substr(1); // chop off the '-'
}
}
else {
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value + 'e+' + precision) / power).toFixed(precision);
}
if (optionals) {
optionalsRegExp = new RegExp('0{1,' + optionals + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
/************************************
Formatting
************************************/
// determine what type of formatting we need to do
function formatNumbro(n, format, roundingFunction) {
var output,
escapedFormat = format.replace(/\{[^\{\}]*\}/g, '');
// figure out what kind of format we are dealing with
if (escapedFormat.indexOf('$') > -1) { // currency!!!!!
output = formatCurrency(n, format, roundingFunction);
} else if (escapedFormat.indexOf('%') > -1) { // percentage
output = formatPercentage(n, format, roundingFunction);
} else if (escapedFormat.indexOf(':') > -1) { // time
output = formatTime(n, format);
} else { // plain ol' numbers or bytes
output = formatNumber(n._value, format, roundingFunction);
}
// return string
return output;
}
// revert to number
function unformatNumbro(n, string) {
var stringOriginal = string,
thousandRegExp,
millionRegExp,
billionRegExp,
trillionRegExp,
bytesMultiplier = false,
power;
if (string.indexOf(':') > -1) {
n._value = unformatTime(string);
} else {
if (string === zeroFormat) {
n._value = 0;
} else {
if (cultures[currentCulture].delimiters.decimal !== '.') {
string = string.replace(/\./g, '').replace(cultures[currentCulture].delimiters.decimal, '.');
}
// see if abbreviations are there so that we can multiply to the correct number
thousandRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.thousand +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
millionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.million +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
billionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.billion +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
trillionRegExp = new RegExp('[^a-zA-Z]' + cultures[currentCulture].abbreviations.trillion +
'(?:\\)|(\\' + cultures[currentCulture].currency.symbol + ')?(?:\\))?)?$');
// see if bytes are there so that we can multiply to the correct number
for (power = 1; power < binarySuffixes.length && !bytesMultiplier; ++power) {
if (string.indexOf(binarySuffixes[power]) > -1) {
bytesMultiplier = Math.pow(1024, power);
} else if (string.indexOf(decimalSuffixes[power]) > -1) {
bytesMultiplier = Math.pow(1000, power);
}
}
var str = string.replace(/[^0-9\.]+/g, '');
if (str === '') {
// An empty string is not a number.
n._value = NaN;
} else {
// do some math to create our number
n._value = ((bytesMultiplier) ? bytesMultiplier : 1) *
((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) *
((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) *
((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) *
((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) *
((string.indexOf('%') > -1) ? 0.01 : 1) *
(((string.split('-').length +
Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2) ? 1 : -1) *
Number(str);
// round if we are talking about bytes
n._value = (bytesMultiplier) ? Math.ceil(n._value) : n._value;
}
}
}
return n._value;
}
function formatCurrency(n, originalFormat, roundingFunction) {
var format = originalFormat,
symbolIndex = format.indexOf('$'),
openParenIndex = format.indexOf('('),
plusSignIndex = format.indexOf('+'),
minusSignIndex = format.indexOf('-'),
space = '',
decimalSeparator = '',
spliceIndex,
output;
if(format.indexOf('$') === -1){
// Use defaults instead of the format provided
if (cultures[currentCulture].currency.position === 'infix') {
decimalSeparator = cultures[currentCulture].currency.symbol;
if (cultures[currentCulture].currency.spaceSeparated) {
decimalSeparator = ' ' + decimalSeparator + ' ';
}
} else if (cultures[currentCulture].currency.spaceSeparated) {
space = ' ';
}
} else {
// check for space before or after currency
if (format.indexOf(' $') > -1) {
space = ' ';
format = format.replace(' $', '');
} else if (format.indexOf('$ ') > -1) {
space = ' ';
format = format.replace('$ ', '');
} else {
format = format.replace('$', '');
}
}
// Format The Number
output = formatNumber(n._value, format, roundingFunction, decimalSeparator);
if (originalFormat.indexOf('$') === -1) {
// Use defaults instead of the format provided
switch (cultures[currentCulture].currency.position) {
case 'postfix':
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
output = output.join('');
} else {
output = output + space + cultures[currentCulture].currency.symbol;
}
break;
case 'infix':
break;
case 'prefix':
if (output.indexOf('(') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = Math.max(openParenIndex, minusSignIndex) + 1;
output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
output = output.join('');
} else {
output = cultures[currentCulture].currency.symbol + space + output;
}
break;
default:
throw Error('Currency position should be among ["prefix", "infix", "postfix"]');
}
} else {
// position the symbol
if (symbolIndex <= 1) {
if (output.indexOf('(') > -1 || output.indexOf('+') > -1 || output.indexOf('-') > -1) {
output = output.split('');
spliceIndex = 1;
if (symbolIndex < openParenIndex || symbolIndex < plusSignIndex || symbolIndex < minusSignIndex) {
// the symbol appears before the "(", "+" or "-"
spliceIndex = 0;
}
output.splice(spliceIndex, 0, cultures[currentCulture].currency.symbol + space);
output = output.join('');
} else {
output = cultures[currentCulture].currency.symbol + space + output;
}
} else {
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + cultures[currentCulture].currency.symbol);
output = output.join('');
} else {
output = output + space + cultures[currentCulture].currency.symbol;
}
}
}
return output;
}
function formatPercentage(n, format, roundingFunction) {
var space = '',
output,
value = n._value * 100;
// check for space before %
if (format.indexOf(' %') > -1) {
space = ' ';
format = format.replace(' %', '');
} else {
format = format.replace('%', '');
}
output = formatNumber(value, format, roundingFunction);
if (output.indexOf(')') > -1) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
}
function formatTime(n) {
var hours = Math.floor(n._value / 60 / 60),
minutes = Math.floor((n._value - (hours * 60 * 60)) / 60),
seconds = Math.round(n._value - (hours * 60 * 60) - (minutes * 60));
return hours + ':' +
((minutes < 10) ? '0' + minutes : minutes) + ':' +
((seconds < 10) ? '0' + seconds : seconds);
}
function unformatTime(string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + (Number(timeArray[0]) * 60 * 60);
// minutes
seconds = seconds + (Number(timeArray[1]) * 60);
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + (Number(timeArray[0]) * 60);
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
function formatByteUnits (value, suffixes, scale) {
var suffix = suffixes[0],
power,
min,
max,
abs = Math.abs(value);
if (abs >= scale) {
for (power = 1; power < suffixes.length; ++power) {
min = Math.pow(scale, power);
max = Math.pow(scale, power + 1);
if (abs >= min && abs < max) {
suffix = suffixes[power];
value = value / min;
break;
}
}
// values greater than or equal to [scale] YB never set the suffix
if (suffix === suffixes[0]) {
value = value / Math.pow(scale, suffixes.length - 1);
suffix = suffixes[suffixes.length - 1];
}
}
return { value: value, suffix: suffix };
}
function formatNumber (value, format, roundingFunction, sep) {
var negP = false,
signed = false,
optDec = false,
abbr = '',
abbrK = false, // force abbreviation to thousands
abbrM = false, // force abbreviation to millions
abbrB = false, // force abbreviation to billions
abbrT = false, // force abbreviation to trillions
abbrForce = false, // force abbreviation
bytes = '',
byteFormat,
units,
ord = '',
abs = Math.abs(value),
totalLength,
length,
minimumPrecision,
pow,
w,
intPrecision,
precision,
prefix,
postfix,
thousands,
d = '',
forcedNeg = false,
neg = false,
indexOpenP,
size,
indexMinus,
paren = '',
minlen,
i;
// check if number is zero and a custom zero format has been set
if (value === 0 && zeroFormat !== null) {
return zeroFormat;
}
if (!isFinite(value)) {
return '' + value;
}
if (format.indexOf('{') === 0) {
var end = format.indexOf('}');
if (end === -1) {
throw Error('Format should also contain a "}"');
}
prefix = format.slice(1, end);
format = format.slice(end + 1);
} else {
prefix = '';
}
if (format.indexOf('}') === format.length - 1) {
var start = format.indexOf('{');
if (start === -1) {
throw Error('Format should also contain a "{"');
}
postfix = format.slice(start + 1, -1);
format = format.slice(0, start + 1);
} else {
postfix = '';
}
// check for min length
var info;
if (format.indexOf('.') === -1) {
info = format.match(/([0-9]+).*/);
} else {
info = format.match(/([0-9]+)\..*/);
}
minlen = info === null ? -1 : info[1].length;
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (format.indexOf('-') !== -1) {
forcedNeg = true;
}
if (format.indexOf('(') > -1) {
negP = true;
format = format.slice(1, -1);
} else if (format.indexOf('+') > -1) {
signed = true;
format = format.replace(/\+/g, '');
}
// see if abbreviation is wanted
if (format.indexOf('a') > -1) {
intPrecision = format.split('.')[0].match(/[0-9]+/g) || ['0'];
intPrecision = parseInt(intPrecision[0], 10);
// check if abbreviation is specified
abbrK = format.indexOf('aK') >= 0;
abbrM = format.indexOf('aM') >= 0;
abbrB = format.indexOf('aB') >= 0;
abbrT = format.indexOf('aT') >= 0;
abbrForce = abbrK || abbrM || abbrB || abbrT;
// check for space before abbreviation
if (format.indexOf(' a') > -1) {
abbr = ' ';
format = format.replace(' a', '');
} else {
format = format.replace('a', '');
}
totalLength = Math.floor(Math.log(abs) / Math.LN10) + 1;
minimumPrecision = totalLength % 3;
minimumPrecision = minimumPrecision === 0 ? 3 : minimumPrecision;
if (intPrecision && abs !== 0) {
length = Math.floor(Math.log(abs) / Math.LN10) + 1 - intPrecision;
pow = 3 * ~~((Math.min(intPrecision, totalLength) - minimumPrecision) / 3);
abs = abs / Math.pow(10, pow);
if (format.indexOf('.') === -1 && intPrecision > 3) {
format += '[.]';
size = length === 0 ? 0 : 3 * ~~(length / 3) - length;
size = size < 0 ? size + 3 : size;
format += zeroes(size);
}
}
if (Math.floor(Math.log(Math.abs(value)) / Math.LN10) + 1 !== intPrecision) {
if (abs >= Math.pow(10, 12) && !abbrForce || abbrT) {
// trillion
abbr = abbr + cultures[currentCulture].abbreviations.trillion;
value = value / Math.pow(10, 12);
} else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9) && !abbrForce || abbrB) {
// billion
abbr = abbr + cultures[currentCulture].abbreviations.billion;
value = value / Math.pow(10, 9);
} else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6) && !abbrForce || abbrM) {
// million
abbr = abbr + cultures[currentCulture].abbreviations.million;
value = value / Math.pow(10, 6);
} else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3) && !abbrForce || abbrK) {
// thousand
abbr = abbr + cultures[currentCulture].abbreviations.thousand;
value = value / Math.pow(10, 3);
}
}
}
// see if we are formatting
// binary-decimal bytes (1024 MB), binary bytes (1024 MiB), or decimal bytes (1000 MB)
for (i = 0; i < byteFormatOrder.length; ++i) {
byteFormat = byteFormatOrder[i];
if (format.indexOf(byteFormat.marker) > -1) {
// check for space before
if (format.indexOf(' ' + byteFormat.marker) >-1) {
bytes = ' ';
}
// remove the marker (with the space if it had one)
format = format.replace(bytes + byteFormat.marker, '');
units = formatByteUnits(value, byteFormat.suffixes, byteFormat.scale);
value = units.value;
bytes = bytes + units.suffix;
break;
}
}
// see if ordinal is wanted
if (format.indexOf('o') > -1) {
// check for space before
if (format.indexOf(' o') > -1) {
ord = ' ';
format = format.replace(' o', '');
} else {
format = format.replace('o', '');
}
if (cultures[currentCulture].ordinal) {
ord = ord + cultures[currentCulture].ordinal(value);
}
}
if (format.indexOf('[.]') > -1) {
optDec = true;
format = format.replace('[.]', '.');
}
w = value.toString().split('.')[0];
precision = format.split('.')[1];
thousands = format.indexOf(',');
if (precision) {
if (precision.indexOf('*') !== -1) {
d = toFixed(value, value.toString().split('.')[1].length, roundingFunction);
} else {
if (precision.indexOf('[') > -1) {
precision = precision.replace(']', '');
precision = precision.split('[');
d = toFixed(value, (precision[0].length + precision[1].length), roundingFunction,
precision[1].length);
} else {
d = toFixed(value, precision.length, roundingFunction);
}
}
w = d.split('.')[0];
if (d.split('.')[1].length) {
var p = sep ? abbr + sep : cultures[currentCulture].delimiters.decimal;
d = p + d.split('.')[1];
} else {
d = '';
}
if (optDec && Number(d.slice(1)) === 0) {
d = '';
}
} else {
w = toFixed(value, 0, roundingFunction);
}
// format number
if (w.indexOf('-') > -1) {
w = w.slice(1);
neg = true;
}
if (w.length < minlen) {
w = zeroes(minlen - w.length) + w;
}
if (thousands > -1) {
w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' +
cultures[currentCulture].delimiters.thousands);
}
if (format.indexOf('.') === 0) {
w = '';
}
indexOpenP = format.indexOf('(');
indexMinus = format.indexOf('-');
if (indexOpenP < indexMinus) {
paren = ((negP && neg) ? '(' : '') + (((forcedNeg && neg) || (!negP && neg)) ? '-' : '');
} else {
paren = (((forcedNeg && neg) || (!negP && neg)) ? '-' : '') + ((negP && neg) ? '(' : '');
}
return prefix +
paren + ((!neg && signed && value !== 0) ? '+' : '') +
w + d +
((ord) ? ord : '') +
((abbr && !sep) ? abbr : '') +
((bytes) ? bytes : '') +
((negP && neg) ? ')' : '') +
postfix;
}
/************************************
Top Level Functions
************************************/
numbro = function(input) {
if (numbro.isNumbro(input)) {
input = input.value();
} else if (input === 0 || typeof input === 'undefined') {
input = 0;
} else if (!Number(input)) {
input = numbro.fn.unformat(input);
}
return new Numbro(Number(input));
};
// version number
numbro.version = VERSION;
// compare numbro object
numbro.isNumbro = function(obj) {
return obj instanceof Numbro;
};
/**
* This function allow the user to set a new language with a fallback if
* the language does not exist. If no fallback language is provided,
* it fallbacks to english.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `setCulture` should be used instead.
*/
numbro.setLanguage = function(newLanguage, fallbackLanguage) {
console.warn('`setLanguage` is deprecated since version 1.6.0. Use `setCulture` instead');
var key = newLanguage,
prefix = newLanguage.split('-')[0],
matchingLanguage = null;
if (!languages[key]) {
Object.keys(languages).forEach(function(language) {
if (!matchingLanguage && language.split('-')[0] === prefix) {
matchingLanguage = language;
}
});
key = matchingLanguage || fallbackLanguage || 'en-US';
}
chooseCulture(key);
};
/**
* This function allow the user to set a new culture with a fallback if
* the culture does not exist. If no fallback culture is provided,
* it falls back to "en-US".
*/
numbro.setCulture = function(newCulture, fallbackCulture) {
var key = newCulture,
suffix = newCulture.split('-')[1],
matchingCulture = null;
if (!cultures[key]) {
if (suffix) {
Object.keys(cultures).forEach(function(language) {
if (!matchingCulture && language.split('-')[1] === suffix) {
matchingCulture = language;
}
});
}
key = matchingCulture || fallbackCulture || 'en-US';
}
chooseCulture(key);
};
/**
* This function will load languages and then set the global language. If
* no arguments are passed in, it will simply return the current global
* language key.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `culture` should be used instead.
*/
numbro.language = function(key, values) {
console.warn('`language` is deprecated since version 1.6.0. Use `culture` instead');
if (!key) {
return currentCulture;
}
if (key && !values) {
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
chooseCulture(key);
}
if (values || !languages[key]) {
setCulture(key, values);
}
return numbro;
};
/**
* This function will load cultures and then set the global culture. If
* no arguments are passed in, it will simply return the current global
* culture code.
*/
numbro.culture = function(code, values) {
if (!code) {
return currentCulture;
}
if (code && !values) {
if (!cultures[code]) {
throw new Error('Unknown culture : ' + code);
}
chooseCulture(code);
}
if (values || !cultures[code]) {
setCulture(code, values);
}
return numbro;
};
/**
* This function provides access to the loaded language data. If
* no arguments are passed in, it will simply return the current
* global language object.
*
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `culture` should be used instead.
*/
numbro.languageData = function(key) {
console.warn('`languageData` is deprecated since version 1.6.0. Use `cultureData` instead');
if (!key) {
return languages[currentCulture];
}
if (!languages[key]) {
throw new Error('Unknown language : ' + key);
}
return languages[key];
};
/**
* This function provides access to the loaded culture data. If
* no arguments are passed in, it will simply return the current
* global culture object.
*/
numbro.cultureData = function(code) {
if (!code) {
return cultures[currentCulture];
}
if (!cultures[code]) {
throw new Error('Unknown culture : ' + code);
}
return cultures[code];
};
numbro.culture('en-US', enUS);
/**
* @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `cultures` should be used instead.
*/
numbro.languages = function() {
console.warn('`languages` is deprecated since version 1.6.0. Use `cultures` instead');
return languages;
};
numbro.cultures = function() {
return cultures;
};
numbro.zeroFormat = function(format) {
zeroFormat = typeof(format) === 'string' ? format : null;
};
numbro.defaultFormat = function(format) {
defaultFormat = typeof(format) === 'string' ? format : '0.0';
};
numbro.defaultCurrencyFormat = function (format) {
defaultCurrencyFormat = typeof(format) === 'string' ? format : '0$';
};
numbro.validate = function(val, culture) {
var _decimalSep,
_thousandSep,
_currSymbol,
_valArray,
_abbrObj,
_thousandRegEx,
cultureData,
temp;
//coerce val to string
if (typeof val !== 'string') {
val += '';
if (console.warn) {
console.warn('Numbro.js: Value is not string. It has been co-erced to: ', val);
}
}
//trim whitespaces from either sides
val = val.trim();
//replace the initial '+' or '-' sign if present
val = val.replace(/^[+-]?/, '');
//if val is just digits return true
if ( !! val.match(/^\d+$/)) {
return true;
}
//if val is empty return false
if (val === '') {
return false;
}
//get the decimal and thousands separator from numbro.cultureData
try {
//check if the culture is understood by numbro. if not, default it to current culture
cultureData = numbro.cultureData(culture);
} catch (e) {
cultureData = numbro.cultureData(numbro.culture());
}
//setup the delimiters and currency symbol based on culture
_currSymbol = cultureData.currency.symbol;
_abbrObj = cultureData.abbreviations;
_decimalSep = cultureData.delimiters.decimal;
if (cultureData.delimiters.thousands === '.') {
_thousandSep = '\\.';
} else {
_thousandSep = cultureData.delimiters.thousands;
}
// validating currency symbol
temp = val.match(/^[^\d\.\,]+/);
if (temp !== null) {
val = val.substr(1);
if (temp[0] !== _currSymbol) {
return false;
}
}
//validating abbreviation symbol
temp = val.match(/[^\d]+$/);
if (temp !== null) {
val = val.slice(0, -1);
if (temp[0] !== _abbrObj.thousand && temp[0] !== _abbrObj.million &&
temp[0] !== _abbrObj.billion && temp[0] !== _abbrObj.trillion) {
return false;
}
}
_thousandRegEx = new RegExp(_thousandSep + '{2}');
if (!val.match(/[^\d.,]/g)) {
_valArray = val.split(_decimalSep);
if (_valArray.length > 2) {
return false;
} else {
if (_valArray.length < 2) {
return ( !! _valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx));
} else {
if (_valArray[0] === '') {
// for values without leading zero eg. .984
return (!_valArray[0].match(_thousandRegEx) &&
!!_valArray[1].match(/^\d+$/));
} else if (_valArray[0].length === 1) {
return ( !! _valArray[0].match(/^\d+$/) &&
!_valArray[0].match(_thousandRegEx) &&
!! _valArray[1].match(/^\d+$/));
} else {
return ( !! _valArray[0].match(/^\d+.*\d$/) &&
!_valArray[0].match(_thousandRegEx) &&
!! _valArray[1].match(/^\d+$/));
}
}
}
}
return false;
};
/**
* * @deprecated Since in version 1.6.0. It will be deleted in version 2.0
* `loadCulturesInNode` should be used instead.
*/
numbro.loadLanguagesInNode = function() {
console.warn('`loadLanguagesInNode` is deprecated since version 1.6.0. Use `loadCulturesInNode` instead');
numbro.loadCulturesInNode();
};
numbro.loadCulturesInNode = function() {
// TODO: Rename the folder in 2.0.0
var cultures = require('./languages');
for(var langLocaleCode in cultures) {
if(langLocaleCode) {
numbro.culture(langLocaleCode, cultures[langLocaleCode]);
}
}
};
/************************************
Helpers
************************************/
function setCulture(code, values) {
cultures[code] = values;
}
function chooseCulture(code) {
currentCulture = code;
var defaults = cultures[code].defaults;
if (defaults && defaults.format) {
numbro.defaultFormat(defaults.format);
}
if (defaults && defaults.currencyFormat) {
numbro.defaultCurrencyFormat(defaults.currencyFormat);
}
}
function inNodejsRuntime() {
return (typeof process !== 'undefined') &&
(process.browser === undefined) &&
(process.title.indexOf('node') === 0 || process.title === 'grunt' || process.title === 'gulp') &&
(typeof require !== 'undefined');
}
/************************************
Floating-point helpers
************************************/
// The floating-point helper functions and implementation
// borrows heavily from sinful.js: http://guipn.github.io/sinful.js/
/**
* Array.prototype.reduce for browsers that don't support it
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Compatibility
*/
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, optInitialValue) {
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index,
value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = optInitialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
function multiplier(x) {
var parts = x.toString().split('.');
if (parts.length < 2) {
return 1;
}
return Math.pow(10, parts[1].length);
}
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
function correctionFactor() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(prev, next) {
var mp = multiplier(prev),
mn = multiplier(next);
return mp > mn ? mp : mn;
}, -Infinity);
}
/************************************
Numbro Prototype
************************************/
numbro.fn = Numbro.prototype = {
clone: function() {
return numbro(this);
},
format: function(inputString, roundingFunction) {
return formatNumbro(this,
inputString ? inputString : defaultFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
formatCurrency: function(inputString, roundingFunction) {
return formatCurrency(this,
inputString ? inputString : defaultCurrencyFormat,
(roundingFunction !== undefined) ? roundingFunction : Math.round
);
},
unformat: function(inputString) {
if (typeof inputString === 'number') {
return inputString;
} else if (typeof inputString === 'string') {
var result = unformatNumbro(this, inputString);
// Any unparseable string (represented as NaN in the result) is
// converted into undefined.
return isNaN(result) ? undefined : result;
} else {
return undefined;
}
},
binaryByteUnits: function() {
return formatByteUnits(this._value, bytes.binary.suffixes, bytes.binary.scale).suffix;
},
byteUnits: function() {
return formatByteUnits(this._value, bytes.general.suffixes, bytes.general.scale).suffix;
},
decimalByteUnits: function() {
return formatByteUnits(this._value, bytes.decimal.suffixes, bytes.decimal.scale).suffix;
},
value: function() {
return this._value;
},
valueOf: function() {
return this._value;
},
set: function(value) {
this._value = Number(value);
return this;
},
add: function(value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr) {
return accum + corrFactor * curr;
}
this._value = [this._value, value].reduce(cback, 0) / corrFactor;
return this;
},
subtract: function(value) {
var corrFactor = correctionFactor.call(null, this._value, value);
function cback(accum, curr) {
return accum - corrFactor * curr;
}
this._value = [value].reduce(cback, this._value * corrFactor) / corrFactor;
return this;
},
multiply: function(value) {
function cback(accum, curr) {
var corrFactor = correctionFactor(accum, curr),
result = accum * corrFactor;
result *= curr * corrFactor;
result /= corrFactor * corrFactor;
return result;
}
this._value = [this._value, value].reduce(cback, 1);
return this;
},
divide: function(value) {
function cback(accum, curr) {
var corrFactor = correctionFactor(accum, curr);
return (accum * corrFactor) / (curr * corrFactor);
}
this._value = [this._value, value].reduce(cback);
return this;
},
difference: function(value) {
return Math.abs(numbro(this._value).subtract(value).value());
}
};
/************************************
Exposing Numbro
************************************/
if (inNodejsRuntime()) {
//Todo: Rename the folder in 2.0.0
numbro.loadCulturesInNode();
}
// CommonJS module is defined
if (hasModule) {
module.exports = numbro;
} else {
/*global ender:false */
if (typeof ender === 'undefined') {
// here, `this` means `window` in the browser, or `global` on the server
// add `numbro` as a global object via a string identifier,
// for Closure Compiler 'advanced' mode
this.numbro = numbro;
}
/*global define:false */
if (typeof define === 'function' && define.amd) {
define([], function() {
return numbro;
});
}
}
}.call(typeof window === 'undefined' ? this : window));
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var gridRole = {
abstract: false,
accessibleNameRequired: true,
baseConcepts: [{
module: 'HTML',
concept: {
name: 'table',
attributes: [{
name: 'role',
value: 'grid'
}]
}
}],
childrenPresentational: false,
nameFrom: ['author'],
props: {
'aria-level': null,
'aria-multiselectable': null,
'aria-readonly': null
},
relatedConcepts: [],
requireContextRole: [],
requiredOwnedElements: [['rowgroup', 'row'], ['row']],
requiredProps: {},
superClass: [['roletype', 'widget', 'composite'], ['roletype', 'structure', 'section', 'table']]
};
exports.default = gridRole;
|
Ext.grid.RowExpander = function(config){
Ext.apply(this, config);
this.addEvents({
beforeexpand : true,
expand: true,
beforecollapse: true,
collapse: true
});
Ext.grid.RowExpander.superclass.constructor.call(this);
if(this.tpl){
if(typeof this.tpl == 'string'){
this.tpl = new Ext.Template(this.tpl);
}
this.tpl.compile();
}
this.state = {};
this.bodyContent = {};
};
Ext.extend(Ext.grid.RowExpander, Ext.util.Observable, {
header: "",
width: 20,
sortable: false,
fixed:true,
menuDisabled:true,
dataIndex: '',
id: 'expander',
lazyRender : true,
enableCaching: true,
getRowClass : function(record, rowIndex, p, ds){
p.cols = p.cols-1;
var content = this.bodyContent[record.id];
if(!content && !this.lazyRender){
content = this.getBodyContent(record, rowIndex);
}
if(content){
p.body = content;
}
return this.state[record.id] ? 'x-grid3-row-expanded' : 'x-grid3-row-collapsed';
},
init : function(grid){
this.grid = grid;
var view = grid.getView();
view.getRowClass = this.getRowClass.createDelegate(this);
view.enableRowBody = true;
grid.on('render', function(){
view.mainBody.on('mousedown', this.onMouseDown, this);
}, this);
},
getBodyContent : function(record, index){
if(!this.enableCaching){
return this.tpl.apply(record.data);
}
var content = this.bodyContent[record.id];
if(!content){
content = this.tpl.apply(record.data);
this.bodyContent[record.id] = content;
}
return content;
},
onMouseDown : function(e, t){
if(t.className == 'x-grid3-row-expander'){
e.stopEvent();
var row = e.getTarget('.x-grid3-row');
this.toggleRow(row);
}
},
renderer : function(v, p, record){
p.cellAttr = 'rowspan="2"';
return '<div class="x-grid3-row-expander"> </div>';
},
beforeExpand : function(record, body, rowIndex){
if(this.fireEvent('beforeexpand', this, record, body, rowIndex) !== false){
if(this.tpl && this.lazyRender){
body.innerHTML = this.getBodyContent(record, rowIndex);
}
return true;
}else{
return false;
}
},
toggleRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
this[Ext.fly(row).hasClass('x-grid3-row-collapsed') ? 'expandRow' : 'collapseRow'](row);
},
expandRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.DomQuery.selectNode('tr:nth(2) div.x-grid3-row-body', row);
if(this.beforeExpand(record, body, row.rowIndex)){
this.state[record.id] = true;
Ext.fly(row).replaceClass('x-grid3-row-collapsed', 'x-grid3-row-expanded');
this.fireEvent('expand', this, record, body, row.rowIndex);
}
},
collapseRow : function(row){
if(typeof row == 'number'){
row = this.grid.view.getRow(row);
}
var record = this.grid.store.getAt(row.rowIndex);
var body = Ext.fly(row).child('tr:nth(1) div.x-grid3-row-body', true);
if(this.fireEvent('beforecollapse', this, record, body, row.rowIndex) !== false){
this.state[record.id] = false;
Ext.fly(row).replaceClass('x-grid3-row-expanded', 'x-grid3-row-collapsed');
this.fireEvent('collapse', this, record, body, row.rowIndex);
}
}
});
|
/**
* @author mrdoob / http://mrdoob.com/
*/
function RollerCoasterGeometry( curve, divisions ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var normals = [];
var colors = [];
var color1 = [ 1, 1, 1 ];
var color2 = [ 1, 1, 0 ];
var up = new THREE.Vector3( 0, 1, 0 );
var forward = new THREE.Vector3();
var right = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var prevQuaternion = new THREE.Quaternion();
prevQuaternion.setFromAxisAngle( up , Math.PI / 2 );
var point = new THREE.Vector3();
var prevPoint = new THREE.Vector3();
prevPoint.copy( curve.getPointAt( 0 ) );
// shapes
var step = [
new THREE.Vector3( -0.225, 0, 0 ),
new THREE.Vector3( 0, -0.050, 0 ),
new THREE.Vector3( 0, -0.175, 0 ),
new THREE.Vector3( 0, -0.050, 0 ),
new THREE.Vector3( 0.225, 0, 0 ),
new THREE.Vector3( 0, -0.175, 0 )
];
var PI2 = Math.PI * 2;
var sides = 5;
var tube1 = [];
for ( var i = 0; i < sides; i ++ ) {
var angle = ( i / sides ) * PI2;
tube1.push( new THREE.Vector3( Math.sin( angle ) * 0.06, Math.cos( angle ) * 0.06, 0 ) );
}
var sides = 6;
var tube2 = [];
for ( var i = 0; i < sides; i ++ ) {
var angle = ( i / sides ) * PI2;
tube2.push( new THREE.Vector3( Math.sin( angle ) * 0.025, Math.cos( angle ) * 0.025, 0 ) );
}
var vector = new THREE.Vector3();
var normal = new THREE.Vector3();
function drawShape( shape, color ) {
normal.set( 0, 0, -1 ).applyQuaternion( quaternion );
for ( var j = 0; j < shape.length; j ++ ) {
vector.copy( shape[ j ] );
vector.applyQuaternion( quaternion );
vector.add( point );
vertices.push( vector.x, vector.y, vector.z );
normals.push( normal.x, normal.y, normal.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
normal.set( 0, 0, 1 ).applyQuaternion( quaternion );
for ( var j = shape.length - 1; j >= 0; j -- ) {
vector.copy( shape[ j ] );
vector.applyQuaternion( quaternion );
vector.add( point );
vertices.push( vector.x, vector.y, vector.z );
normals.push( normal.x, normal.y, normal.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
};
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
var normal1 = new THREE.Vector3();
var normal2 = new THREE.Vector3();
var normal3 = new THREE.Vector3();
var normal4 = new THREE.Vector3();
function extrudeShape( shape, offset, color ) {
for ( var j = 0, jl = shape.length; j < jl; j ++ ) {
var point1 = shape[ j ];
var point2 = shape[ ( j + 1 ) % jl ];
vector1.copy( point1 ).add( offset );
vector1.applyQuaternion( quaternion );
vector1.add( point );
vector2.copy( point2 ).add( offset );
vector2.applyQuaternion( quaternion );
vector2.add( point );
vector3.copy( point2 ).add( offset );
vector3.applyQuaternion( prevQuaternion );
vector3.add( prevPoint );
vector4.copy( point1 ).add( offset );
vector4.applyQuaternion( prevQuaternion );
vector4.add( prevPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
//
normal1.copy( point1 );
normal1.applyQuaternion( quaternion );
normal1.normalize();
normal2.copy( point2 );
normal2.applyQuaternion( quaternion );
normal2.normalize();
normal3.copy( point2 );
normal3.applyQuaternion( prevQuaternion );
normal3.normalize();
normal4.copy( point1 );
normal4.applyQuaternion( prevQuaternion );
normal4.normalize();
normals.push( normal1.x, normal1.y, normal1.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal4.x, normal4.y, normal4.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal3.x, normal3.y, normal3.z );
normals.push( normal4.x, normal4.y, normal4.z );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
colors.push( color[ 0 ], color[ 1 ], color[ 2 ] );
}
};
var offset = new THREE.Vector3();
for ( var i = 1; i <= divisions; i ++ ) {
point.copy( curve.getPointAt( i / divisions ) );
up.set( 0, 1, 0 );
forward.subVectors( point, prevPoint ).normalize();
right.crossVectors( up, forward ).normalize();
up.crossVectors( forward, right );
var angle = Math.atan2( forward.x, forward.z );
quaternion.setFromAxisAngle( up, angle );
if ( i % 2 === 0 ) {
drawShape( step, color2 );
}
extrudeShape( tube1, offset.set( 0, -0.125, 0 ), color2 );
extrudeShape( tube2, offset.set( 0.2, 0, 0 ), color1 );
extrudeShape( tube2, offset.set( -0.2, 0, 0 ), color1 );
prevPoint.copy( point );
prevQuaternion.copy( quaternion );
}
// console.log( vertices.length );
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
this.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );
};
RollerCoasterGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
function RollerCoasterLiftersGeometry( curve, divisions ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var normals = [];
var quaternion = new THREE.Quaternion();
var up = new THREE.Vector3( 0, 1, 0 );
var point = new THREE.Vector3();
var tangent = new THREE.Vector3();
// shapes
var tube1 = [
new THREE.Vector3( 0, 0.05, -0.05 ),
new THREE.Vector3( 0, 0.05, 0.05 ),
new THREE.Vector3( 0, -0.05, 0 )
];
var tube2 = [
new THREE.Vector3( -0.05, 0, 0.05 ),
new THREE.Vector3( -0.05, 0, -0.05 ),
new THREE.Vector3( 0.05, 0, 0 )
];
var tube3 = [
new THREE.Vector3( 0.05, 0, -0.05 ),
new THREE.Vector3( 0.05, 0, 0.05 ),
new THREE.Vector3( -0.05, 0, 0 )
];
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
var normal1 = new THREE.Vector3();
var normal2 = new THREE.Vector3();
var normal3 = new THREE.Vector3();
var normal4 = new THREE.Vector3();
function extrudeShape( shape, fromPoint, toPoint ) {
for ( var j = 0, jl = shape.length; j < jl; j ++ ) {
var point1 = shape[ j ];
var point2 = shape[ ( j + 1 ) % jl ];
vector1.copy( point1 );
vector1.applyQuaternion( quaternion );
vector1.add( fromPoint );
vector2.copy( point2 );
vector2.applyQuaternion( quaternion );
vector2.add( fromPoint );
vector3.copy( point2 );
vector3.applyQuaternion( quaternion );
vector3.add( toPoint );
vector4.copy( point1 );
vector4.applyQuaternion( quaternion );
vector4.add( toPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
//
normal1.copy( point1 );
normal1.applyQuaternion( quaternion );
normal1.normalize();
normal2.copy( point2 );
normal2.applyQuaternion( quaternion );
normal2.normalize();
normal3.copy( point2 );
normal3.applyQuaternion( quaternion );
normal3.normalize();
normal4.copy( point1 );
normal4.applyQuaternion( quaternion );
normal4.normalize();
normals.push( normal1.x, normal1.y, normal1.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal4.x, normal4.y, normal4.z );
normals.push( normal2.x, normal2.y, normal2.z );
normals.push( normal3.x, normal3.y, normal3.z );
normals.push( normal4.x, normal4.y, normal4.z );
}
};
var fromPoint = new THREE.Vector3();
var toPoint = new THREE.Vector3();
for ( var i = 1; i <= divisions; i ++ ) {
point.copy( curve.getPointAt( i / divisions ) );
tangent.copy( curve.getTangentAt( i / divisions ) );
var angle = Math.atan2( tangent.x, tangent.z );
quaternion.setFromAxisAngle( up, angle );
//
if ( point.y > 10 ) {
fromPoint.set( -0.75, -0.35, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 0.75, -0.35, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube1, fromPoint, toPoint );
fromPoint.set( -0.7, -0.3, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( -0.7, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube2, fromPoint, toPoint );
fromPoint.set( 0.7, -0.3, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 0.7, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube3, fromPoint, toPoint );
} else {
fromPoint.set( 0, -0.2, 0 );
fromPoint.applyQuaternion( quaternion );
fromPoint.add( point );
toPoint.set( 0, -point.y, 0 );
toPoint.applyQuaternion( quaternion );
toPoint.add( point );
extrudeShape( tube3, fromPoint, toPoint );
}
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( normals ), 3 ) );
};
RollerCoasterLiftersGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
function RollerCoasterShadowGeometry( curve, divisions ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var up = new THREE.Vector3( 0, 1, 0 );
var forward = new THREE.Vector3();
var quaternion = new THREE.Quaternion();
var prevQuaternion = new THREE.Quaternion();
prevQuaternion.setFromAxisAngle( up , Math.PI / 2 );
var point = new THREE.Vector3();
var prevPoint = new THREE.Vector3();
prevPoint.copy( curve.getPointAt( 0 ) );
prevPoint.y = 0;
var vector1 = new THREE.Vector3();
var vector2 = new THREE.Vector3();
var vector3 = new THREE.Vector3();
var vector4 = new THREE.Vector3();
for ( var i = 1; i <= divisions; i ++ ) {
point.copy( curve.getPointAt( i / divisions ) );
point.y = 0;
forward.subVectors( point, prevPoint );
var angle = Math.atan2( forward.x, forward.z );
quaternion.setFromAxisAngle( up, angle );
vector1.set( -0.3, 0, 0 );
vector1.applyQuaternion( quaternion );
vector1.add( point );
vector2.set( 0.3, 0, 0 );
vector2.applyQuaternion( quaternion );
vector2.add( point );
vector3.set( 0.3, 0, 0 );
vector3.applyQuaternion( prevQuaternion );
vector3.add( prevPoint );
vector4.set( -0.3, 0, 0 );
vector4.applyQuaternion( prevQuaternion );
vector4.add( prevPoint );
vertices.push( vector1.x, vector1.y, vector1.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector4.x, vector4.y, vector4.z );
vertices.push( vector2.x, vector2.y, vector2.z );
vertices.push( vector3.x, vector3.y, vector3.z );
vertices.push( vector4.x, vector4.y, vector4.z );
prevPoint.copy( point );
prevQuaternion.copy( quaternion );
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
};
RollerCoasterShadowGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
function SkyGeometry() {
THREE.BufferGeometry.call( this );
var vertices = [];
for ( var i = 0; i < 100; i ++ ) {
var x = Math.random() * 800 - 400;
var y = Math.random() * 50 + 50;
var z = Math.random() * 800 - 400;
var size = Math.random() * 40 + 20;
vertices.push( x - size, y, z - size );
vertices.push( x + size, y, z - size );
vertices.push( x - size, y, z + size );
vertices.push( x + size, y, z - size );
vertices.push( x + size, y, z + size );
vertices.push( x - size, y, z + size );
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
};
SkyGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
function TreesGeometry( landscape ) {
THREE.BufferGeometry.call( this );
var vertices = [];
var colors = [];
var raycaster = new THREE.Raycaster();
raycaster.ray.direction.set( 0, -1, 0 );
for ( var i = 0; i < 2000; i ++ ) {
var x = Math.random() * 500 - 250;
var z = Math.random() * 500 - 250;
raycaster.ray.origin.set( x, 50, z );
var intersections = raycaster.intersectObject( landscape );
if ( intersections.length === 0 ) continue;
var y = intersections[ 0 ].point.y;
var height = Math.random() * 5 + 0.5;
var angle = Math.random() * Math.PI * 2;
vertices.push( x + Math.sin( angle ), y, z + Math.cos( angle ) );
vertices.push( x, y + height, z );
vertices.push( x + Math.sin( angle + Math.PI ), y, z + Math.cos( angle + Math.PI ) );
angle += Math.PI / 2;
vertices.push( x + Math.sin( angle ), y, z + Math.cos( angle ) );
vertices.push( x, y + height, z );
vertices.push( x + Math.sin( angle + Math.PI ), y, z + Math.cos( angle + Math.PI ) );
var random = Math.random() * 0.1;
for ( var j = 0; j < 6; j ++ ) {
colors.push( 0.2 + random, 0.4 + random, 0 );
}
}
this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertices ), 3 ) );
this.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( colors ), 3 ) );
};
TreesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("language","fa",{button:"تعیین زبان",remove:"حذف زبان"});
|
// Karma configuration
// Generated on Fri Nov 08 2013 09:25:16 GMT-0600 (Central Standard Time)
var util = require('../lib/grunt/utils.js');
var grunt = require('grunt');
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '../',
// frameworks to use
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
// note that the karmangular setup from util.createKarmangularConfig seems
// to take precedence over this, but we can't remove this because then
// the karmangular task doesn't appear to run. So includes the features/**/test, but
// they don't get run if you've used the --fast or --core options
files: [
'bower_components/jquery/jquery.min.js',
'lib/test/jquery.simulate.js',
'bower_components/lodash/dist/lodash.min.js',
'src/js/core/bootstrap.js',
'src/js/**/*.js',
'src/features/**/js/**/*.js',
'test/unit/**/*.spec.js',
'src/features/**/test/**/*.spec.js',
'dist/release/ui-grid.css',
'.tmp/template.js' //templates
],
// list of files to exclude
exclude: [
],
// test results reporter to use
// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: ['dots', 'coverage'],
preprocessors: {
// Cover source files but ignore any .spec.js files. Thanks goodness I found the pattern here: https://github.com/karma-runner/karma/pull/834#issuecomment-35626132
'src/**/!(*.spec)+(.js)': ['coverage']
},
coverageReporter: {
type: 'lcov',
dir: 'coverage',
subdir: '.'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera (has to be installed with `npm install karma-opera-launcher`)
// - Safari (only Mac; has to be installed with `npm install karma-safari-launcher`)
// - PhantomJS
// - IE (only Windows; has to be installed with `npm install karma-ie-launcher`)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 2,
browserNoActivityTimeout: 45000, // 20000,
sauceLabs: {
username: 'nggrid',
startConnect: false,
testName: 'ui-grid unit tests'
},
// For more browsers on Sauce Labs see:
// https://saucelabs.com/docs/platforms/webdriver
customLaunchers: util.customLaunchers()
});
// TODO(c0bra): remove once SauceLabs supports websockets.
// This speeds up the capturing a bit, as browsers don't even try to use websocket. -- (thanks vojta)
if (process.env.TRAVIS) {
config.logLevel = config.LOG_INFO;
config.browserNoActivityTimeout = 120000; // NOTE: from angular.js, for socket.io buffer
config.reporters = ['dots', 'coverage'];
var buildLabel = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')';
// config.transports = ['websocket', 'xhr-polling'];
config.sauceLabs.build = buildLabel;
config.sauceLabs.startConnect = false;
config.sauceLabs.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
config.transports = ['xhr-polling'];
// Debug logging into a file, that we print out at the end of the build.
config.loggers.push({
type: 'file',
filename: process.env.LOGS_DIR + '/' + ('karma.log')
});
// NOTE: From angular.js project, only applies to SauceLabs -- (thanks Vojta again)
// Allocating a browser can take pretty long (eg. if we are out of capacity and need to wait
// for another build to finish) and so the `captureTimeout` typically kills
// an in-queue-pending request, which makes no sense.
config.captureTimeout = 0;
}
if (grunt.option('browsers')) {
var bs = grunt.option('browsers').split(/,/).map(function(b) { return b.trim(); });
config.browsers = bs;
}
};
|
/*
Project: angular-gantt v1.2.7 - Gantt chart component for AngularJS
Authors: Marco Schweighauser, Rémi Alvergnat
License: MIT
Homepage: https://www.angular-gantt.com
Github: https://github.com/angular-gantt/angular-gantt.git
*/
(function(){
'use strict';
angular.module('gantt.drawtask', ['gantt']).directive('ganttDrawTask', ['$document', 'ganttMouseOffset', 'moment', function(document, mouseOffset, moment) {
return {
restrict: 'E',
require: '^gantt',
scope: {
enabled: '=?',
moveThreshold: '=?',
taskModelFactory: '=taskFactory'
},
link: function(scope, element, attrs, ganttCtrl) {
var api = ganttCtrl.gantt.api;
if (scope.enabled === undefined) {
scope.enabled = true;
}
if (scope.moveThreshold === undefined) {
scope.moveThreshold = 0;
}
api.directives.on.new(scope, function(directiveName, directiveScope, element) {
if (directiveName === 'ganttRow') {
var addNewTask = function(x) {
var startDate = api.core.getDateByPosition(x, true);
var endDate = moment(startDate);
var taskModel = scope.taskModelFactory();
taskModel.from = startDate;
taskModel.to = endDate;
var task = directiveScope.row.addTask(taskModel);
task.isResizing = true;
task.updatePosAndSize();
directiveScope.row.updateVisibleTasks();
directiveScope.row.$scope.$digest();
};
var deferDrawing = function(startX) {
var moveTrigger = function(evt) {
var currentX = mouseOffset.getOffset(evt).x;
if (Math.abs(startX - currentX) >= scope.moveThreshold) {
element.off('mousemove', moveTrigger);
addNewTask(startX);
}
};
element.on('mousemove', moveTrigger);
document.one('mouseup', function() {
element.off('mousemove', moveTrigger);
});
};
var drawHandler = function(evt) {
var evtTarget = (evt.target ? evt.target : evt.srcElement);
var enabled = angular.isFunction(scope.enabled) ? scope.enabled(evt): scope.enabled;
if (enabled && evtTarget.className.indexOf('gantt-row') > -1) {
var x = mouseOffset.getOffset(evt).x;
if (scope.moveThreshold === 0) {
addNewTask(x, x);
} else {
deferDrawing(x);
}
}
};
element.on('mousedown', drawHandler);
directiveScope.drawTaskHandler = drawHandler;
}
});
api.directives.on.destroy(scope, function(directiveName, directiveScope, element) {
if (directiveName === 'ganttRow') {
element.off('mousedown', directiveScope.drawTaskHandler);
delete directiveScope.drawTaskHandler;
}
});
}
};
}]);
}());
angular.module('gantt.drawtask.templates', []).run(['$templateCache', function($templateCache) {
}]);
//# sourceMappingURL=angular-gantt-drawtask-plugin.js.map
|
/*
jqGrid 4.9.1 - free jqGrid: https://github.com/free-jqgrid/jqGrid
Copyright (c) 2008-2014, Tony Tomov, tony@trirand.com
Copyright (c) 2014-2015, Oleg Kiriljuk, oleg.kiriljuk@ok-soft-gmbh.com
Dual licensed under the MIT and GPL licenses
http://www.opensource.org/licenses/mit-license.php
http://www.gnu.org/licenses/gpl-2.0.html
Date: 2015-07-23
*/
(function(a){var p={name:"English (United States)",nameEnglish:"English (United States)",isRTL:!1,defaults:{recordtext:"View {0} - {1} of {2}",emptyrecords:"No records to view",loadtext:"Loading...",pgtext:"Page {0} of {1}",pgfirst:"First Page",pglast:"Last Page",pgnext:"Next Page",pgprev:"Previous Page",pgrecs:"Records per Page",showhide:"Toggle Expand Collapse Grid",savetext:"Saving..."},search:{caption:"Search...",Find:"Find",Reset:"Reset",odata:[{oper:"eq",text:"equal"},{oper:"ne",text:"not equal"},
{oper:"lt",text:"less"},{oper:"le",text:"less or equal"},{oper:"gt",text:"greater"},{oper:"ge",text:"greater or equal"},{oper:"bw",text:"begins with"},{oper:"bn",text:"does not begin with"},{oper:"in",text:"is in"},{oper:"ni",text:"is not in"},{oper:"ew",text:"ends with"},{oper:"en",text:"does not end with"},{oper:"cn",text:"contains"},{oper:"nc",text:"does not contain"},{oper:"nu",text:"is null"},{oper:"nn",text:"is not null"}],groupOps:[{op:"AND",text:"all"},{op:"OR",text:"any"}],operandTitle:"Click to select search operation.",
resetTitle:"Reset Search Value"},edit:{addCaption:"Add Record",editCaption:"Edit Record",bSubmit:"Submit",bCancel:"Cancel",bClose:"Close",saveData:"Data has been changed! Save changes?",bYes:"Yes",bNo:"No",bExit:"Cancel",msg:{required:"Field is required",number:"Please, enter valid number",minValue:"value must be greater than or equal to ",maxValue:"value must be less than or equal to",email:"is not a valid e-mail",integer:"Please, enter valid integer value",date:"Please, enter valid date value",
url:"is not a valid URL. Prefix required ('http://' or 'https://')",nodefined:" is not defined!",novalue:" return value is required!",customarray:"Custom function should return array!",customfcheck:"Custom function should be present in case of custom checking!"}},view:{caption:"View Record",bClose:"Close"},del:{caption:"Delete",msg:"Delete selected record(s)?",bSubmit:"Delete",bCancel:"Cancel"},nav:{edittext:"",edittitle:"Edit selected row",addtext:"",addtitle:"Add new row",deltext:"",deltitle:"Delete selected row",
searchtext:"",searchtitle:"Find records",refreshtext:"",refreshtitle:"Reload Grid",alertcap:"Warning",alerttext:"Please, select row",viewtext:"",viewtitle:"View selected row"},col:{caption:"Select columns",bSubmit:"Ok",bCancel:"Cancel"},errors:{errcap:"Error",nourl:"No url is set",norecords:"No records to process",model:"Length of colNames <> colModel!"},formatter:{integer:{thousandsSeparator:",",defaultValue:"0"},number:{decimalSeparator:".",thousandsSeparator:",",decimalPlaces:2,defaultValue:"0.00"},
currency:{decimalSeparator:".",thousandsSeparator:",",decimalPlaces:2,prefix:"",suffix:"",defaultValue:"0.00"},date:{dayNames:"Sun Mon Tue Wed Thr Fri Sat Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),monthNames:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec January February March April May June July August September October November December".split(" "),AmPm:["am","pm","AM","PM"],S:function(a){var b=["st","nd","rd","th"];return 11>a||13<a?b[Math.min((a-1)%10,3)]:"th"},srcformat:"Y-m-d",
newformat:"n/j/Y",masks:{ShortDate:"n/j/Y",LongDate:"l, F d, Y",FullDateTime:"l, F d, Y g:i:s A",MonthDay:"F d",ShortTime:"g:i A",LongTime:"g:i:s A",YearMonth:"F, Y"}}}};a.jgrid=a.jgrid||{};var r=a.jgrid;r.locales=r.locales||{};var u=r.locales;if(null==r.defaults||a.isEmptyObject(u)||void 0===u["en-US"])void 0===u["en-US"]&&a.extend(!0,r,{locales:{"en-US":p}}),r.defaults=r.defaults||{},void 0===r.defaults.locale&&(r.defaults.locale="en-US");r.defaults=r.defaults||{};var n=r.defaults;a.extend(!0,r,
{version:"4.8.0",productName:"free jqGrid",defaults:{},search:{},edit:{},view:{},del:{},nav:{},col:{},errors:{},formatter:{unused:""},icons:{jQueryUI:{common:"ui-icon",pager:{first:"ui-icon-seek-first",prev:"ui-icon-seek-prev",next:"ui-icon-seek-next",last:"ui-icon-seek-end"},sort:{asc:"ui-icon-triangle-1-n",desc:"ui-icon-triangle-1-s"},gridMinimize:{visible:"ui-icon-circle-triangle-n",hidden:"ui-icon-circle-triangle-s"},nav:{edit:"ui-icon-pencil",add:"ui-icon-plus",del:"ui-icon-trash",search:"ui-icon-search",
refresh:"ui-icon-refresh",view:"ui-icon-document",save:"ui-icon-disk",cancel:"ui-icon-cancel",newbutton:"ui-icon-newwin"},actions:{edit:"ui-icon-pencil",del:"ui-icon-trash",save:"ui-icon-disk",cancel:"ui-icon-cancel"},form:{close:"ui-icon-closethick",prev:"ui-icon-triangle-1-w",next:"ui-icon-triangle-1-e",save:"ui-icon-disk",undo:"ui-icon-close",del:"ui-icon-scissors",cancel:"ui-icon-cancel",resizableLtr:"ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se"},search:{search:"ui-icon-search",reset:"ui-icon-arrowreturnthick-1-w",
query:"ui-icon-comment"},subgrid:{plus:"ui-icon-plus",minus:"ui-icon-minus",openLtr:"ui-icon-carat-1-sw",openRtl:"ui-icon-carat-1-se"},grouping:{plus:"ui-icon-circlesmall-plus",minus:"ui-icon-circlesmall-minus"},treeGrid:{minus:"ui-icon-triangle-1-s",leaf:"ui-icon-radio-off",plusLtr:"ui-icon-triangle-1-e",plusRtl:"ui-icon-triangle-1-w"}},fontAwesome:{common:"fa",pager:{common:"fa-fw",first:"fa-step-backward",prev:"fa-backward",next:"fa-forward",last:"fa-step-forward"},sort:{common:"fa-lg",asc:"fa-sort-asc",
desc:"fa-sort-desc"},gridMinimize:{visible:"fa-chevron-circle-up",hidden:"fa-chevron-circle-down"},nav:{common:"fa-lg fa-fw",edit:"fa-pencil",add:"fa-plus",del:"fa-trash-o",search:"fa-search",refresh:"fa-refresh",view:"fa-file-o",save:"fa-floppy-o",cancel:"fa-ban",newbutton:"fa-external-link"},actions:{common:"ui-state-default fa-fw",edit:"fa-pencil",del:"fa-trash-o",save:"fa-floppy-o",cancel:"fa-ban"},form:{close:"fa-times",prev:"fa-caret-left",next:"fa-caret-right",save:"fa-floppy-o",undo:"fa-undo",
del:"fa-trash-o",cancel:"fa-ban",resizableLtr:"ui-resizable-se ui-state-default fa fa-rss fa-rotate-270"},search:{search:"fa-search",reset:"fa-undo",query:"fa-comments-o"},subgrid:{common:"ui-state-default fa-fw",plus:"fa-plus",minus:"fa-minus",openLtr:"fa-reply fa-rotate-180",openRtl:"fa-share fa-rotate-180"},grouping:{common:"fa-fw",plus:"fa-plus-square-o",minus:"fa-minus-square-o"},treeGrid:{common:"fa-fw",minus:"fa-lg fa-sort-desc",leaf:"fa-dot-circle-o",plusLtr:"fa-lg fa-caret-right",plusRtl:"fa-lg fa-caret-left"}}},
guiStyles:{jQueryUI:{gBox:"ui-widget ui-widget-content ui-corner-all",overlay:"ui-widget-overlay",loading:"ui-state-default ui-state-active",hDiv:"ui-state-default ui-corner-top",hTable:"",colHeaders:"ui-state-default",states:{select:"ui-state-highlight",disabled:"ui-state-disabled ui-jqgrid-disablePointerEvents",hover:"ui-state-hover",error:"ui-state-error",active:"ui-state-active",textOfClickable:"ui-state-default"},dialog:{header:"ui-widget-header ui-dialog-titlebar ui-corner-all ui-helper-clearfix",
window:"ui-widget ui-widget-content ui-corner-all ui-front",content:"ui-widget-content",hr:"ui-widget-content",fmButton:"ui-state-default",dataField:"ui-widget-content ui-corner-all",viewLabel:"ui-widget-content",viewData:"ui-widget-content",leftCorner:"ui-corner-left",rightCorner:"ui-corner-right",defaultCorner:"ui-corner-all"},filterToolbar:{dataField:"ui-widget-content"},subgrid:{thSubgrid:"ui-state-default test",rowSubTable:"ui-widget-content",row:"ui-widget-content",tdStart:"",tdWithIcon:"ui-widget-content",
tdData:"ui-widget-content"},grid:"",gridRow:"ui-widget-content",rowNum:"ui-state-default",gridFooter:"",rowFooter:"ui-widget-content",gridTitle:"ui-widget-header ui-corner-top",titleButton:"ui-corner-all",toolbarUpper:"ui-state-default",toolbarBottom:"ui-state-default",pager:"ui-state-default",pagerButton:"ui-corner-all",pagerInput:"ui-widget-content",pagerSelect:"ui-widget-content",top:"ui-corner-top",bottom:"ui-corner-bottom",resizer:"ui-widget-header"}},htmlDecode:function(a){return a&&(" "===
a||" "===a||1===a.length&&160===a.charCodeAt(0))?"":a?String(a).replace(/>/g,">").replace(/</g,"<").replace(/"/g,'"').replace(/&/g,"&"):a},htmlEncode:function(a){return a?String(a).replace(/&/g,"&").replace(/\"/g,""").replace(/</g,"<").replace(/>/g,">"):a},clearArray:function(a){for(;0<a.length;)a.pop()},format:function(b){var c=a.makeArray(arguments).slice(1);null==b&&(b="");return b.replace(/\{(\d+)\}/g,function(a,b){return c[b]})},template:function(b){var c=a.makeArray(arguments).slice(1),
d,v=c.length;null==b&&(b="");return b.replace(/\{([\w\-]+)(?:\:([\w\.]*)(?:\((\.*?)?\))?)?\}/g,function(b,B){var e,l;if(!isNaN(parseInt(B,10)))return c[parseInt(B,10)];for(d=0;d<v;d++)if(a.isArray(c[d]))for(e=c[d],l=e.length;l--;)if(B===e[l].nm)return e[l].v})},msie:"Microsoft Internet Explorer"===navigator.appName,msiever:function(){var a=-1,b=/(MSIE) ([0-9]{1,}[.0-9]{0,})/.exec(navigator.userAgent);null!=b&&3===b.length&&(a=parseFloat(b[2]||-1));return a},fixMaxHeightOfDiv:function(a){return"Microsoft Internet Explorer"===
navigator.appName?Math.min(a,1533917):null!=/(Firefox)/.exec(navigator.userAgent)?Math.min(a,17895696):a},getCellIndex:function(b){b=a(b);if(b.is("tr"))return-1;b=(b.is("td")||b.is("th")?b:b.closest("td,th"))[0];return null==b?-1:r.msie?a.inArray(b,b.parentNode.cells):b.cellIndex},stripHtml:function(a){return(a=String(a))?(a=a.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,""))&&" "!==a&&" "!==a?a.replace(/\"/g,"'"):"":a},stripPref:function(b,c){var d=a.type(b);if("string"===d||"number"===d)b=
String(b),c=""!==b?String(c).replace(String(b),""):c;return c},parse:function(b){"while(1);"===b.substr(0,9)&&(b=b.substr(9));"/*"===b.substr(0,2)&&(b=b.substr(2,b.length-4));b||(b="{}");return!0===r.useJSON&&"object"===typeof JSON&&a.isFunction(JSON.parse)?JSON.parse(b):eval("("+b+")")},getRes:function(a,b){var c=b.split("."),d=c.length,e;if(null!=a){for(e=0;e<d;e++){if(!c[e])return null;a=a[c[e]];if(void 0===a)break;if("string"===typeof a)break}return a}},parseDate:function(b,c,d,v){var e,l,f,g=
0,h=0;e="string"===typeof c?c.match(/^\/Date\((([\-+])?[0-9]+)(([\-+])([0-9]{2})([0-9]{2}))?\)\/$/):null;var m=function(a,b){a=String(a);for(b=parseInt(b,10)||2;a.length<b;)a="0"+a;return a},g={m:1,d:1,y:1970,h:0,i:0,s:0,u:0},t=function(a,b){0===a?12===b&&(b=0):12!==b&&(b+=12);return b};v=a.extend(!0,{},(r.formatter||{}).date,null!=this.p?r.getRes(u[this.p.locale],"formatter.date")||{}:{},v||{});void 0===v.parseRe&&(v.parseRe=/[#%\\\/:_;.,\t\s\-]/);v.masks.hasOwnProperty(b)&&(b=v.masks[b]);if(c&&
null!=c)if(isNaN(c)||"u"!==String(b).toLowerCase())if(c.constructor===Date)g=c;else if(null!==e)g=new Date(parseInt(e[1],10)),e[3]&&(h=60*Number(e[5])+Number(e[6]),h*="-"===e[4]?1:-1,h-=g.getTimezoneOffset(),g.setTime(Number(Number(g)+6E4*h)));else{"ISO8601Long"===v.srcformat&&"Z"===c.charAt(c.length-1)&&(h-=(new Date).getTimezoneOffset());c=String(c).replace(/\T/g,"#").replace(/\t/,"%").split(v.parseRe);b=b.replace(/\T/g,"#").replace(/\t/,"%").split(v.parseRe);l=0;for(f=Math.min(b.length,c.length);l<
f;l++){switch(b[l]){case "M":e=a.inArray(c[l],v.monthNames);-1!==e&&12>e&&(c[l]=e+1,g.m=c[l]);break;case "F":e=a.inArray(c[l],v.monthNames,12);-1!==e&&11<e&&(c[l]=e+1-12,g.m=c[l]);break;case "n":g.m=parseInt(c[l],10);break;case "j":g.d=parseInt(c[l],10);break;case "g":g.h=parseInt(c[l],10);break;case "a":e=a.inArray(c[l],v.AmPm);-1!==e&&2>e&&c[l]===v.AmPm[e]&&(c[l]=e,g.h=t(c[l],g.h));break;case "A":e=a.inArray(c[l],v.AmPm),-1!==e&&1<e&&c[l]===v.AmPm[e]&&(c[l]=e-2,g.h=t(c[l],g.h))}void 0!==c[l]&&(g[b[l].toLowerCase()]=
parseInt(c[l],10))}g.f&&(g.m=g.f);if(0===g.m&&0===g.y&&0===g.d)return" ";g.m=parseInt(g.m,10)-1;b=g.y;70<=b&&99>=b?g.y=1900+g.y:0<=b&&69>=b&&(g.y=2E3+g.y);g=new Date(g.y,g.m,g.d,g.h,g.i,g.s,g.u);0<h&&g.setTime(Number(Number(g)+6E4*h))}else g=new Date(1E3*parseFloat(c));else g=new Date(g.y,g.m,g.d,g.h,g.i,g.s,g.u);v.userLocalTime&&0===h&&(h-=(new Date).getTimezoneOffset(),0<h&&g.setTime(Number(Number(g)+6E4*h)));if(void 0===d)return g;v.masks.hasOwnProperty(d)?d=v.masks[d]:d||(d="Y-m-d");h=g.getHours();
b=g.getMinutes();c=g.getDate();t=g.getMonth()+1;e=g.getTimezoneOffset();l=g.getSeconds();f=g.getMilliseconds();var q=g.getDay(),n=g.getFullYear(),A=(q+6)%7+1,p=(new Date(n,t-1,c)-new Date(n,0,1))/864E5,w=5>A?Math.floor((p+A-1)/7)+1:Math.floor((p+A-1)/7)||(4>((new Date(n-1,0,1)).getDay()+6)%7?53:52),x={d:m(c),D:v.dayNames[q],j:c,l:v.dayNames[q+7],N:A,S:v.S(c),w:q,z:p,W:w,F:v.monthNames[t-1+12],m:m(t),M:v.monthNames[t-1],n:t,t:"?",L:"?",o:"?",Y:n,y:String(n).substring(2),a:12>h?v.AmPm[0]:v.AmPm[1],
A:12>h?v.AmPm[2]:v.AmPm[3],B:"?",g:h%12||12,G:h,h:m(h%12||12),H:m(h),i:m(b),s:m(l),u:f,e:"?",I:"?",O:(0<e?"-":"+")+m(100*Math.floor(Math.abs(e)/60)+Math.abs(e)%60,4),P:"?",T:(String(g).match(/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[\-+]\d{4})?)\b/g)||[""]).pop().replace(/[^\-+\dA-Z]/g,""),Z:"?",c:"?",r:"?",U:Math.floor(g/1E3)};return d.replace(/\\.|[dDjlNSwzWFmMntLoYyaABgGhHisueIOPTZcrU]/g,function(a){return x.hasOwnProperty(a)?
x[a]:a.substring(1)})},jqID:function(a){return String(a).replace(/[!"#$%&'()*+,.\/:; <=>?@\[\\\]\^`{|}~]/g,"\\$&")},getGridComponentId:function(a){if(null==this.p||!this.p.id)return"";var b=this.p.id;switch(a){case 21:return b;case 0:return"gbox_"+b;case 8:return"gview_"+b;case 3:return"alertmod_"+b;case 43:return"rs_m"+b;case 45:return"cb_"+b;case 46:return"sopt_menu";default:return""}},getGridComponentIdSelector:function(a){return(a=r.getGridComponentId.call(this,a))?"#"+r.jqID(a):""},isHTMLElement:function(a){return"object"===
typeof HTMLElement||"function"===typeof HTMLElement?a instanceof HTMLElement:null!=a&&"object"===typeof a&&1===a.nodeType&&"string"===typeof a.nodeName},getGridComponent:function(b,c){var d;if(c instanceof a||0<c.length)d=c[0];else if(r.isHTMLElement(c))d=c,c=a(d);else return a();switch(b){case 21:return c.hasClass("ui-jqgrid-bdiv")?c.find(">div>.ui-jqgrid-btable"):a();case 14:return c.hasClass("ui-jqgrid-hdiv")?c.find(">div>.ui-jqgrid-htable"):a();case 27:return c.hasClass("ui-jqgrid-sdiv")?c.find(">div>.ui-jqgrid-ftable"):
a();case 31:return c.hasClass("ui-jqgrid-hdiv")?c.children(".ui-jqgrid-htable"):a();case 36:return c.hasClass("ui-jqgrid-sdiv")?c.children(".ui-jqgrid-ftable"):a();case 18:return c.hasClass("ui-jqgrid-btable")&&null!=d.grid?a(d.grid.bDiv):a();case 12:return c.hasClass("ui-jqgrid-btable")&&null!=d.grid?a(d.grid.hDiv):a();case 25:return c.hasClass("ui-jqgrid-btable")&&null!=d.grid?a(d.grid.sDiv):a();default:return a()}},fixScrollOffsetAndhBoxPadding:function(){var b=this.grid;if(b){var c=this.p,d=b.bDiv,
e=function(b){var e=a(b).children("div").first();e.css(e.hasClass("ui-jqgrid-hbox-rtl")?"padding-left":"padding-right",c.scrollOffset);b.scrollLeft=d.scrollLeft};0<a(d).width()&&(c.scrollOffset=d.offsetWidth-d.clientWidth,e(b.hDiv),b.sDiv&&e(b.sDiv))}},mergeCssClasses:function(){var b=a.makeArray(arguments),c={},d,e,g,l,f=[];for(d=0;d<b.length;d++)for(g=String(b[d]).split(" "),e=0;e<g.length;e++)l=g[e],""===l||c.hasOwnProperty(l)||(c[l]=!0,f.push(l));return f.join(" ")},hasOneFromClasses:function(b,
c){var d=a(b),e=c.split(" "),g,l=e.length;for(g=0;g<l;g++)if(d.hasClass(e[g]))return!0;return!1},detectRowEditing:function(b){var c,d,e,g=this.rows,l=this.p,f=a.isFunction;if(!this.grid||null==g||null==l||void 0===l.savedRow||0===l.savedRow.length)return null;for(c=0;c<l.savedRow.length;c++)if(d=l.savedRow[c],"number"===typeof d.id&&"number"===typeof d.ic&&void 0!==d.name&&void 0!==d.v&&null!=g[d.id]&&g[d.id].id===b&&f(a.fn.jqGrid.restoreCell)){if(e=g[d.id],null!=e&&e.id===b)return{mode:"cellEditing",
savedRow:d}}else if(d.id===b&&f(a.fn.jqGrid.restoreRow))return{mode:"inlineEditing",savedRow:d};return null},getCell:function(b,c){var d=this.grid,e=this.p;if(!d||!e)return a();if(b instanceof a||0<b.length)b=b[0];if("object"!==typeof HTMLTableRowElement&&"function"!==typeof HTMLTableRowElement||!(b instanceof HTMLTableRowElement)||null==b.cells)return a();e=a(b.cells[c]);d=d.fbRows;return null!=d&&c<d[0].cells.length?e.add(d[b.rowIndex].cells[c]):e},getDataFieldOfCell:function(a,b){var c=this.p,
d=r.getCell.call(this,a,b);c.treeGrid&&0<d.children("div.tree-wrap").length&&(d=d.children("span.cell-wrapperleaf,span.cell-wrapper"));return c.colModel[b].autoResizable?d.children("span."+c.autoResizing.wrapperClassName):d},enumEditableCells:function(b,c,d){var e=this.grid,g=this.rows,l=this.p;if(null==e||null==g||null==l||null==b||null==b.rowIndex||!b.id||!a.isFunction(d))return null;var f,g=l.colModel,h=g.length,m,t,q=b.rowIndex,n,A,p;f=e.fbRows;var w=(e=null!=f)?f[q]:null;e&&(b=this.rows[q]);
for(f=0;f<h&&(m=g[f],t=m.name,"cb"===t||"subgrid"===t||"rn"===t||(e&&!m.frozen&&(e=!1),n=(e?w:b).cells[f],A=a(n),A.hasClass("not-editable-cell")||(p=A.width(),!0===l.treeGrid&&t===l.ExpandColumn?(p-=A.children("div.tree-wrap").outerWidth(),A=A.children("span.cell-wrapperleaf,span.cell-wrapper").first()):p=0,t={rowid:b.id,iCol:f,iRow:q,cmName:t,cm:m,mode:c,td:n,tr:b,trFrozen:w,dataElement:A[0],dataWidth:p},m.edittype||(m.edittype="text"),m=m.editable,m=a.isFunction(m)?m.call(this,t):m,!0!==m||!1!==
d.call(this,t))));f++);},getEditedValue:function(b,c,d){var e,g,l=d?"text":"val",f=c.formatoptions||{};d=c.editoptions||{};var h=d.custom_value,m="[name="+r.jqID(c.name)+"]",t=a(this);switch(c.edittype){case "checkbox":e=["Yes","No"];"string"===typeof d.value&&(e=d.value.split(":"));e=b.find("input[type=checkbox]").is(":checked")?e[0]:e[1];break;case "text":case "password":case "textarea":case "button":b=b.find("input"+m+",textarea"+m);e=b.val();"date"===b[this.p.propOrAttr]("type")&&3===String(e).split("-").length&&
(b=f.newformat||t.jqGrid("getGridRes","formatter.date.newformat"),e=r.parseDate.call(this,"Y-m-d",e,b));break;case "select":b=b.find("select option:selected");d.multiple?(g=[],b.each(function(){g.push(a(this)[l]())}),e=g.join(",")):e=b[l]();break;case "custom":try{if(a.isFunction(h)){if(e=h.call(this,b.find(".customelement"),"get"),void 0===e)throw"e2";}else throw"e1";}catch(q){b=r.info_dialog,d=function(a){t.jqGrid("getGridRes",a)},c=d("errors.errcap"),f=d("edit.bClose"),"e1"===q&&b.call(this,c,
"function 'custom_value' "+d("edit.msg.nodefined"),f),"e2"===q?b.call(this,c,"function 'custom_value' "+d("edit.msg.novalue"),f):b.call(this,c,q.message,f)}break;default:e=b.find("*"+m).text()}return e},guid:1,uidPref:"jqg",randId:function(a){return(a||r.uidPref)+r.guid++},getAccessor:function(b,c){var d,e,g=[],l;if(a.isFunction(c))return c(b);d=b[c];if(void 0===d)try{if("string"===typeof c&&(g=c.split(".")),l=g.length)for(d=b;d&&l--;)e=g.shift(),d=d[e]}catch(f){}return d},getXmlData:function(b,c,
d){var e="string"===typeof c?c.match(/^(.*)\[(\w+)\]$/):null;if(a.isFunction(c))return c(b);if(e&&e[2])return e[1]?a(e[1],b).attr(e[2]):a(b).attr(e[2]);void 0===b&&alert("expr");b=a(b).find(c);return d?b:0<b.length?a(b).text():void 0},cellWidth:function(){var b=a("<div class='ui-jqgrid' style='left:10000px'><div class='ui-jqgrid-view'><div class='ui-jqgrid-bdiv'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;display:block;'></td></tr></table></div></div></div>"),
c=b.appendTo("body").find("td").width();b.remove();return.1<Math.abs(c-5)},isCellClassHidden:function(b){b=a("<div class='ui-jqgrid' style='left:10000px'><div class='ui-jqgrid-view'><div class='ui-jqgrid-bdiv'><table class='ui-jqgrid-btable' style='width:5px;'><tr class='jqgrow'><td style='width:5px;' class='"+(b||"")+"'></td></tr></table></div></div></div>");var c=b.appendTo("body").find("td").is(":hidden");b.remove();return c},cell_width:!0,ajaxOptions:{},from:function(b){var c=this;return new function(b,
d){var e=this,g=b,l=!0,f=!1,h=d,m=/[\$,%]/g,B=null,t=null,q=0,n=!1,A="",p=[],w=Object.prototype.toString,C=!0;if("object"===typeof b&&b.push)0<b.length&&(C="object"!==typeof b[0]?!1:!0);else throw"data provides is not an array";this._hasData=function(){return null===g?!1:0===g.length?!1:!0};this._getStr=function(a){var b=[];f&&b.push("jQuery.trim(");b.push("String("+a+")");f&&b.push(")");l||b.push(".toUpperCase()");return b.join("")};this._strComp=function(a){return"string"===typeof a?".toString()":
""};this._group=function(a,b){return{field:a.toString(),unique:b,items:[]}};this._toStr=function(b){f&&(b=a.trim(b));b=b.toString().replace(/\\/g,"\\\\").replace(/\"/g,'\\"');return l?b:b.toUpperCase()};this._funcLoop=function(b){var c=[];a.each(g,function(a,e){c.push(b(e))});return c};this._append=function(a){var b;h=null===h?"":h+(""===A?" && ":A);for(b=0;b<q;b++)h+="(";n&&(h+="!");h+="("+a+")";n=!1;A="";q=0};this._setCommand=function(a,b){B=a;t=b};this._resetNegate=function(){n=!1};this._repeatCommand=
function(a,b){return null===B?e:null!==a&&null!==b?B(a,b):null!==t&&C?B(t,a):B(a)};this._equals=function(a,b){return 0===e._compare(a,b,1)};this._compare=function(a,b,c){void 0===c&&(c=1);void 0===a&&(a=null);void 0===b&&(b=null);if(null===a&&null===b)return 0;if(null===a&&null!==b)return 1;if(null!==a&&null===b)return-1;if("[object Date]"===w.call(a)&&"[object Date]"===w.call(b))return a<b?-c:a>b?c:0;l||"number"===typeof a||"number"===typeof b||(a=String(a),b=String(b));return a<b?-c:a>b?c:0};this._performSort=
function(){0!==p.length&&(g=e._doSort(g,0))};this._doSort=function(a,b){var c=p[b].by,d=p[b].dir,k=p[b].type,g=p[b].datefmt,l=p[b].sfunc;if(b===p.length-1)return e._getOrder(a,c,d,k,g,l);b++;c=e._getGroup(a,c,d,k,g);d=[];for(k=0;k<c.length;k++)for(l=e._doSort(c[k].items,b),g=0;g<l.length;g++)d.push(l[g]);return d};this._getOrder=function(b,d,g,f,k,v){var h=[],B=[],z="a"===g?1:-1,t,q;void 0===f&&(f="text");q="float"===f||"number"===f||"currency"===f||"numeric"===f?function(a){a=parseFloat(String(a).replace(m,
""));return isNaN(a)?Number.NEGATIVE_INFINITY:a}:"int"===f||"integer"===f?function(a){return a?parseFloat(String(a).replace(m,"")):Number.NEGATIVE_INFINITY}:"date"===f||"datetime"===f?function(a){return r.parseDate.call(c,k,a).getTime()}:a.isFunction(f)?f:function(b){b=null!=b?a.trim(String(b)):"";return l?b:b.toUpperCase()};a.each(b,function(a,b){t=""!==d?r.getAccessor(b,d):b;void 0===t&&(t="");t=q(t,b);B.push({vSort:t,index:a})});a.isFunction(v)?B.sort(function(a,b){a=a.vSort;b=b.vSort;return v.call(this,
a,b,z)}):B.sort(function(a,b){a=a.vSort;b=b.vSort;return e._compare(a,b,z)});f=0;for(var n=b.length;f<n;)g=B[f].index,h.push(b[g]),f++;return h};this._getGroup=function(b,c,d,g,k){var l=[],f=null,v=null;a.each(e._getOrder(b,c,d,g,k),function(a,b){var k=r.getAccessor(b,c);null==k&&(k="");e._equals(v,k)||(v=k,null!==f&&l.push(f),f=e._group(c,k));f.items.push(b)});null!==f&&l.push(f);return l};this.ignoreCase=function(){l=!1;return e};this.useCase=function(){l=!0;return e};this.trim=function(){f=!0;
return e};this.noTrim=function(){f=!1;return e};this.execute=function(){var b=h,c=[];if(null===b)return e;a.each(g,function(){eval(b)&&c.push(this)});g=c;return e};this.data=function(){return g};this.select=function(b){e._performSort();if(!e._hasData())return[];e.execute();if(a.isFunction(b)){var c=[];a.each(g,function(a,e){c.push(b(e))});return c}return g};this.hasMatch=function(){if(!e._hasData())return!1;e.execute();return 0<g.length};this.andNot=function(a,b,c){n=!n;return e.and(a,b,c)};this.orNot=
function(a,b,c){n=!n;return e.or(a,b,c)};this.not=function(a,b,c){return e.andNot(a,b,c)};this.and=function(a,b,c){A=" && ";return void 0===a?e:e._repeatCommand(a,b,c)};this.or=function(a,b,c){A=" || ";return void 0===a?e:e._repeatCommand(a,b,c)};this.orBegin=function(){q++;return e};this.orEnd=function(){null!==h&&(h+=")");return e};this.isNot=function(a){n=!n;return e.is(a)};this.is=function(a){e._append("this."+a);e._resetNegate();return e};this._compareValues=function(a,b,d,g,k){var l;l=C?b:"this";
void 0===d&&(d=null);var f=d,v=void 0===k.stype?"text":k.stype;if(null!==d)switch(v){case "int":case "integer":f=String(f).replace(m,"");f=isNaN(Number(f))||""===f?"0":Number(f);l="parseInt("+l+",10)";f=String(parseInt(f,10));break;case "float":case "number":case "currency":case "numeric":f=String(f).replace(m,"");f=isNaN(Number(f))||""===f?"0":Number(f);l="parseFloat("+l+")";f=String(f);break;case "date":case "datetime":f=String(r.parseDate.call(c,k.newfmt||"Y-m-d",f).getTime());l='jQuery.jgrid.parseDate.call(jQuery("'+
c.p.idSel+'")[0],"'+k.srcfmt+'",'+l+").getTime()";break;default:l=e._getStr(l),f=e._getStr('"'+e._toStr(f)+'"')}e._append(l+" "+g+" "+f);e._setCommand(a,b);e._resetNegate();return e};this.equals=function(a,b,c){return e._compareValues(e.equals,a,b,"==",c)};this.notEquals=function(a,b,c){return e._compareValues(e.equals,a,b,"!==",c)};this.isNull=function(a,b,c){return e._compareValues(e.equals,a,null,"===",c)};this.greater=function(a,b,c){return e._compareValues(e.greater,a,b,">",c)};this.less=function(a,
b,c){return e._compareValues(e.less,a,b,"<",c)};this.greaterOrEquals=function(a,b,c){return e._compareValues(e.greaterOrEquals,a,b,">=",c)};this.lessOrEquals=function(a,b,c){return e._compareValues(e.lessOrEquals,a,b,"<=",c)};this.startsWith=function(b,c){var d=null==c?b:c,d=f?a.trim(d.toString()).length:d.toString().length;C?e._append(e._getStr(b)+".substr(0,"+d+") == "+e._getStr('"'+e._toStr(c)+'"')):(null!=c&&(d=f?a.trim(c.toString()).length:c.toString().length),e._append(e._getStr("this")+".substr(0,"+
d+") == "+e._getStr('"'+e._toStr(b)+'"')));e._setCommand(e.startsWith,b);e._resetNegate();return e};this.endsWith=function(b,c){var d=null==c?b:c,d=f?a.trim(d.toString()).length:d.toString().length;C?e._append(e._getStr(b)+".substr("+e._getStr(b)+".length-"+d+","+d+') == "'+e._toStr(c)+'"'):e._append(e._getStr("this")+".substr("+e._getStr("this")+'.length-"'+e._toStr(b)+'".length,"'+e._toStr(b)+'".length) == "'+e._toStr(b)+'"');e._setCommand(e.endsWith,b);e._resetNegate();return e};this.contains=
function(a,b){C?e._append(e._getStr(a)+'.indexOf("'+e._toStr(b)+'",0) > -1'):e._append(e._getStr("this")+'.indexOf("'+e._toStr(a)+'",0) > -1');e._setCommand(e.contains,a);e._resetNegate();return e};this.groupBy=function(a,b,c,d){return e._hasData()?e._getGroup(g,a,b,c,d):null};this.orderBy=function(b,c,d,g,k){c=null==c?"a":a.trim(c.toString().toLowerCase());null==d&&(d="text");null==g&&(g="Y-m-d");null==k&&(k=!1);if("desc"===c||"descending"===c)c="d";if("asc"===c||"ascending"===c)c="a";p.push({by:b,
dir:c,type:d,datefmt:g,sfunc:k});return e};this.custom=function(a,b,d){e._append('jQuery("'+c.p.idSel+'")[0].p.customSortOperations.'+a+'.filter.call(jQuery("'+c.p.idSel+'")[0],{item:this,cmName:"'+b+'",searchValue:"'+d+'"})');e._setCommand(e.custom,b);e._resetNegate();return e};return e}("string"===typeof b?a.data(b):b,null)},serializeFeedback:function(b,c,d){var e=this;e instanceof a&&0<e.length&&(e=e[0]);if("string"===typeof d)return d;c=a(e).triggerHandler(c,d);if("string"===typeof c)return c;
if(null==c||"object"!==typeof c)c=d;return a.isFunction(b)?b.call(e,c):c},fullBoolFeedback:function(b,c){var d=a.makeArray(arguments).slice(2),e=a(this).triggerHandler(c,d),e=!1===e||"stop"===e?!1:!0;a.isFunction(b)&&(d=b.apply(this,d),!1===d||"stop"===d)&&(e=!1);return e},feedback:function(b,c,d,e){var g=this;g instanceof a&&0<g.length&&(g=g[0]);if(null==b||"string"!==typeof e||2>e.length)return null;var l="on"===e.substring(0,2)?"jqGrid"+c+e.charAt(2).toUpperCase()+e.substring(3):"jqGrid"+c+e.charAt(0).toUpperCase()+
e.substring(1),f=a.makeArray(arguments).slice(4),h=b[e+d];f.unshift(l);f.unshift(h);return r.fullBoolFeedback.apply(g,f)},getIconRes:function(a,b){var c=b.split("."),e,d=c.length,g,l,f=[];a=r.icons[a];if(null==a)return"";e=a;e.common&&f.push(e.common);for(l=0;l<d;l++){g=c[l];if(!g)break;e=e[g];if(void 0===e){if("common"===g)break;return""}if("string"===typeof e){f.push(e);break}null!=e&&e.common&&f.push(e.common)}return r.mergeCssClasses.apply(this,f)},builderSortIcons:function(){var a=this.p,b=r.getRes(r.guiStyles[a.guiStyle],
"states.disabled"),c=function(c){return r.mergeCssClasses("ui-grid-ico-sort","ui-icon-"+c,"horizontal"===a.viewsortcols[1]?"ui-i-"+c:"",b,r.getIconRes(a.iconSet,"sort."+c),"ui-sort-"+a.direction)};return"<span class='s-ico"+(a.sortIconsBeforeText?" jqgrid-icons-first":"")+"' style='display:none'><span class='"+c("asc")+"'></span><span class='"+c("desc")+"'></span></span>"},builderFmButon:function(a,b,c,e,d){var g=this.p;return null==g?"":"<a id='"+a+"' class='"+r.mergeCssClasses("fm-button",r.getRes(r.guiStyles[g.guiStyle],
"dialog.fmButton"),r.getRes(r.guiStyles[g.guiStyle],"dialog."+("right"===d?"rightCorner":"left"===d?"leftCorner":"defaultCorner")),"right"===e?"fm-button-icon-right":"left"===e?"fm-button-icon-left":"")+"' role='button' tabindex='0'>"+(c?"<span class='fm-button-icon "+(r.getIconRes(g.iconSet,c)||c)+"'></span>":"")+(b?"<span class='fm-button-text'>"+b+"</span>":"")+"</a>"},convertOnSaveLocally:function(b,c,e,d,g,l){if(null==this.p)return b;if(a.isFunction(c.convertOnSave))return c.convertOnSave.call(this,
{newValue:b,cm:c,oldValue:e,id:d,item:g,iCol:l});if("boolean"!==typeof e&&"number"!==typeof e)return b;"boolean"!==typeof e||"checkbox"!==c.edittype&&"checkbox"!==c.formatter?"number"!==typeof e||isNaN(b)||("number"===c.formatter||"currency"===c.formatter?b=parseFloat(b):"integer"===c.formatter&&(b=parseInt(b,10))):(e=String(b).toLowerCase(),c=null!=c.editoptions&&"string"===typeof c.editoptions.value?c.editoptions.value.split(":"):["yes","no"],0<=a.inArray(e,["1","true",c[0].toLowerCase()])?b=!0:
0<=a.inArray(e,["0","false",c[1].toLowerCase()])&&(b=!1));return b},parseDataToHtml:function(b,c,e,d,g,l,f){var h=this,m=h.p,t=a(h),q,n,A,p,w,C,x,E=!1,y=[],u=!0===m.altRows?m.altclass:"",K=[],L=m.grouping?!0===m.groupingView.groupCollapse:!1,k=parseInt(m.rowNum,10),R,W=a.fn.jqGrid,ba=!0===m.treeGrid&&-1<m.treeANode?h.rows[m.treeANode].rowIndex+1:h.rows.length,ca=h.formatCol,ha=function(a,b,c,k,e,d){b=h.formatter(a,b,c,e,"add",d);return"<td role='gridcell' "+ca(c,k,b,e,a,d)+">"+b+"</td>"},ja=function(a,
b,c,k){return"<td role='gridcell' "+ca(b,c,"",null,a,!0)+"><input role='checkbox' type='checkbox' id='jqg_"+m.id+"_"+a+"' class='cbox' name='jqg_"+m.id+"_"+a+"'"+(k?" checked='checked' aria-checked='true'":" aria-checked='false'")+"/></td>"},da=function(a,b,c,k){c=(parseInt(c,10)-1)*parseInt(k,10)+1+b;return"<td role='gridcell' class='"+W.getGuiStyles.call(t,"rowNum","jqgrid-rownum")+"' "+ca(a,b,c,null,b,!0)+">"+c+"</td>"};1>=ba&&(m.rowIndexes={});"local"!==m.datatype||m.deselectAfterSort||(E=!0);
l&&(k*=l+1);for(l=0;l<Math.min(b,k);l++){p=c[l];w=e[l];C=null!=d?d[l]:w;q=1===g?0:g;n=1===(q+l)%2?u:"";E&&(A=m.multiselect?-1!==a.inArray(p,m.selarrrow):p===m.selrow);x=y.length;y.push("");for(q=0;q<m.colModel.length;q++)switch(R=m.colModel[q].name,R){case "rn":y.push(da(q,l,m.page,m.rowNum));break;case "cb":y.push(ja(p,q,l,A));break;case "subgrid":y.push(W.addSubGridCell.call(t,q,l+g));break;default:y.push(ha(p,w[R],q,l+g,C,w))}y[x]=h.constructTr(p,L,n,w,C,A);y.push("</tr>");m.rowIndexes[p]=ba;ba++;
m.grouping&&(K.push(y),m.groupingView._locgr||W.groupingPrepare.call(t,w,l),y=[]);y.length>m.maxItemsToJoin&&(y=[y.join("")])}m.grouping&&(f&&(m.groupingView._locgr=!0),y=[W.groupingRender.call(t,K,m.colModel.length,m.page,k)],r.clearArray(K));return y},getMethod:function(b){return this.getAccessor(a.fn.jqGrid,b)},extend:function(b){a.extend(a.fn.jqGrid,b);this.no_legacy_api||a.fn.extend(b)}});var d=r.clearArray,f=r.jqID,h=r.getGridComponentIdSelector,b=r.getGridComponentId,c=r.getGridComponent,e=
r.stripPref,l=r.randId,m=r.getAccessor,g=r.convertOnSaveLocally,t=r.stripHtml,w=r.htmlEncode,A=r.htmlDecode,q=r.mergeCssClasses,y=r.hasOneFromClasses,E=function(){var b=a.makeArray(arguments);b.unshift("");b.unshift("");b.unshift(this.p);return r.feedback.apply(this,b)};a.fn.jqGrid=function(g){var D=a.fn.jqGrid,z;if("string"===typeof g){z=D[g];if(!z)throw"jqGrid - No such method: "+g;return z.apply(this,a.makeArray(arguments).slice(1))}return this.each(function(){if(!this.grid){var v=this,z,A,G=a(v),
p=a.isFunction,C=a.isArray,F=a.extend,J=a.inArray,H=a.trim,N=a.each,Y=D.setSelection,X=D.getGridRes,T=p(n.fatalError)?n.fatalError:alert,x=g.locale||n.locale||"en-US",O=null!=u[x]&&"boolean"===typeof u[x].isRTL?u[x].isRTL?"rtl":"ltr":"ltr",aa=g.iconSet||n.iconSet||"jQueryUI",Q=g.guiStyle||n.guiStyle||"jQueryUI",K=function(a){return r.getIconRes(aa,a)},L=function(a,b){return q(r.getRes(r.guiStyles[Q],a),b||"")};null==g&&(g={datatype:"local"});void 0!==g.datastr&&C(g.datastr)&&(A=g.datastr,g.datastr=
[]);void 0!==g.data&&(z=g.data,g.data=[]);null!=r.formatter&&null!=r.formatter.unused||T("CRITICAL ERROR!!!\n\n\nOne uses probably\n\n\t$.extend($.jgrid.defaults, {...});\n\nto set default settings of jqGrid instead of the usage the DEEP version of jQuery.extend (with true as the first parameter):\n\n\t$.extend(true, $.jgrid.defaults, {...});\n\nOne other possible reason:\n\nyou included some OLD version of language file (grid.locale-en.js for example) AFTER jquery.jqGrid.min.js. For example all language files of jqGrid 4.7.0 uses non-deep call of jQuery.extend.\n\n\nSome options of jqGrid could still work, but another one will be broken.");
void 0===g.datatype&&void 0!==g.dataType&&(g.datatype=g.dataType,delete g.dataType);void 0===g.mtype&&void 0!==g.type&&(g.mtype=g.type,delete g.type);var k=F(!0,{height:"auto",page:1,rowNum:20,maxRowNum:1E4,autoresizeOnLoad:!1,columnsToReResizing:[],autoResizing:{wrapperClassName:"ui-jqgrid-cell-wrapper",minColWidth:33,maxColWidth:300,adjustGridWidth:!0,compact:!1,fixWidthOnShrink:!1},doubleClickSensitivity:250,minResizingWidth:10,rowTotal:null,records:0,pager:"",pgbuttons:!0,pginput:!0,colModel:[],
additionalProperties:[],arrayReader:[],rowList:[],colNames:[],sortorder:"asc",sortname:"",mtype:"GET",altRows:!1,selarrrow:[],savedRow:[],shrinkToFit:!0,xmlReader:{},subGrid:!1,subGridModel:[],reccount:0,lastpage:0,lastsort:0,selrow:null,singleSelectClickMode:"toggle",beforeSelectRow:null,onSelectRow:null,onSortCol:null,ondblClickRow:null,onRightClickRow:null,onPaging:null,onSelectAll:null,onInitGrid:null,loadComplete:null,gridComplete:null,loadError:null,loadBeforeSend:null,afterInsertRow:null,beforeRequest:null,
beforeProcessing:null,onHeaderClick:null,viewrecords:!1,loadonce:!1,multiselect:!1,multikey:!1,editurl:"clientArray",search:!1,caption:"",hidegrid:!0,hiddengrid:!1,useUnformattedDataForCellAttr:!0,postData:{},userData:{},treeGrid:!1,treeGridModel:"nested",treeReader:{},treeANode:-1,ExpandColumn:null,tree_root_level:0,prmNames:{page:"page",rows:"rows",sort:"sidx",order:"sord",search:"_search",nd:"nd",id:"id",oper:"oper",editoper:"edit",addoper:"add",deloper:"del",subgridid:"id",npage:null,totalrows:"totalrows"},
forceFit:!1,gridstate:"visible",cellEdit:!1,iCol:-1,iRow:-1,nv:0,loadui:"enable",toolbar:[!1,""],scroll:!1,multiboxonly:!1,deselectAfterSort:!0,scrollrows:!1,autowidth:!1,scrollOffset:18,cellLayout:5,subGridWidth:16,multiselectWidth:16,multiselectPosition:"left",gridview:null==g||null==g.afterInsertRow,rownumWidth:25,rownumbers:!1,pagerpos:"center",footerrow:!1,userDataOnFooter:!1,hoverrows:!0,altclass:"ui-priority-secondary",viewsortcols:[!1,"vertical",!0],resizeclass:"",autoencode:!1,remapColumns:[],
cmNamesInputOrder:[],ajaxGridOptions:{},direction:O,toppager:!1,headertitles:!1,scrollTimeout:40,maxItemsToJoin:32768,data:[],lastSelectedData:[],quickEmpty:!0,_index:{},iColByName:{},iPropByName:{},reservedColumnNames:["rn","cb","subgrid"],grouping:!1,groupingView:{groupField:[],groupOrder:[],groupText:[],groupColumnShow:[],groupSummary:[],showSummaryOnHide:!1,sortitems:[],sortnames:[],summary:[],summaryval:[],displayField:[],groupSummaryPos:[],formatDisplayField:[],_locgr:!1,commonIconClass:K("grouping.common"),
plusicon:K("grouping.plus"),minusicon:K("grouping.minus")},ignoreCase:!0,cmTemplate:{},idPrefix:"",iconSet:aa,guiStyle:Q,locale:x,multiSort:!1,treeIcons:{commonIconClass:K("treeGrid.common"),plusLtr:K("treeGrid.plusLtr"),plusRtl:K("treeGrid.plusRtl"),minus:K("treeGrid.minus"),leaf:K("treeGrid.leaf")},subGridOptions:{commonIconClass:K("subgrid.common"),plusicon:K("subgrid.plus"),minusicon:K("subgrid.minus")}},n,{navOptions:F(!0,{commonIconClass:K("nav.common"),editicon:K("nav.edit"),addicon:K("nav.add"),
delicon:K("nav.del"),searchicon:K("nav.search"),refreshicon:K("nav.refresh"),viewicon:K("nav.view"),saveicon:K("nav.save"),cancelicon:K("nav.cancel"),buttonicon:K("nav.newbutton")},r.nav||{}),actionsNavOptions:F(!0,{commonIconClass:K("actions.common"),editicon:K("actions.edit"),delicon:K("actions.del"),saveicon:K("actions.save"),cancelicon:K("actions.cancel")},r.actionsNav||{}),formEditing:F(!0,{commonIconClass:K("form.common"),prevIcon:K("form.prev"),nextIcon:K("form.next"),saveicon:[!0,"left",K("form.save")],
closeicon:[!0,"left",K("form.undo")]},r.edit||{}),searching:F(!0,{commonIconClass:K("search.common"),findDialogIcon:K("search.search"),resetDialogIcon:K("search.reset"),queryDialogIcon:K("search.query")},r.search||{}),formViewing:F(!0,{commonIconClass:K("form.common"),prevIcon:K("form.prev"),nextIcon:K("form.next"),closeicon:[!0,"left",K("form.cancel")]},r.view||{}),formDeleting:F(!0,{commonIconClass:K("form.common"),delicon:[!0,"left",K("form.del")],cancelicon:[!0,"left",K("form.cancel")]},r.del||
{})},g||{}),R=function(a){var b=r.getRes(k,a);return void 0!==b?b:X.call(G,"defaults."+a)};k.recordpos=k.recordpos||("rtl"===k.direction?"left":"right");k.subGridOptions.openicon="rtl"===k.direction?K("subgrid.openRtl"):K("subgrid.openLtr");k.autoResizing.widthOfVisiblePartOfSortIcon=void 0!==k.autoResizing.widthOfVisiblePartOfSortIcon?k.autoResizing.widthOfVisiblePartOfSortIcon:"fontAwesome"===k.iconSet?13:12;k.datatype=void 0!==k.datatype?k.datatype:void 0!==z||null==k.url?"local":null!=k.jsonReader&&
"object"===typeof k.jsonReader?"json":"xml";k.jsonReader=k.jsonReader||{};k.url=k.url||"";k.cellsubmit=void 0!==k.cellsubmit?k.cellsubmit:void 0===k.cellurl?"clientArray":"remote";k.gridview=void 0!==k.gridview?k.gridview:null==k.afterInsertRow;void 0!==z&&(k.data=z,g.data=z);void 0!==A&&(k.datastr=A,g.datastr=A);if("TABLE"!==v.tagName.toUpperCase())T("Element is not a table!");else if(""===v.id&&G.attr("id",l()),void 0!==document.documentMode&&5>=document.documentMode)T("Grid can not be used in this ('quirks') mode!");
else{G.empty().attr("tabindex","0");v.p=k;k.id=v.id;k.idSel="#"+f(v.id);k.gBoxId=b.call(v,0);k.gBox=h.call(v,0);k.gViewId=b.call(v,8);k.gView=h.call(v,8);k.rsId=b.call(v,43);k.rs=h.call(v,43);k.cbId=b.call(v,45);k.cb=h.call(v,45);k.useProp=!!a.fn.prop;k.propOrAttr=k.useProp?"prop":"attr";var W=k.propOrAttr,ba=r.fixScrollOffsetAndhBoxPadding,ca=function(a){var b={},c,k=a.length;for(c=0;c<k;c++)b[a[c].name]=c;return b},ha=function(a){var b={},c,k=a.length,e;for(c=0;c<k;c++)e=a[c],b["string"===typeof e?
e:e.name]=c;return b},ja=function(){var b={},c,k;this.p.rowIndexes=b;for(k=0;k<this.rows.length;k++)c=this.rows[k],a(c).hasClass("jqgrow")&&(b[c.id]=c.rowIndex)},da=function(){var b,c=k.colModel;b=k.cmNamesInputOrder;var e=k.additionalProperties,d=b.length,g,l,f,h;k.arrayReaderInfos={};g=k.arrayReaderInfos;for(h=0;h<d;h++)l=b[h],0>J(l,k.reservedColumnNames)&&!g.hasOwnProperty(l)&&(f=k.iColByName[l],void 0!==f?g[l]={name:c[f].name,index:f,order:h,type:0}:(f=k.iPropByName[l],void 0!==f?g[l]={name:c[f].name,
index:f,order:h,type:1}:l===(k.prmNames.rowidName||"rowid")&&(g[l]={index:f,type:2})));d=c.length;for(b=0;b<d;b++)l=c[b].name,0>J(l,k.reservedColumnNames)&&!g.hasOwnProperty(l)&&(g[l]={name:l,index:b,order:h,type:0},h++);d=e.length;for(b=0;b<d;b++)l=e[b],null==l||g.hasOwnProperty(l)||("object"===typeof l&&"string"===a.type(l.name)&&(l=l.name),g[l]={name:l,index:b,order:h,type:1},h++)},P=function(b){var c=a(this).data("pageX");c?(c=String(c).split(";"),c=c[c.length-1],a(this).data("pageX",c+";"+b.pageX)):
a(this).data("pageX",b.pageX)},ea=function(a,b){a=parseInt(a,10);return isNaN(a)?b||0:a},M={headers:[],cols:[],footers:[],dragStart:function(b,e,d,g){var l=a(this.bDiv),f=l.closest(k.gBox).offset();g=g.offset().left+("rtl"===k.direction?0:this.headers[b].width+(r.cell_width?0:ea(k.cellLayout,0))-2);this.resizing={idx:b,startX:g,sOL:g,moved:!1,delta:g-e.pageX};this.curGbox=a(k.rs);this.curGbox.prependTo("body");this.curGbox.css({display:"block",left:g,top:d[1]+f.top,height:d[2]});this.curGbox.data("idx",
b);this.curGbox.data("delta",g-e.pageX);P.call(this.curGbox,e);E.call(c(21,l),"resizeStart",e,b);document.onselectstart=function(){return!1};a(document).bind("mousemove.jqGrid",function(a){if(M.resizing)return M.dragMove(a),!1}).bind("mouseup.jqGrid"+k.id,function(){if(M.resizing)return M.dragEnd(),!1})},dragMove:function(b){var c=this.resizing;if(c){var e=b.pageX+c.delta-c.startX,d=this.headers;b=d[c.idx];var g="ltr"===k.direction?b.width+e:b.width-e;c.moved=!0;g>k.minResizingWidth&&(null==this.curGbox&&
(this.curGbox=a(k.rs)),this.curGbox.css({left:c.sOL+e}),!0===k.forceFit?(c=d[c.idx+k.nv],e="ltr"===k.direction?c.width-e:c.width+e,e>k.autoResizing.minColWidth&&(b.newWidth=g,c.newWidth=e)):(this.newWidth="ltr"===k.direction?k.tblwidth+e:k.tblwidth-e,b.newWidth=g))}},resizeColumn:function(b,e,d){var g=this.headers,l=this.footers,f=g[b],h=f.newWidth||f.width,m=c(21,this.bDiv),v=c(14,this.hDiv).children("thead").children("tr").first()[0].cells,h=parseInt(h,10);k.colModel[b].width=h;f.width=h;v[b].style.width=
h+"px";this.cols[b].style.width=h+"px";this.fbRows&&(a(this.fbRows[0].cells[b]).css("width",h),a(c(31,this.fhDiv)[0].rows[0].cells[b]).css("width",h),k.footerrow&&a(c(36,this.fsDiv)[0].rows[0].cells[b]).css("width",h));0<l.length&&(l[b].style.width=h+"px");!0!==d&&ba.call(m[0]);!0===k.forceFit?(g=g[b+k.nv],h=g.newWidth||g.width,g.width=h,v[b+k.nv].style.width=h+"px",this.cols[b+k.nv].style.width=h+"px",0<l.length&&(l[b+k.nv].style.width=h+"px"),k.colModel[b+k.nv].width=h):(k.tblwidth=this.newWidth||
k.tblwidth,m.css("width",k.tblwidth+"px"),c(14,this.hDiv).css("width",k.tblwidth+"px"),!0!==d&&(this.hDiv.scrollLeft=this.bDiv.scrollLeft,k.footerrow&&(c(27,this.sDiv).css("width",k.tblwidth+"px"),this.sDiv.scrollLeft=this.bDiv.scrollLeft)));k.autowidth||void 0!==k.widthOrg&&"auto"!==k.widthOrg&&"100%"!==k.widthOrg||!0===d||D.setGridWidth.call(m,this.newWidth+k.scrollOffset,!1);e||E.call(m[0],"resizeStop",h,b)},dragEnd:function(){this.hDiv.style.cursor="default";this.resizing&&(null!==this.resizing&&
!0===this.resizing.moved&&(a(this.headers[this.resizing.idx].el).removeData("autoResized"),this.resizeColumn(this.resizing.idx,!1)),a(k.rs).removeData("pageX"),this.resizing=!1,setTimeout(function(){a(k.rs).css("display","none").prependTo(k.gBox)},k.doubleClickSensitivity));this.curGbox=null;document.onselectstart=function(){return!0};a(document).unbind("mousemove.jqGrid").unbind("mouseup.jqGrid"+k.id)},populateVisible:function(){var b=this,c=a(b),e=b.grid,d=e.bDiv,g=a(d);e.timer&&clearTimeout(e.timer);
e.timer=null;if(g=g.height()){var l,f;if(b.rows.length)try{f=(l=b.rows[1])?a(l).outerHeight()||e.prevRowHeight:e.prevRowHeight}catch(h){f=e.prevRowHeight}if(f){e.prevRowHeight=f;l=k.rowNum;e.scrollTop=d.scrollTop;var d=e.scrollTop,m=Math.round(c.position().top)-d,c=m+c.height();f*=l;var v,t,D;c<g&&0>=m&&(void 0===k.lastpage||(parseInt((c+d+f-1)/f,10)||0)<=k.lastpage)&&(t=parseInt((g-c+f-1)/f,10)||1,0<=c||2>t||!0===k.scroll?(v=(Math.round((c+d)/f)||0)+1,m=-1):m=1);0<m&&(v=(parseInt(d/f,10)||0)+1,t=
(parseInt((d+g)/f,10)||0)+2-v,D=!0);!t||k.lastpage&&(v>k.lastpage||1===k.lastpage||v===k.page&&v===k.lastpage)||(e.hDiv.loading?e.timer=setTimeout(function(){e.populateVisible.call(b)},k.scrollTimeout):(k.page=v,D&&(e.selectionPreserver.call(b),e.emptyRows.call(b,!1,!1)),e.populate.call(b,t)))}}},scrollGrid:function(a){var b=c(21,this);a&&a.stopPropagation();if(0===b.length)return!0;var e=b[0].grid;k.scroll&&(a=this.scrollTop,void 0===e.scrollTop&&(e.scrollTop=0),a!==e.scrollTop&&(e.scrollTop=a,e.timer&&
clearTimeout(e.timer),e.timer=setTimeout(function(){e.populateVisible.call(b[0])},k.scrollTimeout)));e.hDiv.scrollLeft=this.scrollLeft;k.footerrow&&(e.sDiv.scrollLeft=this.scrollLeft)},selectionPreserver:function(){var b=a(this),c=k.selrow,e=k.selarrrow?a.makeArray(k.selarrrow):null,g=this.grid.bDiv,l=g.scrollLeft,f=function(){var a;k.selrow=null;d(k.selarrrow);if(k.multiselect&&e&&0<e.length)for(a=0;a<e.length;a++)e[a]!==c&&Y.call(b,e[a],!1,null);c&&Y.call(b,c,!1,null);g.scrollLeft=l;b.unbind(".selectionPreserver",
f)};b.bind("jqGridGridComplete.selectionPreserver",f)}};v.grid=M;E.call(v,"beforeInitGrid");k.iColByName=ca(k.colModel);k.iPropByName=ha(k.additionalProperties);var Z,fa;if(0===k.colNames.length)for(Z=0;Z<k.colModel.length;Z++)k.colNames[Z]=void 0!==k.colModel[Z].label?k.colModel[Z].label:k.colModel[Z].name;if(k.colNames.length!==k.colModel.length)T(X.call(G,"errors.model"));else{var O=a("<div class='ui-jqgrid-view' role='grid' aria-multiselectable='"+!!k.multiselect+"'></div>"),ka=(x=r.msie)&&8>
r.msiever();k.direction=H(k.direction.toLowerCase());-1===J(k.direction,["ltr","rtl"])&&(k.direction="ltr");fa=k.direction;a(O).insertBefore(v);G.removeClass("scroll").appendTo(O);z=a("<div class='"+L("gBox","ui-jqgrid")+"'></div>");a(z).attr({id:k.gBoxId,dir:fa}).insertBefore(O);a(O).attr("id",k.gViewId).appendTo(z);a("<div class='"+L("overlay","jqgrid-overlay")+"' id='lui_"+k.id+"'></div>").insertBefore(O);a("<div class='"+L("loading","loading")+"' id='load_"+k.id+"'>"+R("loadtext")+"</div>").insertBefore(O);
ka&&G.attr({cellspacing:"0"});G.attr({role:"presentation","aria-labelledby":"gbox_"+v.id});var xa=function(a,b,c,e,d,g){var l=k.colModel[a],f=c,h="style='",m=l.classes,D=l.align?"text-align:"+l.align+";":"",z,B=function(a){return"string"===typeof a?a.replace(/\'/g,"'"):a},q=" aria-describedby='"+k.id+"_"+l.name+"'";!0===l.hidden&&(D+="display:none;");if(0===b)D+="width: "+M.headers[a].width+"px;";else if(p(l.cellattr)||"string"===typeof l.cellattr&&null!=r.cellattr&&p(r.cellattr[l.cellattr]))if(a=
p(l.cellattr)?l.cellattr:r.cellattr[l.cellattr],k.useUnformattedDataForCellAttr&&null!=g?f=g[l.name]:l.autoResizable&&(f="<span class='"+k.autoResizing.wrapperClassName+"'>",f=c.substring(f.length,c.length-7)),e=a.call(v,d,f,e,l,g),"string"===typeof e)for(e=e.replace(/\n/g,"
");;){c=/^\s*(\w+[\w|\-]*)\s*=\s*([\"|\'])(.*?)\2(.*)/.exec(e);if(null===c||5>c.length)return!z&&l.title&&(z=f),q+" style='"+B(D)+"'"+(m?" class='"+B(m)+"'":"")+(z?" title='"+B(z)+"'":"");h=c[3];e=c[4];switch(c[1].toLowerCase()){case "class":m=
m?m+(" "+h):h;break;case "title":z=h;break;case "style":D+=h;break;default:q+=" "+c[1]+"="+c[2]+h+c[2]}}h=h+(D+"'")+((void 0!==m?" class='"+m+"'":"")+(l.title&&f?' title="'+t(c)+'"':""));return h+=q},ga=function(a){return null==a||""===a?" ":k.autoencode?w(a):String(a)},za=function(a){var b=k.treeReader,c=b.loaded,e=b.leaf_field,d=b.expanded_field,g=function(a){return!0===a||"true"===a||"1"===a};if("nested"===k.treeGridModel&&!a[e]){var l=parseInt(a[b.left_field],10),b=parseInt(a[b.right_field],
10);a[e]=b===l+1?!0:!1}void 0!==a[c]&&(a[c]=g(a[c]));a[e]=g(a[e]);a[d]=g(a[d])},Ea=function(){var a=k.data,b=a.length,c,e,d,g,f,h,t,D=k.localReader,z=k.additionalProperties,B=D.cell,q,A,n,G=k.arrayReaderInfos;if("local"!==k.datatype||!0!==D.repeatitems){if(k.treeGrid)for(c=0;c<b;c++)za(a[c])}else for(g=!1===k.keyName?p(D.id)?D.id.call(v,a):D.id:k.keyName,isNaN(g)?p(g)||null==k.arrayReaderInfos[g]||(f=k.arrayReaderInfos[g].order):f=Number(g),c=0;c<b;c++){e=a[c];d=B?m(e,B)||e:e;A=C(d);t={};for(q in G)G.hasOwnProperty(q)&&
(n=G[q],h=m(d,A?n.order:n.name),1===n.type&&(n=z[n.index],null!=n&&p(n.convert)&&(h=n.convert(h,d))),void 0!==h&&(t[q]=h));void 0!==t[g]?e=void 0!==t[g]?t[g]:l():(e=m(e,C(e)?f:g),void 0===e&&(e=m(d,C(d)?f:g)),void 0===e&&(e=l()));e=String(e);t[D.id]=e;k.treeGrid&&za(t);F(a[c],t)}},ma=function(){var a=k.data.length,b,c,e;b=!1===k.keyName||k.loadonce?k.localReader.id:k.keyName;k._index={};for(c=0;c<a;c++)e=m(k.data[c],b),void 0===e&&(e=String(c+1)),k._index[e]=c},pa=function(){var b,c,e=a.fn.fmatter;
for(b=0;b<k.colModel.length;b++)c=k.colModel[b].formatter,"string"===typeof c&&null!=e&&p(e[c])&&p(e[c].pageFinalization)&&e[c].pageFinalization.call(this,b)},ta=function(b,c){var e,d,g=k.colModel,l=g.length,f,h=function(a){return null==a||""===a?" ":w(a)},m=function(a){return null==a||""===a?" ":String(a)};for(e=0;e<l;e++)d=g[e],d.cellBuilder=null,b||(f={colModel:d,gid:k.id,pos:e},void 0===d.formatter?d.cellBuilder=k.autoencode?h:m:"string"===typeof d.formatter?d.cellBuilder=a.fn.fmatter.getCellBuilder.call(v,
d.formatter,f,c||"add"):p(d.getCellBuilder)&&(d.cellBuilder=d.getCellBuilder.call(v,f,c||"add")))},la=function(b,c,e,g){var f=a(this),h=new Date,v=k.datatype,t="local"!==v&&k.loadonce||"xmlstring"===v||"jsonstring"===v,z=("xmlstring"===v||"xml"===v)&&a.isXMLDoc(b),B=k.localReader,q=m;if(b&&("xml"!==v||z)){-1!==k.treeANode||k.scroll?c=1<c?c:1:(M.emptyRows.call(this,!1,!0),c=1);t&&(d(k.data),d(k.lastSelectedData),k._index={},k.localReader.id="_id_");k.reccount=0;switch(v){case "xml":case "xmlstring":B=
k.xmlReader;q=r.getXmlData;break;case "json":case "jsonp":case "jsonstring":B=k.jsonReader}var n,A,G,w,x,I={},V,F=k.colModel,y=F.length,J,H,u,N,P,sa=k.arrayReaderInfos,X={},O=function(a){return function(b){b=b.getAttribute(a);return null!==b?b:void 0}},Y=function(a){return function(){var b=X[a];if(null!=b)return b=b.childNodes,0<b.length?b[0].nodeValue:void 0}};k.page=ea(q(b,B.page),k.page);k.lastpage=ea(q(b,B.total),1);k.records=ea(q(b,B.records));p(B.userdata)?k.userData=B.userdata.call(this,b)||
{}:z?q(b,B.userdata,!0).each(function(){k.userData[this.getAttribute("name")]=a(this).text()}):k.userData=q(b,B.userdata)||{};ta();var T={},L=k.additionalProperties,K=function(a){z&&"string"===typeof a&&(/^\w+$/.test(a)?T[a]=Y(a):/^\[\w+\]$/.test(a)&&(T[a]=O(a.substring(1,a.length-1))))};for(n=0;n<y;n++)if(I=F[n],J=I.name,"cb"!==J&&"subgrid"!==J&&"rn"!==J){G=z?I.xmlmap||J:"local"===v&&!k.dataTypeOrg||"json"===v||"jsonp"===v?I.jsonmap||J:J;!1!==k.keyName&&!0===I.key&&(k.keyName=J);if("string"===typeof G||
p(G))T[J]=G;K(J)}y=L.length;for(n=0;n<y;n++)H=L[n],"object"===typeof H&&null!=H&&(H=H.name),K(H);w=!1===k.keyName?p(B.id)?B.id.call(this,b):B.id:k.keyName;isNaN(w)?p(w)||(sa[J]&&(x=sa[J].order),z&&("string"===typeof w&&/^\[\w+\]$/.test(w)?w=O(w.substring(1,w.length-1)):"string"===typeof w&&/^\w+$/.test(w)&&(w=Y(w)))):x=Number(w);G=q(b,B.root,!0);if(B.row)if(1===G.length&&"string"===typeof B.row&&/^\w+$/.test(B.row)){v=[];u=G[0].childNodes;N=u.length;for(H=0;H<N;H++)P=u[H],1===P.nodeType&&P.nodeName===
B.row&&v.push(P);G=v}else G=q(G,B.row,!0);null==G&&C(b)&&(G=b);G||(G=[]);b=G.length;0<b&&0>=k.page&&(k.page=1);y=parseInt(k.rowNum,10);g&&(y*=g+1);var K=[],F=[],R,v=[];for(n=0;n<b;n++){R=G[n];A=B.repeatitems&&B.cell?q(R,B.cell,!0)||R:R;V=B.repeatitems&&(z||C(A));I={};X={};if(z&&!V&&null!=A)for(u=A.childNodes,N=u.length,H=0;H<N;H++)P=u[H],1===P.nodeType&&(X[P.nodeName]=P);for(J in sa)sa.hasOwnProperty(J)&&(H=sa[J],V?(u=A[H.order],z&&null!=u&&(u=u.textContent||u.text)):u=null!=T[J]&&"string"!==typeof T[J]?
T[J](A):q(A,"string"===typeof T[J]?T[J]:H.name),1===H.type&&(H=L[H.index],null!=H&&p(H.convert)&&(u=H.convert(u,A))),void 0!==u&&(I[J]=u));void 0!==I[w]?R=void 0!==I[w]?I[w]:l():(R=q(R,C(R)?x:w),void 0===R&&(R=q(A,C(A)?x:w)),void 0===R&&(R=l()));R=String(R);V=k.idPrefix+R;k.treeGrid&&za(I);if(n<y)F.push(V),K.push(A),v.push(I);else if(!t)break;if(t||!0===k.treeGrid)I._id_=R,k.data.push(I),k._index[I._id_]=k.data.length-1}c=r.parseDataToHtml.call(this,b,F,v,K,c,g,t);ta(!0);g=-1<k.treeANode?k.treeANode:
0;B=a(this.tBodies[0]);!0===k.treeGrid&&0<g?a(this.rows[g]).after(c.join("")):k.scroll?B.append(c.join("")):(null==this.firstElementChild||void 0!=document.documentMode&&9>=document.documentMode?B.html(B.html()+c.join("")):this.firstElementChild.innerHTML+=c.join(""),this.grid.cols=this.rows[0].cells);k.grouping&&ja.call(this);if(!0===k.subGrid)try{D.addSubGrid.call(f,k.iColByName.subgrid)}catch(Q){}if(!1===k.gridview||p(k.afterInsertRow))for(n=0;n<Math.min(b,y);n++)E.call(this,"afterInsertRow",F[n],
v[n],K[n]);k.totaltime=new Date-h;0<n&&0===k.records&&(k.records=b);d(c);if(!0===k.treeGrid)try{D.setTreeNode.call(f,g+1,n+g+1)}catch(W){}k.reccount=Math.min(b,y);k.treeANode=-1;k.userDataOnFooter&&D.footerData.call(f,"set",k.userData,!0);t&&(k.records=b,k.lastpage=Math.ceil(b/y));e||this.updatepager(!1,!0);pa.call(this)}},wa=function(){function b(a){var c=0,e,d,g,f,h,m,v;if(null!=a.groups){(d=a.groups.length&&"OR"===a.groupOp.toString().toUpperCase())&&w.orBegin();for(e=0;e<a.groups.length;e++){0<
c&&d&&w.or();try{b(a.groups[e])}catch(t){T(t)}c++}d&&w.orEnd()}if(null!=a.rules)try{(g=a.rules.length&&"OR"===a.groupOp.toString().toUpperCase())&&w.orBegin();for(e=0;e<a.rules.length;e++)h=a.rules[e],f=a.groupOp.toString().toUpperCase(),A[h.op]&&h.field?(0<c&&f&&"OR"===f&&(w=w.or()),v=l[h.field],m=v.reader,w=A[h.op](w,f)(p(m)?'jQuery.jgrid.getAccessor(this,jQuery("'+k.idSel+'")[0].p.colModel['+v.iCol+"].jsonmap)":"jQuery.jgrid.getAccessor(this,'"+m+"')",h.data,l[h.field])):null!=k.customSortOperations&&
null!=k.customSortOperations[h.op]&&p(k.customSortOperations[h.op].filter)&&(w=w.custom(h.op,h.field,h.data)),c++;g&&w.orEnd()}catch(D){T(D)}}var c=a(this),e=k.multiSort?[]:"",d=[],g=!1,l={},f=[],h=[],m,v,t,z=X.call(G,"formatter.date");if(!C(k.data))return{};var B=k.grouping?k.groupingView:!1,q,n;N(k.colModel,function(a){var b=this.index||this.name;v=this.sorttype||"text";l[this.name]={reader:k.dataTypeOrg?this.name:this.jsonmap||this.name,iCol:a,stype:v,srcfmt:"",newfmt:"",sfunc:this.sortfunc||null};
if("date"===v||"datetime"===v)this.formatter&&"string"===typeof this.formatter&&"date"===this.formatter?(m=this.formatoptions&&this.formatoptions.srcformat?this.formatoptions.srcformat:z.srcformat,t=this.formatoptions&&this.formatoptions.newformat?this.formatoptions.newformat:z.newformat):m=t=this.datefmt||"Y-m-d",l[this.name].srcfmt=m,l[this.name].newfmt=t;if(k.grouping)for(n=0,q=B.groupField.length;n<q;n++)this.name===B.groupField[n]&&(f[n]=l[b],h[n]=b);k.multiSort?this.lso&&(e.push(this.name),
a=this.lso.split("-"),d.push(a[a.length-1])):g||this.index!==k.sortname&&this.name!==k.sortname||(e=this.name,g=!0)});if(k.treeGrid)return D.SortTree.call(c,e,k.sortorder,null!=l[e]&&l[e].stype?l[e].stype:"text",null!=l[e]&&l[e].srcfmt?l[e].srcfmt:""),!1;var A={eq:function(a){return a.equals},ne:function(a){return a.notEquals},lt:function(a){return a.less},le:function(a){return a.lessOrEquals},gt:function(a){return a.greater},ge:function(a){return a.greaterOrEquals},cn:function(a){return a.contains},
nc:function(a,b){return"OR"===b?a.orNot().contains:a.andNot().contains},bw:function(a){return a.startsWith},bn:function(a,b){return"OR"===b?a.orNot().startsWith:a.andNot().startsWith},en:function(a,b){return"OR"===b?a.orNot().endsWith:a.andNot().endsWith},ew:function(a){return a.endsWith},ni:function(a,b){return"OR"===b?a.orNot().equals:a.andNot().equals},"in":function(a){return a.equals},nu:function(a){return a.isNull},nn:function(a,b){return"OR"===b?a.orNot().isNull:a.andNot().isNull}},w=r.from.call(this,
k.data);k.ignoreCase&&(w=w.ignoreCase());if(!0===k.search){var I=k.postData.filters;if(I)"string"===typeof I&&(I=r.parse(I)),b(I);else try{w=A[k.postData.searchOper](w)(k.postData.searchField,k.postData.searchString,l[k.postData.searchField])}catch(x){}}if(k.grouping)for(n=0;n<q;n++)w.orderBy(h[n],B.groupOrder[n],f[n].stype,f[n].srcfmt);k.multiSort?N(e,function(a){w.orderBy(this,d[a],l[this].stype,l[this].srcfmt,l[this].sfunc)}):e&&k.sortorder&&g&&("DESC"===k.sortorder.toUpperCase()?w.orderBy(k.sortname,
"d",l[e].stype,l[e].srcfmt,l[e].sfunc):w.orderBy(k.sortname,"a",l[e].stype,l[e].srcfmt,l[e].sfunc));k.lastSelectedData=w.select();var I=parseInt(k.rowNum,10),V=k.lastSelectedData.length,F=parseInt(k.page,10),E=Math.ceil(V/I),y={};if(k.grouping&&k.groupingView._locgr){k.groupingView.groups=[];var J,H,u;if(k.footerrow&&k.userDataOnFooter){for(H in k.userData)k.userData.hasOwnProperty(H)&&(k.userData[H]=0);u=!0}for(J=0;J<V;J++){if(u)for(H in k.userData)k.userData.hasOwnProperty(H)&&(k.userData[H]+=parseFloat(k.lastSelectedData[J][H]||
0));D.groupingPrepare.call(c,k.lastSelectedData[J],J,I)}}l=w=null;c=k.localReader;y[c.total]=E;y[c.page]=F;y[c.records]=V;y[c.root]=k.lastSelectedData.slice((F-1)*I,F*I);y[c.userdata]=k.userData;return y},Aa=function(b){var c=b.outerWidth();0>=c&&(c=a(this).closest(".ui-jqgrid>.ui-jqgrid-view").css("font-size")||"11px",a(document.body).append("<div id='testpg' class='"+L("gBox","ui-jqgrid")+"' style='font-size:"+c+";visibility:hidden;margin:0;padding:0;' ></div>"),a(b).clone().appendTo("#testpg"),
c=a("#testpg>.ui-pg-table").width(),a("#testpg").remove());0<c&&b.parent().width(c);return c},ua=function(){this.grid.hDiv.loading=!0;k.hiddengrid||D.progressBar.call(a(this),{method:"show",loadtype:k.loadui,htmlcontent:R("loadtext")})},va=function(){this.grid.hDiv.loading=!1;D.progressBar.call(a(this),{method:"hide",loadtype:k.loadui})},qa=function(b){var c=this,e=a(c),g=c.grid;if(!g.hDiv.loading){var l=k.scroll&&!1===b,f={},h,m=k.prmNames;0>=k.page&&(k.page=Math.min(1,k.lastpage));null!==m.search&&
(f[m.search]=k.search);null!==m.nd&&(f[m.nd]=(new Date).getTime());if(isNaN(parseInt(k.rowNum,10))||0>=parseInt(k.rowNum,10))k.rowNum=k.maxRowNum;null!==m.rows&&(f[m.rows]=k.rowNum);null!==m.page&&(f[m.page]=k.page);null!==m.sort&&(f[m.sort]=k.sortname);null!==m.order&&(f[m.order]=k.sortorder);null!==k.rowTotal&&null!==m.totalrows&&(f[m.totalrows]=k.rowTotal);var t=p(k.loadComplete),z=t?k.loadComplete:null,B=0;b=b||1;1<b?null!==m.npage?(f[m.npage]=b,B=b-1,b=1):z=function(a){k.page++;g.hDiv.loading=
!1;t&&k.loadComplete.call(c,a);qa.call(c,b-1)}:null!==m.npage&&delete k.postData[m.npage];if(k.grouping){D.groupingSetup.call(e);var q=k.groupingView,n,A="",G,w,I;for(n=0;n<q.groupField.length;n++){G=q.groupField[n];for(w=0;w<k.colModel.length;w++)I=k.colModel[w],I.name===G&&I.index&&(G=I.index);A+=G+" "+q.groupOrder[n]+", "}f[m.sort]=A+f[m.sort]}F(k.postData,f);var x=k.scroll?c.rows.length-1:1,V=function(){var a=e.width(),b=e.closest(".ui-jqgrid-view").width(),c=e.css("height");b<a&&0===k.reccount?
e.css("height","1px"):"0"!==c&&"0px"!==c&&e.css("height","")},C=function(){var a;if(k.autoresizeOnLoad)D.autoResizeAllColumns.call(e);else for(a=0;a<k.columnsToReResizing.length;a++)D.autoResizeColumn.call(e,k.columnsToReResizing[a]);d(k.columnsToReResizing)},m=function(){E.call(c,"loadComplete",h);C();e.triggerHandler("jqGridAfterLoadComplete",[h]);va.call(c);k.datatype="local";k.datastr=null;ba.call(c);V()},y=function(a){e.triggerHandler("jqGridLoadComplete",[a]);z&&z.call(c,a);C();e.triggerHandler("jqGridAfterLoadComplete",
[a]);l&&g.populateVisible.call(c);1===b&&va.call(c);ba.call(c);V()};if(E.call(c,"beforeRequest"))if(p(k.datatype))k.datatype.call(c,k.postData,"load_"+k.id,x,b,B);else switch(f=k.datatype.toLowerCase(),f){case "json":case "jsonp":case "xml":case "script":a.ajax(F({url:k.url,type:k.mtype,dataType:f,data:r.serializeFeedback.call(v,k.serializeGridData,"jqGridSerializeGridData",k.postData),success:function(a,e,d){if(p(k.beforeProcessing)&&!1===k.beforeProcessing.call(c,a,e,d))va.call(c);else if(la.call(c,
a,x,1<b,B),y(a),k.loadonce||k.treeGrid)k.dataTypeOrg=k.datatype,k.datatype="local"},error:function(a,e,d){p(k.loadError)&&k.loadError.call(c,a,e,d);1===b&&va.call(c)},beforeSend:function(a,b){var e=!0;p(k.loadBeforeSend)&&(e=k.loadBeforeSend.call(c,a,b));void 0===e&&(e=!0);if(!1===e)return!1;ua.call(c)}},r.ajaxOptions,k.ajaxGridOptions));break;case "xmlstring":ua.call(c);h="string"===typeof k.datastr?a.parseXML(k.datastr):k.datastr;la.call(c,h);m();break;case "jsonstring":ua.call(c);h="string"===
typeof k.datastr?r.parse(k.datastr):k.datastr;la.call(c,h);m();break;case "local":case "clientside":ua.call(c),k.datatype="local",f=wa.call(c),la.call(c,f,x,1<b,B),y(f)}}},sa=function(b){var c=this.grid;a(k.cb,c.hDiv)[k.propOrAttr]("checked",b);if(k.frozenColumns)a(k.cb,c.fhDiv)[k.propOrAttr]("checked",b)};A=function(b,c){var e=L("states.hover"),g=L("states.disabled"),l="<td class='ui-pg-button "+g+"'><span class='ui-separator'></span></td>",h="",m="<table "+(ka?"cellspacing='0' ":"")+"style='table-layout:auto;white-space: pre;"+
("left"===k.pagerpos?"margin-right:auto;":"right"===k.pagerpos?"margin-left:auto;":"margin-left:auto;margin-right:auto;")+"' class='ui-pg-table'><tbody><tr>",t="",D,z,B,q,n=function(a,b,c){if(!E.call(v,"onPaging",a,{newPage:b,currentPage:ea(k.page,1),lastPage:ea(k.lastpage,1),currentRowNum:ea(k.rowNum,10),newRowNum:c}))return!1;k.selrow=null;k.multiselect&&(d(k.selarrrow),sa.call(v,!1));d(k.savedRow);return!0};c+="_"+b;D="pg_"+b;z=b+"_left";B=b+"_center";q=b+"_right";a("#"+f(b)).append("<div id='"+
D+"' class='ui-pager-control' role='group'><table "+(ka?"cellspacing='0' ":"")+"class='ui-pg-table' style='width:100%;table-layout:fixed;height:100%;'><tbody><tr><td id='"+z+"' style='text-align:left;'></td><td id='"+B+"' style='text-align:center;white-space:pre;'></td><td id='"+q+"' style='text-align:right;'></td></tr></tbody></table></div>").attr("dir","ltr");D="#"+f(D);if(0<k.rowList.length){t="<td dir='"+fa+"'>";z=R("pgrecs");t+="<select class='"+L("pagerSelect","ui-pg-selbox")+"' role='listbox' "+
(z?"title='"+z+"'":"")+">";for(z=0;z<k.rowList.length;z++)B=k.rowList[z].toString().split(":"),1===B.length&&(B[1]=B[0]),t+='<option role="option" value="'+B[0]+'"'+(ea(k.rowNum,0)===ea(B[0],0)?' selected="selected"':"")+">"+B[1]+"</option>";t+="</select></td>"}"rtl"===fa&&(m+=t);!0===k.pginput&&(h="<td dir='"+fa+"'>"+r.format(R("pgtext")||"","<input class='"+L("pagerInput","ui-pg-input")+"' type='text' size='2' maxlength='7' value='0' role='textbox'/>","<span id='sp_1_"+b+"'>0</span>")+"</td>");
b="#"+f(b);if(!0===k.pgbuttons){B=["first","prev","next","last"];var G=L("pagerButton","ui-pg-button");q=function(a){var b=R("pg"+a);return"<td role='button' tabindex='0' id='"+a+c+"' class='"+G+"' "+(b?"title='"+b+"'":"")+"><span class='"+K("pager."+a)+"'></span></td>"};"rtl"===fa&&B.reverse();for(z=0;z<B.length;z++)m+=q(B[z]),1===z&&(m+=""!==h?l+h+l:"")}else""!==h&&(m+=h);"ltr"===fa&&(m+=t);m+="</tr></tbody></table>";!0===k.viewrecords&&a("td"+b+"_"+k.recordpos,D).append("<span dir='"+fa+"' style='text-align:"+
k.recordpos+"' class='ui-paging-info'></span>");var A=a("td"+b+"_"+k.pagerpos,D);A.append(m);l=Aa.call(this,A.children(".ui-pg-table"));k._nvtd=[];k._nvtd[0]=l?Math.floor((k.width-l)/2):Math.floor(k.width/3);k._nvtd[1]=0;m=null;a(".ui-pg-selbox",D).bind("change",function(){var b=ea(this.value,10),c=Math.round(k.rowNum*(k.page-1)/b-.5)+1;if(!n("records",c,b))return!1;k.page=c;k.rowNum=b;k.pager&&a(".ui-pg-selbox",k.pager).val(b);k.toppager&&a(".ui-pg-selbox",k.toppager).val(b);qa.call(v);return!1});
!0===k.pgbuttons&&(a(".ui-pg-button",D).hover(function(){y(this,g)?this.style.cursor="default":(a(this).addClass(e),this.style.cursor="pointer")},function(){y(this,g)||(a(this).removeClass(e),this.style.cursor="default")}),a("#first"+f(c)+", #prev"+f(c)+", #next"+f(c)+", #last"+f(c)).click(function(){if(y(this,g))return!1;var a=ea(k.page,1),b=a,e=this.id,d=ea(k.lastpage,1),l=!1,f=!0,h=!0,m=!0,t=!0;0===d||1===d?t=m=h=f=!1:1<d&&1<=a?1===a?h=f=!1:a===d&&(t=m=!1):1<d&&0===a&&(t=m=!1,a=d-1);this.id===
"first"+c&&f&&(e="first",b=1,l=!0);this.id==="prev"+c&&h&&(e="prev",b=a-1,l=!0);this.id==="next"+c&&m&&(e="next",b=a+1,l=!0);this.id==="last"+c&&t&&(e="last",b=d,l=!0);if(!n(e,b,ea(k.rowNum,10)))return!1;k.page=b;l&&qa.call(v);return!1}));!0===k.pginput&&a("input.ui-pg-input",D).bind("keypress.jqGrid",function(b){b=b.charCode||b.keyCode||0;var c=ea(a(this).val(),1);if(13===b){if(!n("user",c,ea(k.rowNum,10)))return!1;a(this).val(c);k.page=0<a(this).val()?a(this).val():k.page;qa.call(v);return!1}return this});
A.children(".ui-pg-table").bind("keydown.jqGrid",function(a){13===a.which&&(a=A.find(":focus"),0<a.length&&a.trigger("click"))})};var Ra=function(b,c){var e,d="",g=k.colModel,l=g[b],f=!1,h="",m=L("states.disabled"),t=k.frozenColumns?a(c):a(v.grid.headers[b].el),D=t.find("span.s-ico"),z=D.children("span.ui-icon-asc"),B=D.children("span.ui-icon-desc"),q=z,n=B;t.find("span.ui-grid-ico-sort").addClass(m);t.attr("aria-selected","false");if(l.lso)if("asc"===l.lso)l.lso+="-desc",h="desc",q=B,n=z;else if("desc"===
l.lso)l.lso+="-asc",h="asc";else{if("asc-desc"===l.lso||"desc-asc"===l.lso)l.lso="",k.viewsortcols[0]||D.hide()}else l.lso=h=l.firstsortorder||"asc",q=z,n=B;h&&(D.show(),q.removeClass(m).css("display",""),k.showOneSortIcon&&n.hide(),t.attr("aria-selected","true"));k.sortorder="";N(g,function(a){this.lso&&(0<a&&f&&(d+=", "),e=this.lso.split("-"),d+=g[a].index||g[a].name,d+=" "+e[e.length-1],f=!0,k.sortorder=e[e.length-1])});d=d.substring(0,d.lastIndexOf(k.sortorder));k.sortname=d},Oa=function(b,c,
e,g,l){var h=this.grid,m=L("states.disabled");if(k.colModel[c].sortable&&!(0<k.savedRow.length)){e||(k.lastsort===c&&""!==k.sortname?"asc"===k.sortorder?k.sortorder="desc":"desc"===k.sortorder&&(k.sortorder="asc"):k.sortorder=k.colModel[c].firstsortorder||"asc",k.page=1);if(k.multiSort)Ra(c,l);else{if(g){if(k.lastsort===c&&k.sortorder===g&&!e)return;k.sortorder=g}var v=h.headers;e=h.fhDiv;g=v[k.lastsort]?a(v[k.lastsort].el):a();l=k.frozenColumns?a(l):a(v[c].el);var v=l.find("span.s-ico"),t=k.colModel[k.lastsort],
z=v.children("span.ui-icon-"+k.sortorder),B=v.children("span.ui-icon-"+("asc"===k.sortorder?"desc":"asc"));g.find("span.ui-grid-ico-sort").addClass(m);g.attr("aria-selected","false");k.frozenColumns&&(e.find("span.ui-grid-ico-sort").addClass(m),e.find("th").attr("aria-selected","false"));z.removeClass(m).css("display","");k.showOneSortIcon&&B.removeClass(m).hide();l.attr("aria-selected","true");k.viewsortcols[0]||(k.lastsort!==c?(k.frozenColumns&&e.find("span.s-ico").hide(),g.find("span.s-ico").hide(),
v.show()):""===k.sortname&&v.show());k.lastsort!==c&&"true"===g.data("autoResized")&&(null!=t&&null!=t.autoResizing&&t.autoResizing.compact||k.autoResizing.compact)&&k.columnsToReResizing.push(k.lastsort);k.lastsort!==c&&"true"===l.data("autoResized")&&(t=k.colModel[c],(null!=t&&null!=t.autoResizing&&t.autoResizing.compact||k.autoResizing.compact)&&k.columnsToReResizing.push(c));b=b.substring(5+k.id.length+1);k.sortname=k.colModel[c].index||b}E.call(this,"onSortCol",k.sortname,c,k.sortorder)?("local"===
k.datatype?k.deselectAfterSort&&D.resetSelection.call(a(this)):(k.selrow=null,k.multiselect&&sa.call(this,!1),d(k.selarrrow),d(k.savedRow)),k.scroll&&(m=h.bDiv.scrollLeft,M.emptyRows.call(this,!0,!1),h.hDiv.scrollLeft=m),k.subGrid&&"local"===k.datatype&&a("td.sgexpanded","#"+f(k.id)).each(function(){a(this).trigger("click")}),qa.call(this),k.lastsort=c,k.sortname!==b&&c&&(k.lastsort=c)):k.lastsort=c}},Sa=function(a){var b=a,c;for(c=a+1;c<k.colModel.length;c++)if(!0!==k.colModel[c].hidden){b=c;break}return b-
a},ia;-1===J(k.multikey,["shiftKey","altKey","ctrlKey"])&&(k.multikey=!1);k.keyName=!1;k.sortorder=k.sortorder.toLowerCase();r.cell_width=r.cellWidth();var oa=r.cmTemplate;for(Z=0;Z<k.colModel.length;Z++)ia="string"===typeof k.colModel[Z].template?null==oa||"object"!==typeof oa[k.colModel[Z].template]&&!a.isFunction(oa[k.colModel[Z].template])?{}:oa[k.colModel[Z].template]:k.colModel[Z].template,p(ia)&&(ia=ia.call(v,{cm:k.colModel[Z],iCol:Z})),k.colModel[Z]=F(!0,{},k.cmTemplate,ia||{},k.colModel[Z]),
!1===k.keyName&&!0===k.colModel[Z].key&&(k.keyName=k.colModel[Z].name);!0===k.grouping&&(k.scroll=!1,k.rownumbers=!1,k.treeGrid=!1,k.gridview=!0);if(k.subGrid)try{D.setSubGrid.call(G)}catch(Ua){}!k.multiselect||"left"!==k.multiselectPosition&&"right"!==k.multiselectPosition||(Z="left"===k.multiselectPosition?"unshift":"push",k.colNames[Z]("<input role='checkbox' id='"+k.cbId+"' class='cbox' type='checkbox' aria-checked='false'/>"),k.colModel[Z]({name:"cb",width:r.cell_width?k.multiselectWidth+k.cellLayout:
k.multiselectWidth,labelClasses:"jqgh_cbox",classes:"td_cbox",sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0,frozen:!0}));k.rownumbers&&(k.colNames.unshift(""),k.colModel.unshift({name:"rn",width:r.cell_width?k.rownumWidth+k.cellLayout:k.rownumWidth,labelClasses:"jqgh_rn",classes:"td_rn",sortable:!1,resizable:!1,hidedlg:!0,search:!1,align:"center",fixed:!0,frozen:!0}));k.iColByName=ca(k.colModel);k.xmlReader=F(!0,{root:"rows",row:"row",page:"rows>page",total:"rows>total",records:"rows>records",
repeatitems:!0,cell:"cell",id:"[id]",userdata:"userdata",subgrid:{root:"rows",row:"row",repeatitems:!0,cell:"cell"}},k.xmlReader);k.jsonReader=F(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!0,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},k.jsonReader);k.localReader=F(!0,{root:"rows",page:"page",total:"total",records:"records",repeatitems:!1,cell:"cell",id:"id",userdata:"userdata",subgrid:{root:"rows",repeatitems:!0,cell:"cell"}},
k.localReader);k.scroll&&(k.pgbuttons=!1,k.pginput=!1,k.rowList=[]);if(!0===k.treeGrid){try{D.setTreeGrid.call(G)}catch(Va){}"local"!==k.datatype&&(k.localReader={id:"_id_"});k.iPropByName=ha(k.additionalProperties)}(function(){var a=k.remapColumns,b=k.colModel,c=b.length,e=[],d,g;for(d=0;d<c;d++)g=b[d].name,0>J(g,k.reservedColumnNames)&&e.push(g);if(null!=a)for(b=e.slice(),d=0;d<a.length;d++)e[d]=b[a[d]];k.cmNamesInputOrder=e})();da();k.data.length&&(Ea.call(v),ma());if(!0===k.shrinkToFit&&!0===
k.forceFit)for(Z=k.colModel.length-1;0<=Z;Z--)if(!0!==k.colModel[Z].hidden){k.colModel[Z].resizable=!1;break}var Ia,Fa,Ga,Ha,ca=[],ha=[];ia=[];var da="<thead><tr class='ui-jqgrid-labels' role='row'>",Ba=L("states.hover"),Ca=L("states.disabled");if(k.multiSort)for(ca=k.sortname.split(","),Z=0;Z<ca.length;Z++)ia=H(ca[Z]).split(" "),ca[Z]=H(ia[0]),ha[Z]=ia[1]?H(ia[1]):k.sortorder||"asc";for(Z=0;Z<k.colNames.length;Z++){H=k.colModel[Z];ia=k.headertitles||H.headerTitle?' title="'+t("string"===typeof H.headerTitle?
H.headerTitle:k.colNames[Z])+'"':"";da+="<th id='"+k.id+"_"+H.name+"' role='columnheader' class='"+L("colHeaders","ui-th-column ui-th-"+fa+" "+(H.labelClasses||""))+"'"+ia+">";ia=H.index||H.name;switch(H.labelAlign){case "left":oa="text-align:left;";break;case "right":oa="text-align:right;"+(!1===H.sortable?"":"padding-right:"+k.autoResizing.widthOfVisiblePartOfSortIcon+"px;");break;case "likeData":oa=void 0===H.align||"left"===H.align?"text-align:left;":"right"===H.align?"text-align:right;"+(!1===
H.sortable?"":"padding-right:"+k.autoResizing.widthOfVisiblePartOfSortIcon+"px;"):"";break;default:oa=""}da+="<div id='jqgh_"+k.id+"_"+H.name+"'"+(x?" class='ui-th-div-ie'":"")+(""===oa?"":" style='"+oa+"'")+">";oa=H.autoResizable&&"actions"!==H.formatter?"<span class='"+k.autoResizing.wrapperClassName+"'>"+k.colNames[Z]+"</span>":k.colNames[Z];k.sortIconsBeforeText?(da+=(k.builderSortIcons||r.builderSortIcons).call(v,Z),da+=oa):(da+=oa,da+=(k.builderSortIcons||r.builderSortIcons).call(v,Z));da+=
"</div></th>";H.width=H.width?parseInt(H.width,10):150;"boolean"!==typeof H.title&&(H.title=!0);H.lso="";ia===k.sortname&&(k.lastsort=Z);k.multiSort&&(ia=J(ia,ca),-1!==ia&&(H.lso=ha[ia]))}G.append(da+"</tr></thead>");a(v.tHead).children("tr").children("th").hover(function(){a(this).addClass(Ba)},function(){a(this).removeClass(Ba)});k.multiselect&&a(k.cb,v).bind("click",function(){d(k.selarrrow);var b=L("states.select"),c,e=[],g=k.iColByName.cb,l=function(c,e){a(c)[e?"addClass":"removeClass"](b).attr(e?
{"aria-selected":"true",tabindex:"0"}:{"aria-selected":"false",tabindex:"-1"});if(void 0!==g)a(c.cells[g]).children("input.cbox")[k.propOrAttr]("checked",e)},f=M.fbRows,h=Ca+" ui-subgrid jqgroup jqfoot jqgfirstrow";this.checked?(c=!0,k.selrow=1<v.rows.length?v.rows[v.rows.length-1].id:null):(c=!1,k.selrow=null);a(v.rows).each(function(a){y(this,h)||(l(this,c),(c?k.selarrrow:e).push(this.id),f&&l(f[a],c))});E.call(v,"onSelectAll",c?k.selarrrow:e,c)}).closest("th.ui-th-column").css("padding","0");!0===
k.autowidth&&(H=Math.floor(a(z).innerWidth()),k.width=0<H?H:"nw");isNaN(k.width)?isNaN(parseFloat(k.width))||(k.width=parseFloat(k.width)):k.width=Number(k.width);k.widthOrg=k.width;(function(){var a=0,b=r.cell_width?0:ea(k.cellLayout,0),c=0,e,d=ea(k.scrollOffset,0),g,l=!1,f,h=0,m,v=r.isCellClassHidden;N(k.colModel,function(){void 0===this.hidden&&(this.hidden=!1);if(k.grouping&&k.autowidth){var e=J(this.name,k.groupingView.groupField);0<=e&&k.groupingView.groupColumnShow.length>e&&(this.hidden=!k.groupingView.groupColumnShow[e])}this.widthOrg=
g=ea(this.width,0);!1!==this.hidden||v(this.classes)||(a+=g+b,this.fixed?h+=g+b:c++)});isNaN(k.width)&&(k.width=a+(!1!==k.shrinkToFit||isNaN(k.height)?0:d));M.width=k.width;k.tblwidth=a;!1===k.shrinkToFit&&!0===k.forceFit&&(k.forceFit=!1);!0===k.shrinkToFit&&0<c&&(f=M.width-b*c-h,isNaN(k.height)||(f-=d,l=!0),a=0,N(k.colModel,function(d){!1!==this.hidden||v(this.classes)||this.fixed||(this.width=g=Math.round(f*this.width/(k.tblwidth-b*c-h)),a+=g,e=d)}),m=0,l?M.width-h-(a+b*c)!==d&&(m=M.width-h-(a+
b*c)-d):l||1===Math.abs(M.width-h-(a+b*c))||(m=M.width-h-(a+b*c)),k.colModel[e].width+=m,k.tblwidth=a+m+b*c+h,k.tblwidth>k.width&&(k.colModel[e].width-=k.tblwidth-parseInt(k.width,10),k.tblwidth=k.width))})();a(z).css("width",M.width+"px").append("<div class='"+L("resizer","ui-jqgrid-resize-mark")+"' id='"+k.rsId+"'> </div>");a(k.rs).bind("selectstart",function(){return!1}).click(P).dblclick(function(b){var c=a(this).data("idx"),e=a(this).data("pageX"),d=k.colModel[c];if(null==e)return!1;var e=
String(e).split(";"),g=parseFloat(e[0]),l=parseFloat(e[1]);if(2===e.length&&(5<Math.abs(g-l)||5<Math.abs(b.pageX-g)||5<Math.abs(b.pageX-l)))return!1;E.call(v,"resizeDblClick",c,d,b)&&null!=d&&d.autoResizable&&D.autoResizeColumn.call(G,c);return!1});a(O).css("width",M.width+"px");var ya="";k.footerrow&&(ya+="<table role='presentation' style='width:"+k.tblwidth+"px' class='ui-jqgrid-ftable'"+(ka?" cellspacing='0'":"")+"><tbody><tr role='row' class='"+L("rowFooter","footrow footrow-"+fa)+"'>");var Da=
"<tr class='jqgfirstrow' role='row' style='height:auto'>";k.disableClick=!1;a("th",v.tHead.rows[0]).each(function(b){var c=k.colModel[b],e=c.name,d=a(this),g=d.children("div"),l=g.children("span.s-ico"),f=k.showOneSortIcon;Ia=c.width;void 0===c.resizable&&(c.resizable=!0);c.resizable?(Fa=document.createElement("span"),a(Fa).html(" ").addClass("ui-jqgrid-resize ui-jqgrid-resize-"+fa).bind("selectstart",function(){return!1}),d.addClass(k.resizeclass)):Fa="";d.css("width",Ia+"px").prepend(Fa);Fa=
null;var h="";!0===c.hidden&&(d.css("display","none"),h="display:none;");Da+="<td role='gridcell' "+(c.classes?"class='"+c.classes+"' ":"")+"style='height:0;width:"+Ia+"px;"+h+"'></td>";M.headers[b]={width:Ia,el:this};Ga=c.sortable;"boolean"!==typeof Ga&&(Ga=c.sortable=!0);"cb"!==e&&"subgrid"!==e&&"rn"!==e&&Ga&&k.viewsortcols[2]&&g.addClass("ui-jqgrid-sortable");Ga&&(k.multiSort?(e="desc"===c.lso?"asc":"desc",k.viewsortcols[0]?(l.show(),c.lso&&(l.children("span.ui-icon-"+c.lso).removeClass(Ca),f&&
l.children("span.ui-icon-"+e).hide())):c.lso&&(l.show(),l.children("span.ui-icon-"+c.lso).removeClass(Ca),f&&l.children("span.ui-icon-"+e).hide())):(c="desc"===k.sortorder?"asc":"desc",k.viewsortcols[0]?(l.show(),b===k.lastsort&&(l.children("span.ui-icon-"+k.sortorder).removeClass(Ca),f&&l.children("span.ui-icon-"+c).hide())):b===k.lastsort&&""!==k.sortname&&(l.show(),l.children("span.ui-icon-"+k.sortorder).removeClass(Ca),f&&l.children("span.ui-icon-"+c).hide())));k.footerrow&&(ya+="<td role='gridcell' "+
xa(b,0,"",null,"",!1)+"> </td>")}).mousedown(function(b){var c=a(this),e=c.closest(".ui-jqgrid-hdiv").hasClass("frozen-div"),d=function(){var b=[c.position().left+c.outerWidth()];"rtl"===k.direction&&(b[0]=k.width-b[0]);b[0]-=e?0:M.bDiv.scrollLeft;b.push(a(M.hDiv).position().top);b.push(a(M.bDiv).offset().top-a(M.hDiv).offset().top+a(M.bDiv).height()+(M.sDiv?a(M.sDiv).height():0));return b},g;if(1===a(b.target).closest("th>span.ui-jqgrid-resize").length)return g=k.iColByName[(this.id||"").substring(k.id.length+
1)],null!=g&&(!0===k.forceFit&&(k.nv=Sa(g)),M.dragStart(g,b,d(),c)),!1}).click(function(b){if(k.disableClick)return k.disableClick=!1;var c="th.ui-th-column>div",e,d,c=k.viewsortcols[2]?c+".ui-jqgrid-sortable":c+">span.s-ico>span.ui-grid-ico-sort";b=a(b.target).closest(c);if(1===b.length)return k.viewsortcols[2]||(e=!0,d=b.hasClass("ui-icon-desc")?"desc":"asc"),b=k.iColByName[(this.id||"").substring(k.id.length+1)],null!=b&&Oa.call(v,a("div",this)[0].id,b,e,d,this),!1});if(k.sortable&&a.fn.sortable)try{D.sortableColumns.call(G,
a(v.tHead.rows[0]))}catch(Wa){}k.footerrow&&(ya+="</tr></tbody></table>");Da+="</tr>";O=document.createElement("tbody");v.appendChild(O);G.addClass(L("grid","ui-jqgrid-btable")).append(Da);var Da=null,O=a("<table class='"+L("hTable","ui-jqgrid-htable")+"' style='width:"+k.tblwidth+"px' role='presentation' aria-labelledby='gbox_"+k.id+"'"+(ka?" cellspacing='0'":"")+"></table>").append(v.tHead),ra=k.caption&&!0===k.hiddengrid?!0:!1,H=a("<div class='ui-jqgrid-hbox"+("rtl"===fa?"-rtl":"")+"'></div>"),
Ja=L("bottom");M.hDiv=document.createElement("div");a(M.hDiv).css({width:M.width+"px"}).addClass(L("hDiv","ui-jqgrid-hdiv")).append(H).scroll(function(){var b=a(this).next(".ui-jqgrid-bdiv")[0];b&&(b.scrollLeft=this.scrollLeft)});a(H).append(O);O=null;ra&&a(M.hDiv).hide();k.rowNum=parseInt(k.rowNum,10);if(isNaN(k.rowNum)||0>=k.rowNum)k.rowNum=k.maxRowNum;k.pager&&("string"===typeof k.pager&&"#"!==k.pager.substr(0,1)?(H=k.pager,O=a("#"+f(k.pager))):!0===k.pager?(H=l(),O=a("<div id='"+H+"'></div>"),
O.appendTo("body"),k.pager="#"+f(H)):(O=a(k.pager),H=O.attr("id")),0<O.length?(O.css({width:M.width+"px"}).addClass(L("pager","ui-jqgrid-pager "+Ja)).appendTo(z),ra&&O.hide(),A.call(v,H,""),k.pager="#"+f(H)):k.pager="");!1===k.cellEdit&&!0===k.hoverrows&&G.bind("mouseover",function(b){Ha=a(b.target).closest("tr.jqgrow");"ui-subgrid"!==a(Ha).attr("class")&&a(Ha).addClass(Ba)}).bind("mouseout",function(b){Ha=a(b.target).closest("tr.jqgrow");a(Ha).removeClass(Ba)});var na,Ka,Pa,La=function(b){var c,
e;do if(c=a(b).closest("td"),0<c.length){b=c.parent();e=b.parent().parent();if(b.is(".jqgrow")&&(e[0]===this||e.is("table.ui-jqgrid-btable")&&(e[0].id||"").replace("_frozen","")===this.id))break;b=c.parent()}while(0<c.length);return c};G.before(M.hDiv).click(function(b){var c=L("states.select"),e=b.target,g=La.call(this,e),l=g.parent();if(0!==l.length&&!y(l,Ca)){na=l[0].id;var h=a(e).hasClass("cbox"),m=E.call(v,"beforeSelectRow",na,b),t=r.detectRowEditing.call(v,na),t=null!=t&&"cellEditing"!==t.mode;
if("A"!==e.tagName&&(!t||h))if(Ka=g[0].cellIndex,Pa=g.html(),E.call(v,"onCellSelect",na,Ka,Pa,b),!0===k.cellEdit)if(k.multiselect&&h&&m)Y.call(G,na,!0,b);else{na=l[0].rowIndex;try{D.editCell.call(G,na,Ka,!0)}catch(z){}}else if(m)if(k.multikey)b[k.multikey]?Y.call(G,na,!0,b):k.multiselect&&h&&(h=a("#jqg_"+f(k.id)+"_"+na).is(":checked"),a("#jqg_"+f(k.id)+"_"+na)[W]("checked",!h));else if(k.multiselect&&k.multiboxonly){if(!h){var B=k.frozenColumns?k.id+"_frozen":"";a(k.selarrrow).each(function(b,e){var d=
D.getGridRowById.call(G,e);d&&a(d).removeClass(c);a("#jqg_"+f(k.id)+"_"+f(e))[k.propOrAttr]("checked",!1);B&&(a("#"+f(e),"#"+f(B)).removeClass(c),a("#jqg_"+f(k.id)+"_"+f(e),"#"+f(B))[k.propOrAttr]("checked",!1))});d(k.selarrrow)}Y.call(G,na,!0,b)}else e=k.selrow,Y.call(G,na,!0,b),"toggle"!==k.singleSelectClickMode||k.multiselect||e!==na||(this.grid.fbRows&&(l=l.add(this.grid.fbRows[na])),l.removeClass(c).attr({"aria-selected":"false",tabindex:"-1"}),k.selrow=null)}}).bind("reloadGrid",function(b,
c){var e=this.grid,g=a(this);!0===k.treeGrid&&(k.datatype=k.treedatatype);c=F({},n.reloadGridOptions||{},k.reloadGridOptions||{},c||{});"local"===k.datatype&&k.dataTypeOrg&&k.loadonce&&c.fromServer&&(k.datatype=k.dataTypeOrg,delete k.dataTypeOrg);c.current&&e.selectionPreserver.call(this);"local"===k.datatype?(D.resetSelection.call(g),k.data.length&&(Ea.call(this),ma())):k.treeGrid||(k.selrow=null,k.iRow=-1,k.iCol=-1,k.multiselect&&(d(k.selarrrow),sa.call(this,!1)),d(k.savedRow));k.scroll&&M.emptyRows.call(this,
!0,!1);if(c.page){var l=parseInt(c.page,10);l>k.lastpage&&(l=k.lastpage);1>l&&(l=1);k.page=l;e.bDiv.scrollTop=e.prevRowHeight?(l-1)*e.prevRowHeight*k.rowNum:0}e.prevRowHeight&&k.scroll&&void 0===c.page?(delete k.lastpage,e.populateVisible.call(this)):e.populate.call(this);!0===k._inlinenav&&g.jqGrid("showAddEditButtons",!1);return!1}).dblclick(function(a){var b=La.call(this,a.target),c=b.parent();if(0<b.length&&!E.call(v,"ondblClickRow",c.attr("id"),c[0].rowIndex,b[0].cellIndex,a))return!1}).bind("contextmenu",
function(a){var b=La.call(this,a.target),c=b.parent(),e=c.attr("id");if(0!==b.length&&(k.multiselect||Y.call(G,e,!0,a),!E.call(v,"onRightClickRow",e,c[0].rowIndex,b[0].cellIndex,a)))return!1});M.bDiv=document.createElement("div");x&&"auto"===String(k.height).toLowerCase()&&(k.height="100%");a(M.bDiv).append(a('<div style="position:relative;'+(ka?"height:0.01%;":"")+'"></div>').append("<div></div>").append(v)).addClass("ui-jqgrid-bdiv").css({height:k.height+(isNaN(k.height)?"":"px"),width:M.width+
"px"}).scroll(M.scrollGrid);G.css({width:k.tblwidth+"px"});a.support.tbody||2===a(">tbody",v).length&&a(">tbody:gt(0)",v).remove();k.multikey&&a(M.bDiv).bind(r.msie?"selectstart":"mousedown",function(){return!1});ra&&a(M.bDiv).hide();M.cDiv=document.createElement("div");var Ma=K("gridMinimize.visible"),Qa=K("gridMinimize.hidden"),x=R("showhide"),Na=!0===k.hidegrid?a("<a role='link' class='"+L("titleButton","ui-jqgrid-titlebar-close")+"'"+(x?" title='"+x+"'":"")+"/>").hover(function(){Na.addClass(Ba)},
function(){Na.removeClass(Ba)}).append("<span class='"+Ma+"'></span>"):"";a(M.cDiv).append("<span class='ui-jqgrid-title'>"+k.caption+"</span>").append(Na).addClass(L("gridTitle","ui-jqgrid-titlebar ui-jqgrid-caption"+("rtl"===fa?"-rtl":"")));a(M.cDiv).insertBefore(M.hDiv);k.toolbar[0]&&(M.uDiv=document.createElement("div"),"top"===k.toolbar[1]?a(M.uDiv).insertBefore(M.hDiv):"bottom"===k.toolbar[1]&&a(M.uDiv).insertAfter(M.hDiv),x=L("toolbarUpper","ui-userdata"),"both"===k.toolbar[1]?(M.ubDiv=document.createElement("div"),
a(M.uDiv).addClass(x).attr("id","t_"+k.id).insertBefore(M.hDiv),a(M.ubDiv).addClass(L("toolbarBottom","ui-userdata")).attr("id","tb_"+k.id).insertAfter(M.hDiv),ra&&a(M.ubDiv).hide()):a(M.uDiv).width(M.width).addClass(x).attr("id","t_"+k.id),ra&&a(M.uDiv).hide());"string"===typeof k.datatype&&(k.datatype=k.datatype.toLowerCase());k.toppager?(k.toppager=k.id+"_toppager",M.topDiv=a("<div id='"+k.toppager+"'></div>")[0],a(M.topDiv).addClass(L("pager","ui-jqgrid-toppager")).css({width:M.width+"px"}).insertBefore(M.hDiv),
A.call(v,k.toppager,"_t"),k.toppager="#"+f(k.toppager)):""!==k.pager||k.scroll||(k.rowNum=k.maxRowNum);k.footerrow&&(M.sDiv=a("<div class='ui-jqgrid-sdiv'></div>")[0],H=a("<div class='ui-jqgrid-hbox"+("rtl"===fa?"-rtl":"")+"'></div>"),a(M.sDiv).append(H).width(M.width).insertAfter(M.hDiv),a(H).append(ya),M.footers=a(".ui-jqgrid-ftable",M.sDiv)[0].rows[0].cells,k.rownumbers&&(M.footers[0].className=L("rowNum","jqgrid-rownum")),ra&&a(M.sDiv).hide());H=null;if(k.caption){var Ta=k.datatype;!0===k.hidegrid&&
(a(".ui-jqgrid-titlebar-close",M.cDiv).click(function(b){var c=".ui-jqgrid-bdiv,.ui-jqgrid-hdiv,.ui-jqgrid-pager,.ui-jqgrid-sdiv",e=this;!0===k.toolbar[0]&&("both"===k.toolbar[1]&&(c+=",#"+f(a(M.ubDiv).attr("id"))),c+=",#"+f(a(M.uDiv).attr("id")));var d=a(c,k.gView).length;k.toppager&&(c+=","+k.toppager);"visible"===k.gridstate?a(c,k.gBox).slideUp("fast",function(){d--;0===d&&(a("span",e).removeClass(Ma).addClass(Qa),k.gridstate="hidden",a(k.gBox).hasClass("ui-resizable")&&a(".ui-resizable-handle",
k.gBox).hide(),a(M.cDiv).addClass(Ja),ra||E.call(v,"onHeaderClick",k.gridstate,b))}):"hidden"===k.gridstate&&(a(M.cDiv).removeClass(Ja),a(c,k.gBox).slideDown("fast",function(){d--;0===d&&(a("span",e).removeClass(Qa).addClass(Ma),ra&&(k.datatype=Ta,qa.call(v),ra=!1),k.gridstate="visible",a(k.gBox).hasClass("ui-resizable")&&a(".ui-resizable-handle",k.gBox).show(),ra||E.call(v,"onHeaderClick",k.gridstate,b))}));return!1}),ra&&(k.datatype="local",a(".ui-jqgrid-titlebar-close",M.cDiv).trigger("click")))}else a(M.cDiv).hide(),
a(M.cDiv).nextAll("div:visible").first().addClass("ui-corner-top");a(M.hDiv).after(M.bDiv);a(z).click(P).dblclick(function(b){var c=a(k.rs),e=c.offset(),d=c.data("idx"),g=c.data("delta"),l=k.colModel[d],f=a(this).data("pageX")||c.data("pageX");if(null==f)return!1;var f=String(f).split(";"),h=parseFloat(f[0]),m=parseFloat(f[1]);if(2===f.length&&(5<Math.abs(h-m)||5<Math.abs(b.pageX-h)||5<Math.abs(b.pageX-m)))return!1;E.call(v,"resizeDblClick",d,l)&&e.left-1<=b.pageX+g&&b.pageX+g<=e.left+c.outerWidth()+
1&&null!=l&&l.autoResizable&&D.autoResizeColumn.call(G,d);return!1});k.pager||a(M.cDiv).nextAll("div:visible").filter(":last").addClass(Ja);a(".ui-jqgrid-labels",M.hDiv).bind("selectstart",function(){return!1});v.formatCol=xa;v.sortData=Oa;v.updatepager=function(b,e){var d=this,g=a(d),l=d.grid,f,h,m,v,t,z,D=k.pager||"",B=k.pager?"_"+k.pager.substr(1):"";f=l.bDiv;var q=a.fmatter?a.fmatter.NumberFormat:null,n=k.toppager?"_"+k.toppager.substr(1):"",A=L("states.hover"),p=L("states.disabled");h=parseInt(k.page,
10)-1;0>h&&(h=0);h*=parseInt(k.rowNum,10);v=h+k.reccount;if(k.scroll){z=a(c(21,f)[0].rows).slice(1);h=v-z.length;k.reccount=z.length;if(z=z.outerHeight()||l.prevRowHeight)m=h*z,t=r.fixMaxHeightOfDiv.call(d,parseInt(k.records,10)*z),a(f).children("div").first().css({height:t+"px"}).children("div").first().css({height:m+"px",display:m+"px"?"":"none"}),0===f.scrollTop&&1<k.page&&(f.scrollTop=k.rowNum*(k.page-1)*z);f.scrollLeft=l.hDiv.scrollLeft}if(D+=k.toppager?(D?",":"")+k.toppager:"")z=X.call(G,"formatter.integer")||
{},l=ea(k.page),f=ea(k.lastpage),a(".selbox",D)[W]("disabled",!1),!0===k.pginput&&(a(".ui-pg-input",D).val(k.page),m=k.toppager?"#sp_1"+B+",#sp_1"+n:"#sp_1"+B,a(m).html(a.fmatter?q(k.lastpage,z):k.lastpage).closest(".ui-pg-table").each(function(){Aa.call(d,a(this))})),k.viewrecords&&(0===k.reccount?a(".ui-paging-info",D).html(R("emptyrecords")):(m=h+1,t=k.records,a.fmatter&&(m=q(m,z),v=q(v,z),t=q(t,z)),a(".ui-paging-info",D).html(r.format(R("recordtext"),m,v,t)))),!0===k.pgbuttons&&(0>=l&&(l=f=0),
1===l||0===l?(a("#first"+B+", #prev"+B).addClass(p).removeClass(A),k.toppager&&a("#first_t"+n+", #prev_t"+n).addClass(p).removeClass(A)):(a("#first"+B+", #prev"+B).removeClass(p),k.toppager&&a("#first_t"+n+", #prev_t"+n).removeClass(p)),l===f||0===l?(a("#next"+B+", #last"+B).addClass(p).removeClass(A),k.toppager&&a("#next_t"+n+", #last_t"+n).addClass(p).removeClass(A)):(a("#next"+B+", #last"+B).removeClass(p),k.toppager&&a("#next_t"+n+", #last_t"+n).removeClass(p)));!0===b&&!0===k.rownumbers&&a(">td.jqgrid-rownum",
d.rows).each(function(b){a(this).html(h+1+b)});e&&k.jqgdnd&&g.jqGrid("gridDnD","updateDnD");E.call(d,"gridComplete");g.triggerHandler("jqGridAfterGridComplete")};v.refreshIndex=ma;v.setHeadCheckBox=sa;v.fixScrollOffsetAndhBoxPadding=ba;v.constructTr=function(b,c,e,d,g,l){var f="-1",h="",m,v=c?"display:none;":"";e=L("gridRow","jqgrow ui-row-"+k.direction)+(e?" "+e:"")+(l?" "+L("states.select"):"");l=a(this).triggerHandler("jqGridRowAttr",[d,g,b]);"object"!==typeof l&&(l=p(k.rowattr)?k.rowattr.call(this,
d,g,b):"string"===typeof k.rowattr&&null!=r.rowattr&&p(r.rowattr[k.rowattr])?r.rowattr[k.rowattr].call(this,d,g,b):{});if(null!=l&&!a.isEmptyObject(l)){l.hasOwnProperty("id")&&(b=l.id,delete l.id);l.hasOwnProperty("tabindex")&&(f=l.tabindex,delete l.tabindex);l.hasOwnProperty("style")&&(v+=l.style,delete l.style);l.hasOwnProperty("class")&&(e+=" "+l["class"],delete l["class"]);try{delete l.role}catch(t){}for(m in l)l.hasOwnProperty(m)&&(h+=" "+m+"="+l[m])}k.treeGrid&&parseInt(d[k.treeReader.level_field],
10)!==parseInt(k.tree_root_level,10)&&(((d=D.getNodeParent.call(a(this),d))&&d.hasOwnProperty(k.treeReader.expanded_field)?d[k.treeReader.expanded_field]:1)||c||(v+="display:none;"));return'<tr role="row" id="'+b+'" tabindex="'+f+'" class="'+e+'"'+(""===v?"":' style="'+v+'"')+h+">"};v.formatter=function(b,c,d,g,l,f){var h=k.colModel[d];if(void 0!==h.formatter){b=""!==String(k.idPrefix)?e(k.idPrefix,b):b;var m={rowId:b,colModel:h,gid:k.id,pos:d,rowData:f};c=p(h.cellBuilder)?h.cellBuilder.call(v,c,
m,g,l):p(h.formatter)?h.formatter.call(v,c,m,g,l):a.fmatter?a.fn.fmatter.call(v,h.formatter,c,m,g,l):ga(c)}else c=ga(c);c=h.autoResizable&&"actions"!==h.formatter?"<span class='"+k.autoResizing.wrapperClassName+"'>"+c+"</span>":c;k.treeGrid&&"edit"!==l&&(void 0===k.ExpandColumn&&0===d||k.ExpandColumn===h.name)&&(null==f&&(f=k.data[k._index[b]]),b=parseInt(f[k.treeReader.level_field]||0,10),b=0===parseInt(k.tree_root_level,10)?b:b-1,d=f[k.treeReader.leaf_field],l=f[k.treeReader.expanded_field],f=f[k.treeReader.icon_field],
c="<div class='tree-wrap tree-wrap-"+k.direction+"' style='width:"+18*(b+1)+"px;'><div class='"+q(k.treeIcons.commonIconClass,d?(void 0!==f&&""!==f?f:k.treeIcons.leaf)+" tree-leaf":l?k.treeIcons.minus+" tree-minus":k.treeIcons.plus+" tree-plus","treeclick")+"' style='"+(!0===k.ExpandColClick?"cursor:pointer;":"")+("rtl"===k.direction?"right:":"left:")+18*b+"px;'></div></div><span class='cell-wrapper"+(d?"leaf":"")+"'"+(k.ExpandColClick?" style='cursor:pointer;'":"")+">"+c+"</span>");return c};F(M,
{populate:qa,emptyRows:function(b,c){var e=M.bDiv,g=null!=M.fbDiv?M.fbDiv.children(".ui-jqgrid-btable")[0]:null,l=function(b){if(b){var c=b.rows;if(k.deepempty)c&&a(c).slice(1).remove();else if(k.quickEmpty)for(;1<c.length;)b.deleteRow(c.length-1);else c=c[0],a(b.firstChild).empty().append(c)}};a(this).unbind(".jqGridFormatter");l(this);l(g);b&&k.scroll&&(a(e.firstChild).css({height:"auto"}),a(e.firstChild.firstChild).css({height:0,display:"none"}),0!==e.scrollTop&&(e.scrollTop=0));!0===c&&k.treeGrid&&
(d(k.data),d(k.lastSelectedData),k._index={});k.rowIndexes={};k.iRow=-1;k.iCol=-1},beginReq:ua,endReq:va});v.addXmlData=la;v.addJSONData=la;v.rebuildRowIndexes=ja;v.grid.cols=v.rows[0].cells;E.call(v,"onInitGrid");k.treeGrid&&"local"===k.datatype&&null!=k.data&&0<k.data.length&&(k.datatype="jsonstring",k.datastr=k.data,k.data=[]);qa.call(v);k.hiddengrid=!1}}}})};var C=a.fn.jqGrid;r.extend({getGridRes:function(b){var c=this[0];if(!c||!c.grid||!c.p)return null;c=r.getRes(u[c.p.locale],b)||r.getRes(u["en-US"],
b);b=r.getRes(r,b);return"object"!==typeof c||null===c||a.isArray(c)?void 0!==b?b:c:a.extend(!0,{},c,b||{})},getGuiStyles:function(b,c){var e=this instanceof a&&0<this.length?this[0]:this;return e&&e.grid&&e.p?r.mergeCssClasses(r.getRes(r.guiStyles[e.p.guiStyle||r.defaults.guiStyle||"jQueryUI"],b),c||""):""},getGridParam:function(a){var b=this[0];return b&&b.grid?a?void 0!==b.p[a]?b.p[a]:null:b.p:null},setGridParam:function(b,c){return this.each(function(){null==c&&(c=!1);this.grid&&"object"===typeof b&&
(!0===c?this.p=a.extend({},this.p,b):a.extend(!0,this.p,b))})},getGridRowById:function(b){if(null==b)return null;var c,e=b.toString();this.each(function(){var d,l=this.rows,g;null!=this.p.rowIndexes&&(g=this.p.rowIndexes[e],(g=l[g])&&g.id===e&&(c=g));if(!c)try{for(d=l.length;d--;)if(g=l[d],e===g.id){c=g;break}}catch(h){c=a(this.grid.bDiv).find("#"+f(b)),c=0<c.length?c[0]:null}});return c},getDataIDs:function(){var b=[];this.each(function(){var c=this.rows,e=c.length,d,g;if(e&&0<e)for(d=0;d<e;d++)g=
c[d],a(g).hasClass("jqgrow")&&b.push(g.id)});return b},setSelection:function(b,c,e){return this.each(function(){function d(b,c){var e=c.clientHeight,g=c.scrollTop,l=a(b).position().top,f=b.clientHeight;l+f>=e+g?c.scrollTop=l-(e+g)+f+g:l<e+g&&l<g&&(c.scrollTop=l)}var g=a(this),l=this.p,f,h,m,t=C.getGuiStyles;m=C.getGridRowById;var n=t.call(g,"states.select"),q=t.call(g,"states.disabled"),A=this.grid.fbRows,t=function(b,c){var e=c?"addClass":"removeClass",d=l.iColByName.cb,g=c?{"aria-selected":"true",
tabindex:"0"}:{"aria-selected":"false",tabindex:"-1"},f=function(b){a(b)[e](n).attr(g);if(void 0!==d)a(b.cells[d]).children("input.cbox")[l.propOrAttr]("checked",c)};f(b);A&&f(A[b.rowIndex])};void 0!==b&&(c=!1===c?!1:!0,null!=e&&(h=a(e.target).closest("tr.jqgrow"),0<h.length&&(f=h[0],A&&(f=this.rows[f.rowIndex]))),null==f&&(f=m.call(g,b)),!f||!f.className||-1<f.className.indexOf(q)||(!0===l.scrollrows&&(h=m.call(g,b),null!=h&&(h=h.rowIndex,0<=h&&d(this.rows[h],this.grid.bDiv))),l.multiselect?(this.setHeadCheckBox(!1),
l.selrow=f.id,m=a.inArray(l.selrow,l.selarrrow),-1===m?(g=!0,l.selarrrow.push(l.selrow)):null!==r.detectRowEditing.call(this,f.id)?g=!0:(g=!1,l.selarrrow.splice(m,1),m=l.selarrrow[0],l.selrow=void 0===m?null:m),"ui-subgrid"!==f.className&&t(f,g),c&&E.call(this,"onSelectRow",f.id,g,e)):"ui-subgrid"!==f.className&&(l.selrow!==f.id?(null!==l.selrow&&(g=m.call(g,l.selrow))&&t(g,!1),t(f,!0),g=!0):g=!1,l.selrow=f.id,c&&E.call(this,"onSelectRow",f.id,g,e))))})},resetSelection:function(b){return this.each(function(){var c=
a(this),e=this.p,g=C.getGuiStyles,l=C.getGridRowById,f=g.call(c,"states.select"),h="edit-cell "+f,g="selected-row "+g.call(c,"states.hover"),m=e.iColByName.cb,t=void 0!==m,n=this.grid.fbRows,q=function(b){var c={"aria-selected":"false",tabindex:"-1"};a(b).removeClass(f).attr(c);if(t)a(b.cells[m]).children("input.cbox")[e.propOrAttr]("checked",!1);if(n&&(b=n[b.rowIndex],a(b).removeClass(f).attr(c),t))a(b.cells[m]).children("input.cbox")[e.propOrAttr]("checked",!1)};void 0!==b?(c=l.call(c,b),q(c),t&&
(this.setHeadCheckBox(!1),c=a.inArray(b,e.selarrrow),-1!==c&&e.selarrrow.splice(c,1))):e.multiselect?(a(this.rows).each(function(){var b=a.inArray(this.id,e.selarrrow);-1!==b&&(q(this),e.selarrrow.splice(b,1))}),this.setHeadCheckBox(!1),d(e.selarrrow),e.selrow=null):e.selrow&&(c=l.call(c,e.selrow),q(c),e.selrow=null);!0===e.cellEdit&&0<=parseInt(e.iCol,10)&&0<=parseInt(e.iRow,10)&&(c=this.rows[e.iRow],null!=c&&(a(c.cells[e.iCol]).removeClass(h),a(c).removeClass(g)),n&&(c=n[e.iRow],null!=c&&(a(c.cells[e.iCol]).removeClass(h),
a(c).removeClass(g))));d(e.savedRow)})},getRowData:function(b,c){var d={},g;"object"===typeof b&&(c=b,b=void 0);c=c||{};this.each(function(){var l=this.p,f=!1,h,m=2,t=0,n=this.rows,q,p,w,r,E;if(void 0===b)f=!0,g=[],m=n.length;else if(h=C.getGridRowById.call(a(this),b),!h)return d;for(;t<m;){f&&(h=n[t]);if(a(h).hasClass("jqgrow")){p=a("td[role=gridcell]",h);for(q=0;q<p.length;q++)if(w=l.colModel[q],r=w.name,!("cb"===r||"subgrid"===r||"rn"===r||"actions"===w.formatter||c.skipHidden&&w.hidden))if(E=
p[q],!0===l.treeGrid&&r===l.ExpandColumn)d[r]=A(a("span",E).first().html());else try{d[r]=a.unformat.call(this,E,{rowId:h.id,colModel:w},q)}catch(y){d[r]=A(a(E).html())}!c.includeId||!1!==l.keyName&&null!=d[l.keyName]||(d[l.prmNames.id]=e(l.idPrefix,h.id));f&&(g.push(d),d={})}t++}});return g||d},delRowData:function(b){var c=!1,d,g,l;this.each(function(){var f=this.p;d=C.getGridRowById.call(a(this),b);if(!d)return!1;f.subGrid&&(l=a(d).next(),l.hasClass("ui-subgrid")&&l.remove());a(d).remove();f.records--;
f.reccount--;this.updatepager(!0,!1);c=!0;f.multiselect&&(g=a.inArray(b,f.selarrrow),-1!==g&&f.selarrrow.splice(g,1));f.multiselect&&0<f.selarrrow.length?f.selrow=f.selarrrow[f.selarrrow.length-1]:f.selrow===b&&(f.selrow=null);if("local"===f.datatype){var h=e(f.idPrefix,b),h=f._index[h];void 0!==h&&(f.data.splice(h,1),this.refreshIndex())}this.rebuildRowIndexes();if(!0===f.altRows&&c){var m=f.altclass,t=this.grid.fbRows;a(this.rows).each(function(b){var c=a(this);t&&(c=c.add(t[this.rowIndex]));c[0===
b%2?"addClass":"removeClass"](m)})}E.call(this,"afterDelRow",b)});return c},setRowData:function(b,c,d){var l=!0;this.each(function(){var f=this,h=f.p,q,n,A=typeof d,p={};if(!f.grid)return!1;n=C.getGridRowById.call(a(f),b);if(!n)return!1;if(c)try{var w=e(h.idPrefix,b),r,y=h._index[w],u=null!=y?h.data[y]:void 0;a(h.colModel).each(function(e){var d=this.name,l;l=m(c,d);void 0!==l&&("local"===h.datatype&&null!=u&&(q=g.call(f,l,this,u[d],w,u,e),a.isFunction(this.saveLocally)?this.saveLocally.call(f,{newValue:q,
newItem:p,oldItem:u,id:w,cm:this,cmName:d,iCol:e}):p[d]=q),q=f.formatter(b,l,e,c,"edit"),l=this.title?{title:t(q)}:{},e=a(n.cells[e]),!0===h.treeGrid&&d===h.ExpandColumn&&(e=e.children("span.cell-wrapperleaf,span.cell-wrapper").first()),e.html(q).attr(l))});if("local"===h.datatype){if(h.treeGrid)for(r in h.treeReader)h.treeReader.hasOwnProperty(r)&&delete p[h.treeReader[r]];void 0!==u&&(h.data[y]=a.extend(!0,u,p));p=null}E.call(f,"afterSetRow",{rowid:b,inputData:c,iData:y,iRow:n.rowIndex,tr:n,localData:p,
cssProp:d})}catch(X){l=!1}l&&("string"===A?a(n).addClass(d):null!==d&&"object"===A&&a(n).css(d),a(f).triggerHandler("jqGridAfterGridComplete"))});return l},addRowData:function(b,c,e,d){0>a.inArray(e,"first last before after afterSelected beforeSelected".split(" "))&&(e="last");var f=!1,h,t,q,n,A,p,w,y,u,X,T;c&&(a.isArray(c)?(p=!0,w=b):(c=[c],p=!1),this.each(function(){var x=this.p,O=c.length,aa=a(this),Q=this.rows,K=0,L=C.getGridRowById,k=x.colModel,R={},W=x.additionalProperties;p||(void 0!==b?b=
String(b):(b=l(),!1!==x.keyName&&(w=x.keyName,void 0!==c[0][w]&&(b=c[0][w]))));for(y=x.altclass;K<O;){u=c[K];t=[];if(p)try{b=u[w],void 0===b&&(b=l())}catch(ba){b=l()}T=b;for(n=0;n<k.length;n++)X=k[n],h=X.name,"rn"!==h&&"cb"!==h&&"subgrid"!==h&&(A=g.call(this,u[h],X,void 0,T,{},n),a.isFunction(X.saveLocally)?X.saveLocally.call(this,{newValue:A,newItem:R,oldItem:{},id:T,cm:X,cmName:h,iCol:n}):void 0!==A&&(R[h]=A));for(n=0;n<W.length;n++)A=m(u,W[n]),void 0!==A&&(R[W[n]]=A);"local"===x.datatype&&(R[x.localReader.id]=
T,x._index[T]=x.data.length,x.data.push(R));t=r.parseDataToHtml.call(this,1,[b],[u]);t=t.join("");if(0===Q.length)a("table:first",this.grid.bDiv).append(t);else{if("afterSelected"===e||"beforeSelected"===e)void 0===d&&null!==x.selrow?(d=x.selrow,e="afterSelected"===e?"after":"before"):e="afterSelected"===e?"last":"first";switch(e){case "last":a(Q[Q.length-1]).after(t);q=Q.length-1;break;case "first":a(Q[0]).after(t);q=1;break;case "after":if(q=L.call(aa,d))a(Q[q.rowIndex+1]).hasClass("ui-subgrid")?
(a(Q[q.rowIndex+1]).after(t),q=q.rowIndex+2):(a(q).after(t),q=q.rowIndex+1);break;case "before":if(q=L.call(aa,d))a(q).before(t),q=q.rowIndex-1}}!0===x.subGrid&&C.addSubGrid.call(aa,x.iColByName.subgrid,q);x.records++;x.reccount++;0===x.lastpage&&(x.lastpage=1);E.call(this,"afterAddRow",{rowid:b,inputData:c,position:e,srcRowid:d,iRow:q,localData:R,iData:x.data.length-1});K++}!0!==x.altRows||p||("last"===e?0===(Q.length-1)%2&&a(Q[Q.length-1]).addClass(y):a(Q).each(function(b){1===b%2?a(this).addClass(y):
a(this).removeClass(y)}));this.rebuildRowIndexes();this.updatepager(!0,!0);f=!0}));return f},footerData:function(b,c,e){function d(a){for(var b in a)if(a.hasOwnProperty(b))return!1;return!0}var l,g=!1,f={},h;null==b&&(b="get");"boolean"!==typeof e&&(e=!0);b=b.toLowerCase();this.each(function(){var m=this,q=m.p,n;if(!m.grid||!q.footerrow||"set"===b&&d(c))return!1;g=!0;a(q.colModel).each(function(d){l=this.name;"set"===b?void 0!==c[l]&&(n=e?m.formatter("",c[l],d,c,"edit"):c[l],h=this.title?{title:t(n)}:
{},a("tr.footrow td:eq("+d+")",m.grid.sDiv).html(n).attr(h),g=!0):"get"===b&&(f[l]=a("tr.footrow td:eq("+d+")",m.grid.sDiv).html())})});return"get"===b?f:g},showHideCol:function(b,c){return this.each(function(){var e=this,d=a(e),l=e.grid,g=!1,f=e.p,h=r.cell_width?0:f.cellLayout,m;if(l){"string"===typeof b&&(b=[b]);c="none"!==c?"":"none";var t=""===c?!0:!1,q=f.groupHeader;(q=q&&("object"===typeof q||a.isFunction(q)))&&C.destroyGroupHeader.call(d,!1);a(f.colModel).each(function(d){if(-1!==a.inArray(this.name,
b)&&this.hidden===t){if(!0===f.frozenColumns&&!0===this.frozen)return!0;a("tr[role=row]",l.hDiv).each(function(){a(this.cells[d]).css("display",c)});a(e.rows).each(function(){var b=this.cells[d];(!a(this).hasClass("jqgroup")||null!=b&&1===b.colSpan)&&a(b).css("display",c)});f.footerrow&&a("tr.footrow td:eq("+d+")",l.sDiv).css("display",c);m=parseInt(this.width,10);f.tblwidth="none"===c?f.tblwidth-(m+h):f.tblwidth+(m+h);this.hidden=!t;g=!0;E.call(e,"onShowHideCol",t,this.name,d)}});!0===g&&C.setGridWidth.call(d,
(f.autowidth||void 0!==f.widthOrg&&"auto"!==f.widthOrg&&"100%"!==f.widthOrg?f.width:f.tblwidth)+parseInt(f.scrollOffset,10));if(q)if(null!=f.pivotOptions&&null!=f.pivotOptions.colHeaders&&1<f.pivotOptions.colHeaders.length)for(var n=f.pivotOptions.colHeaders,q=0;q<n.length;q++)n[q]&&n[q].groupHeaders.length&&C.setGroupHeaders.call(d,n[q]);else C.setGroupHeaders.call(d,f.groupHeader)}})},hideCol:function(b){return this.each(function(){C.showHideCol.call(a(this),b,"none")})},showCol:function(b){return this.each(function(){C.showHideCol.call(a(this),
b,"")})},remapColumns:function(b,c,e){function d(c){var e=c.length?t(c):a.extend({},c);a.each(b,function(a){c[a]=e[this]})}function l(c,e){(e?c.children(e):c.children()).each(function(){var c=this,e=t(c.cells);a.each(b,function(a){var b=e[this],d=c.cells[a];b.cellIndex!==a&&b.parentNode.insertBefore(b,d)})})}var g=this[0],f=g.p,h=g.grid,m,t=a.makeArray;if(null!=h&&null!=f){d(f.colModel);d(f.colNames);d(h.headers);l(a(h.hDiv).find(">div>.ui-jqgrid-htable>thead"),e&&":not(.ui-jqgrid-labels)");c&&l(a(g.tBodies[0]),
"tr.jqgfirstrow,tr.jqgrow,tr.jqfoot");f.footerrow&&l(a(h.sDiv).find(">div>.ui-jqgrid-ftable>tbody").first());f.remapColumns&&(f.remapColumns.length?d(f.remapColumns):f.remapColumns=t(b));f.lastsort=a.inArray(f.lastsort,b);f.iColByName={};h=0;for(m=f.colModel.length;h<m;h++)f.iColByName[f.colModel[h].name]=h;E.call(g,"onRemapColumns",b,c,e)}},remapColumnsByName:function(b,c,e){var d=this[0].p,l=[],g,f;b=b.slice();g=a.inArray;d.subGrid&&0>g("subgrid",b)&&b.unshift("subgrid");d.multiselect&&0>g("cb",
b)&&b.unshift("cb");d.rownumbers&&0>g("rn",b)&&b.unshift("rn");g=0;for(f=b.length;g<f;g++)l.push(d.iColByName[b[g]]);C.remapColumns.call(this,l,c,e);return this},setGridWidth:function(b,e){return this.each(function(){var d=this.p,g,l=this.grid,f=0,h,m=0,t=!1,q,n=0,A=r.isCellClassHidden;if(l&&null!=d){this.fixScrollOffsetAndhBoxPadding();var p=d.colModel,w=d.scrollOffset,C=r.cell_width?0:d.cellLayout,y=l.headers,x=l.footers,E=l.bDiv,u=l.hDiv,Q=l.sDiv,K=l.cols,L,k,R=a(u).find(">div>.ui-jqgrid-htable>thead>tr").first()[0].cells,
W=function(b){l.width=d.width=b;a(d.gBox).css("width",b+"px");a(d.gView).css("width",b+"px");a(E).css("width",b+"px");a(u).css("width",b+"px");d.pager&&a(d.pager).css("width",b+"px");d.toppager&&a(d.toppager).css("width",b+"px");!0===d.toolbar[0]&&(a(l.uDiv).css("width",b+"px"),"both"===d.toolbar[1]&&a(l.ubDiv).css("width",b+"px"));d.footerrow&&a(Q).css("width",b+"px")};"boolean"!==typeof e&&(e=d.shrinkToFit);if(!isNaN(b)){b=parseInt(b,10);W(b);!1===e&&!0===d.forceFit&&(d.forceFit=!1);if(!0===e){a.each(p,
function(){!1!==this.hidden||A(this.classes)||(g=this.widthOrg,f+=g+C,this.fixed?n+=this.width+C:m++)});if(0===m)return;d.tblwidth=parseInt(f,10);q=b-C*m-n;!isNaN(d.height)&&(E.clientHeight<E.scrollHeight||1===this.rows.length)&&(t=!0,q-=w);k=q/(d.tblwidth-C*m-n);if(0>k)return;f=0;L=0<K.length;a.each(p,function(a){!1!==this.hidden||A(this.classes)||this.fixed||(this.width=g=Math.round(this.widthOrg*k),f+=g,y[a].width=g,R[a].style.width=g+"px",d.footerrow&&(x[a].style.width=g+"px"),L&&(K[a].style.width=
g+"px"),h=a)});if(!h)return;q=0;t?b-n-(f+C*m)!==w&&(q=b-n-(f+C*m)-w):1!==Math.abs(b-n-(f+C*m))&&(q=b-n-(f+C*m));p=p[h];p.width+=q;d.tblwidth=parseInt(f+q+C*m+n,10);d.tblwidth>b&&(q=d.tblwidth-parseInt(b,10),d.tblwidth=b,p.width-=q);g=p.width;q=y[h];q.width=g;R[h].style.width=g+"px";L&&(K[h].style.width=g+"px");d.footerrow&&(x[h].style.width=g+"px");d.tblwidth+(t?w:0)<d.width&&W(d.tblwidth+(t?w:0));E.offsetWidth>E.clientWidth&&(d.autowidth||void 0!==d.widthOrg&&"auto"!==d.widthOrg&&"100%"!==d.widthOrg||
W(E.offsetWidth))}d.tblwidth&&(d.tblwidth=parseInt(d.tblwidth,10),b=d.tblwidth,a(this).css("width",b+"px"),c(14,u).css("width",b+"px"),u.scrollLeft=E.scrollLeft,d.footerrow&&c(27,Q).css("width",b+"px"),q=Math.abs(b-d.width),d.shrinkToFit&&!e&&3>q&&0<q&&(b<d.width&&W(b),E.offsetWidth>E.clientWidth&&(d.autowidth||void 0!==d.widthOrg&&"auto"!==d.widthOrg&&"100%"!==d.widthOrg||W(E.offsetWidth))));this.fixScrollOffsetAndhBoxPadding();a(this).triggerHandler("jqGridResetFrozenHeights")}}})},setGridHeight:function(b){return this.each(function(){var c=
this.grid,e=this.p;if(c){var d=a(c.bDiv);d.css({height:b+(isNaN(b)?"":"px")});!0===e.frozenColumns&&a(e.idSel+"_frozen").parent().height(d.height()-16);e.height=b;e.scroll&&c.populateVisible.call(this);this.fixScrollOffsetAndhBoxPadding();a(this).triggerHandler("jqGridResetFrozenHeights")}})},setCaption:function(b){return this.each(function(){var c=this.grid.cDiv;this.p.caption=b;a("span.ui-jqgrid-title, span.ui-jqgrid-title-rtl",c).html(b);a(c).show();a(c).nextAll("div").removeClass(C.getGuiStyles.call(this,
"top"));a(this).triggerHandler("jqGridResetFrozenHeights")})},setLabel:function(b,c,e,d){return this.each(function(){var g,l=this.p;if(this.grid){if(isNaN(b)){if(g=l.iColByName[b],void 0===g)return}else g=parseInt(b,10);if(0<=g){var f=a("tr.ui-jqgrid-labels th:eq("+g+")",this.grid.hDiv);if(c){var h=a(".s-ico",f);a("[id^=jqgh_]",f).empty().html(c).append(h);l.colNames[g]=c}e&&("string"===typeof e?a(f).addClass(e):a(f).css(e));"object"===typeof d&&a(f).attr(d)}}})},setCell:function(b,c,d,l,f,h){return this.each(function(){var m=
this.p,q=-1,n=m.colModel,p,w,E,y,u,X,T,x={},O;if(this.grid&&(q=isNaN(c)?m.iColByName[c]:parseInt(c,10),0<=q&&(y=C.getGridRowById.call(a(this),b)))){u=r.getCell.call(this,y,q);if(""!==d||!0===h){w=n[q];"local"===m.datatype&&(O=e(m.idPrefix,b),p=m._index[O],void 0!==p&&(E=m.data[p]));if(null==E)for(p=0;p<y.cells.length;p++){if(p!==q&&(X=r.getDataFieldOfCell.call(this,y,p),0<X.length)){try{T=a.unformat.call(this,X,{rowId:b,colModel:n[p]},p)}catch(aa){T=A(X[0].innerHTML)}x[n[p].name]=T}}else x=E;x[w.name]=
d;n=this.formatter(b,d,q,x,"edit");m=m.colModel[q].title?{title:t(n)}:{};u.html(n).attr(m);null!=E&&(n=g.call(this,d,w,E[w.name],O,E,q),a.isFunction(w.saveLocally)?w.saveLocally.call(this,{newValue:n,newItem:E,oldItem:E,id:O,cm:w,cmName:w.name,iCol:q}):E[w.name]=n)}if(l||f){u=r.getCell.call(this,y,q);if(l)u["string"===typeof l?"addClass":"css"](l);"object"===typeof f&&u.attr(f)}}})},getCell:function(b,c){var e=!1;this.each(function(){var d,g=this.p,l,f;if(this.grid&&(d=isNaN(c)?g.iColByName[c]:parseInt(c,
10),0<=d&&(l=C.getGridRowById.call(a(this),b)))){f=r.getDataFieldOfCell.call(this,l,d).first();try{e=a.unformat.call(this,f,{rowId:l.id,colModel:g.colModel[d]},d)}catch(h){e=A(f.html())}}});return e},getCol:function(b,c,e){var d=[],g,l=0,f,h,m;c="boolean"!==typeof c?!1:c;void 0===e&&(e=!1);this.each(function(){var t,q=this.p,n;if(this.grid&&(t=isNaN(b)?q.iColByName[b]:parseInt(b,10),0<=t)){var p=this.rows,w=p.length,C=0,E=0,x;if(w&&0<w){for(;C<w;){x=p[C];if(a(x).hasClass("jqgrow")){n=r.getDataFieldOfCell.call(this,
x,t).first();try{g=a.unformat.call(this,n,{rowId:x.id,colModel:q.colModel[t]},t)}catch(y){g=A(n.html())}e?(m=parseFloat(g),isNaN(m)||(l+=m,void 0===h&&(h=f=m),f=Math.min(f,m),h=Math.max(h,m),E++)):c?d.push({id:x.id,value:g}):d.push(g)}C++}if(e)switch(e.toLowerCase()){case "sum":d=l;break;case "avg":d=l/E;break;case "count":d=w-1;break;case "min":d=f;break;case "max":d=h}}}});return d},clearGridData:function(b){return this.each(function(){var c=this.p,e=this.rows,g=this.grid;g&&c&&e&&("boolean"!==
typeof b&&(b=!1),a(this).unbind(".jqGridFormatter"),g.emptyRows.call(this,!1,!0),c.footerrow&&b&&a(".ui-jqgrid-ftable td",g.sDiv).html(" "),c.selrow=null,d(c.selarrrow),d(c.savedRow),d(c.data),d(c.lastSelectedData),c._index={},c.rowIndexes={},c.records=0,c.page=1,c.lastpage=0,c.reccount=0,this.updatepager(!0,!1))})},getInd:function(b,c){var e=C.getGridRowById.call(a(this),b);return e?!0===c?e:e.rowIndex:!1},bindKeys:function(b){var c=a.extend({onEnter:null,onSpace:null,onLeftKey:null,onRightKey:null,
scrollingRows:!0},b||{});return this.each(function(){var b=this,d=b.p,g=a(b);a("body").is("[role]")||a("body").attr("role","application");d.scrollrows=c.scrollingRows;g.bind("keydown.jqGrid",function(l){var f=a(this).find("tr[tabindex=0]")[0],h=r.detectRowEditing.call(b,a(l.target).closest("tr.jqgrow").attr("id")),m=function(b){do if(f=f[b],null===f)return;while(a(f).is(":hidden")||!a(f).hasClass("jqgrow"));C.setSelection.call(g,f.id,!0);l.preventDefault()},t=function(e,l){var f=c["on"+e+(l||"")];
g.triggerHandler("jqGridKey"+e,[d.selrow]);a.isFunction(f)&&f.call(b,d.selrow)},q=function(b){if(d.treeGrid){var c=d.data[d._index[e(d.idPrefix,f.id)]][d.treeReader.expanded_field];"Right"===b&&(c=!c);c&&a(f).find("div.treeclick").trigger("click")}t(b,"Key")};if(f&&null===h)switch(l.keyCode){case 38:m("previousSibling");break;case 40:m("nextSibling");break;case 37:q("Left");break;case 39:q("Right");break;case 13:t("Enter");break;case 32:t("Space")}})})},unbindKeys:function(){return this.each(function(){a(this).unbind("keydown.jqGrid")})},
getLocalRow:function(a){var b=!1,c;this.each(function(){void 0!==a&&(c=this.p._index[e(this.p.idPrefix,a)],0<=c&&(b=this.p.data[c]))});return b},progressBar:function(b){b=a.extend({htmlcontent:"",method:"hide",loadtype:"disable"},b||{});return this.each(function(){var c="show"===b.method?!0:!1,e=f(this.p.id),d=a("#load_"+e);""!==b.htmlcontent&&d.html(b.htmlcontent);switch(b.loadtype){case "enable":d.toggle(c);break;case "block":a("#lui_"+e).toggle(c),d.toggle(c)}})},setColWidth:function(b,c,e,d){return this.each(function(){var g=
a(this),l=this.grid,f=this.p,h;if("string"===typeof b){if(b=f.iColByName[b],void 0===b)return}else if("number"!==typeof b)return;h=l.headers[b];null!=h&&(h.newWidth=c,l.newWidth=f.tblwidth+c-h.width,l.resizeColumn(b,!f.frozenColumns,d),!1===e||d||(this.fixScrollOffsetAndhBoxPadding(),C.setGridWidth.call(g,l.newWidth+f.scrollOffset,!1)))})},getAutoResizableWidth:function(b){var c=this;if(0===c.length)return-1;var c=c[0],e=c.rows,d,g,l,f=c.p,h=f.colModel[b],m=a(c.grid.headers[b].el),e=m.find(">div");
l=parseFloat(m.css("padding-left")||0);d=parseFloat(m.css("padding-right")||0);g=e.find("span.s-ico");var t=e.find(">."+f.autoResizing.wrapperClassName),q=t.outerWidth(),n=parseFloat(t.css("width")||0),p=m=0,w=null!=h.autoResizing&&void 0!==h.autoResizable.compact?h.autoResizable.compact:f.autoResizing.compact,A=f.autoResizing.wrapperClassName;if(null==h||!h.autoResizable||0===t.length||h.hidden||r.isCellClassHidden(h.classes)||h.fixed)return-1;if(!w||g.is(":visible")||"none"!==g.css("display"))p=
f.autoResizing.widthOfVisiblePartOfSortIcon,"center"===e.css("text-align")&&(p+=p),"horizontal"===f.viewsortcols[1]&&(p+=p);p+=q+l+(n===q?l+d:0)+parseFloat(e.css("margin-left")||0)+parseFloat(e.css("margin-right")||0);l=0;for(e=c.rows;l<e.length;l++)d=e[l],g=d.cells[b],c=a(d.cells[b]),null!=g&&(a(d).hasClass("jqgrow")||a(d).hasClass("jqgroup")&&1===g.colSpan)?(d=a(g.firstChild),d.hasClass(A)?p=Math.max(p,d.outerWidth()+m):f.treeGrid&&f.ExpandColumn===h.name&&(d=c.children(".cell-wrapper,.cell-wrapperleaf"),
p=Math.max(p,d.outerWidth()+m+c.children(".tree-wrap").outerWidth()))):a(d).hasClass("jqgfirstrow")&&(m=(r.cell_width?parseFloat(c.css("padding-left")||0)+parseFloat(c.css("padding-right")||0):0)+parseFloat(c.css("border-right")||0)+parseFloat(c.css("border-left")||0));p=Math.max(p,null!=h.autoResizing&&void 0!==h.autoResizing.minColWidth?h.autoResizing.minColWidth:f.autoResizing.minColWidth);return Math.min(p,null!=h.autoResizing&&void 0!==h.autoResizing.maxColWidth?h.autoResizing.maxColWidth:f.autoResizing.maxColWidth)},
autoResizeColumn:function(b,c){return this.each(function(){var e=a(this),d=this.p,g=d.colModel[b],l,f=a(this.grid.headers[b].el);l=C.getAutoResizableWidth.call(e,b);null==g||0>l||(C.setColWidth.call(e,b,l,d.autoResizing.adjustGridWidth&&!d.autoResizing.fixWidthOnShrink&&!c,c),d.autoResizing.fixWidthOnShrink&&d.shrinkToFit&&!c&&(g.fixed=!0,l=g.widthOrg,g.widthOrg=g.width,C.setGridWidth.call(e,d.width,!0),g.widthOrg=l,g.fixed=!1),f.data("autoResized","true"))})},autoResizeAllColumns:function(){return this.each(function(){var b=
a(this),c=this.p,e=c.colModel,d=e.length,g,l,f=c.shrinkToFit,h=c.autoResizing.adjustGridWidth,m=c.autoResizing.fixWidthOnShrink,t=parseInt(c.widthOrg,10),q=this.grid,n=C.autoResizeColumn;c.shrinkToFit=!1;c.autoResizing.adjustGridWidth=!0;c.autoResizing.fixWidthOnShrink=!1;for(g=0;g<d;g++)l=e[g],l.autoResizable&&"actions"!==l.formatter&&n.call(b,g,!0);q.hDiv.scrollLeft=q.bDiv.scrollLeft;c.footerrow&&(q.sDiv.scrollLeft=q.bDiv.scrollLeft);this.fixScrollOffsetAndhBoxPadding();isNaN(t)?h&&C.setGridWidth.call(b,
q.newWidth+c.scrollOffset,!1):C.setGridWidth.call(b,t,!1);c.autoResizing.fixWidthOnShrink=m;c.autoResizing.adjustGridWidth=h;c.shrinkToFit=f})}})})(jQuery);
(function(a){var p=a.jgrid,r=function(){var d=a.makeArray(arguments);d.unshift("");d.unshift("");d.unshift(this.p);return p.feedback.apply(this,d)},u=function(a,f){return p.mergeCssClasses(p.getRes(p.guiStyles[this.p.guiStyle],"states."+a),f||"")},n=function(d,f){var h=this.grid.fbRows;return a((null!=h&&h[0].cells.length>f?h[d.rowIndex]:d).cells[f])};p.extend({editCell:function(d,f,h){return this.each(function(){var b=this,c=a(b),e=b.p,l,m,g,t;l=b.rows;if(b.grid&&!0===e.cellEdit&&null!=l&&null!=
l[d]){d=parseInt(d,10);f=parseInt(f,10);var w=l[d],A=w.id,q=a(w),y=parseInt(e.iCol,10),E=parseInt(e.iRow,10),C=a(l[E]),B=e.savedRow;e.selrow=A;e.knv||c.jqGrid("GridNav");if(0<B.length){if(!0===h&&d===E&&f===y)return;c.jqGrid("saveCell",B[0].id,B[0].ic)}else setTimeout(function(){a("#"+p.jqID(e.knv)).attr("tabindex","-1").focus()},1);t=e.colModel[f];l=t.name;if("subgrid"!==l&&"cb"!==l&&"rn"!==l){g=n.call(b,w,f);w=t.editable;a.isFunction(w)&&(w=w.call(b,{rowid:A,iCol:f,iRow:d,name:l,cm:t,mode:"cell"}));
var D=u.call(b,"select","edit-cell"),z=u.call(b,"hover","selected-row");if(!0!==w||!0!==h||g.hasClass("not-editable-cell"))0<=y&&0<=E&&(n.call(b,C[0],y).removeClass(D),C.removeClass(z)),g.addClass(D),q.addClass(z),m=g.html().replace(/\ \;/ig,""),r.call(b,"onSelectCell",A,l,m,d,f);else{0<=y&&0<=E&&(n.call(b,C[0],y).removeClass(D),C.removeClass(z));g.addClass(D);q.addClass(z);t.edittype||(t.edittype="text");q=t.edittype;try{m=a.unformat.call(b,g,{rowId:A,colModel:t},f)}catch(v){m="textarea"===q?
g.text():g.html()}e.autoencode&&(m=p.htmlDecode(m));B.push({id:d,ic:f,name:l,v:m});if(" "===m||" "===m||1===m.length&&160===m.charCodeAt(0))m="";a.isFunction(e.formatCell)&&(y=e.formatCell.call(b,A,l,m,d,f),void 0!==y&&(m=y));r.call(b,"beforeEditCell",A,l,m,d,f);t=a.extend({},t.editoptions||{},{id:d+"_"+l,name:l,rowId:A,mode:"cell"});var V=p.createEl.call(b,q,t,m,!0,a.extend({},p.ajaxOptions,e.ajaxSelectOptions||{})),q=g;(y=!0===e.treeGrid&&l===e.ExpandColumn)&&(q=g.children("span.cell-wrapperleaf,span.cell-wrapper"));
q.html("").append(V).attr("tabindex","0");y&&a(V).width(g.width()-g.children("div.tree-wrap").outerWidth());p.bindEv.call(b,V,t);setTimeout(function(){a(V).focus()},1);a("input, select, textarea",g).bind("keydown",function(e){27===e.keyCode&&(0<a("input.hasDatepicker",g).length?a(".ui-datepicker").is(":hidden")?c.jqGrid("restoreCell",d,f):a("input.hasDatepicker",g).datepicker("hide"):c.jqGrid("restoreCell",d,f));if(13===e.keyCode&&!e.shiftKey)return c.jqGrid("saveCell",d,f),!1;if(9===e.keyCode){if(b.grid.hDiv.loading)return!1;
e.shiftKey?c.jqGrid("prevCell",d,f):c.jqGrid("nextCell",d,f)}e.stopPropagation()});r.call(b,"afterEditCell",A,l,m,d,f);c.triggerHandler("jqGridAfterEditCell",[A,l,m,d,f])}e.iCol=f;e.iRow=d}}})},saveCell:function(d,f){return this.each(function(){var h=this,b=a(h),c=h.p,e=p.info_dialog,l=p.jqID;if(h.grid&&!0===c.cellEdit){var m=b.jqGrid("getGridRes","errors"),g=m.errcap,t=b.jqGrid("getGridRes","edit").bClose,w=c.savedRow,A=1<=w.length?0:null;if(null!==A){var q=h.rows[d],y=q.id,E=a(q),C=c.colModel[f],
B=C.name,D,z=n.call(h,q,f);D=p.getEditedValue.call(h,z,C,!C.formatter);if(D!==w[A].v){A=b.triggerHandler("jqGridBeforeSaveCell",[y,B,D,d,f]);void 0!==A&&(D=A);a.isFunction(c.beforeSaveCell)&&(A=c.beforeSaveCell.call(h,y,B,D,d,f),void 0!==A&&(D=A));var v=p.checkValues.call(h,D,f),q=C.formatoptions||{};if(!0===v[0]){A=b.triggerHandler("jqGridBeforeSubmitCell",[y,B,D,d,f])||{};a.isFunction(c.beforeSubmitCell)&&((A=c.beforeSubmitCell.call(h,y,B,D,d,f))||(A={}));0<a("input.hasDatepicker",z).length&&a("input.hasDatepicker",
z).datepicker("hide");"date"===C.formatter&&!0!==q.sendFormatted&&(D=a.unformat.date.call(h,D,C));if("remote"===c.cellsubmit)if(c.cellurl){var u={};c.autoencode&&(D=p.htmlEncode(D));u[B]=D;var m=c.prmNames,C=m.oper,I=h.grid.hDiv;u[m.id]=p.stripPref(c.idPrefix,y);u[C]=m.editoper;u=a.extend(A,u);b.jqGrid("progressBar",{method:"show",loadtype:c.loadui,htmlcontent:p.defaults.savetext||"Saving..."});I.loading=!0;a.ajax(a.extend({url:c.cellurl,data:p.serializeFeedback.call(h,c.serializeCellData,"jqGridSerializeCellData",
u),type:"POST",complete:function(l){b.jqGrid("progressBar",{method:"hide",loadtype:c.loadui});I.loading=!1;if((300>l.status||304===l.status)&&(0!==l.status||4!==l.readyState)){var m=b.triggerHandler("jqGridAfterSubmitCell",[h,l,u.id,B,D,d,f])||[!0,""];!0===m[0]&&a.isFunction(c.afterSubmitCell)&&(m=c.afterSubmitCell.call(h,l,u.id,B,D,d,f));!0===m[0]?(b.jqGrid("setCell",y,f,D,!1,!1,!0),z.addClass("dirty-cell"),E.addClass("edited"),r.call(h,"afterSaveCell",y,B,D,d,f),w.splice(0,1)):(e.call(h,g,m[1],
t),b.jqGrid("restoreCell",d,f))}},error:function(m,q,n){a("#lui_"+l(c.id)).hide();I.loading=!1;b.triggerHandler("jqGridErrorCell",[m,q,n]);a.isFunction(c.errorCell)?c.errorCell.call(h,m,q,n):e.call(h,g,m.status+" : "+m.statusText+"<br/>"+q,t);b.jqGrid("restoreCell",d,f)}},p.ajaxOptions,c.ajaxCellOptions||{}))}else try{e.call(h,g,m.nourl,t),b.jqGrid("restoreCell",d,f)}catch(G){}"clientArray"===c.cellsubmit&&(b.jqGrid("setCell",y,f,D,!1,!1,!0),z.addClass("dirty-cell"),E.addClass("edited"),r.call(h,
"afterSaveCell",y,B,D,d,f),w.splice(0,1))}else try{setTimeout(function(){e.call(h,g,D+" "+v[1],t)},100),b.jqGrid("restoreCell",d,f)}catch(S){}}else b.jqGrid("restoreCell",d,f)}setTimeout(function(){a("#"+l(c.knv)).attr("tabindex","-1").focus()},0)}})},restoreCell:function(d,f){return this.each(function(){var h=this.p,b=this.rows[d],c=b.id,e,l;if(this.grid&&!0===h.cellEdit){var m=h.savedRow;e=n.call(this,b,f);if(1<=m.length){if(a.isFunction(a.fn.datepicker))try{a("input.hasDatepicker",e).datepicker("hide")}catch(g){}b=
h.colModel[f];!0===h.treeGrid&&b.name===h.ExpandColumn?e.children("span.cell-wrapperleaf,span.cell-wrapper").empty():e.empty();e.attr("tabindex","-1");e=m[0].v;l=b.formatoptions||{};"date"===b.formatter&&!0!==l.sendFormatted&&(e=a.unformat.date.call(this,e,b));a(this).jqGrid("setCell",c,f,e,!1,!1,!0);r.call(this,"afterRestoreCell",c,e,d,f);m.splice(0,1)}setTimeout(function(){a("#"+h.knv).attr("tabindex","-1").focus()},0)}})},nextCell:function(d,f){return this.each(function(){var h=a(this),b=this.p,
c=!1,e,l,m,g=this.rows;if(this.grid&&!0===b.cellEdit&&null!=g&&null!=g[d]){for(e=f+1;e<b.colModel.length;e++)if(m=b.colModel[e],l=m.editable,a.isFunction(l)&&(l=l.call(this,{rowid:g[d].id,iCol:e,iRow:d,name:m.name,cm:m,mode:"cell"})),!0===l){c=e;break}!1!==c?h.jqGrid("editCell",d,c,!0):0<b.savedRow.length&&h.jqGrid("saveCell",d,f)}})},prevCell:function(d,f){return this.each(function(){var h=a(this),b=this.p,c=!1,e,l,m,g=this.rows;if(this.grid&&!0===b.cellEdit&&null!=g&&null!=g[d]){for(e=f-1;0<=e;e--)if(m=
b.colModel[e],l=m.editable,a.isFunction(l)&&(l=l.call(this,{rowid:g[d].id,iCol:e,iRow:d,name:m.name,cm:m,mode:"cell"})),!0===l){c=e;break}!1!==c?h.jqGrid("editCell",d,c,!0):0<b.savedRow.length&&h.jqGrid("saveCell",d,f)}})},GridNav:function(){return this.each(function(){function d(a,b,c){a=h.rows[a];if("v"===c.substr(0,1)){var e=g.clientHeight,d=g.scrollTop,l=a.offsetTop+a.clientHeight,f=a.offsetTop;"vd"===c&&l>=e&&(g.scrollTop+=a.clientHeight);"vu"===c&&f<d&&(g.scrollTop-=a.clientHeight)}"h"===c&&
(c=g.scrollLeft,b=a.cells[b],a=b.offsetLeft,b.offsetLeft+b.clientWidth>=g.clientWidth+parseInt(c,10)?g.scrollLeft+=b.clientWidth:a<c&&(g.scrollLeft-=b.clientWidth))}function f(a,b){var e=0,d,l=c.colModel;if("lft"===b)for(e=a+1,d=a;0<=d;d--)if(!0!==l[d].hidden){e=d;break}if("rgt"===b)for(e=a-1,d=a;d<l.length;d++)if(!0!==l[d].hidden){e=d;break}return e}var h=this,b=a(h),c=h.p,e=h.grid,l,m;if(e&&!0===c.cellEdit){var g=e.bDiv;c.knv=c.id+"_kn";var t=a("<div style='position:fixed;top:0px;width:1px;height:1px;' tabindex='0'><div tabindex='-1' style='width:1px;height:1px;' id='"+
c.knv+"'></div></div>");a(t).insertBefore(e.cDiv);a("#"+c.knv).focus().keydown(function(a){var e=parseInt(c.iRow,10),g=parseInt(c.iCol,10);m=a.keyCode;"rtl"===c.direction&&(37===m?m=39:39===m&&(m=37));switch(m){case 38:0<e-1&&(d(e-1,g,"vu"),b.jqGrid("editCell",e-1,g,!1));break;case 40:e+1<=h.rows.length-1&&(d(e+1,g,"vd"),b.jqGrid("editCell",e+1,g,!1));break;case 37:0<=g-1&&(l=f(g-1,"lft"),d(e,l,"h"),b.jqGrid("editCell",e,l,!1));break;case 39:g+1<=c.colModel.length-1&&(l=f(g+1,"rgt"),d(e,l,"h"),b.jqGrid("editCell",
e,l,!1));break;case 13:0<=g&&0<=e&&b.jqGrid("editCell",e,g,!0);break;default:return!0}return!1})}})},getChangedCells:function(d){var f=[];d||(d="all");this.each(function(){var h=this,b=h.p,c=p.htmlDecode,e=h.rows;h.grid&&!0===b.cellEdit&&a(e).each(function(l){var m={};if(a(this).hasClass("edited")){var g=this;a(this.cells).each(function(f){var p=b.colModel[f],A=p.name,q=n.call(h,g,f);if("cb"!==A&&"subgrid"!==A&&"rn"!==A&&("dirty"!==d||q.hasClass("dirty-cell")))try{m[A]=a.unformat.call(h,q[0],{rowId:e[l].id,
colModel:p},f)}catch(r){m[A]=c(q.html())}});m.id=this.id;f.push(m)}})});return f}})})(jQuery);
(function(a){var p=a.jgrid,r=p.getMethod("getGridRes"),u=function(a,d){return p.mergeCssClasses(p.getRes(p.guiStyles[this.p.guiStyle],a),d||"")};p.jqModal=p.jqModal||{};a.extend(!0,p.jqModal,{toTop:!0});a.extend(p,{showModal:function(a){a.w.show()},closeModal:function(a){a.w.hide().attr("aria-hidden","true");a.o&&a.o.remove()},hideModal:function(n,d){d=a.extend({jqm:!0,gb:"",removemodal:!1,formprop:!1,form:""},d||{});var f=d.gb&&"string"===typeof d.gb&&"#gbox_"===d.gb.substr(0,6)?a("#"+d.gb.substr(6))[0]:
!1;if(d.onClose){var h=f?d.onClose.call(f,n):d.onClose(n);if("boolean"===typeof h&&!h)return}if(d.formprop&&f&&d.form){h=a(n)[0].style.height;-1<h.indexOf("px")&&(h=parseFloat(h));var b,c;"edit"===d.form?(b="#"+p.jqID("FrmGrid_"+d.gb.substr(6)),c="formProp"):"view"===d.form&&(b="#"+p.jqID("ViewGrid_"+d.gb.substr(6)),c="viewProp");a(f).data(c,{top:parseFloat(a(n).css("top")),left:parseFloat(a(n).css("left")),width:a(n).width(),height:h,dataheight:a(b).height(),datawidth:a(b).width()})}if(a.fn.jqm&&
!0===d.jqm)a(n).attr("aria-hidden","true").jqmHide();else{if(""!==d.gb)try{a(">.jqgrid-overlay",d.gb).filter(":first").hide()}catch(e){}a(n).hide().attr("aria-hidden","true")}d.removemodal&&a(n).remove()},findPos:function(a){var d=0,f=0;if(a.offsetParent){do d+=a.offsetLeft,f+=a.offsetTop,a=a.offsetParent;while(a)}return[d,f]},createModal:function(n,d,f,h,b,c,e){var l=p.jqID,m=this.p;f=a.extend(!0,{resizingRightBottomIcon:"ui-icon ui-icon-gripsmall-diagonal-se"},p.jqModal||{},null!=m?m.jqModal||{}:
{},f);var g=document.createElement("div"),t="#"+l(n.themodal),w="rtl"===a(f.gbox).attr("dir")?!0:!1,A=n.resizeAlso?"#"+l(n.resizeAlso):!1;e=a.extend({},e||{});g.className=u.call(this,"dialog.window","ui-jqdialog");g.id=n.themodal;g.dir=w?"rtl":"ltr";var q=document.createElement("div");q.className=u.call(this,"dialog.header","ui-jqdialog-titlebar "+(w?"ui-jqdialog-titlebar-rtl":"ui-jqdialog-titlebar-ltr"));q.id=n.modalhead;a(q).append("<span class='ui-jqdialog-title'>"+f.caption+"</span>");var r=u.call(this,
"states.hover"),E=a("<a class='ui-jqdialog-titlebar-close ui-corner-all'></a>").hover(function(){E.addClass(r)},function(){E.removeClass(r)}).append("<span class='"+p.getIconRes(m.iconSet,"form.close")+"'></span>");a(q).append(E);m=document.createElement("div");a(m).addClass(u.call(this,"dialog.content","ui-jqdialog-content")).attr("id",n.modalcontent);a(m).append(d);g.appendChild(m);a(g).prepend(q);!0===c?a("body").append(g):"string"===typeof c?a(c).append(g):a(g).insertBefore(h);a(g).css(e);void 0===
f.jqModal&&(f.jqModal=!0);d={};if(a.fn.jqm&&!0===f.jqModal)0===f.left&&0===f.top&&f.overlay&&(c=[],c=p.findPos(b),f.left=c[0]+4,f.top=c[1]+4),d.top=f.top+"px",d.left=f.left;else if(0!==f.left||0!==f.top)d.left=f.left,d.top=f.top+"px";a("a.ui-jqdialog-titlebar-close",q).click(function(){var b=a(t).data("onClose")||f.onClose,c=a(t).data("gbox")||f.gbox;p.hideModal(t,{gb:c,jqm:f.jqModal,onClose:b,removemodal:f.removemodal||!1,formprop:!f.recreateForm||!1,form:f.form||""});return!1});0!==f.width&&f.width||
(f.width=300);0!==f.height&&f.height||(f.height=200);f.zIndex||((h=a(h).parents("*[role=dialog]").filter(":first").css("z-index"))?(f.zIndex=parseInt(h,10)+2,f.toTop=!0):f.zIndex=950);d.left&&(d.left+="px");a(g).css(a.extend({width:isNaN(f.width)?"auto":f.width+"px",height:isNaN(f.height)?"auto":f.height+"px",zIndex:f.zIndex,overflow:"hidden"},d)).attr({tabIndex:"-1",role:"dialog","aria-labelledby":n.modalhead,"aria-hidden":"true"});void 0===f.drag&&(f.drag=!0);void 0===f.resize&&(f.resize=!0);if(f.drag)if(a.fn.jqDrag)a(q).css("cursor",
"move"),a(g).jqDrag(q);else try{a(g).draggable({handle:a("#"+l(q.id))})}catch(C){}if(f.resize)if(a.fn.jqResize)a(g).append("<div class='jqResize ui-resizable-handle ui-resizable-se "+f.resizingRightBottomIcon+"'></div>"),a(t).jqResize(".jqResize",A);else try{a(g).resizable({handles:"se, sw",alsoResize:A})}catch(B){}!0===f.closeOnEscape&&a(g).keydown(function(b){27===b.which&&(b=a(t).data("onClose")||f.onClose,p.hideModal(t,{gb:f.gbox,jqm:f.jqModal,onClose:b,removemodal:f.removemodal||!1,formprop:!f.recreateForm||
!1,form:f.form||""}))})},viewModal:function(n,d){d=a.extend(!0,{overlay:30,modal:!1,overlayClass:"ui-widget-overlay",onShow:p.showModal,onHide:p.closeModal,gbox:"",jqm:!0,jqM:!0},p.jqModal||{},d||{});if(a.fn.jqm&&!0===d.jqm)d.jqM?a(n).attr("aria-hidden","false").jqm(d).jqmShow():a(n).attr("aria-hidden","false").jqmShow();else{""!==d.gbox&&(a(">.jqgrid-overlay",d.gbox).filter(":first").show(),a(n).data("gbox",d.gbox));a(n).show().attr("aria-hidden","false");try{a(":input:visible",n)[0].focus()}catch(f){}}},
info_dialog:function(n,d,f,h){var b=this,c=b.p,e=a.extend(!0,{width:290,height:"auto",dataheight:"auto",drag:!0,resize:!1,left:250,top:170,zIndex:1E3,jqModal:!0,modal:!1,closeOnEscape:!0,align:"center",buttonalign:"center",buttons:[]},p.jqModal||{},null!=c?c.jqModal||{}:{},{caption:"<b>"+n+"</b>"},h||{}),l=e.jqModal;a.fn.jqm&&!l&&(l=!1);n="";var m=u.call(b,"states.hover");if(0<e.buttons.length)for(h=0;h<e.buttons.length;h++)void 0===e.buttons[h].id&&(e.buttons[h].id="info_button_"+h),n+=p.builderFmButon.call(b,
e.buttons[h].id,e.buttons[h].text);h=isNaN(e.dataheight)?e.dataheight:e.dataheight+"px";d="<div id='info_id'>"+("<div id='infocnt' style='margin:0px;padding-bottom:1em;width:100%;overflow:auto;position:relative;height:"+h+";"+("text-align:"+e.align+";")+"'>"+d+"</div>");if(f||""!==n)d+="<hr class='"+u.call(b,"dialog.hr")+"' style='margin:1px'/><div style='text-align:"+e.buttonalign+";padding:.8em 0 .5em 0;background-image:none;border-width: 1px 0 0 0;'>"+(f?p.builderFmButon.call(b,"closedialog",f):
"")+n+"</div>";d+="</div>";try{"false"===a("#info_dialog").attr("aria-hidden")&&p.hideModal("#info_dialog",{jqm:l}),a("#info_dialog").remove()}catch(g){}p.createModal.call(b,{themodal:"info_dialog",modalhead:"info_head",modalcontent:"info_content",resizeAlso:"infocnt"},d,e,"","",!0);n&&a.each(e.buttons,function(c){a("#"+p.jqID(b.id),"#info_id").bind("click",function(){e.buttons[c].onClick.call(a("#info_dialog"));return!1})});a("#closedialog","#info_id").click(function(){p.hideModal("#info_dialog",
{jqm:l,onClose:a("#info_dialog").data("onClose")||e.onClose,gb:a("#info_dialog").data("gbox")||e.gbox});return!1});a(".fm-button","#info_dialog").hover(function(){a(this).addClass(m)},function(){a(this).removeClass(m)});a.isFunction(e.beforeOpen)&&e.beforeOpen();p.viewModal("#info_dialog",{onHide:function(a){a.w.hide().remove();a.o&&a.o.remove()},modal:e.modal,jqm:l});a.isFunction(e.afterOpen)&&e.afterOpen();try{a("#info_dialog").focus()}catch(t){}},bindEv:function(n,d){a.isFunction(d.dataInit)&&
d.dataInit.call(this,n,d);d.dataEvents&&a.each(d.dataEvents,function(){void 0!==this.data?a(n).bind(this.type,this.data,this.fn):a(n).bind(this.type,this.fn)})},createEl:function(n,d,f,h,b){function c(b,c,e){var d="dataInit dataEvents dataUrl buildSelect sopt searchhidden defaultValue attr custom_element custom_value selectFilled rowId mode".split(" ");void 0!==e&&a.isArray(e)&&a.merge(d,e);a.each(c,function(c,e){-1===a.inArray(c,d)&&a(b).attr(c,e)});c.hasOwnProperty("id")||a(b).attr("id",p.randId())}
var e="",l=this,m=l.p,g=p.info_dialog,t=r.call(a(l),"errors.errcap"),w=r.call(a(l),"edit"),A=w.msg,w=w.bClose;switch(n){case "textarea":e=document.createElement("textarea");h?d.cols||a(e).css({width:"100%","box-sizing":"border-box"}):d.cols||(d.cols=20);d.rows||(d.rows=2);if(" "===f||" "===f||1===f.length&&160===f.charCodeAt(0))f="";e.value=f;c(e,d);a(e).attr({role:"textbox"});break;case "checkbox":e=document.createElement("input");e.type="checkbox";if(d.value){var q=d.value.split(":");
f===q[0]&&(e.checked=!0,e.defaultChecked=!0);e.value=q[0];a(e).data("offval",q[1])}else q=String(f).toLowerCase(),0>q.search(/(false|f|0|no|n|off|undefined)/i)&&""!==q?(e.checked=!0,e.defaultChecked=!0,e.value=f):e.value="on",a(e).data("offval","off");c(e,d,["value"]);a(e).attr({role:"checkbox","aria-checked":e.checked?"true":"false"});break;case "select":e=document.createElement("select");e.setAttribute("role","listbox");t=[];h=m.iColByName[d.name];n=m.colModel[h];!0===d.multiple?(g=!0,e.multiple=
"multiple",a(e).attr("aria-multiselectable","true")):g=!1;if(void 0!==d.dataUrl){var q=null,y=d.postData||b.postData;try{q=d.rowId}catch(E){}m&&m.idPrefix&&(q=p.stripPref(m.idPrefix,q));a.ajax(a.extend({url:a.isFunction(d.dataUrl)?d.dataUrl.call(l,q,f,String(d.name)):d.dataUrl,type:"GET",dataType:"html",data:a.isFunction(y)?y.call(l,q,f,String(d.name)):y,context:{elem:e,options:d,vl:f,cm:n,iCol:h},success:function(b,e,d){var g=[],f=this.elem;e=this.vl;var h=this.cm,m=this.iCol,t=a.extend({},this.options),
q=!0===t.multiple;b=a.isFunction(t.buildSelect)?t.buildSelect.call(l,b,d,h,m):b;"string"===typeof b&&(b=a(a.trim(b)).html());b&&(a(f).append(b),c(f,t,y?["postData"]:void 0),void 0===t.size&&(t.size=q?3:1),q?(g=e.split(","),g=a.map(g,function(b){return a.trim(b)})):g[0]=a.trim(e),setTimeout(function(){a("option",f).each(function(b){0===b&&f.multiple&&(this.selected=!1);a(this).attr("role","option");if(-1<a.inArray(a.trim(a(this).text()),g)||-1<a.inArray(a.trim(a(this).val()),g))this.selected="selected"});
p.fullBoolFeedback.call(l,t.selectFilled,"jqGridSelectFilled",{elem:f,options:t,cm:h,cmName:h.name,iCol:m})},0))}},b||{}))}else if(d.value){void 0===d.size&&(d.size=g?3:1);g&&(t=f.split(","),t=a.map(t,function(b){return a.trim(b)}));"function"===typeof d.value&&(d.value=d.value());var C,B,m=void 0===d.separator?":":d.separator;b=void 0===d.delimiter?";":d.delimiter;A=function(a,b){if(0<b)return a};if("string"===typeof d.value)for(C=d.value.split(b),q=0;q<C.length;q++)B=C[q].split(m),2<B.length&&(B[1]=
a.map(B,A).join(m)),b=document.createElement("option"),b.setAttribute("role","option"),b.value=B[0],b.innerHTML=B[1],e.appendChild(b),w=a.trim(B[0]),B=a.trim(B[1]),g||w!==a.trim(f)&&B!==a.trim(f)||(b.selected="selected"),g&&(-1<a.inArray(B,t)||-1<a.inArray(w,t))&&(b.selected="selected");else if("object"===typeof d.value)for(q in m=d.value,m)m.hasOwnProperty(q)&&(b=document.createElement("option"),b.setAttribute("role","option"),b.value=q,b.innerHTML=m[q],e.appendChild(b),g||a.trim(q)!==a.trim(f)&&
a.trim(m[q])!==a.trim(f)||(b.selected="selected"),g&&(-1<a.inArray(a.trim(m[q]),t)||-1<a.inArray(a.trim(q),t))&&(b.selected="selected"));c(e,d,["value"]);p.fullBoolFeedback.call(l,d.selectFilled,"jqGridSelectFilled",{elem:e,options:d,cm:n,cmName:n.name,iCol:h})}break;case "text":case "password":case "button":q="button"===n?"button":"textbox";e=document.createElement("input");e.type=n;e.value=f;c(e,d);"button"!==n&&(h?d.size||a(e).css({width:"100%","box-sizing":"border-box"}):d.size||(d.size=20));
a(e).attr("role",q);break;case "image":case "file":e=document.createElement("input");e.type=n;c(e,d);break;case "custom":e=document.createElement("span");try{if(a.isFunction(d.custom_element))if(C=d.custom_element.call(l,f,d),C instanceof jQuery||p.isHTMLElement(C)||"string"===typeof C)C=a(C).addClass("customelement").attr({id:d.id,name:d.name}),a(e).empty().append(C);else throw"editoptions.custom_element returns value of a wrong type";else throw"editoptions.custom_element is not a function";}catch(D){"e1"===
D&&g.call(l,t,"function 'custom_element' "+A.nodefined,w),"e2"===D?g.call(l,t,"function 'custom_element' "+A.novalue,w):g.call(l,t,"string"===typeof D?D:D.message,w)}}return e},checkDate:function(a,d){var f={},h;a=a.toLowerCase();h=-1!==a.indexOf("/")?"/":-1!==a.indexOf("-")?"-":-1!==a.indexOf(".")?".":"/";a=a.split(h);d=d.split(h);if(3!==d.length)return!1;var b=-1,c,e=h=-1,l;for(l=0;l<a.length;l++)c=isNaN(d[l])?0:parseInt(d[l],10),f[a[l]]=c,c=a[l],-1!==c.indexOf("y")&&(b=l),-1!==c.indexOf("m")&&
(e=l),-1!==c.indexOf("d")&&(h=l);c="y"===a[b]||"yyyy"===a[b]?4:"yy"===a[b]?2:-1;var m;l=[0,31,29,31,30,31,30,31,31,30,31,30,31];if(-1===b)return!1;m=f[a[b]].toString();2===c&&1===m.length&&(c=1);if(m.length!==c||0===f[a[b]]&&"00"!==d[b]||-1===e)return!1;m=f[a[e]].toString();if(1>m.length||1>f[a[e]]||12<f[a[e]]||-1===h)return!1;m=f[a[h]].toString();!(c=1>m.length||1>f[a[h]]||31<f[a[h]])&&(c=2===f[a[e]])&&(b=f[a[b]],c=f[a[h]]>(0!==b%4||0===b%100&&0!==b%400?28:29));return c||f[a[h]]>l[f[a[e]]]?!1:!0},
isEmpty:function(a){return a.match(/^\s+$/)||""===a?!0:!1},checkTime:function(a){var d=/^(\d{1,2}):(\d{2})([apAP][Mm])?$/;if(!p.isEmpty(a))if(a=a.match(d)){if(a[3]){if(1>a[1]||12<a[1])return!1}else if(23<a[1])return!1;if(59<a[2])return!1}else return!1;return!0},checkValues:function(n,d,f,h){var b,c,e=this.p;c=e.colModel;var l=p.isEmpty,m=r.call(a(this),"edit.msg"),g=r.call(a(this),"formatter.date.masks");if(void 0===f){"string"===typeof d&&(d=e.iColByName[d]);if(void 0===d||0>d)return[!0,"",""];h=
c[d];f=h.editrules;null!=h.formoptions&&(b=h.formoptions.label)}else b=void 0===h?"_":h,h=c[d];if(f){b||(b=null!=e.colNames?e.colNames[d]:h.label);if(!0===f.required&&l(n))return[!1,b+": "+m.required,""];e=!1===f.required?!1:!0;if(!0===f.number&&(!1!==e||!l(n))&&isNaN(n))return[!1,b+": "+m.number,""];if(void 0!==f.minValue&&!isNaN(f.minValue)&&parseFloat(n)<parseFloat(f.minValue))return[!1,b+": "+m.minValue+" "+f.minValue,""];if(void 0!==f.maxValue&&!isNaN(f.maxValue)&&parseFloat(n)>parseFloat(f.maxValue))return[!1,
b+": "+m.maxValue+" "+f.maxValue,""];var t;if(!(!0!==f.email||!1===e&&l(n)||(t=/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,
t.test(n))))return[!1,b+": "+m.email,""];if(!(!0!==f.integer||!1===e&&l(n)||!isNaN(n)&&0===n%1&&-1===n.indexOf(".")))return[!1,b+": "+m.integer,""];if(!(!0!==f.date||!1===e&&l(n)||(h.formatoptions&&h.formatoptions.newformat?(c=h.formatoptions.newformat,g.hasOwnProperty(c)&&(c=g[c])):c=c[d].datefmt||"Y-m-d",p.checkDate(c,n))))return[!1,b+": "+m.date+" - "+c,""];if(!0===f.time&&!(!1===e&&l(n)||p.checkTime(n)))return[!1,b+": "+m.date+" - hh:mm (am/pm)",""];if(!(!0!==f.url||!1===e&&l(n)||(t=/^(((https?)|(ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i,
t.test(n))))return[!1,b+": "+m.url,""];if(!0===f.custom&&(!1!==e||!l(n)))return a.isFunction(f.custom_func)?(n=f.custom_func.call(this,n,b,d),a.isArray(n)?n:[!1,m.customarray,""]):[!1,m.customfcheck,""]}return[!0,"",""]}})})(jQuery);
(function(a){var p=a.jgrid,r=p.getMethod("getGridRes"),u=p.jqID,n=function(a,f){return p.mergeCssClasses(p.getRes(p.guiStyles[this.p.guiStyle||p.defaults.guiStyle||"jQueryUI"],a),f||"")};p.extend({getColProp:function(a){var f=this[0];return null!=f&&f.grid&&(a=f.p.iColByName[a],void 0!==a)?f.p.colModel[a]:{}},setColProp:function(d,f){return this.each(function(){var h=this.p,b;this.grid&&null!=h&&f&&(b=h.iColByName[d],void 0!==b&&a.extend(!0,h.colModel[b],f))})},sortGrid:function(a,f,h){return this.each(function(){var b=
this.grid,c=this.p,e=c.colModel,l=e.length,m,g,t=!1;if(b)for(a||(a=c.sortname),"boolean"!==typeof f&&(f=!1),g=0;g<l;g++)if(m=e[g],m.index===a||m.name===a){!0===c.frozenColumns&&!0===m.frozen&&(t=b.fhDiv.find("#"+c.id+"_"+a));t&&0!==t.length||(t=b.headers[g].el);b=m.sortable;("boolean"!==typeof b||b)&&this.sortData("jqgh_"+c.id+"_"+a,g,f,h,t);break}})},clearBeforeUnload:function(){return this.each(function(){var d=this.p,f=this.grid,h,b=p.clearArray,c=Object.prototype.hasOwnProperty;a.isFunction(f.emptyRows)&&
f.emptyRows.call(this,!0,!0);a(document).unbind("mouseup.jqGrid"+d.id);a(f.hDiv).unbind("mousemove");a(this).unbind();var e,l=f.headers.length;for(e=0;e<l;e++)f.headers[e].el=null;for(h in f)f.hasOwnProperty(h)&&(f.propOrMethod=null);f="formatCol sortData updatepager refreshIndex setHeadCheckBox constructTr clearToolbar fixScrollOffsetAndhBoxPadding rebuildRowIndexes modalAlert toggleToolbar triggerToolbar formatter addXmlData addJSONData ftoolbar _inlinenav nav grid p".split(" ");l=f.length;for(e=
0;e<l;e++)c.call(this,f[e])&&(this[f[e]]=null);this._index={};b(d.data);b(d.lastSelectedData);b(d.selarrrow);b(d.savedRow)})},GridDestroy:function(){return this.each(function(){var d=this.p;if(this.grid&&null!=d){d.pager&&a(d.pager).remove();try{a("#alertmod_"+d.idSel).remove(),a(this).jqGrid("clearBeforeUnload"),a(d.gBox).remove()}catch(f){}}})},GridUnload:function(){return this.each(function(){var d=a(this),f=this.p,h=a.fn.jqGrid;this.grid&&(d.removeClass(h.getGuiStyles.call(d,"grid","ui-jqgrid-btable")),
f.pager&&a(f.pager).empty().removeClass(h.getGuiStyles.call(d,"pagerBottom","ui-jqgrid-pager")).removeAttr("style").removeAttr("dir"),d.jqGrid("clearBeforeUnload"),d.removeAttr("style").removeAttr("tabindex").removeAttr("role").removeAttr("aria-labelledby").removeAttr("style"),d.empty(),d.insertBefore(f.gBox).show(),a(f.pager).insertBefore(f.gBox).show(),a(f.gBox).remove())})},setGridState:function(d){return this.each(function(){var f=this.p,h=this.grid,b=h.cDiv,c=a(h.uDiv),e=a(h.ubDiv);if(h&&null!=
f){var l=f.iconSet||p.defaults.iconSet||"jQueryUI",h=p.getIconRes(l,"gridMinimize.visible"),l=p.getIconRes(l,"gridMinimize.hidden");"hidden"===d?(a(".ui-jqgrid-bdiv, .ui-jqgrid-hdiv",f.gView).slideUp("fast"),f.pager&&a(f.pager).slideUp("fast"),f.toppager&&a(f.toppager).slideUp("fast"),!0===f.toolbar[0]&&("both"===f.toolbar[1]&&e.slideUp("fast"),c.slideUp("fast")),f.footerrow&&a(".ui-jqgrid-sdiv",f.gBox).slideUp("fast"),a(".ui-jqgrid-titlebar-close span",b).removeClass(h).addClass(l),f.gridstate="hidden"):
"visible"===d&&(a(".ui-jqgrid-hdiv, .ui-jqgrid-bdiv",f.gView).slideDown("fast"),f.pager&&a(f.pager).slideDown("fast"),f.toppager&&a(f.toppager).slideDown("fast"),!0===f.toolbar[0]&&("both"===f.toolbar[1]&&e.slideDown("fast"),c.slideDown("fast")),f.footerrow&&a(".ui-jqgrid-sdiv",f.gBox).slideDown("fast"),a(".ui-jqgrid-titlebar-close span",b).removeClass(l).addClass(h),f.gridstate="visible")}})},filterToolbar:function(d){return this.each(function(){var f=this,h=f.grid,b=a(f),c=f.p,e=p.bindEv,l=p.info_dialog;
if(!this.ftoolbar){var m=a.extend(!0,{autosearch:!0,autosearchDelay:500,searchOnEnter:!0,beforeSearch:null,afterSearch:null,beforeClear:null,afterClear:null,searchurl:"",stringResult:!1,groupOp:"AND",defaultSearch:"bw",searchOperators:!1,resetIcon:"x",applyLabelClasses:!0,operands:{eq:"==",ne:"!",lt:"<",le:"<=",gt:">",ge:">=",bw:"^",bn:"!^","in":"=",ni:"!=",ew:"|",en:"!@",cn:"~",nc:"!~",nu:"#",nn:"!#"}},p.search,c.searching||{},d||{}),g=c.colModel,t=function(a){return r.call(b,a)},w=t("errors.errcap"),
A=t("edit.bClose"),q=t("edit.msg"),y=n.call(f,"states.hover"),E=n.call(f,"states.select"),C=n.call(f,"filterToolbar.dataField"),B=function(){var e={},d=0,l={};a.each(g,function(){var b=this,g=b.index||b.name,q,p;q=b.searchoptions||{};var n=a("#gs_"+u(b.name),!0===b.frozen&&!0===c.frozenColumns?h.fhDiv:h.hDiv),v=function(a,c){var e=b.formatoptions||{};return void 0!==e[a]?e[a]:t("formatter."+(c||b.formatter)+"."+a)},A=function(a){var b=v("thousandsSeparator").replace(/([\.\*\_\'\(\)\{\}\+\?\\])/g,
"\\$1");return a.replace(new RegExp(b,"g"),"")};p=m.searchOperators?n.parent().prev().children("a").data("soper")||m.defaultSearch:q.sopt?q.sopt[0]:"select"===b.stype?"eq":m.defaultSearch;if("custom"===b.stype&&a.isFunction(q.custom_value)&&0<n.length&&"SPAN"===n[0].nodeName.toUpperCase())q=q.custom_value.call(f,n.children(".customelement").filter(":first"),"get");else switch(q=a.trim(n.val()),b.formatter){case "integer":q=A(q).replace(v("decimalSeparator","number"),".");""!==q&&(q=String(parseInt(q,
10)));break;case "number":q=A(q).replace(v("decimalSeparator"),".");""!==q&&(q=String(parseFloat(q)));break;case "currency":var n=v("prefix"),w=v("suffix");n&&n.length&&(q=q.substr(n.length));w&&w.length&&(q=q.substr(0,q.length-w.length));q=A(q).replace(v("decimalSeparator"),".");""!==q&&(q=String(parseFloat(q)))}if(q||"nu"===p||"nn"===p)e[g]=q,l[g]=p,d++;else try{delete c.postData[g]}catch(k){}});var q=0<d?!0:!1;if(m.stringResult||m.searchOperators||"local"===c.datatype){var p='{"groupOp":"'+m.groupOp+
'","rules":[',n=0;a.each(e,function(a,b){0<n&&(p+=",");p+='{"field":"'+a+'",';p+='"op":"'+l[a]+'",';p+='"data":"'+(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}';n++});p+="]}";a.extend(c.postData,{filters:p});a.each(["searchField","searchString","searchOper"],function(a,b){c.postData.hasOwnProperty(b)&&delete c.postData[b]})}else a.extend(c.postData,e);var v;c.searchurl&&(v=c.url,b.jqGrid("setGridParam",{url:c.searchurl}));var A="stop"===b.triggerHandler("jqGridToolbarBeforeSearch")?!0:!1;
!A&&a.isFunction(m.beforeSearch)&&(A=m.beforeSearch.call(f));A||b.jqGrid("setGridParam",{search:q}).trigger("reloadGrid",[a.extend({page:1},m.reloadGridSearchOptions||{})]);v&&b.jqGrid("setGridParam",{url:v});b.triggerHandler("jqGridToolbarAfterSearch");a.isFunction(m.afterSearch)&&m.afterSearch.call(f)},D=t("search.odata")||[],z=c.customSortOperations,v=function(e,d,l){a("#sopt_menu").remove();d=parseInt(d,10);l=parseInt(l,10)+18;var f,h=0,t=[],q=a(e).data("soper"),h=a(e).data("colname");d='<ul id="sopt_menu" class="ui-search-menu" role="menu" tabindex="0" style="z-index:9999;font-size:'+
(a(".ui-jqgrid-view").css("font-size")||"11px")+";left:"+d+"px;top:"+l+'px;">';h=c.iColByName[h];if(void 0!==h){h=g[h];l=a.extend({},h.searchoptions);var n,v,A;l.sopt||(l.sopt=[],l.sopt[0]="select"===h.stype?"eq":m.defaultSearch);a.each(D,function(){t.push(this.oper)});null!=z&&a.each(z,function(a){t.push(a)});for(h=0;h<l.sopt.length;h++)v=l.sopt[h],f=a.inArray(v,t),-1!==f&&(f=D[f],void 0!==f?(A=m.operands[v],n=f.text):null!=z&&(n=z[v],A=n.operand,n=n.text),f=q===v?E:"",d+='<li class="ui-menu-item '+
f+'" role="presentation"><a class="ui-corner-all g-menu-item" tabindex="0" role="menuitem" value="'+v+'" data-oper="'+A+'"><table'+(p.msie&&8>p.msiever()?' cellspacing="0"':"")+'><tr><td style="width:25px">'+A+"</td><td>"+n+"</td></tr></table></a></li>");d+="</ul>";a("body").append(d);a("#sopt_menu").addClass("ui-menu ui-widget ui-widget-content ui-corner-all");a("#sopt_menu > li > a").hover(function(){a(this).addClass(y)},function(){a(this).removeClass(y)}).click(function(){var c=a(this).attr("value"),
d=a(this).data("oper");b.triggerHandler("jqGridToolbarSelectOper",[c,d,e]);a("#sopt_menu").hide();a(e).text(d).data("soper",c);!0===m.autosearch&&(d=a(e).parent().next().children()[0],(a(d).val()||"nu"===c||"nn"===c)&&B())})}},V,I=a("<tr class='ui-search-toolbar' role='row'></tr>");a.each(g,function(b){var d,g;g="";var h,v,r=this.searchoptions,E=this.editoptions,y=a("<th role='columnheader' class='"+n.call(f,"colHeaders","ui-th-column ui-th-"+c.direction+" "+(m.applyLabelClasses?this.labelClasses||
"":""))+"'></th>"),u=a("<div style='position:relative;height:auto;'></div>"),T=a("<table class='ui-search-table'"+(p.msie&&8>p.msiever()?" cellspacing='0'":"")+"><tr><td class='ui-search-oper'></td><td class='ui-search-input'></td><td class='ui-search-clear' style='width:1px'></td></tr></table>");!0===this.hidden&&a(y).css("display","none");this.search=!1===this.search?!1:!0;void 0===this.stype&&(this.stype="text");d=a.extend({mode:"filter"},r||{});if(this.search){if(m.searchOperators){g=d.sopt?d.sopt[0]:
"select"===this.stype?"eq":m.defaultSearch;for(v=0;v<D.length;v++)if(D[v].oper===g){h=m.operands[g]||"";break}if(void 0===h&&null!=z)for(var x in z)if(z.hasOwnProperty(x)&&x===g){h=z[x].operand;break}void 0===h&&(h="=");g="<a title='"+(null!=d.searchtitle?d.searchtitle:t("search.operandTitle"))+"' style='padding-right: 0.5em;' data-soper='"+g+"' class='soptclass' data-colname='"+this.name+"'>"+h+"</a>"}a("td",T).filter(":first").data("colindex",b).append(g);null!=d.sopt&&1!==d.sopt.length||a("td.ui-search-oper",
T).hide();void 0===d.clearSearch&&(d.clearSearch="text"===this.stype?!0:!1);d.clearSearch?(g=t("search.resetTitle")||"Clear Search Value",a("td",T).eq(2).append("<a title='"+g+"' style='padding-right: 0.2em;padding-left: 0.3em;' class='clearsearchclass'>"+m.resetIcon+"</a>")):a("td",T).eq(2).hide();switch(this.stype){case "select":if(g=this.surl||d.dataUrl)a(u).append(T),a.ajax(a.extend({url:g,context:{stbl:T,options:d,cm:this,iCol:b},dataType:"html",success:function(b,c,d){c=this.cm;var g=this.iCol,
l=this.options,k=this.stbl,h=k.find("td.ui-search-input>select");void 0!==l.buildSelect?(b=l.buildSelect.call(f,b,d,c,g))&&a("td",k).eq(1).append(b):a("td",k).eq(1).append(b);void 0!==l.defaultValue&&h.val(l.defaultValue);h.attr({name:c.index||c.name,id:"gs_"+c.name});l.attr&&h.attr(l.attr);h.addClass(C);h.css({width:"100%"});e.call(f,h[0],l);p.fullBoolFeedback.call(f,l.selectFilled,"jqGridSelectFilled",{elem:h[0],options:l,cm:c,cmName:c.name,iCol:g,mode:"filter"});!0===m.autosearch&&h.change(function(){B();
return!1})}},p.ajaxOptions,c.ajaxSelectOptions||{}));else{var O,aa,Q;r?(O=void 0===r.value?"":r.value,aa=void 0===r.separator?":":r.separator,Q=void 0===r.delimiter?";":r.delimiter):E&&(O=void 0===E.value?"":E.value,aa=void 0===E.separator?":":E.separator,Q=void 0===E.delimiter?";":E.delimiter);if(O){var K=document.createElement("select");K.style.width="100%";a(K).attr({name:this.index||this.name,id:"gs_"+this.name,role:"listbox"});var L;if("string"===typeof O)for(g=O.split(Q),L=0;L<g.length;L++)O=
g[L].split(aa),Q=document.createElement("option"),Q.value=O[0],Q.innerHTML=O[1],K.appendChild(Q);else if("object"===typeof O)for(L in O)O.hasOwnProperty(L)&&(Q=document.createElement("option"),Q.value=L,Q.innerHTML=O[L],K.appendChild(Q));void 0!==d.defaultValue&&a(K).val(d.defaultValue);d.attr&&a(K).attr(d.attr);a(K).addClass(C);a(u).append(T);e.call(f,K,d);a("td",T).eq(1).append(K);p.fullBoolFeedback.call(f,d.selectFilled,"jqGridSelectFilled",{elem:K,options:r||E||{},cm:this,cmName:this.name,iCol:b,
mode:"filter"});!0===m.autosearch&&a(K).change(function(){B();return!1})}}break;case "text":b=void 0!==d.defaultValue?d.defaultValue:"";a("td",T).eq(1).append("<input type='text' role='textbox' class='"+C+"' style='width:100%;padding:0;' name='"+(this.index||this.name)+"' id='gs_"+this.name+"' value='"+b+"'/>");a(u).append(T);d.attr&&a("input",u).attr(d.attr);e.call(f,a("input",u)[0],d);!0===m.autosearch&&(m.searchOnEnter?a("input",u).keypress(function(a){return 13===(a.charCode||a.keyCode||0)?(B(),
!1):this}):a("input",u).keydown(function(a){switch(a.which){case 13:return!1;case 9:case 16:case 37:case 38:case 39:case 40:case 27:break;default:V&&clearTimeout(V),V=setTimeout(function(){B()},m.autosearchDelay)}}));break;case "custom":a("td",T).eq(1).append("<span style='width:95%;padding:0;' class='"+C+"' name='"+(this.index||this.name)+"' id='gs_"+this.name+"'/>");a(u).append(T);try{if(a.isFunction(d.custom_element))if(K=d.custom_element.call(f,void 0!==d.defaultValue?d.defaultValue:"",d))K=a(K).addClass("customelement"),
a(u).find("span[name='"+(this.index||this.name)+"']").append(K);else throw"e2";else throw"e1";}catch(k){"e1"===k&&l.call(f,w,"function 'custom_element' "+q.nodefined,A),"e2"===k?l.call(f,w,"function 'custom_element' "+q.novalue,A):l.call(f,w,"string"===typeof k?k:k.message,A)}}}a(y).append(u);a(I).append(y);m.searchOperators||a("td",T).eq(0).hide()});a(h.hDiv).find(">div>.ui-jqgrid-htable>thead").append(I);m.searchOperators&&(a(".soptclass",I).click(function(b){var c=a(this).offset();v(this,c.left,
c.top);b.stopPropagation()}),a("body").on("click",function(b){"soptclass"!==b.target.className&&a("#sopt_menu").hide()}));a(".clearsearchclass",I).click(function(){var b=a(this).parents("tr").filter(":first"),c=parseInt(a("td.ui-search-oper",b).data("colindex"),10),e=a.extend({},g[c].searchoptions||{}).defaultValue||"";"select"===g[c].stype?e?a("td.ui-search-input select",b).val(e):a("td.ui-search-input select",b)[0].selectedIndex=0:a("td.ui-search-input input",b).val(e);!0===m.autosearch&&B()});
f.ftoolbar=!0;f.triggerToolbar=B;f.clearToolbar=function(e){var d={},l=0,t;e="boolean"!==typeof e?!0:e;a.each(g,function(){var b,e=a("#gs_"+u(this.name),!0===this.frozen&&!0===c.frozenColumns?h.fhDiv:h.hDiv),g,m=this.searchoptions||{};void 0!==m.defaultValue&&(b=m.defaultValue);t=this.index||this.name;switch(this.stype){case "select":g=0<e.length?!e[0].multiple:!0;e.find("option").each(function(c){this.selected=0===c&&g;if(a(this).val()===b)return this.selected=!0,!1});if(void 0!==b)d[t]=b,l++;else try{delete c.postData[t]}catch(q){}break;
case "text":e.val(b||"");if(void 0!==b)d[t]=b,l++;else try{delete c.postData[t]}catch(p){}break;case "custom":a.isFunction(m.custom_value)&&0<e.length&&"SPAN"===e[0].nodeName.toUpperCase()&&m.custom_value.call(f,e.children(".customelement").filter(":first"),"set",b||"")}});var q=0<l?!0:!1;c.resetsearch=!0;if(m.stringResult||m.searchOperators||"local"===c.datatype){var p='{"groupOp":"'+m.groupOp+'","rules":[',n=0;a.each(d,function(a,b){0<n&&(p+=",");p+='{"field":"'+a+'",';p+='"op":"eq",';p+='"data":"'+
(b+"").replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"}';n++});p+="]}";a.extend(c.postData,{filters:p});a.each(["searchField","searchString","searchOper"],function(a,b){c.postData.hasOwnProperty(b)&&delete c.postData[b]})}else a.extend(c.postData,d);var v;c.searchurl&&(v=c.url,b.jqGrid("setGridParam",{url:c.searchurl}));var A="stop"===b.triggerHandler("jqGridToolbarBeforeClear")?!0:!1;!A&&a.isFunction(m.beforeClear)&&(A=m.beforeClear.call(f));A||e&&b.jqGrid("setGridParam",{search:q}).trigger("reloadGrid",
[a.extend({page:1},m.reloadGridResetOptions||{})]);v&&b.jqGrid("setGridParam",{url:v});b.triggerHandler("jqGridToolbarAfterClear");a.isFunction(m.afterClear)&&m.afterClear()};f.toggleToolbar=function(){var b=a("tr.ui-search-toolbar",h.hDiv),e=!0===c.frozenColumns?a("tr.ui-search-toolbar",h.fhDiv):!1;"none"===b.css("display")?(b.show(),e&&e.show()):(b.hide(),e&&e.hide())}}})},destroyFilterToolbar:function(){return this.each(function(){this.ftoolbar&&(this.toggleToolbar=this.clearToolbar=this.triggerToolbar=
null,this.ftoolbar=!1,a(this.grid.hDiv).find("table thead tr.ui-search-toolbar").remove())})},destroyGroupHeader:function(d){void 0===d&&(d=!0);return this.each(function(){var f,h,b,c;f=this.grid;var e=this.p.colModel,l=a("table.ui-jqgrid-htable thead",f.hDiv);if(f){a(this).unbind(".setGroupHeaders");var m=a("<tr>",{role:"row"}).addClass("ui-jqgrid-labels"),g=f.headers;f=0;for(h=g.length;f<h;f++){b=e[f].hidden?"none":"";b=a(g[f].el).width(g[f].width).css("display",b);try{b.removeAttr("rowSpan")}catch(t){b.attr("rowSpan",
1)}m.append(b);c=b.children("span.ui-jqgrid-resize");0<c.length&&(c[0].style.height="");b.children("div")[0].style.top=""}a(l).children("tr.ui-jqgrid-labels").remove();a(l).prepend(m);!0===d&&a(this).jqGrid("setGridParam",{groupHeader:null})}})},setGroupHeaders:function(d){d=a.extend({useColSpanStyle:!1,applyLabelClasses:!0,groupHeaders:[]},d||{});return this.each(function(){this.p.groupHeader=d;var f,h,b=0,c,e,l,m,g,t,w=this.p.colModel,A=w.length,q=this.grid.headers,r=a("table.ui-jqgrid-htable",
this.grid.hDiv),E=p.isCellClassHidden,C=r.children("thead").children("tr.ui-jqgrid-labels"),B=C.last().addClass("jqg-second-row-header");c=r.children("thead");var D=r.find(".jqg-first-row-header");void 0===D[0]?D=a("<tr>",{role:"row","aria-hidden":"true"}).addClass("jqg-first-row-header").css("height","auto"):D.empty();var z=function(a,b){var c=b.length,e;for(e=0;e<c;e++)if(b[e].startColumnName===a)return e;return-1};a(this).prepend(c);c=a("<tr>",{role:"row"}).addClass("ui-jqgrid-labels jqg-third-row-header");
for(f=0;f<A;f++)if(l=q[f].el,m=a(l),h=w[f],e={height:"0",width:q[f].width+"px",display:h.hidden?"none":""},a("<th>",{role:"gridcell"}).css(e).addClass("ui-first-th-"+this.p.direction+(d.applyLabelClasses?" "+(h.labelClasses||""):"")).appendTo(D),l.style.width="",e=n.call(this,"colHeaders","ui-th-column-header ui-th-"+this.p.direction+" "+(d.applyLabelClasses?h.labelClasses||"":"")),g=z(h.name,d.groupHeaders),0<=g){g=d.groupHeaders[g];b=g.numberOfColumns;t=g.titleText;for(g=h=0;g<b&&f+g<A;g++)w[f+
g].hidden||E(w[f+g].classes)||a(q[f+g].el).is(":hidden")||h++;e=a("<th>").attr({role:"columnheader"}).addClass(e).css({height:"22px","border-top":"0 none"}).html(t);0<h&&e.attr("colspan",String(h));this.p.headertitles&&e.attr("title",e.text());0===h&&e.hide();m.before(e);c.append(l);--b}else 0===b?d.useColSpanStyle?m.attr("rowspan",C.length+1):(a("<th>",{role:"columnheader"}).addClass(e).css({display:h.hidden?"none":"","border-top":"0 none"}).insertBefore(m),c.append(l)):(c.append(l),b--);w=a(this).children("thead");
w.prepend(D);c.insertAfter(B);r.append(w);d.useColSpanStyle&&(r.find("span.ui-jqgrid-resize").each(function(){var b=a(this).parent();b.is(":visible")&&(this.style.cssText="height: "+b.height()+"px !important; cursor: col-resize;")}),r.find(".ui-th-column>div").each(function(){var b=a(this),c=b.parent();c.is(":visible")&&c.is(":has(span.ui-jqgrid-resize)")&&!b.hasClass("ui-jqgrid-rotate")&&!b.hasClass("ui-jqgrid-rotateOldIE")&&b.css("top",(c.height()-b.outerHeight(!0))/2+"px")}));a(this).triggerHandler("jqGridAfterSetGroupHeaders")})},
setFrozenColumns:function(){return this.each(function(){var d=this,f=a(d),h=d.p,b=d.grid;if(b&&null!=h&&!0!==h.frozenColumns){var c=h.colModel,e,l=c.length,m=-1,g=!1,t=[],p=u(h.id),A=n.call(d,"states.hover"),q=n.call(d,"states.disabled");if(!0!==h.subGrid&&!0!==h.treeGrid&&!h.scroll){for(e=0;e<l&&!0===c[e].frozen;e++)g=!0,m=e,t.push("#jqgh_"+p+"_"+u(c[e].name));h.sortable&&(c=a(b.hDiv).find(".ui-jqgrid-htable .ui-jqgrid-labels"),c.sortable("destroy"),f.jqGrid("setGridParam",{sortable:{options:{items:0<
t.length?">th:not(:has("+t.join(",")+"),:hidden)":">th:not(:hidden)"}}}),f.jqGrid("sortableColumns",c));if(0<=m&&g){g=h.caption?a(b.cDiv).outerHeight():0;t=a(".ui-jqgrid-htable",h.gView).height();h.toppager&&(g+=a(b.topDiv).outerHeight());!0===h.toolbar[0]&&"bottom"!==h.toolbar[1]&&(g+=a(b.uDiv).outerHeight());b.fhDiv=a('<div style="position:absolute;overflow:hidden;" + (p.direction === "rtl" ? "right:0;" : "left:0;") + "top:'+g+"px;height:"+t+'px;" class="'+n.call(d,"hDiv","frozen-div ui-jqgrid-hdiv")+
'"></div>');b.fbDiv=a('<div style="position:absolute;overflow:hidden;" + (p.direction === "rtl" ? "right:0;" : "left:0;") + "top:'+(parseInt(g,10)+parseInt(t,10)+1)+'px;overflow:hidden" class="frozen-bdiv ui-jqgrid-bdiv"></div>');a(h.gView).append(b.fhDiv);c=a(".ui-jqgrid-htable",h.gView).clone(!0);if(h.groupHeader){a("tr.jqg-first-row-header",c).each(function(){a("th:gt("+m+")",this).remove()});a("tr.jqg-third-row-header",c).each(function(){a(this).children("th[id]").each(function(){var b=a(this).attr("id");
b&&b.substr(0,d.id.length+1)===d.id+"_"&&(b=b.substr(d.id.length+1),h.iColByName[b]>m&&a(this).remove())})});var r=-1,E=-1,C,B;a("tr.jqg-second-row-header th",c).each(function(){C=parseInt(a(this).attr("colspan")||1,10);B=parseInt(a(this).attr("rowspan")||1,10);1<B?(r++,E++):C&&(r+=C,E++);if(r===m)return!1});r!==m&&(E=m);a("tr.jqg-second-row-header",c).each(function(){a("th:gt("+E+")",this).remove()})}else a("tr",c).each(function(){a("th:gt("+m+")",this).remove()});a(c).width(1);a(b.fhDiv).append(c).mousemove(function(a){if(b.resizing)return b.dragMove(a),
!1}).scroll(function(){this.scrollLeft=0});h.footerrow&&(c=a(".ui-jqgrid-bdiv",h.gView).height(),b.fsDiv=a('<div style="position:absolute;" + (p.direction === "rtl" ? "right:0;" : "left:0;") + "top:'+(parseInt(g,10)+parseInt(t,10)+parseInt(c,10)+1)+'px;" class="frozen-sdiv ui-jqgrid-sdiv"></div>'),a(h.gView).append(b.fsDiv),g=a(".ui-jqgrid-ftable",h.gView).clone(!0),a("tr",g).each(function(){a("td:gt("+m+")",this).remove()}),a(g).width(1),a(b.fsDiv).append(g));f.bind("jqGridSortCol.setFrozenColumns",
function(c,e,d){c=a("tr.ui-jqgrid-labels:last th:eq("+h.lastsort+")",b.fhDiv);e=a("tr.ui-jqgrid-labels:last th:eq("+d+")",b.fhDiv);a("span.ui-grid-ico-sort",c).addClass(q);a(c).attr("aria-selected","false");a("span.ui-icon-"+h.sortorder,e).removeClass(q);a(e).attr("aria-selected","true");h.viewsortcols[0]||h.lastsort===d||(a("span.s-ico",c).hide(),a("span.s-ico",e).show())});a(h.gView).append(b.fbDiv);a(b.bDiv).scroll(function(){a(b.fbDiv).scrollTop(a(this).scrollTop())});!0===h.hoverrows&&a(h.idSel).unbind("mouseover").unbind("mouseout");
var D=function(a,b){var c=a.height();1<=Math.abs(c-b)&&(a.height(b),c=a.height(),1<=Math.abs(b-c)&&a.height(b+Math.round(b-c)))},z=function(a,b){var c=a.width();1<=Math.abs(c-b)&&(a.width(b),c=a.width(),1<=Math.abs(b-c)&&a.width(b+Math.round(b-c)))},v=function(b,c){var d,g,l,f,t,q,p,n,v=a(c).position().top,A,w;if(null!=b&&0<b.length){b.css("rtl"===h.direction?{top:v,right:0}:{top:v,left:0});l=b.children("table").children("tbody,thead").children("tr");f=a(c).children("div").children("table").children("tbody,thead").children("tr");
g=Math.min(l.length,f.length);A=0<g?a(l[0]).position().top:0;w=0<g?a(f[0]).position().top:0;for(d=0;d<g;d++){t=a(f[d]);v=t.position().top;q=a(l[d]);p=q.position().top;n=t.height();if(null!=h.groupHeader&&h.groupHeader.useColSpanStyle&&0===n)for(e=n=0;e<m;e++)"TH"===t[0].cells[e].nodeName.toUpperCase()&&(n=Math.max(n,a(t[0].cells[e]).height()));t=n+(v-w)+(A-p);D(q,t)}D(b,c.clientHeight)}};f.bind("jqGridAfterGridComplete.setFrozenColumns",function(){a(h.idSel+"_frozen").remove();a(b.fbDiv).height(b.hDiv.clientHeight);
var c=a(this).clone(!0),e=c[0].rows,d=f[0].rows;a(e).filter("tr[role=row]").each(function(){a(this.cells).filter("td[role=gridcell]:gt("+m+")").remove()});b.fbRows=e;c.width(1).attr("id",h.id+"_frozen");c.appendTo(b.fbDiv);if(!0===h.hoverrows){var g=function(b,c,e){a(b)[c](A);a(e[b.rowIndex])[c](A)};a(e).filter(".jqgrow").hover(function(){g(this,"addClass",d)},function(){g(this,"removeClass",d)});a(d).filter(".jqgrow").hover(function(){g(this,"addClass",e)},function(){g(this,"removeClass",e)})}v(b.fhDiv,
b.hDiv);v(b.fbDiv,b.bDiv);b.sDiv&&v(b.fsDiv,b.sDiv)});var V=function(){a(b.fbDiv).scrollTop(a(b.bDiv).scrollTop());v(b.fhDiv,b.hDiv);v(b.fbDiv,b.bDiv);b.sDiv&&v(b.fsDiv,b.sDiv);var c=b.fhDiv[0].clientWidth;null!=b.fhDiv&&1<=b.fhDiv.length&&D(a(b.fhDiv),b.hDiv.clientHeight);null!=b.fbDiv&&0<b.fbDiv.length&&z(a(b.fbDiv),c);null!=b.fsDiv&&0<=b.fsDiv.length&&z(a(b.fsDiv),c)};a(h.gBox).bind("resizestop.setFrozenColumns",function(){setTimeout(function(){V()},50)});f.bind("jqGridInlineEditRow.setFrozenColumns jqGridAfterEditCell.setFrozenColumns jqGridAfterRestoreCell.setFrozenColumns jqGridInlineAfterRestoreRow.setFrozenColumns jqGridAfterSaveCell.setFrozenColumns jqGridInlineAfterSaveRow.setFrozenColumns jqGridResetFrozenHeights.setFrozenColumns jqGridGroupingClickGroup.setFrozenColumns jqGridResizeStop.setFrozenColumns",
V);b.hDiv.loading||f.triggerHandler("jqGridAfterGridComplete");h.frozenColumns=!0}}}})},destroyFrozenColumns:function(){return this.each(function(){var d=a(this),f=this.grid,h=this.p,b=u(h.id);if(f&&!0===h.frozenColumns){a(f.fhDiv).remove();a(f.fbDiv).remove();f.fhDiv=null;f.fbDiv=null;f.fbRows=null;h.footerrow&&(a(f.fsDiv).remove(),f.fsDiv=null);d.unbind(".setFrozenColumns");if(!0===h.hoverrows){var c,e=n.call(this,"states.hover");d.bind("mouseover",function(b){c=a(b.target).closest("tr.jqgrow");
"ui-subgrid"!==a(c).attr("class")&&a(c).addClass(e)}).bind("mouseout",function(b){c=a(b.target).closest("tr.jqgrow");a(c).removeClass(e)})}h.frozenColumns=!1;h.sortable&&(f=a(f.hDiv).find(".ui-jqgrid-htable .ui-jqgrid-labels"),f.sortable("destroy"),d.jqGrid("setGridParam",{sortable:{options:{items:">th:not(:has(#jqgh_"+b+"_cb,#jqgh_"+b+"_rn,#jqgh_"+b+"_subgrid),:hidden)"}}}),d.jqGrid("sortableColumns",f))}})}})})(jQuery);
(function(a){var p=a.jgrid;a.fn.jqFilter=function(r){if("string"===typeof r){var u=a.fn.jqFilter[r];if(!u)throw"jqFilter - No such method: "+r;var n=a.makeArray(arguments).slice(1);return u.apply(this,n)}var d=a.extend(!0,{filter:null,columns:[],onChange:null,afterRedraw:null,checkValues:null,error:!1,errmsg:"",errorcheck:!0,showQuery:!0,sopt:null,ops:[],operands:null,numopts:"eq ne lt le gt ge nu nn in ni".split(" "),stropts:"eq ne bw bn ew en cn nc nu nn in ni".split(" "),strarr:["text","string",
"blob"],groupOps:[{op:"AND",text:"AND"},{op:"OR",text:"OR"}],groupButton:!0,ruleButtons:!0,direction:"ltr"},p.filter,r||{});return this.each(function(){if(!this.filter){this.p=d;if(null===d.filter||void 0===d.filter)d.filter={groupOp:d.groupOps[0].op,rules:[],groups:[]};var f,h=d.columns.length,b,c=/msie/i.test(navigator.userAgent)&&!window.opera,e=function(){return a("#"+p.jqID(d.id))[0]||null},l=p.getRes(p.guiStyles[e().p.guiStyle],"states.error"),m=p.getRes(p.guiStyles[e().p.guiStyle],"dialog.content");
d.initFilter=a.extend(!0,{},d.filter);if(h){for(f=0;f<h;f++)b=d.columns[f],b.stype?b.inputtype=b.stype:b.inputtype||(b.inputtype="text"),b.sorttype?b.searchtype=b.sorttype:b.searchtype||(b.searchtype="string"),void 0===b.hidden&&(b.hidden=!1),b.label||(b.label=b.name),b.index&&(b.name=b.index),b.hasOwnProperty("searchoptions")||(b.searchoptions={}),b.hasOwnProperty("searchrules")||(b.searchrules={});d.showQuery&&a(this).append("<table class='queryresult "+m+"' style='display:block;max-width:440px;border:0px none;' dir='"+
d.direction+"'><tbody><tr><td class='query'></td></tr></tbody></table>");var g=function(b,c){var g=[!0,""],l=e();if(a.isFunction(c.searchrules))g=c.searchrules.call(l,b,c);else if(p&&p.checkValues)try{g=p.checkValues.call(l,b,-1,c.searchrules,c.label)}catch(f){}g&&g.length&&!1===g[0]&&(d.error=!g[0],d.errmsg=g[1])};this.onchange=function(){d.error=!1;d.errmsg="";return a.isFunction(d.onChange)?d.onChange.call(this,d):!1};this.reDraw=function(){a("table.group:first",this).remove();var b=this.createTableForGroup(d.filter,
null);a(this).append(b);a.isFunction(d.afterRedraw)&&d.afterRedraw.call(this,d)};this.createTableForGroup=function(b,c){var e=this,g,f=a("<table class='group "+m+"' style='border:0px none;'><tbody></tbody></table>"),h="left";"rtl"===d.direction&&(h="right",f.attr("dir","rtl"));null===c&&f.append("<tr class='error' style='display:none;'><th colspan='5' class='"+l+"' align='"+h+"'></th></tr>");var p=a("<tr></tr>");f.append(p);h=a("<th colspan='5' align='"+h+"'></th>");p.append(h);if(!0===d.ruleButtons){var n=
a("<select class='opsel'></select>");h.append(n);var p="",r;for(g=0;g<d.groupOps.length;g++)r=b.groupOp===e.p.groupOps[g].op?" selected='selected'":"",p+="<option value='"+e.p.groupOps[g].op+"'"+r+">"+e.p.groupOps[g].text+"</option>";n.append(p).bind("change",function(){b.groupOp=a(n).val();e.onchange()})}p="<span></span>";d.groupButton&&(p=a("<input type='button' value='+ {}' title='Add subgroup' class='add-group'/>"),p.bind("click",function(){void 0===b.groups&&(b.groups=[]);b.groups.push({groupOp:d.groupOps[0].op,
rules:[],groups:[]});e.reDraw();e.onchange();return!1}));h.append(p);if(!0===d.ruleButtons){var p=a("<input type='button' value='+' title='Add rule' class='add-rule ui-add'/>"),z;p.bind("click",function(){var c,d,l;void 0===b.rules&&(b.rules=[]);for(g=0;g<e.p.columns.length;g++)if(c=void 0===e.p.columns[g].search?!0:e.p.columns[g].search,d=!0===e.p.columns[g].hidden,(l=!0===e.p.columns[g].searchoptions.searchhidden)&&c||c&&!d){z=e.p.columns[g];break}c=z.searchoptions.sopt?z.searchoptions.sopt:e.p.sopt?
e.p.sopt:-1!==a.inArray(z.searchtype,e.p.strarr)?e.p.stropts:e.p.numopts;b.rules.push({field:z.name,op:c[0],data:""});e.reDraw();return!1});h.append(p)}null!==c&&(p=a("<input type='button' value='-' title='Delete group' class='delete-group'/>"),h.append(p),p.bind("click",function(){for(g=0;g<c.groups.length;g++)if(c.groups[g]===b){c.groups.splice(g,1);break}e.reDraw();e.onchange();return!1}));if(void 0!==b.groups)for(g=0;g<b.groups.length;g++)h=a("<tr></tr>"),f.append(h),p=a("<td class='first'></td>"),
h.append(p),p=a("<td colspan='4'></td>"),p.append(this.createTableForGroup(b.groups[g],b)),h.append(p);void 0===b.groupOp&&(b.groupOp=e.p.groupOps[0].op);if(void 0!==b.rules)for(g=0;g<b.rules.length;g++)f.append(this.createTableRowForRule(b.rules[g],b));return f};this.createTableRowForRule=function(b,g){var l=this,f=e(),h=a("<tr></tr>"),m,n,B,r="",z;h.append("<td class='first'></td>");var v=a("<td class='columns'></td>");h.append(v);var u=a("<select></select>"),I,G=[];v.append(u);u.bind("change",
function(){b.field=a(u).val();var e=a(this).parents("tr:first"),d,g;for(g=0;g<l.p.columns.length;g++)if(l.p.columns[g].name===b.field){d=l.p.columns[g];break}if(d){var h=a.extend({},d.searchoptions||{},{id:p.randId(),name:d.name,mode:"search"});c&&"text"===d.inputtype&&!h.size&&(h.size=10);var m=p.createEl.call(f,d.inputtype,h,"",!0,l.p.ajaxSelectOptions||{},!0);a(m).addClass("input-elm");n=h.sopt?h.sopt:l.p.sopt?l.p.sopt:-1!==a.inArray(d.searchtype,l.p.strarr)?l.p.stropts:l.p.numopts;d="";var v=
0,w,r;G=[];a.each(l.p.ops,function(){G.push(this.oper)});l.p.cops&&a.each(l.p.cops,function(a){G.push(a)});for(g=0;g<n.length;g++)r=n[g],I=a.inArray(n[g],G),-1!==I&&(w=l.p.ops[I],w=void 0!==w?w.text:l.p.cops[r].text,0===v&&(b.op=r),d+="<option value='"+r+"'>"+w+"</option>",v++);a(".selectopts",e).empty().append(d);a(".selectopts",e)[0].selectedIndex=0;p.msie&&9>p.msiever()&&(g=parseInt(a("select.selectopts",e)[0].offsetWidth,10)+1,a(".selectopts",e).width(g),a(".selectopts",e).css("width","auto"));
a(".data",e).empty().append(m);p.bindEv.call(f,m,h);a(".input-elm",e).bind("change",function(c){c=c.target;b.data="SPAN"===c.nodeName.toUpperCase()&&h&&a.isFunction(h.custom_value)?h.custom_value.call(f,a(c).children(".customelement:first"),"get"):c.value;l.onchange()});setTimeout(function(){b.data=a(m).val();l.onchange()},0)}});var v=0,S,U;for(m=0;m<l.p.columns.length;m++)if(z=void 0===l.p.columns[m].search?!0:l.p.columns[m].search,S=!0===l.p.columns[m].hidden,(U=!0===l.p.columns[m].searchoptions.searchhidden)&&
z||z&&!S)z="",b.field===l.p.columns[m].name&&(z=" selected='selected'",v=m),r+="<option value='"+l.p.columns[m].name+"'"+z+">"+l.p.columns[m].label+"</option>";u.append(r);r=a("<td class='operators'></td>");h.append(r);B=d.columns[v];c&&"text"===B.inputtype&&!B.searchoptions.size&&(B.searchoptions.size=10);v=p.createEl.call(f,B.inputtype,a.extend({},B.searchoptions||{},{id:p.randId(),name:B.name}),b.data,!0,l.p.ajaxSelectOptions||{},!0);if("nu"===b.op||"nn"===b.op)a(v).attr("readonly","true"),a(v).attr("disabled",
"true");var F=a("<select class='selectopts'></select>");r.append(F);F.bind("change",function(){b.op=a(F).val();var c=a(this).parents("tr:first"),c=a(".input-elm",c)[0];"nu"===b.op||"nn"===b.op?(b.data="","SELECT"!==c.tagName.toUpperCase()&&(c.value=""),c.setAttribute("readonly","true"),c.setAttribute("disabled","true")):("SELECT"===c.tagName.toUpperCase()&&(b.data=c.value),c.removeAttribute("readonly"),c.removeAttribute("disabled"));l.onchange()});n=B.searchoptions.sopt?B.searchoptions.sopt:l.p.sopt?
l.p.sopt:-1!==a.inArray(B.searchtype,l.p.strarr)?l.p.stropts:l.p.numopts;r="";a.each(l.p.ops,function(){G.push(this.oper)});l.p.cops&&a.each(l.p.cops,function(a){G.push(a)});for(m=0;m<n.length;m++)U=n[m],I=a.inArray(n[m],G),-1!==I&&(S=l.p.ops[I],z=b.op===U?" selected='selected'":"",r+="<option value='"+U+"'"+z+">"+(void 0!==S?S.text:l.p.cops[U].text)+"</option>");F.append(r);r=a("<td class='data'></td>");h.append(r);r.append(v);p.bindEv.call(f,v,B.searchoptions);a(v).addClass("input-elm").bind("change",
function(){b.data="custom"===B.inputtype?B.searchoptions.custom_value.call(f,a(this).children(".customelement:first"),"get"):a(this).val();l.onchange()});r=a("<td></td>");h.append(r);!0===d.ruleButtons&&(v=a("<input type='button' value='-' title='Delete rule' class='delete-rule ui-del'/>"),r.append(v),v.bind("click",function(){for(m=0;m<g.rules.length;m++)if(g.rules[m]===b){g.rules.splice(m,1);break}l.reDraw();l.onchange();return!1}));return h};this.getStringForGroup=function(a){var b="(",c;if(void 0!==
a.groups)for(c=0;c<a.groups.length;c++){1<b.length&&(b+=" "+a.groupOp+" ");try{b+=this.getStringForGroup(a.groups[c])}catch(e){alert(e)}}if(void 0!==a.rules)try{for(c=0;c<a.rules.length;c++)1<b.length&&(b+=" "+a.groupOp+" "),b+=this.getStringForRule(a.rules[c])}catch(d){alert(d)}b+=")";return"()"===b?"":b};this.getStringForRule=function(b){var c="",e="",l,f,h=b.data,m;for(l=0;l<d.ops.length;l++)if(d.ops[l].oper===b.op){c=d.operands.hasOwnProperty(b.op)?d.operands[b.op]:"";e=d.ops[l].oper;break}if(""===
e&&null!=d.cops)for(m in d.cops)if(d.cops.hasOwnProperty(m)&&(e=m,c=d.cops[m].operand,a.isFunction(d.cops[m].buildQueryValue)))return d.cops[m].buildQueryValue.call(d,{cmName:b.field,searchValue:h,operand:c});for(l=0;l<d.columns.length;l++)if(d.columns[l].name===b.field){f=d.columns[l];break}if(null==f)return"";if("bw"===e||"bn"===e)h+="%";if("ew"===e||"en"===e)h="%"+h;if("cn"===e||"nc"===e)h="%"+h+"%";if("in"===e||"ni"===e)h=" ("+h+")";d.errorcheck&&g(b.data,f);return-1!==a.inArray(f.searchtype,
["int","integer","float","number","currency"])||"nn"===e||"nu"===e?b.field+" "+c+" "+h:b.field+" "+c+' "'+h+'"'};this.resetFilter=function(){d.filter=a.extend(!0,{},d.initFilter);this.reDraw();this.onchange()};this.hideError=function(){a("th."+l,this).html("");a("tr.error",this).hide()};this.showError=function(){a("th."+l,this).html(d.errmsg);a("tr.error",this).show()};this.toUserFriendlyString=function(){return this.getStringForGroup(d.filter)};this.toString=function(){function a(c){var e="(",d;
if(void 0!==c.groups)for(d=0;d<c.groups.length;d++)1<e.length&&(e="OR"===c.groupOp?e+" || ":e+" && "),e+=a(c.groups[d]);if(void 0!==c.rules)for(d=0;d<c.rules.length;d++){1<e.length&&(e="OR"===c.groupOp?e+" || ":e+" && ");var l=c.rules[d];if(b.p.errorcheck){for(var f=void 0,h=void 0,f=0;f<b.p.columns.length;f++)if(b.p.columns[f].name===l.field){h=b.p.columns[f];break}h&&g(l.data,h)}e+=l.op+"(item."+l.field+",'"+l.data+"')"}e+=")";return"()"===e?"":e}var b=this;return a(d.filter)};this.reDraw();if(d.showQuery)this.onchange();
this.filter=!0}}})};a.extend(a.fn.jqFilter,{toSQLString:function(){var a="";this.each(function(){a=this.toUserFriendlyString()});return a},filterData:function(){var a;this.each(function(){a=this.p.filter});return a},getParameter:function(a){return void 0!==a&&this.p.hasOwnProperty(a)?this.p[a]:this.p},resetFilter:function(){return this.each(function(){this.resetFilter()})},addFilter:function(a){"string"===typeof a&&(a=p.parse(a));this.each(function(){this.p.filter=a;this.reDraw();this.onchange()})}})})(jQuery);
(function(a){var p=a.jgrid,r=p.feedback,u=p.fullBoolFeedback,n=p.jqID,d=p.hideModal,f=p.viewModal,h=p.createModal,b=p.info_dialog,c=p.mergeCssClasses,e=p.hasOneFromClasses,l=a.fn.jqGrid,m=p.builderFmButon,g=function(a,b){var c=a[0].style[b];return 0<=c.indexOf("px")?parseFloat(c):c},t=function(b,c,e){var d=e.w;c=a(c);var l,f,h;e.c.toTop?(l=this.closest(".ui-jqgrid").offset(),f=d.offset(),h=f.top-l.top,l=f.left-l.left):(h=g(d,"top"),l=g(d,"left"));this.data(b,{top:h,left:l,width:g(d,"width"),height:g(d,
"height"),dataheight:g(c,"height")||"auto",datawidth:g(c,"width")||"auto"});d.remove();e.o&&e.o.remove()},w=function(a,b,e){!0===b[0]&&(e="<span class='"+c("fm-button-icon",e,b[2])+"'></span>","right"===b[1]?a.addClass("fm-button-icon-right").append(e):a.addClass("fm-button-icon-left").prepend(e))},A=function(a,b){return p.mergeCssClasses(p.getRes(p.guiStyles[this.p.guiStyle],a),b||"")},q=function(a){return A.call(this,"states."+a)},y=function(a){return" "===a||" "===a||1===a.length&&160===
a.charCodeAt(0)};p.extend({searchGrid:function(b){return this.each(function(){function e(b){H("beforeShow",b)&&(a(S).data("onClose",v.onClose),f(S,{gbox:U,jqm:v.jqModal,overlay:v.overlay,modal:v.modal,overlayClass:v.overlayClass,toTop:v.toTop,onHide:function(a){t.call(w,"searchProp",y,a)}}),H("afterShow",b))}var g=this,w=a(g),z=g.p;if(g.grid&&null!=z){var v=a.extend(!0,{recreateFilter:!1,drag:!0,sField:"searchField",sValue:"searchString",sOper:"searchOper",sFilter:"filters",loadDefaults:!0,beforeShowSearch:null,
afterShowSearch:null,onInitializeSearch:null,afterRedraw:null,afterChange:null,closeAfterSearch:!1,closeAfterReset:!1,closeOnEscape:!1,searchOnEnter:!1,multipleSearch:!1,multipleGroup:!1,top:0,left:0,removemodal:!0,resize:!0,width:450,height:"auto",dataheight:"auto",showQuery:!1,errorcheck:!0,sopt:null,stringResult:void 0,onClose:null,onSearch:null,onReset:null,columns:[],tmplNames:null,tmplFilters:null,tmplLabel:" Template: ",showOnLoad:!1,layer:null,operands:{eq:"=",ne:"<>",lt:"<",le:"<=",gt:">",
ge:">=",bw:"LIKE",bn:"NOT LIKE","in":"IN",ni:"NOT IN",ew:"LIKE",en:"NOT LIKE",cn:"LIKE",nc:"NOT LIKE",nu:"IS NULL",nn:"IS NOT NULL"}},l.getGridRes.call(w,"search"),p.search||{},z.searching||{},b||{}),y="fbox_"+z.id,I=v.commonIconClass,G={themodal:"searchmod"+y,modalhead:"searchhd"+y,modalcontent:"searchcnt"+y,resizeAlso:y},S="#"+n(G.themodal),U=z.gBox,F=z.gView,J=z.postData[v.sFilter],H=function(){var b=a.makeArray(arguments);b.unshift("Search");b.unshift("Filter");b.unshift(v);return r.apply(g,b)};
"string"===typeof J&&(J=p.parse(J));!0===v.recreateFilter?a(S).remove():w.data("searchProp")&&a.extend(v,w.data("searchProp"));if(void 0!==a(S)[0])e(a("#fbox_"+z.idSel));else{var N=a("<div><div id='"+y+"' class='searchFilter' style='overflow:auto'></div></div>").insertBefore(F);"rtl"===z.direction&&N.attr("dir","rtl");var Y="",X="",T,x=!1,O,aa=-1,Q=a.extend([],z.colModel);O=m.call(g,y+"_search",v.Find,c(I,v.findDialogIcon),"right");var K=m.call(g,y+"_reset",v.Reset,c(I,v.resetDialogIcon),"left");
v.showQuery&&(Y=m.call(g,y+"_query","Query",c(I,v.queryDialogIcon),"left")+" ");v.columns.length?(Q=v.columns,aa=0,T=Q[0].index||Q[0].name):a.each(Q,function(a,b){b.label||(b.label=z.colNames[a]);if(!x){var c=void 0===b.search?!0:b.search,e=!0===b.hidden;if(b.searchoptions&&!0===b.searchoptions.searchhidden&&c||c&&!e)x=!0,T=b.index||b.name,aa=a}});if(!J&&T||!1===v.multipleSearch)I="eq",0<=aa&&Q[aa].searchoptions&&Q[aa].searchoptions.sopt?I=Q[aa].searchoptions.sopt[0]:v.sopt&&v.sopt.length&&(I=
v.sopt[0]),J={groupOp:"AND",rules:[{field:T,op:I,data:""}]};x=!1;v.tmplNames&&v.tmplNames.length&&(x=!0,X=v.tmplLabel,X+="<select class='ui-template'>",X+="<option value='default'>Default</option>",a.each(v.tmplNames,function(a,b){X+="<option value='"+a+"'>"+b+"</option>"}),X+="</select>");O="<table class='EditTable' style='border:0px none;margin-top:5px' id='"+y+"_2'><tbody><tr><td colspan='2'><hr class='"+A.call(g,"dialog.hr")+"' style='margin:1px'/></td></tr><tr><td class='EditButton EditButton-"+
z.direction+"' style='float:"+("rtl"===z.direction?"right":"left")+";'>"+K+X+"</td><td class='EditButton EditButton-"+z.direction+"'>"+Y+O+"</td></tr></tbody></table>";y=n(y);v.gbox="#gbox_"+y;v.height="auto";y="#"+y;a(y).jqFilter({columns:Q,filter:v.loadDefaults?J:null,showQuery:v.showQuery,errorcheck:v.errorcheck,sopt:v.sopt,groupButton:v.multipleGroup,ruleButtons:v.multipleSearch,afterRedraw:v.afterRedraw,ops:v.odata,cops:z.customSortOperations,operands:v.operands,ajaxSelectOptions:z.ajaxSelectOptions,
groupOps:v.groupOps,onChange:function(){this.p.showQuery&&a(".query",this).html(this.toUserFriendlyString());u.call(g,v.afterChange,"jqGridFilterAfterChange",a(y),v)},direction:z.direction,id:z.id});N.append(O);x&&v.tmplFilters&&v.tmplFilters.length&&a(".ui-template",N).bind("change",function(){var b=a(this).val();"default"===b?a(y).jqFilter("addFilter",J):a(y).jqFilter("addFilter",v.tmplFilters[parseInt(b,10)]);return!1});!0===v.multipleGroup&&(v.multipleSearch=!0);H("onInitialize",a(y));v.layer?
h.call(g,G,N,v,F,a(U)[0],"#"+n(v.layer),{position:"relative"}):h.call(g,G,N,v,F,a(U)[0]);(v.searchOnEnter||v.closeOnEscape)&&a(S).keydown(function(b){var c=a(b.target);if(!(!v.searchOnEnter||13!==b.which||c.hasClass("add-group")||c.hasClass("add-rule")||c.hasClass("delete-group")||c.hasClass("delete-rule")||c.hasClass("fm-button")&&c.is("[id$=_query]")))return a(y+"_search").click(),!1;if(v.closeOnEscape&&27===b.which)return a("#"+n(G.modalhead)).find(".ui-jqdialog-titlebar-close").click(),!1});Y&&
a(y+"_query").bind("click",function(){a(".queryresult",N).toggle();return!1});void 0===v.stringResult&&(v.stringResult=v.multipleSearch);a(y+"_search").bind("click",function(){var b={},c,e,l=a(y);e=l.find(".input-elm");e.filter(":focus")&&(e=e.filter(":focus"));e.change();e=l.jqFilter("filterData");if(v.errorcheck&&(l[0].hideError(),v.showQuery||l.jqFilter("toSQLString"),l[0].p.error))return l[0].showError(),!1;if(v.stringResult||"local"===z.datatype){try{c=xmlJsonClass.toJson(e,"","",!1)}catch(f){try{c=
JSON.stringify(e)}catch(h){}}"string"===typeof c&&(b[v.sFilter]=c,a.each([v.sField,v.sValue,v.sOper],function(){b[this]=""}))}else v.multipleSearch?(b[v.sFilter]=e,a.each([v.sField,v.sValue,v.sOper],function(){b[this]=""})):(b[v.sField]=e.rules[0].field,b[v.sValue]=e.rules[0].data,b[v.sOper]=e.rules[0].op,b[v.sFilter]="");z.search=!0;a.extend(z.postData,b);u.call(g,v.onSearch,"jqGridFilterSearch",z.filters)&&w.trigger("reloadGrid",[a.extend({page:1},v.reloadGridSearchOptions||{})]);v.closeAfterSearch&&
d(S,{gb:U,jqm:v.jqModal,onClose:v.onClose,removemodal:v.removemodal});return!1});a(y+"_reset").bind("click",function(){var b={},c=a(y);z.search=!1;z.resetsearch=!0;!1===v.multipleSearch?b[v.sField]=b[v.sValue]=b[v.sOper]="":b[v.sFilter]="";c[0].resetFilter();x&&a(".ui-template",N).val("default");a.extend(z.postData,b);u.call(g,v.onReset,"jqGridFilterReset")&&w.trigger("reloadGrid",[a.extend({page:1},v.reloadGridResetOptions||{})]);v.closeAfterReset&&d(S,{gb:U,jqm:v.jqModal,onClose:v.onClose,removemodal:v.removemodal});
return!1});e(a(y));var L=q.call(g,"hover");a(".fm-button:not(."+q.call(g,"disabled").split(" ").join(".")+")",N).hover(function(){a(this).addClass(L)},function(){a(this).removeClass(L)})}}})},editGridRow:function(g,u){return this.each(function(){function B(){a(K+" > tbody > tr > td .FormElement").each(function(){var c=a(".customelement",this),e=this.name;if(c.length){if(e=c.attr("name"),c=ha[e],void 0!==c&&(c=ca[c],c=c.editoptions||{},a.isFunction(c.custom_value))){try{if(P[e]=c.custom_value.call(J,
a("#"+n(e),K),"get"),void 0===P[e])throw"e1";}catch(d){"e1"===d?b.call(J,fa,"function 'custom_value' "+x.msg.novalue,x.bClose):b.call(J,fa,d.message,x.bClose)}return!0}}else{switch(a(this)[0].type){case "checkbox":P[e]=a(this).is(":checked")?a(this).val():a(this).data("offval");break;case "select-one":P[e]=a("option:selected",this).val();break;case "select-multiple":P[e]=a(this).val();P[e]=P[e]?P[e].join(","):"";a("option:selected",this).each(function(b,c){a(c).text()});break;case "password":case "text":case "textarea":case "button":P[e]=
a(this).val();break;case "date":P[e]=a(this).val(),3===String(P[e]).split("-").length&&(c=ha[e],void 0!==c&&(c=ca[c],c=c.formatoptions||{},c=c.newformat||X.call(H,"formatter.date.newformat"),P[e]=p.parseDate.call(H[0],"Y-m-d",P[e],c)))}N.autoencode&&(P[e]=p.htmlEncode(P[e]))}});return!0}function D(b,c,e){var d=0,g=[],f=!1,h="",k;for(k=1;k<=e;k++)h+="<td class='CaptionTD'> </td><td class='DataTD'> </td>";"_empty"!==b&&(f=l.getInd.call(H,b));a(ca).each(function(l){var k=this.name,m,t,q,v,
w;m=this.editable;var r=!1,z=!1;w="_empty"===b?"addForm":"editForm";a.isFunction(m)&&(m=m.call(J,{rowid:b,iCol:l,iRow:f,cmName:k,cm:this,mode:w}));v=(this.editrules&&!0===this.editrules.edithidden?0:!0===this.hidden||"hidden"===m)?"style='display:none'":"";switch(String(m).toLowerCase()){case "hidden":m=!0;break;case "disabled":r=m=!0;break;case "readonly":z=m=!0}if("cb"!==k&&"subgrid"!==k&&!0===m&&"rn"!==k){if(!1===f)q="";else{m=a(J.rows[f].cells[l]);try{q=a.unformat.call(J,m,{rowId:b,colModel:this},
l)}catch(B){q=this.edittype&&"textarea"===this.edittype?m.text():m.html()}y(q)&&(q="")}m=a.extend({},this.editoptions||{},{id:k,name:k,rowId:b,mode:w});var D=a.extend({},{elmprefix:"",elmsuffix:"",rowabove:!1,rowcontent:""},this.formoptions||{}),u=parseInt(D.rowpos,10)||d+1,C=parseInt(2*(parseInt(D.colpos,10)||1),10);"_empty"===b&&m.defaultValue&&(q=a.isFunction(m.defaultValue)?m.defaultValue.call(J):m.defaultValue);this.edittype||(this.edittype="text");N.autoencode&&(q=p.htmlDecode(q));w=p.createEl.call(J,
this.edittype,m,q,!1,a.extend({},p.ajaxOptions,N.ajaxSelectOptions||{}));if(x.checkOnSubmit||x.checkOnUpdate)x._savedData[k]=q;a(w).addClass("FormElement");-1<a.inArray(this.edittype,["text","textarea","password","select"])&&a(w).addClass(A.call(J,"dialog.dataField"));t=a(c).find("tr[data-rowpos="+u+"]");if(D.rowabove){var E=a("<tr><td class='contentinfo' colspan='"+2*e+"'>"+D.rowcontent+"</td></tr>");a(c).append(E);E[0].rp=u}0===t.length&&(t=a("<tr "+v+" data-rowpos='"+u+"'></tr>").addClass("FormData").attr("id",
"tr_"+k),a(t).append(h),a(c).append(t),t[0].rp=u);v=a("td:eq("+(C-2)+")",t[0]);t=a("td:eq("+(C-1)+")",t[0]);v.html(void 0===D.label?N.colNames[l]:D.label||" ");t[y(t.html())?"html":"append"](D.elmprefix).append(w).append(D.elmsuffix);r?(v.addClass(ga),t.addClass(ga),a(w).prop("readonly",!0),a(w).prop("disabled",!0)):z&&a(w).prop("readonly",!0);"custom"===this.edittype&&a.isFunction(m.custom_value)&&m.custom_value.call(J,a("#"+n(k),O),"set",q);p.bindEv.call(J,w,m);g[d]=l;d++}});0<d&&(k=a("<tr class='FormData' style='display:none'><td class='CaptionTD'> </td><td colspan='"+
(2*e-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='"+Y+"_id' value='"+b+"'/></td></tr>"),k[0].rp=d+999,a(c).append(k),x.checkOnSubmit||x.checkOnUpdate)&&(x._savedData[Y+"_id"]=b);return g}function z(c,e){var d,g=0,f,k,h,m,t;if(x.checkOnSubmit||x.checkOnUpdate)x._savedData={},x._savedData[Y+"_id"]=c;var q=N.colModel;if("_empty"===c)a(q).each(function(){d=this.name;h=a.extend({},this.editoptions||{});(k=a("#"+n(d),e))&&k.length&&null!==k[0]&&(m="","custom"===this.edittype&&
a.isFunction(h.custom_value)?h.custom_value.call(J,k,"set",m):h.defaultValue?(m=a.isFunction(h.defaultValue)?h.defaultValue.call(J):h.defaultValue,"checkbox"===k[0].type?(t=m.toLowerCase(),0>t.search(/(false|f|0|no|n|off|undefined)/i)&&""!==t?(k[0].checked=!0,k[0].defaultChecked=!0,k[0].value=m):(k[0].checked=!1,k[0].defaultChecked=!1)):k.val(m)):"checkbox"===k[0].type?(k[0].checked=!1,k[0].defaultChecked=!1,m=a(k).data("offval")):k[0].type&&"select"===k[0].type.substr(0,6)?k[0].selectedIndex=0:k.val(m),
!0===x.checkOnSubmit||x.checkOnUpdate)&&(x._savedData[d]=m)}),a("#id_g",e).val(c);else{var v=l.getInd.call(H,c,!0);v&&(a(v.cells).filter("td[role=gridcell]").each(function(l){d=q[l].name;if("cb"!==d&&"subgrid"!==d&&"rn"!==d&&!0===q[l].editable){try{f=a.unformat.call(J,a(this),{rowId:c,colModel:q[l]},l)}catch(k){f="textarea"===q[l].edittype?a(this).text():a(this).html()}N.autoencode&&(f=p.htmlDecode(f));if(!0===x.checkOnSubmit||x.checkOnUpdate)x._savedData[d]=f;d="#"+n(d);switch(q[l].edittype){case "password":case "text":case "button":case "image":case "textarea":y(f)&&
(f="");a(d,e).val(f);break;case "select":var h=f.split(","),h=a.map(h,function(b){return a.trim(b)});a(d+" option",e).each(function(){var b=a(this),c=a.trim(b.val()),b=a.trim(b.text());q[l].editoptions.multiple||a.trim(f)!==b&&h[0]!==b&&h[0]!==c?q[l].editoptions.multiple?-1<a.inArray(b,h)||-1<a.inArray(c,h)?this.selected=!0:this.selected=!1:this.selected=!1:this.selected=!0});break;case "checkbox":f=String(f);if(q[l].editoptions&&q[l].editoptions.value)if(q[l].editoptions.value.split(":")[0]===f)a(d,
e)[ba]({checked:!0,defaultChecked:!0});else a(d,e)[ba]({checked:!1,defaultChecked:!1});else f=f.toLowerCase(),0>f.search(/(false|f|0|no|n|off|undefined)/i)&&""!==f?(a(d,e)[ba]("checked",!0),a(d,e)[ba]("defaultChecked",!0)):(a(d,e)[ba]("checked",!1),a(d,e)[ba]("defaultChecked",!1));break;case "custom":try{if(q[l].editoptions&&a.isFunction(q[l].editoptions.custom_value))q[l].editoptions.custom_value.call(J,a(d,e),"set",f);else throw"e1";}catch(m){"e1"===m?b.call(J,fa,"function 'custom_value' "+x.msg.nodefined,
x.bClose):b.call(J,fa,m.message,x.bClose)}}g++}}),0<g&&a("#id_g",K).val(c))}}function v(){var b=x.url||N.editurl;a.each(ca,function(c,e){var d=e.name,g=P[d];"date"!==e.formatter||null!=e.formatoptions&&!0===e.formatoptions.sendFormatted||(P[d]=a.unformat.date.call(J,g,e));"clientArray"!==b&&e.editoptions&&!0===e.editoptions.NullIfEmpty&&P.hasOwnProperty(d)&&""===g&&(P[d]="null")})}function V(){var b=[!0,"",""],c={},e=N.prmNames,g,f,k,h,m,t=H.triggerHandler("jqGridAddEditBeforeCheckValues",[a(O),M]);
t&&"object"===typeof t&&(P=t);a.isFunction(x.beforeCheckValues)&&(t=x.beforeCheckValues.call(J,P,a(O),M))&&"object"===typeof t&&(P=t);for(k in P)if(P.hasOwnProperty(k)&&(b=p.checkValues.call(J,P[k],k),!1===b[0]))break;v();b[0]&&(c=H.triggerHandler("jqGridAddEditClickSubmit",[x,P,M]),void 0===c&&a.isFunction(x.onclickSubmit)&&(c=x.onclickSubmit.call(J,x,P,M)||{}),b=H.triggerHandler("jqGridAddEditBeforeSubmit",[P,a(O),M]),void 0===b&&(b=[!0,"",""]),b[0]&&a.isFunction(x.beforeSubmit)&&(b=x.beforeSubmit.call(J,
P,a(O),M)));if(b[0]&&!x.processing){x.processing=!0;a("#sData",L).addClass(Ea);k=x.url||N.editurl;f=e.oper;g="clientArray"===k&&!1!==N.keyName?N.keyName:e.id;P[f]="_empty"===a.trim(P[Y+"_id"])?e.addoper:e.editoper;P[f]!==e.addoper?P[g]=P[Y+"_id"]:void 0===P[g]&&(P[g]=P[Y+"_id"]);delete P[Y+"_id"];P=a.extend(P,x.editData,c);if(!0===N.treeGrid)for(m in P[f]===e.addoper&&(h=N.selrow,P["adjacency"===N.treeGridModel?N.treeReader.parent_id_field:"parent_id"]=h),N.treeReader)N.treeReader.hasOwnProperty(m)&&
(c=N.treeReader[m],!P.hasOwnProperty(c)||P[f]===e.addoper&&"parent_id_field"===m||delete P[c]);P[g]=p.stripPref(N.idPrefix,P[g]);m=a.extend({url:k,type:x.mtype,data:p.serializeFeedback.call(J,a.isFunction(x.serializeEditData)?x.serializeEditData:N.serializeEditData,"jqGridAddEditSerializeEditData",P),complete:function(c,k){a("#sData",L).removeClass(Ea);P[g]=N.idPrefix+a("#id_g",K).val();300<=c.status&&304!==c.status||0===c.status&&4===c.readyState?(b[0]=!1,b[1]=H.triggerHandler("jqGridAddEditErrorTextFormat",
[c,M]),a.isFunction(x.errorTextFormat)?b[1]=x.errorTextFormat.call(J,c,M):b[1]=k+" Status: '"+c.statusText+"'. Error code: "+c.status):(b=H.triggerHandler("jqGridAddEditAfterSubmit",[c,P,M]),void 0===b&&(b=[!0,"",""]),b[0]&&a.isFunction(x.afterSubmit)&&(b=x.afterSubmit.call(J,c,P,M)));if(!1===b[0])a("#FormError>td",K).html(b[1]),a("#FormError",K).show();else{N.autoencode&&a.each(P,function(a,b){P[a]=p.htmlDecode(b)});var m=[a.extend({},x.reloadGridOptions||{})];P[f]===e.addoper?(b[2]||(b[2]=p.randId()),
null==P[g]||"_empty"===P[g]||P[f]===e.addoper?P[g]=b[2]:b[2]=P[g],x.reloadAfterSubmit?H.trigger("reloadGrid",m):!0===N.treeGrid?l.addChildNode.call(H,b[2],h,P):l.addRowData.call(H,b[2],P,x.addedrow),x.closeAfterAdd?(!0!==N.treeGrid&&T.call(H,b[2]),d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form})):x.clearAfterAdd&&z("_empty",O)):(x.reloadAfterSubmit?(H.trigger("reloadGrid",m),x.closeAfterEdit||setTimeout(function(){T.call(H,P[g])},1E3)):!0===
N.treeGrid?l.setTreeRow.call(H,P[g],P):l.setRowData.call(H,P[g],P),x.closeAfterEdit&&d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form}));if(a.isFunction(x.afterComplete)){var t=c;setTimeout(function(){H.triggerHandler("jqGridAddEditAfterComplete",[t,P,a(O),M]);x.afterComplete.call(J,t,P,a(O),M);t=null},50)}if(x.checkOnSubmit||x.checkOnUpdate)if(a(O).data("disabled",!1),"_empty"!==x._savedData[Y+"_id"])for(var q in x._savedData)x._savedData.hasOwnProperty(q)&&
P[q]&&(x._savedData[q]=P[q])}x.processing=!1;try{a(":input:visible",O)[0].focus()}catch(n){}}},p.ajaxOptions,x.ajaxEditOptions);m.url||x.useDataProxy||(a.isFunction(N.dataProxy)?x.useDataProxy=!0:(b[0]=!1,b[1]+=" "+p.errors.nourl));b[0]&&(x.useDataProxy?(c=N.dataProxy.call(J,m,"set_"+Y),void 0===c&&(c=[!0,""]),!1===c[0]?(b[0]=!1,b[1]=c[1]||"Error deleting the selected row!"):(m.data.oper===e.addoper&&x.closeAfterAdd&&d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,
form:x.form}),m.data.oper===e.editoper&&x.closeAfterEdit&&d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form}))):"clientArray"===m.url?(x.reloadAfterSubmit=!1,P=m.data,m.complete({status:200,statusText:""},"")):a.ajax(m))}!1===b[0]&&(a("#FormError>td",K).html(b[1]),a("#FormError",K).show())}function I(a,b){var c=!1,e;for(e in a)if(a.hasOwnProperty(e)&&String(a[e])!==String(b[e])){c=!0;break}return c}function G(){var b=!0;a("#FormError",K).hide();
x.checkOnUpdate&&(P={},B(),ea=I(P,x._savedData))&&(a(O).data("disabled",!0),a(".confirm",R).show(),b=!1);return b}function S(){var b=p.detectRowEditing.call(J,g);if(null!=b)if("inlineEditing"===b.mode)l.restoreRow.call(H,g);else{var b=b.savedRow,c=J.rows[b.id];l.restoreCell.call(H,b.id,b.ic);a(c.cells[b.ic]).removeClass("edit-cell "+za);a(c).addClass(za).attr({"aria-selected":"true",tabindex:"0"})}}function U(b,c){var d=c[1].length-1;0===b?a("#pData",L).addClass(ga):void 0!==c[1][b-1]&&e(a("#"+n(c[1][b-
1])),ga)?a("#pData",L).addClass(ga):a("#pData",L).removeClass(ga);b===d?a("#nData",L).addClass(ga):void 0!==c[1][b+1]&&e(a("#"+n(c[1][b+1])),ga)?a("#nData",L).addClass(ga):a("#nData",L).removeClass(ga)}function F(){var b=l.getDataIDs.call(H),c=a("#id_g",K).val();return[a.inArray(c,b),b]}var J=this,H=a(J),N=J.p;if(J.grid&&null!=N&&g){var Y=N.id,X=l.getGridRes,T=l.setSelection,x=a.extend(!0,{top:0,left:0,width:300,datawidth:"auto",height:"auto",dataheight:"auto",drag:!0,resize:!0,url:null,mtype:"POST",
clearAfterAdd:!0,closeAfterEdit:!1,reloadAfterSubmit:!0,onInitializeForm:null,beforeInitData:null,beforeShowForm:null,afterShowForm:null,beforeSubmit:null,afterSubmit:null,onclickSubmit:null,afterComplete:null,onclickPgButtons:null,afterclickPgButtons:null,editData:{},recreateForm:!1,closeOnEscape:!1,addedrow:"first",topinfo:"",bottominfo:"",savekey:[!1,13],navkeys:[!1,38,40],checkOnSubmit:!1,checkOnUpdate:!1,_savedData:{},processing:!1,onClose:null,ajaxEditOptions:{},serializeEditData:null,viewPagerButtons:!0,
overlayClass:"ui-widget-overlay",removemodal:!0,form:"edit"},X.call(H,"edit"),p.edit,N.formEditing||{},u||{}),O="FrmGrid_"+Y,aa=O,Q="TblGrid_"+Y,K="#"+n(Q),L=K+"_2",k={themodal:"editmod"+Y,modalhead:"edithd"+Y,modalcontent:"editcnt"+Y,resizeAlso:O},R="#"+n(k.themodal),W=N.gBox,ba=N.propOrAttr,ca=N.colModel,ha=N.iColByName,ja=1,da=0,P,ea,M,Z=x.commonIconClass,fa=X.call(H,"errors.errcap"),ka=function(){var b=a.makeArray(arguments);b.unshift("");b.unshift("AddEdit");b.unshift(x);return r.apply(J,b)},
xa=q.call(J,"hover"),ga=q.call(J,"disabled"),za=q.call(J,"select"),Ea=q.call(J,"active"),ma=q.call(J,"error"),O="#"+n(O);"new"===g?(g="_empty",M="add",x.caption=x.addCaption):(x.caption=x.editCaption,M="edit");if(!x.recreateForm){var pa=H.data("formProp");pa&&(pa.top=Math.max(pa.top,0),pa.left=Math.max(pa.left,0),a.extend(x,pa))}pa=!0;!x.checkOnUpdate||!0!==x.jqModal&&void 0!==x.jqModal||x.modal||(pa=!1);var ta=isNaN(x.dataheight)?x.dataheight:x.dataheight+"px",la=isNaN(x.datawidth)?x.datawidth:x.datawidth+
"px",aa=a("<form name='FormPost' id='"+aa+"' class='FormGrid' onSubmit='return false;' style='width:"+la+";overflow:auto;position:relative;height:"+ta+";'></form>").data("disabled",!1),wa=a("<table id='"+Q+"' class='EditTable'"+(p.msie&&8>p.msiever()?" cellspacing='0'":"")+"><tbody></tbody></table>");a(ca).each(function(){var a=this.formoptions;ja=Math.max(ja,a?a.colpos||0:0);da=Math.max(da,a?a.rowpos||0:0)});a(aa).append(wa);ma=a("<tr id='FormError' style='display:none'><td class='"+ma+"' colspan='"+
2*ja+"'> </td></tr>");ma[0].rp=0;a(wa).append(ma);ma=a("<tr style='display:none' class='tinfo'><td class='topinfo' colspan='"+2*ja+"'>"+(x.topinfo||" ")+"</td></tr>");ma[0].rp=0;a(wa).append(ma);if(ka("beforeInitData",aa,M)){S();ta=(ma="rtl"===N.direction?!0:!1)?"nData":"pData";la=ma?"pData":"nData";D(g,wa,ja);var ta=m.call(J,ta,"",c(Z,x.prevIcon),"","left"),la=m.call(J,la,"",c(Z,x.nextIcon),"","right"),Aa=m.call(J,"sData",x.bSubmit),ua=m.call(J,"cData",x.bCancel),Q="<table"+(p.msie&&8>
p.msiever()?" cellspacing='0'":"")+" class='EditTable' id='"+Q+"_2'><tbody><tr><td colspan='2'><hr class='"+A.call(J,"dialog.hr")+"' style='margin:1px'/></td></tr><tr id='Act_Buttons'><td class='navButton navButton-"+N.direction+"'>"+(ma?la+ta:ta+la)+"</td><td class='EditButton EditButton-"+N.direction+"'>"+Aa+" "+ua+"</td></tr>",Q=Q+("<tr style='display:none' class='binfo'><td class='bottominfo' colspan='2'>"+(x.bottominfo||" ")+"</td></tr>"),Q=Q+"</tbody></table>";if(0<da){var va=[];a.each(a(wa)[0].rows,
function(a,b){va[a]=b});va.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(va,function(b,c){a("tbody",wa).append(c)})}x.gbox=W;var qa=!1;!0===x.closeOnEscape&&(x.closeOnEscape=!1,qa=!0);Q=a("<div></div>").append(aa).append(Q);h.call(J,k,Q,x,N.gView,a(W)[0]);x.topinfo&&a(".tinfo",K).show();x.bottominfo&&a(".binfo",L).show();Q=Q=null;a(R).keydown(function(b){var c=(b.target.tagName||"").toUpperCase(),e,g;if(!0===a(O).data("disabled"))return!1;if(13===b.which&&"TEXTAREA"!==c){e=a(L).find(":focus");
g=e.attr("id");if(0<e.length&&0<=a.inArray(g,["pData","nData","cData"]))return e.trigger("click"),!1;if(!0===x.savekey[0]&&13===x.savekey[1])return a("#sData",L).trigger("click"),!1}if(!0===x.savekey[0]&&b.which===x.savekey[1]&&"TEXTAREA"!==c)return a("#sData",L).trigger("click"),!1;if(27===b.which){if(!G())return!1;qa&&d(R,{gb:x.gbox,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form});return!1}if(!0===x.navkeys[0]){if("_empty"===a("#id_g",K).val())return!0;
if(b.which===x.navkeys[1])return a("#pData",L).trigger("click"),!1;if(b.which===x.navkeys[2])return a("#nData",L).trigger("click"),!1}});x.checkOnUpdate&&(a("a.ui-jqdialog-titlebar-close span",R).removeClass("jqmClose"),a("a.ui-jqdialog-titlebar-close",R).unbind("click").click(function(){if(!G())return!1;d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form});return!1}));w(a("#sData",L),x.saveicon,Z);w(a("#cData",L),x.closeicon,Z);if(x.checkOnSubmit||
x.checkOnUpdate)Aa=m.call(J,"sNew",x.bYes),la=m.call(J,"nNew",x.bNo),ua=m.call(J,"cNew",x.bExit),k=x.zIndex||999,k++,a("<div class='"+x.overlayClass+" jqgrid-overlay confirm' style='z-index:"+k+";display:none;'> </div><div class='"+A.call(J,"dialog.content","confirm ui-jqconfirm")+"' style='z-index:"+(k+1)+"'>"+x.saveData+"<br/><br/>"+Aa+la+ua+"</div>").insertAfter(O),a("#sNew",R).click(function(){V();a(O).data("disabled",!1);a(".confirm",R).hide();return!1}),a("#nNew",R).click(function(){a(".confirm",
R).hide();a(O).data("disabled",!1);setTimeout(function(){a(":input:visible",O)[0].focus()},0);return!1}),a("#cNew",R).click(function(){a(".confirm",R).hide();a(O).data("disabled",!1);d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form});return!1});ka("onInitializeForm",a(O),M);"_empty"!==g&&x.viewPagerButtons?a("#pData,#nData",L).show():a("#pData,#nData",L).hide();ka("beforeShowForm",a(O),M);a(R).data("onClose",x.onClose);f(R,{gbox:W,jqm:x.jqModal,
overlay:x.overlay,modal:x.modal,overlayClass:x.overlayClass,toTop:x.toTop,onHide:function(a){t.call(H,"formProp",O,a)}});pa||a("."+n(x.overlayClass)).click(function(){if(!G())return!1;d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form});return!1});a(".fm-button",R).hover(function(){a(this).addClass(xa)},function(){a(this).removeClass(xa)});a("#sData",L).click(function(){P={};a("#FormError",K).hide();B();"_empty"===P[Y+"_id"]?V():!0===x.checkOnSubmit?
(ea=I(P,x._savedData))?(a(O).data("disabled",!0),a(".confirm",R).show()):V():V();return!1});a("#cData",L).click(function(){if(!G())return!1;d(R,{gb:W,jqm:x.jqModal,onClose:x.onClose,removemodal:x.removemodal,formprop:!x.recreateForm,form:x.form});return!1});a("#nData",L).click(function(){if(!G())return!1;a("#FormError",K).hide();var b=F();b[0]=parseInt(b[0],10);if(-1!==b[0]&&b[1][b[0]+1]){if(!ka("onclickPgButtons","next",a(O),b[1][b[0]]))return!1;z(b[1][b[0]+1],O);T.call(H,b[1][b[0]+1]);ka("afterclickPgButtons",
"next",a(O),b[1][b[0]+1]);U(b[0]+1,b)}return!1});a("#pData",L).click(function(){if(!G())return!1;a("#FormError",K).hide();var b=F();if(-1!==b[0]&&b[1][b[0]-1]){if(!ka("onclickPgButtons","prev",a(O),b[1][b[0]])||e(a("#"+n(b[1][b[0]-1])),ga))return!1;z(b[1][b[0]-1],O);T.call(H,b[1][b[0]-1]);ka("afterclickPgButtons","prev",a(O),b[1][b[0]-1]);U(b[0]-1,b)}return!1});ka("afterShowForm",a(O),M);k=F();U(k[0],k)}}})},viewGridRow:function(b,g){return this.each(function(){function B(){!0!==F.closeOnEscape&&
!0!==F.navkeys[0]||setTimeout(function(){a(".ui-jqdialog-titlebar-close","#"+n(x.modalhead)).attr("tabindex","-1").focus()},0)}function D(b,c,e){var d,g,f,k=0,h,m,t=[],q=l.getInd.call(G,b),n;n=A.call(I,"dialog.viewData","DataTD form-view-data");var v=A.call(I,"dialog.viewLabel","CaptionTD form-view-label"),w="<td class='"+v+"' width='"+F.labelswidth+"'> </td><td class='"+n+" ui-helper-reset'> </td>",r="",v="<td class='"+v+"'></td><td class='"+n+"'></td>",z=["integer","number","currency"],
x=0,B=0,D,u,C;for(n=1;n<=e;n++)r+=1===n?w:v;a(Q).each(function(){(g=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)||"right"!==this.align||(this.formatter&&-1!==a.inArray(this.formatter,z)?x=Math.max(x,parseInt(this.width,10)):B=Math.max(B,parseInt(this.width,10)))});D=0!==x?x:0!==B?B:0;a(Q).each(function(b){d=this.name;u=!1;m=(g=this.editrules&&!0===this.editrules.edithidden?!1:!0===this.hidden?!0:!1)?"style='display:none'":"";C="boolean"!==typeof this.viewable?!0:this.viewable;
if("cb"!==d&&"subgrid"!==d&&"rn"!==d&&C){h=!1===q?"":p.getDataFieldOfCell.call(I,I.rows[q],b).html();u="right"===this.align&&0!==D?!0:!1;var l=a.extend({},{rowabove:!1,rowcontent:""},this.formoptions||{}),n=parseInt(l.rowpos,10)||k+1,v=parseInt(2*(parseInt(l.colpos,10)||1),10);if(l.rowabove){var w=a("<tr><td class='contentinfo' colspan='"+2*e+"'>"+l.rowcontent+"</td></tr>");a(c).append(w);w[0].rp=n}f=a(c).find("tr[data-rowpos="+n+"]");0===f.length&&(f=a("<tr "+m+" data-rowpos='"+n+"'></tr>").addClass("FormData").attr("id",
"trv_"+d),a(f).append(r),a(c).append(f),f[0].rp=n);l=void 0===l.label?S.colNames[b]:l.label;n=a("td:eq("+(v-1)+")",f[0]);a("td:eq("+(v-2)+")",f[0]).html("<b>"+(l||" ")+"</b>");n[y(n.html())?"html":"append"]("<span>"+(h||" ")+"</span>").attr("id","v_"+d);u&&a("td:eq("+(v-1)+") span",f[0]).css({"text-align":"right",width:D+"px"});t[k]=b;k++}});0<k&&(b=a("<tr class='FormData' style='display:none'><td class='CaptionTD'> </td><td colspan='"+(2*e-1)+"' class='DataTD'><input class='FormElement' id='id_g' type='text' name='id' value='"+
b+"'/></td></tr>"),b[0].rp=k+99,a(c).append(b));return t}function z(b){var c,e,d=0,g=l.getInd.call(G,b,!0),f;g&&(a("td",g).each(function(b){f=Q[b];c=f.name;e=f.editrules&&!0===f.editrules.edithidden?!1:!0===f.hidden?!0:!1;"cb"!==c&&"subgrid"!==c&&"rn"!==c&&(c=n("v_"+c),a("#"+c+" span",H).html(p.getDataFieldOfCell.call(I,g,b).html()),e&&a("#"+c,H).parents("tr:first").hide(),d++)}),0<d&&a("#id_g",H).val(b))}function v(b,c){var d=c[1].length-1;0===b?a("#pData",N).addClass(W):void 0!==c[1][b-1]&&e(a("#"+
n(c[1][b-1])),W)?a("#pData",N).addClass(W):a("#pData",N).removeClass(W);b===d?a("#nData",N).addClass(W):void 0!==c[1][b+1]&&e(a("#"+n(c[1][b+1])),W)?a("#nData",N).addClass(W):a("#nData",N).removeClass(W)}function u(){var b=l.getDataIDs.call(G),c=a("#id_g",H).val();return[a.inArray(c,b),b]}var I=this,G=a(I),S=I.p;if(I.grid&&null!=S&&b){var U=S.id,F=a.extend(!0,{top:0,left:0,width:0,datawidth:"auto",height:"auto",dataheight:"auto",drag:!0,resize:!0,closeOnEscape:!1,labelswidth:"30%",navkeys:[!1,38,
40],onClose:null,beforeShowForm:null,beforeInitData:null,viewPagerButtons:!0,recreateForm:!1,removemodal:!0,form:"view"},l.getGridRes.call(G,"view"),p.view||{},S.formViewing||{},g||{}),J="#ViewGrid_"+n(U),H="#ViewTbl_"+n(U),N=H+"_2",Y="ViewGrid_"+U,X="ViewTbl_"+U,T=F.commonIconClass,x={themodal:"viewmod"+U,modalhead:"viewhd"+U,modalcontent:"viewcnt"+U,resizeAlso:Y},O="#"+n(x.themodal),aa=S.gBox,Q=S.colModel,K=1,L=0,k=function(){var b=a.makeArray(arguments);b.unshift("");b.unshift("View");b.unshift(F);
return r.apply(I,b)},R=q.call(I,"hover"),W=q.call(I,"disabled");F.recreateForm||G.data("viewProp")&&a.extend(F,G.data("viewProp"));var U=isNaN(F.dataheight)?F.dataheight:F.dataheight+"px",ba=isNaN(F.datawidth)?F.datawidth:F.datawidth+"px",Y=a("<form name='FormPost' id='"+Y+"' class='FormGrid' style='width:"+ba+";overflow:auto;position:relative;height:"+U+";'></form>"),ca=a("<table id='"+X+"' class='EditTable' cellspacing='1' cellpadding='2' border='0' style='table-layout:fixed'><tbody></tbody></table>");
a(Q).each(function(){var a=this.formoptions;K=Math.max(K,a?a.colpos||0:0);L=Math.max(L,a?a.rowpos||0:0)});Y.append(ca);if(k("beforeInitData",Y)){D(b,ca,K);var ha=(U="rtl"===S.direction?!0:!1)?"pData":"nData",ba=m.call(I,U?"nData":"pData","",c(T,F.prevIcon),"","left"),ha=m.call(I,ha,"",c(T,F.nextIcon),"","right"),ja=m.call(I,"cData",F.bClose);if(0<L){var da=[];a.each(a(ca)[0].rows,function(a,b){da[a]=b});da.sort(function(a,b){return a.rp>b.rp?1:a.rp<b.rp?-1:0});a.each(da,function(b,c){a("tbody",ca).append(c)})}F.gbox=
aa;X=a("<div></div>").append(Y).append("<table border='0' class='EditTable' id='"+X+"_2'><tbody><tr id='Act_Buttons'><td class='navButton navButton-"+S.direction+"' width='"+(F.labelswidth||"auto")+"'>"+(U?ha+ba:ba+ha)+"</td><td class='EditButton EditButton-"+S.direction+"'>"+ja+"</td></tr></tbody></table>");h.call(I,x,X,F,S.gView,a(S.gView)[0]);F.viewPagerButtons||a("#pData, #nData",N).hide();X=null;a(O).keydown(function(b){var c,e;if(!0===a(J).data("disabled"))return!1;if(13===b.which&&(c=a(N).find(":focus"),
e=c.attr("id"),0<c.length&&0<=a.inArray(e,["pData","nData","cData"])))return c.trigger("click"),!1;if(27===b.which)return F.closeOnEscape&&d(O,{gb:aa,jqm:F.jqModal,onClose:F.onClose,removemodal:F.removemodal,formprop:!F.recreateForm,form:F.form}),!1;if(!0===F.navkeys[0]){if(b.which===F.navkeys[1])return a("#pData",N).trigger("click"),!1;if(b.which===F.navkeys[2])return a("#nData",N).trigger("click"),!1}});w(a("#cData",N),F.closeicon,T);k("beforeShowForm",a(J));f(O,{gbox:aa,jqm:F.jqModal,overlay:F.overlay,
toTop:F.toTop,modal:F.modal,onHide:function(a){t.call(G,"viewProp",J,a)}});a(".fm-button:not(."+W.split(" ").join(".")+")",N).hover(function(){a(this).addClass(R)},function(){a(this).removeClass(R)});B();a("#cData",N).click(function(){d(O,{gb:aa,jqm:F.jqModal,onClose:F.onClose,removemodal:F.removemodal,formprop:!F.recreateForm,form:F.form});return!1});a("#nData",N).click(function(){a("#FormError",H).hide();var b=u();b[0]=parseInt(b[0],10);if(-1!==b[0]&&b[1][b[0]+1]){if(!k("onclickPgButtons","next",
a(J),b[1][b[0]]))return!1;z(b[1][b[0]+1]);l.setSelection.call(G,b[1][b[0]+1]);k("afterclickPgButtons","next",a(J),b[1][b[0]+1]);v(b[0]+1,b)}B();return!1});a("#pData",N).click(function(){a("#FormError",H).hide();var b=u();if(-1!==b[0]&&b[1][b[0]-1]){if(!k("onclickPgButtons","prev",a(J),b[1][b[0]]))return!1;z(b[1][b[0]-1]);l.setSelection.call(G,b[1][b[0]-1]);k("afterclickPgButtons","prev",a(J),b[1][b[0]-1]);v(b[0]-1,b)}B();return!1});T=u();v(T[0],T)}}})},delGridRow:function(b,c){return this.each(function(){var e=
this,g=e.p,t=a(e);if(e.grid&&null!=g&&b){var v=g.id,u=a.extend(!0,{top:0,left:0,width:240,removemodal:!0,height:"auto",dataheight:"auto",drag:!0,resize:!0,url:"",mtype:"POST",reloadAfterSubmit:!0,beforeShowForm:null,beforeInitData:null,afterShowForm:null,beforeSubmit:null,onclickSubmit:null,afterSubmit:null,closeOnEscape:!1,delData:{},onClose:null,ajaxDelOptions:{},processing:!1,serializeDelData:null,useDataProxy:!1},l.getGridRes.call(t,"del"),p.del||{},g.formDeleting||{},c||{}),y="DelTbl_"+v,G="#DelTbl_"+
n(v),S,U,F,J,H={themodal:"delmod"+v,modalhead:"delhd"+v,modalcontent:"delcnt"+v,resizeAlso:y},N="#"+n(H.themodal),Y=g.gBox,X=u.commonIconClass,T=function(){var b=a.makeArray(arguments);b.unshift("");b.unshift("Delete");b.unshift(u);return r.apply(e,b)},x=q.call(e,"hover"),O=q.call(e,"active"),aa=q.call(e,"error");a.isArray(b)||(b=[String(b)]);if(void 0!==a(N)[0]){if(!T("beforeInitData",a(G)))return;a("#DelData>td",G).text(b.join()).data("rowids",b);a("#DelError",G).hide();!0===u.processing&&(u.processing=
!1,a("#dData",G).removeClass(O));T("beforeShowForm",a(G));f(N,{gbox:Y,jqm:u.jqModal,jqM:!1,overlay:u.overlay,toTop:u.toTop,modal:u.modal})}else{var Q=isNaN(u.dataheight)?u.dataheight:u.dataheight+"px",K=isNaN(u.datawidth)?u.datawidth:u.datawidth+"px",Q="<div id='"+y+"' class='formdata' style='width:"+K+";overflow:auto;position:relative;height:"+Q+";'><table class='DelTable'><tbody>",Q=Q+("<tr id='DelError' style='display:none'><td class='"+aa+"'></td></tr>"),Q=Q+("<tr id='DelData' style='display:none'><td >"+
b.join()+"</td></tr>"),Q=Q+('<tr><td class="delmsg" style="white-space:pre;">'+u.msg+"</td></tr><tr><td > </td></tr>"),Q=Q+"</tbody></table></div>",aa=m.call(e,"dData",u.bSubmit),K=m.call(e,"eData",u.bCancel),Q=Q+("<table"+(p.msie&&8>p.msiever()?" cellspacing='0'":"")+" class='EditTable' id='"+y+"_2'><tbody><tr><td><hr class='"+A.call(e,"dialog.hr")+"' style='margin:1px'/></td></tr><tr><td class='DelButton EditButton EditButton-"+g.direction+"'>"+aa+" "+K+"</td></tr></tbody></table>");u.gbox=
Y;h.call(e,H,Q,u,g.gView,a(g.gView)[0]);a("#DelData>td",G).data("rowids",b);if(!T("beforeInitData",a(Q)))return;a(".fm-button",G+"_2").hover(function(){a(this).addClass(x)},function(){a(this).removeClass(x)});w(a("#dData",G+"_2"),u.delicon,X);w(a("#eData",G+"_2"),u.cancelicon,X);a("#dData",G+"_2").click(function(){var b=[!0,""],c,f=a("#DelData>td",G),h=f.text(),m=f.data("rowids"),f={};a.isFunction(u.onclickSubmit)&&(f=u.onclickSubmit.call(e,u,h)||{});a.isFunction(u.beforeSubmit)&&(b=u.beforeSubmit.call(e,
h));if(b[0]&&!u.processing){u.processing=!0;F=g.prmNames;S=a.extend({},u.delData,f);J=F.oper;S[J]=F.deloper;U=F.id;h=m.slice();if(!h.length)return!1;for(c in h)h.hasOwnProperty(c)&&(h[c]=p.stripPref(g.idPrefix,h[c]));S[U]=h.join();a(this).addClass(O);c=a.extend({url:u.url||g.editurl,type:u.mtype,data:a.isFunction(u.serializeDelData)?u.serializeDelData.call(e,S):S,complete:function(c,f){var k;a("#dData",G+"_2").removeClass(O);300<=c.status&&304!==c.status||0===c.status&&4===c.readyState?(b[0]=!1,a.isFunction(u.errorTextFormat)?
b[1]=u.errorTextFormat.call(e,c):b[1]=f+" Status: '"+c.statusText+"'. Error code: "+c.status):a.isFunction(u.afterSubmit)&&(b=u.afterSubmit.call(e,c,S));if(!1===b[0])a("#DelError>td",G).html(b[1]),a("#DelError",G).show();else{if(u.reloadAfterSubmit&&"local"!==g.datatype)t.trigger("reloadGrid",[a.extend({},u.reloadGridOptions||{})]);else if(!0===g.treeGrid)try{l.delTreeNode.call(t,m[0])}catch(q){}else for(m=m.slice(),k=0;k<m.length;k++)l.delRowData.call(t,m[k]);setTimeout(function(){T("afterComplete",
c,h,a(G))},50)}u.processing=!1;b[0]&&d(N,{gb:Y,jqm:u.jqModal,onClose:u.onClose,removemodal:u.removemodal})}},p.ajaxOptions,u.ajaxDelOptions);c.url||u.useDataProxy||(a.isFunction(g.dataProxy)?u.useDataProxy=!0:(b[0]=!1,b[1]+=" "+p.errors.nourl));b[0]&&(u.useDataProxy?(c=g.dataProxy.call(e,c,"del_"+v),void 0===c&&(c=[!0,""]),!1===c[0]?(b[0]=!1,b[1]=c[1]||"Error deleting the selected row!"):d(N,{gb:Y,jqm:u.jqModal,onClose:u.onClose,removemodal:u.removemodal})):"clientArray"===c.url?(S=c.data,c.complete({status:200,
statusText:""},"")):a.ajax(c))}!1===b[0]&&(a("#DelError>td",G).html(b[1]),a("#DelError",G).show());return!1});a("#eData",G+"_2").click(function(){d(N,{gb:Y,jqm:u.jqModal,onClose:u.onClose,removemodal:u.removemodal});return!1});T("beforeShowForm",a(G));f(N,{gbox:Y,jqm:u.jqModal,overlay:u.overlay,toTop:u.toTop,modal:u.modal})}T("afterShowForm",a(G));!0===u.closeOnEscape&&setTimeout(function(){a(".ui-jqdialog-titlebar-close","#"+n(H.modalhead)).attr("tabindex","-1").focus()},0)}})},navGrid:function(b,
d,g,m,t,v,w){"object"===typeof b&&(w=v,v=t,t=m,m=g,g=d,d=b,b=void 0);m=m||{};g=g||{};w=w||{};t=t||{};v=v||{};return this.each(function(){var u=this,r=u.p,y=a(u);if(u.grid&&null!=r&&!(u.nav&&0<a(b).find(".navtable").length)){var U=r.id,F=a.extend({edit:!0,add:!0,del:!0,search:!0,refresh:!0,refreshstate:"firstpage",view:!1,closeOnEscape:!0,beforeRefresh:null,afterRefresh:null,cloneToTop:!1,hideEmptyPagerParts:!0,alertwidth:200,alertheight:"auto",alerttop:null,removemodal:!0,alertleft:null,alertzIndex:null,
iconsOverText:!1},l.getGridRes.call(y,"nav"),p.nav||{},r.navOptions||{},d||{});F.position=F.position||("rtl"===r.direction?"right":"left");var J,H=r.idSel,N=r.gBox,Y=F.commonIconClass,X={themodal:"alertmod_"+U,modalhead:"alerthd_"+U,modalcontent:"alertcnt_"+U},T=function(){return function(){var b=document.documentElement,c=window,e=1024,d=768,g=y.closest(".ui-jqgrid").offset();void 0===a("#"+n(X.themodal))[0]&&(F.alerttop||F.alertleft||(void 0!==c.innerWidth?(e=c.innerWidth,d=c.innerHeight):null!=
b&&void 0!==b.clientWidth&&0!==b.clientWidth&&(e=b.clientWidth,d=b.clientHeight),e=e/2-parseInt(F.alertwidth,10)/2-g.left,d=d/2-25-g.top),h.call(u,X,"<div>"+F.alerttext+"</div><span tabindex='0'><span tabindex='-1' id='"+U+"_jqg_alrt'></span></span>",{gbox:N,jqModal:F.jqModal,drag:!0,resize:!0,caption:F.alertcap,top:null!=F.alerttop?F.alerttop:d,left:null!=F.alertleft?F.alertleft:e,width:F.alertwidth,height:F.alertheight,closeOnEscape:F.closeOnEscape,zIndex:F.alertzIndex,removemodal:F.removemodal},
r.gView,a(N)[0],!1));f("#"+n(X.themodal),{gbox:N,toTop:F.alertToTop,jqm:F.jqModal});var l=a("#"+n(X.modalhead)).find(".ui-jqdialog-titlebar-close");l.attr({tabindex:"0",href:"#",role:"button"});setTimeout(function(){l.focus()},50)}}(),x,O=function(b){if(13===b.which&&(b=a(this).find(":focus"),0<b.length))return b.trigger("click"),!1},aa=q.call(u,"hover"),Q=q.call(u,"disabled");if(u.grid){u.modalAlert=T;void 0===b&&(r.pager?(b=r.pager,r.toppager&&(F.cloneToTop=!0)):r.toppager&&(b=r.toppager));var K=
1,L,k,R,W,ba,ca=["left","center","right"],ha="<div class='ui-pg-button "+Q+"'><span class='ui-separator'></span></div>",ja=function(){e(this,Q)||a(this).addClass(aa)},da=function(){a(this).removeClass(aa)},P=function(){e(this,Q)||(a.isFunction(F.addfunc)?F.addfunc.call(u):l.editGridRow.call(y,"new",m));return!1},ea=function(b,c,d){if(!e(this,Q)){var g=r.selrow;g?a.isFunction(b)?b.call(u,g):l[c].call(y,g,d):T()}return!1},M=function(){return ea.call(this,F.editfunc,"editGridRow",g)},Z=function(){return ea.call(this,
F.viewfunc,"viewGridRow",w)},fa=function(){var b;e(this,Q)||(r.multiselect?(b=r.selarrrow,0===b.length&&(b=null)):b=r.selrow,b?a.isFunction(F.delfunc)?F.delfunc.call(u,b):l.delGridRow.call(y,b,t):T());return!1},ka=function(){e(this,Q)||(a.isFunction(F.searchfunc)?F.searchfunc.call(u,v):l.searchGrid.call(y,v));return!1},xa=function(){if(!e(this,Q)){a.isFunction(F.beforeRefresh)&&F.beforeRefresh.call(u);r.search=!1;r.resetsearch=!0;try{if("currentfilter"!==F.refreshstate){r.postData.filters="";try{a("#fbox_"+
H).jqFilter("resetFilter")}catch(b){}a.isFunction(u.clearToolbar)&&u.clearToolbar(!1)}}catch(c){}switch(F.refreshstate){case "firstpage":y.trigger("reloadGrid",[a.extend({},F.reloadGridOptions||{},{page:1})]);break;case "current":case "currentfilter":y.trigger("reloadGrid",[a.extend({},F.reloadGridOptions||{},{current:!0})])}a.isFunction(F.afterRefresh)&&F.afterRefresh.call(u)}return!1},ga=function(b,e,d,g,l){var f=a("<div class='ui-pg-button ui-corner-all' tabindex='0' role='button'></div>"),k=F[b+
"icon"],h=a.trim(F[b+"text"]);f.append("<div class='ui-pg-div'><span class='"+(F.iconsOverText?c("ui-pg-button-icon-over-text",Y,k):c(Y,k))+"'></span>"+(h?"<span class='ui-pg-button-text"+(F.iconsOverText?" ui-pg-button-icon-over-text":"")+"'>"+h+"</span>":"")+"</div>");a(g).append(f);f.attr({title:F[b+"title"]||"",id:e||b+"_"+l}).click(d).hover(ja,da);return f};F.cloneToTop&&r.toppager&&(K=2);for(L=0;L<K;L++){x=a("<div class='ui-pg-table navtable' role='toolbar' style='float:"+("rtl"===r.direction?
"right":"left")+";table-layout:auto;'></div>");0===L?(k=b,R=U,k===r.toppager&&(R+="_top",K=1)):(k=r.toppager,R=U+"_top");F.add&&ga("add",m.id,P,x,R);F.edit&&ga("edit",g.id,M,x,R);F.view&&ga("view",w.id,Z,x,R);F.del&&ga("del",t.id,fa,x,R);(F.add||F.edit||F.del||F.view)&&a(x).append(ha);F.search&&(J=ga("search",v.id,ka,x,R),v.showOnLoad&&!0===v.showOnLoad&&a(J,x).click());F.refresh&&ga("refresh","",xa,x,R);J=a(".ui-jqgrid>.ui-jqgrid-view").css("font-size")||"11px";a("body").append("<div id='testpg2' class='"+
A.call(u,"gBox","ui-jqgrid")+"' style='font-size:"+J+";visibility:hidden;' ></div>");J=a(x).clone().appendTo("#testpg2").width();a("#testpg2").remove();a(k+"_"+F.position,k).append(x);if(F.hideEmptyPagerParts)for(R=0;R<ca.length;R++)ca[R]!==F.position&&(ba=a(k+"_"+ca[R],k),0===ba.length||0===ba[0].childNodes.length?ba.hide():1===ba[0].childNodes.length&&(W=ba[0].firstChild,!a(W).is("table.ui-pg-table")||0!==W.rows&&0!==W.rows[0].cells.length||ba.hide()));r._nvtd&&(J>r._nvtd[0]&&(a(k+"_"+F.position,
k).width(J),r._nvtd[0]=J),r._nvtd[1]=J);u.nav=!0;x.bind("keydown.jqGrid",O)}y.triggerHandler("jqGridResetFrozenHeights")}}})},navButtonAdd:function(b,d){"object"===typeof b&&(d=b,b=void 0);return this.each(function(){var g=this,f=g.p;if(g.grid){var h=a.extend({caption:"newButton",title:"",onClickButton:null,position:"last",cursor:"pointer",iconsOverText:!1},l.getGridRes.call(a(g),"nav"),p.nav||{},f.navOptions||{},d||{}),m=q.call(g,"hover"),t=q.call(g,"disabled");if(void 0===b)if(f.pager)if(l.navButtonAdd.call(a(g),
f.pager,h),f.toppager)b=f.toppager;else return;else f.toppager&&(b=f.toppager);"string"===typeof b&&0!==b.indexOf("#")&&(b="#"+n(b));var f=a(".navtable",b),w=h.commonIconClass;if(0<f.length&&!(h.id&&0<f.find("#"+n(h.id)).length)){var u=a("<div tabindex='0' role='button'></div>");"NONE"===h.buttonicon.toString().toUpperCase()?a(u).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'>"+(h.caption?"<span class='ui-pg-button-text"+(h.iconsOverText?" ui-pg-button-icon-over-text":"")+"'>"+
h.caption+"</span>":"")+"</div>"):a(u).addClass("ui-pg-button ui-corner-all").append("<div class='ui-pg-div'><span class='"+(h.iconsOverText?c("ui-pg-button-icon-over-text",w,h.buttonicon):c(w,h.buttonicon))+"'></span>"+(h.caption?"<span class='ui-pg-button-text"+(h.iconsOverText?" ui-pg-button-icon-over-text":"")+"'>"+h.caption+"</span>":"")+"</div>");h.id&&a(u).attr("id",h.id);"first"===h.position&&0<f.children("div.ui-pg-button").length?f.children("div.ui-pg-button").filter(":first").before(u):
f.append(u);a(u,f).attr("title",h.title||"").click(function(b){e(this,t)||a.isFunction(h.onClickButton)&&h.onClickButton.call(g,h,b);return!1}).hover(function(){e(this,t)||a(this).addClass(m)},function(){a(this).removeClass(m)});a(g).triggerHandler("jqGridResetFrozenHeights")}}})},navSeparatorAdd:function(b,c){c=a.extend({sepclass:"ui-separator",sepcontent:"",position:"last"},c||{});return this.each(function(){if(this.grid){"string"===typeof b&&0!==b.indexOf("#")&&(b="#"+n(b));var e=a(".navtable",
b)[0];if(0<e.length){var d="<div class='ui-pg-button "+q.call(this,"disabled")+"'><span class='"+c.sepclass+"'></span>"+c.sepcontent+"</div>";"first"===c.position?0===a(">div.ui-pg-button",e).length?e.append(d):a(">div.ui-pg-button",e).filter(":first").before(d):e.append(d)}}})},GridToForm:function(b,c){return this.each(function(){var e,d,g,f;if(this.grid){var h=l.getRowData.call(a(this),b),m=this.p.propOrAttr;if(h)for(e in h)if(h.hasOwnProperty(e))if(d=a("[name="+n(e)+"]",c),d.is("input:radio")||
d.is("input:checkbox"))for(g=0;g<d.length;g++)f=a(d[g]),f[m]("checked",f.val()===String(h[e]));else d.val(h[e])}})},FormToGrid:function(b,c,e,d){return this.each(function(){if(this.grid){e||(e="set");d||(d="first");var g=a(c).serializeArray(),f={};a.each(g,function(a,b){f[b.name]=b.value});"add"===e?l.addRowData.call(a(this),b,f,d):"set"===e&&l.setRowData.call(a(this),b,f)}})}})})(jQuery);
(function(a){var p=a.jgrid,r=a.fn.jqGrid;p.extend({groupingSetup:function(){return this.each(function(){var u,n;n=this.p;var d=n.colModel,f=n.groupingView,h,b,c=function(){return""};if(null===f||"object"!==typeof f&&!a.isFunction(f))n.grouping=!1;else if(f.groupField.length){void 0===f.visibiltyOnNextGrouping&&(f.visibiltyOnNextGrouping=[]);f.lastvalues=[];f._locgr||(f.groups=[]);f.counters=[];for(u=0;u<f.groupField.length;u++)f.groupOrder[u]||(f.groupOrder[u]="asc"),f.groupText[u]||(f.groupText[u]=
"{0}"),"boolean"!==typeof f.groupColumnShow[u]&&(f.groupColumnShow[u]=!0),"boolean"!==typeof f.groupSummary[u]&&(f.groupSummary[u]=!1),f.groupSummaryPos[u]||(f.groupSummaryPos[u]="footer"),h=d[n.iColByName[f.groupField[u]]],!0===f.groupColumnShow[u]?(f.visibiltyOnNextGrouping[u]=!0,null!=h&&!0===h.hidden&&r.showCol.call(a(this),f.groupField[u])):(f.visibiltyOnNextGrouping[u]=a("#"+p.jqID(n.id+"_"+f.groupField[u])).is(":visible"),null!=h&&!0!==h.hidden&&r.hideCol.call(a(this),f.groupField[u]));f.summary=
[];f.hideFirstGroupCol&&(f.formatDisplayField[0]=function(a){return a});u=0;for(n=d.length;u<n;u++)h=d[u],f.hideFirstGroupCol&&!h.hidden&&f.groupField[0]===h.name&&(h.formatter=c),h.summaryType&&(b={nm:h.name,st:h.summaryType,v:"",sr:h.summaryRound,srt:h.summaryRoundType||"round"},h.summaryDivider&&(b.sd=h.summaryDivider,b.vd=""),f.summary.push(b))}else n.grouping=!1})},groupingPrepare:function(p,n){this.each(function(){var d=this,f=d.p.groupingView,h=f.groups,b=f.counters,c=f.lastvalues,e=f.isInTheSameGroup,
l=f.groupField.length,m,g,t,w,A=0,q=r.groupingCalculations.handler,y=function(){a.isFunction(this.st)?this.v=this.st.call(d,this.v,this.nm,p):(this.v=q.call(a(d),this.st,this.v,this.nm,this.sr,this.srt,p),"avg"===this.st.toLowerCase()&&this.sd&&(this.vd=q.call(a(d),this.st,this.vd,this.sd,this.sr,this.srt,p)))};for(m=0;m<l;m++)g=f.groupField[m],t=f.displayField[m],w=p[g],t=null==t?null:p[t],null==t&&(t=w),void 0!==w&&(g={idx:m,dataIndex:g,value:w,displayValue:t,startRow:n,cnt:1,summary:[]},0===n?
(h.push(g),c[m]=w,b[m]={cnt:1,pos:h.length-1,summary:a.extend(!0,[],f.summary)}):(t={cnt:1,pos:h.length,summary:a.extend(!0,[],f.summary)},"object"===typeof w||(a.isArray(e)&&a.isFunction(e[m])?e[m].call(d,c[m],w,m,f):c[m]===w)?1===A?(h.push(g),c[m]=w,b[m]=t):(b[m].cnt+=1,h[b[m].pos].cnt=b[m].cnt):(h.push(g),c[m]=w,A=1,b[m]=t)),a.each(b[m].summary,y),h[b[m].pos].summary=b[m].summary)});return this},groupingToggle:function(u){this.each(function(){var n=this.p,d=p.jqID,f=n.groupingView,h=f.minusicon,
b=f.plusicon,c=a("#"+d(u)),c=c.length?c[0].nextSibling:null,e=a("#"+d(u)+" span.tree-wrap-"+n.direction),l,m,g=!1,t=n.frozenColumns?n.id+"_frozen":!1,d=(d=t?a("#"+d(u),"#"+d(t)):!1)&&d.length?d[0].nextSibling:null;l=u.split("_");var w=parseInt(l[l.length-2],10),r,q=function(b){b=a.map(b.split(" "),function(a){if(a.substring(0,r.length+1)===r+"_")return parseInt(a.substring(r.length+1),10)});return 0<b.length?b[0]:void 0};l.splice(l.length-2,2);r=l.join("_");if(e.hasClass(h)){for(;c;){if(a(c).hasClass("jqfoot")){l=
parseInt(a(c).data("jqfootlevel"),10);if(!f.showSummaryOnHide&&l===w||l>w)a(c).hide(),t&&a(d).hide();if(l<w)break}else{l=q(c.className);if(void 0!==l&&l<=w)break;a(c).hide();t&&a(d).hide()}c=c.nextSibling;t&&(d=d.nextSibling)}e.removeClass(h).addClass(b);g=!0}else{for(m=void 0;c;){if(a(c).hasClass("jqfoot")){l=parseInt(a(c).data("jqfootlevel"),10);if(l===w||f.showSummaryOnHide&&l===w+1)a(c).show(),t&&a(d).show();if(l<=w)break}l=q(c.className);void 0===m&&(m=void 0===l);if(void 0!==l){if(l<=w)break;
l===w+1&&(a(c).show().find(">td>span.tree-wrap-"+n.direction).removeClass(h).addClass(b),t&&a(d).show().find(">td>span.tree-wrap-"+n.direction).removeClass(h).addClass(b))}else m&&(a(c).show(),t&&a(d).show());c=c.nextSibling;t&&(d=d.nextSibling)}e.removeClass(b).addClass(h)}a(this).triggerHandler("jqGridGroupingClickGroup",[u,g]);a.isFunction(n.onClickGroup)&&n.onClickGroup.call(this,u,g)});return!1},groupingRender:function(r,n,d,f){function h(a,b,c){var e=!1,d;if(0===b)e=c[a];else if(d=c[a].idx,
0===d)e=c[a];else for(;0<=a;a--)if(c[a].idx===d-b){e=c[a];break}return e}function b(b,c,d,g){var f=h(b,c,d),m=l.colModel,t=f.cnt;b="";var q,w,r;c=function(){var a;if(this.nm===m[q].name){r=m[q].summaryTpl||"{0}";"string"===typeof this.st&&"avg"===this.st.toLowerCase()&&(this.sd&&this.vd?this.v/=this.vd:this.v&&0<t&&(this.v/=t));try{this.groupCount=f.cnt,this.groupIndex=f.dataIndex,this.groupValue=f.value,a=e.formatter("",this.v,q,this)}catch(b){a=this.v}w="<td "+e.formatCol(q,1,"")+">"+p.format(r,
a)+"</td>";return!1}};for(q=g;q<n;q++)w="<td "+e.formatCol(q,1,"")+"> </td>",a.each(f.summary,c),b+=w;return b}var c="",e=this[0],l=e.p,m=0,g=l.groupingView,t=a.makeArray(g.groupSummary),w,A=[],q="",y,E,C=(g.groupCollapse?g.plusicon:g.minusicon)+" tree-wrap-"+l.direction,B=g.groupField.length;a.each(l.colModel,function(a,b){var c;for(c=0;c<B;c++)if(g.groupField[c]===b.name){A[c]=a;break}});t.reverse();a.each(g.groups,function(h,z){if(g._locgr&&!(z.startRow+z.cnt>(d-1)*f&&z.startRow<d*f))return!0;
m++;E=l.id+"ghead_"+z.idx;y=E+"_"+h;q="<span style='cursor:pointer;' class='"+g.commonIconClass+" "+C+"' onclick=\"jQuery('#"+p.jqID(l.id).replace("\\","\\\\")+"').jqGrid('groupingToggle','"+y+"');return false;\"></span>";try{a.isArray(g.formatDisplayField)&&a.isFunction(g.formatDisplayField[z.idx])?(z.displayValue=g.formatDisplayField[z.idx].call(e,z.displayValue,z.value,l.colModel[A[z.idx]],z.idx,g),w=z.displayValue):w=e.formatter(y,z.displayValue,A[z.idx],z.value)}catch(v){w=z.displayValue}c+=
'<tr id="'+y+'"'+(g.groupCollapse&&0<z.idx?' style="display:none;" ':" ")+'role="row" class="ui-widget-content jqgroup ui-row-'+l.direction+" "+E+'"><td style="padding-left:'+12*z.idx+'px;"';var V=a.isFunction(g.groupText[z.idx])?g.groupText[z.idx].call(e,w,z.cnt,z.summary):p.template(g.groupText[z.idx],w,z.cnt,z.summary),I=1,G,S,U;S=0;U=B-1===z.idx;"string"!==typeof V&&"number"!==typeof V&&(V=w);"header"===g.groupSummaryPos[z.idx]?(I=1,"cb"!==l.colModel[0].name&&"cb"!==l.colModel[1].name||I++,"subgrid"!==
l.colModel[0].name&&"subgrid"!==l.colModel[1].name||I++,c+=(1<I?" colspan='"+I+"'":"")+">"+q+V+"</td>",c+=b(h,0,g.groups,!1===g.groupColumnShow[z.idx]?I-1:I)):c+=' colspan="'+(!1===g.groupColumnShow[z.idx]?n-1:n)+'">'+q+V+"</td>";c+="</tr>";if(U){V=g.groups[h+1];U=z.startRow;I=void 0!==V?V.startRow:g.groups[h].startRow+g.groups[h].cnt;g._locgr&&(S=(d-1)*f,S>z.startRow&&(U=S));for(;U<I&&r[U-S];U++)c+=r[U-S].join("");if("header"!==g.groupSummaryPos[z.idx]){if(void 0!==V){for(G=0;G<g.groupField.length&&
V.dataIndex!==g.groupField[G];G++);m=g.groupField.length-G}for(V=0;V<m;V++)t[V]&&(S="",g.groupCollapse&&!g.showSummaryOnHide&&(S=' style="display:none;"'),c+="<tr"+S+' data-jqfootlevel="'+(z.idx-V)+'" role="row" class="ui-widget-content jqfoot ui-row-'+l.direction+'">',c+=b(h,V,g.groups,0),c+="</tr>");m=G}}});return c},groupingGroupBy:function(u,n){return this.each(function(){var d=this.p,f=d.groupingView,h,b;"string"===typeof u&&(u=[u]);d.grouping=!0;f._locgr=!1;void 0===f.visibiltyOnNextGrouping&&
(f.visibiltyOnNextGrouping=[]);for(h=0;h<f.groupField.length;h++)b=d.colModel[d.iColByName[f.groupField[h]]],!f.groupColumnShow[h]&&f.visibiltyOnNextGrouping[h]&&null!=b&&!0===b.hidden&&r.showCol.call(a(this),f.groupField[h]);for(h=0;h<u.length;h++)f.visibiltyOnNextGrouping[h]=a(d.idSel+"_"+p.jqID(u[h])).is(":visible");d.groupingView=a.extend(d.groupingView,n||{});f.groupField=u;a(this).trigger("reloadGrid")})},groupingRemove:function(p){return this.each(function(){var n=this.p,d=this.tBodies[0],
f=n.groupingView;void 0===p&&(p=!0);n.grouping=!1;if(!0===p){for(n=0;n<f.groupField.length;n++)!f.groupColumnShow[n]&&f.visibiltyOnNextGrouping[n]&&r.showCol.call(a(this),f.groupField);a("tr.jqgroup, tr.jqfoot",d).remove();a("tr.jqgrow:hidden",d).show()}else a(this).trigger("reloadGrid")})},groupingCalculations:{handler:function(a,p,d,f,h,b){var c={sum:function(){return parseFloat(p||0)+parseFloat(b[d]||0)},min:function(){return""===p?parseFloat(b[d]||0):Math.min(parseFloat(p),parseFloat(b[d]||0))},
max:function(){return""===p?parseFloat(b[d]||0):Math.max(parseFloat(p),parseFloat(b[d]||0))},count:function(){""===p&&(p=0);return b.hasOwnProperty(d)?p+1:0},avg:function(){return c.sum()}};if(!c[a])throw"jqGrid Grouping No such method: "+a;a=c[a]();null!=f&&("fixed"===h?a=a.toFixed(f):(f=Math.pow(10,f),a=Math.round(a*f)/f));return a}}})})(jQuery);
(function(a){a.jgrid.extend({jqGridImport:function(p){p=a.extend({imptype:"xml",impstring:"",impurl:"",mtype:"GET",impData:{},xmlGrid:{config:"roots>grid",data:"roots>rows"},jsonGrid:{config:"grid",data:"data"},ajaxOptions:{}},p||{});return this.each(function(){var r=this,u=function(d,h){var b=a(h.xmlGrid.config,d)[0],c=a(h.xmlGrid.data,d)[0],e,l;if(xmlJsonClass.xml2json&&a.jgrid.parse){b=xmlJsonClass.xml2json(b," ");b=a.jgrid.parse(b);for(l in b)b.hasOwnProperty(l)&&(e=b[l]);void 0!==e&&(c?(c=b.grid.datatype,
b.grid.datatype="xmlstring",b.grid.datastr=d,a(r).jqGrid(e).jqGrid("setGridParam",{datatype:c})):a(r).jqGrid(e))}else alert("xml2json or parse are not present")},n=function(d,h){if(d&&"string"===typeof d){var b=!1,c,e;a.jgrid.useJSON&&(a.jgrid.useJSON=!1,b=!0);c=a.jgrid.parse(d);b&&(a.jgrid.useJSON=!0);b=c[h.jsonGrid.config];(c=c[h.jsonGrid.data])?(e=b.datatype,b.datatype="jsonstring",b.datastr=c,a(r).jqGrid(b).jqGrid("setGridParam",{datatype:e})):a(r).jqGrid(b)}},d;switch(p.imptype){case "xml":a.ajax(a.extend({url:p.impurl,
type:p.mtype,data:p.impData,dataType:"xml",complete:function(d){!(300>d.status||304===d.status)||0===d.status&&4===d.readyState||(u(d.responseXML,p),a(r).triggerHandler("jqGridImportComplete",[d,p]),a.isFunction(p.importComplete)&&p.importComplete(d))}},p.ajaxOptions));break;case "xmlstring":p.impstring&&"string"===typeof p.impstring&&(d=a.parseXML(p.impstring))&&(u(d,p),a(r).triggerHandler("jqGridImportComplete",[d,p]),a.isFunction(p.importComplete)&&p.importComplete(d),p.impstring=null);break;case "json":a.ajax(a.extend({url:p.impurl,
type:p.mtype,data:p.impData,dataType:"json",complete:function(d){try{!(300>d.status||304===d.status)||0===d.status&&4===d.readyState||(n(d.responseText,p),a(r).triggerHandler("jqGridImportComplete",[d,p]),a.isFunction(p.importComplete)&&p.importComplete(d))}catch(h){}}},p.ajaxOptions));break;case "jsonstring":p.impstring&&"string"===typeof p.impstring&&(n(p.impstring,p),a(r).triggerHandler("jqGridImportComplete",[p.impstring,p]),a.isFunction(p.importComplete)&&p.importComplete(p.impstring),p.impstring=
null)}})},jqGridExport:function(p){p=a.extend({exptype:"xmlstring",root:"grid",ident:"\t"},p||{});var r=null;this.each(function(){if(this.grid){var u,n=a.extend(!0,{},a(this).jqGrid("getGridParam"));n.rownumbers&&(n.colNames.splice(0,1),n.colModel.splice(0,1));n.multiselect&&(n.colNames.splice(0,1),n.colModel.splice(0,1));n.subGrid&&(n.colNames.splice(0,1),n.colModel.splice(0,1));n.knv=null;if(n.treeGrid)for(u in n.treeReader)n.treeReader.hasOwnProperty(u)&&(n.colNames.splice(n.colNames.length-1),
n.colModel.splice(n.colModel.length-1));switch(p.exptype){case "xmlstring":r="<"+p.root+">"+xmlJsonClass.json2xml(n,p.ident)+"</"+p.root+">";break;case "jsonstring":r="{"+xmlJsonClass.toJson(n,p.root,p.ident,!1)+"}",void 0!==n.postData.filters&&(r=r.replace(/filters":"/,'filters":'),r=r.replace(/\}\]\}"/,"}]}"))}}});return r},excelExport:function(p){p=a.extend({exptype:"remote",url:null,oper:"oper",tag:"excel",exportOptions:{}},p||{});return this.each(function(){var r;this.grid&&"remote"===p.exptype&&
(r=a.extend({},this.p.postData),r[p.oper]=p.tag,r=jQuery.param(r),r=-1!==p.url.indexOf("?")?p.url+"&"+r:p.url+"?"+r,window.location=r)})}})})(jQuery);
(function(a){var p=a.jgrid,r=p.fullBoolFeedback,u=p.hasOneFromClasses,n=p.enumEditableCells,d=p.info_dialog,f=function(b){var c=a.makeArray(arguments).slice(1);c.unshift("");c.unshift("Inline");c.unshift(b);return p.feedback.apply(this,c)},h=function(a){return p.getRes(p.guiStyles[this.p.guiStyle],"states."+a)};p.inlineEdit=p.inlineEdit||{};p.extend({editRow:function(b,c,e,d,m,g,t,w,u,q){var y={},E=a.makeArray(arguments).slice(1);"object"===a.type(E[0])?y=E[0]:(void 0!==c&&(y.keys=c),a.isFunction(e)&&
(y.oneditfunc=e),a.isFunction(d)&&(y.successfunc=d),void 0!==m&&(y.url=m),null!=g&&(y.extraparam=g),a.isFunction(t)&&(y.aftersavefunc=t),a.isFunction(w)&&(y.errorfunc=w),a.isFunction(u)&&(y.afterrestorefunc=u),a.isFunction(q)&&(y.beforeEditRow=q));return this.each(function(){var c=this,e=a(c),d=c.p,g=0,l=null,m={},t=d.colModel,q=d.prmNames;if(c.grid){var w=a.extend(!0,{keys:!1,oneditfunc:null,successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,
beforeEditRow:null,mtype:"POST",focusField:!0},p.inlineEdit,d.inlineEditing||{},y),u=e.jqGrid("getInd",b,!0),A=w.focusField;if(!1!==u&&(w.extraparam[q.oper]===q.addoper||f.call(c,w,"beforeEditRow",w,b))&&"0"===(a(u).attr("editable")||"0")&&!a(u).hasClass("not-editable-row")){q=p.detectRowEditing.call(c,b);if(null!=q&&"cellEditing"===q.mode){var q=q.savedRow,E=c.rows[q.id],H=h.call(c,"select");e.jqGrid("restoreCell",q.id,q.ic);a(E.cells[q.ic]).removeClass("edit-cell "+H);a(E).addClass(H).attr({"aria-selected":"true",
tabindex:"0"})}n.call(c,u,a(u).hasClass("jqgrid-new-row")?"add":"edit",function(e){var f=e.cm,h=a(e.dataElement),t=e.dataWidth,q,n=f.name,w=f.edittype,r=e.iCol,u=f.editoptions||{};try{q=a.unformat.call(this,e.td,{rowId:b,colModel:f},r)}catch(A){q="textarea"===w?h.text():h.html()}m[n]=q;h.html("");f=a.extend({},u,{id:b+"_"+n,name:n,rowId:b,mode:e.mode});if(" "===q||" "===q||1===q.length&&160===q.charCodeAt(0))q="";q=p.createEl.call(c,w,f,q,!0,a.extend({},p.ajaxOptions,d.ajaxSelectOptions||
{}));a(q).addClass("editable");h.append(q);t&&a(q).width(e.dataWidth);p.bindEv.call(c,q,f);"select"===w&&!0===u.multiple&&void 0===u.dataUrl&&p.msie&&a(q).width(a(q).width());null===l&&(l=r);g++});0<g&&(m.id=b,d.savedRow.push(m),a(u).attr("editable","1"),A&&("number"===typeof A&&parseInt(A,10)<=t.length?l=A:"string"===typeof A&&(l=d.iColByName[A]),setTimeout(function(){var b=a(u.cells[l]).find("input,textarea,select,button,object,*[tabindex]").filter(":input:visible:not(:disabled)");0<b.length&&b.focus()},
0)),!0===w.keys&&a(u).bind("keydown",function(a){if(27===a.keyCode)return e.jqGrid("restoreRow",b,w.afterrestorefunc),!1;if(13===a.keyCode){if("TEXTAREA"===a.target.tagName)return!0;e.jqGrid("saveRow",b,w);return!1}}),r.call(c,w.oneditfunc,"jqGridInlineEditRow",b,w))}}})},saveRow:function(b,c,e,l,m,g,t,w){var u=a.makeArray(arguments).slice(1),q={},y=this[0],E=a(y),C=null!=y?y.p:null,B;if(y.grid&&null!=C){"object"===a.type(u[0])?q=u[0]:(a.isFunction(c)&&(q.successfunc=c),void 0!==e&&(q.url=e),void 0!==
l&&(q.extraparam=l),a.isFunction(m)&&(q.aftersavefunc=m),a.isFunction(g)&&(q.errorfunc=g),a.isFunction(t)&&(q.afterrestorefunc=t),a.isFunction(w)&&(q.beforeSaveRow=w));var D=function(a){return E.jqGrid("getGridRes",a)},q=a.extend(!0,{successfunc:null,url:null,extraparam:{},aftersavefunc:null,errorfunc:null,afterrestorefunc:null,restoreAfterError:!0,beforeSaveRow:null,ajaxSaveOptions:{},serializeSaveData:null,mtype:"POST",saveui:"enable",savetext:D("defaults.savetext")||"Saving..."},p.inlineEdit,C.inlineEditing||
{},q),z={},v={},u={},V,I,G;I=E.jqGrid("getInd",b,!0);var S=a(I);B=C.prmNames;var U=D("errors.errcap"),F=D("edit.bClose"),J;if(!1!==I&&(B=q.extraparam[B.oper]===B.addoper?"add":"edit",f.call(y,q,"beforeSaveRow",q,b,B)&&(B=S.attr("editable"),q.url=q.url||C.editurl,J="clientArray"!==q.url,"1"===B)))if(n.call(y,I,S.hasClass("jqgrid-new-row")?"add":"edit",function(b){var c=b.cm,e,d=c.formatter,g=c.editoptions||{},l=c.formatoptions||{};e=p.getEditedValue.call(y,a(b.dataElement),c,!d);G=p.checkValues.call(y,
e,b.iCol);if(!1===G[0])return!1;J&&C.autoencode&&(e=p.htmlEncode(e));"date"===d&&!0!==l.sendFormatted&&(e=a.unformat.date.call(y,e,c));J&&!0===g.NullIfEmpty&&""===e&&(e="null");z[c.name]=e}),!1===G[0])try{var H=E.jqGrid("getGridRowById",b),N=p.findPos(H);d.call(y,U,G[1],F,{left:N[0],top:N[1]+a(H).outerHeight()})}catch(Y){alert(G[1])}else if(H=b,B=C.prmNames,N=!1===C.keyName?B.id:C.keyName,z&&(z[B.oper]=B.editoper,void 0===z[N]||""===z[N]?z[N]=b:I.id!==C.idPrefix+z[N]&&(I=p.stripPref(C.idPrefix,b),
void 0!==C._index[I]&&(C._index[z[N]]=C._index[I],delete C._index[I]),b=C.idPrefix+z[N],S.attr("id",b),C.selrow===H&&(C.selrow=b),a.isArray(C.selarrrow)&&(I=a.inArray(H,C.selarrrow),0<=I&&(C.selarrrow[I]=b)),C.multiselect&&(I="jqg_"+C.id+"_"+b,S.find("input.cbox").attr("id",I).attr("name",I))),z=a.extend({},z,C.inlineData||{},q.extraparam)),J)E.jqGrid("progressBar",{method:"show",loadtype:q.saveui,htmlcontent:q.savetext}),u=a.extend({},z,u),u[N]=p.stripPref(C.idPrefix,u[N]),a.ajax(a.extend({url:q.url,
data:p.serializeFeedback.call(y,a.isFunction(q.serializeSaveData)?q.serializeSaveData:C.serializeRowData,"jqGridInlineSerializeSaveData",u),type:q.mtype,complete:function(c,e){E.jqGrid("progressBar",{method:"hide",loadtype:q.saveui,htmlcontent:q.savetext});if((300>c.status||304===c.status)&&(0!==c.status||4!==c.readyState)){var d,g;g=E.triggerHandler("jqGridInlineSuccessSaveRow",[c,b,q]);a.isArray(g)||(g=[!0,z]);g[0]&&a.isFunction(q.successfunc)&&(g=q.successfunc.call(y,c));a.isArray(g)?(d=g[0],z=
g[1]||z):d=g;if(!0===d){C.autoencode&&a.each(z,function(a,b){z[a]=p.htmlDecode(b)});z=a.extend({},z,v);E.jqGrid("setRowData",b,z);S.attr("editable","0");for(d=0;d<C.savedRow.length;d++)if(String(C.savedRow[d].id)===String(b)){V=d;break}0<=V&&C.savedRow.splice(V,1);r.call(y,q.aftersavefunc,"jqGridInlineAfterSaveRow",b,c,z,q);S.removeClass("jqgrid-new-row").unbind("keydown")}else r.call(y,q.errorfunc,"jqGridInlineErrorSaveRow",b,c,e,null,q),!0===q.restoreAfterError&&E.jqGrid("restoreRow",b,q.afterrestorefunc)}},
error:function(c,e,g){a("#lui_"+p.jqID(C.id)).hide();E.triggerHandler("jqGridInlineErrorSaveRow",[b,c,e,g,q]);if(a.isFunction(q.errorfunc))q.errorfunc.call(y,b,c,e,g);else{c=c.responseText||c.statusText;try{d.call(y,U,'<div class="'+h.call(y,"error")+'">'+c+"</div>",F,{buttonalign:"right"})}catch(l){alert(c)}}!0===q.restoreAfterError&&E.jqGrid("restoreRow",b,q.afterrestorefunc)}},p.ajaxOptions,C.ajaxRowOptions,q.ajaxSaveOptions||{}));else{z=a.extend({},z,v);I=E.jqGrid("setRowData",b,z);S.attr("editable",
"0");for(u=0;u<C.savedRow.length;u++)if(String(C.savedRow[u].id)===String(H)){V=u;break}0<=V&&C.savedRow.splice(V,1);r.call(y,q.aftersavefunc,"jqGridInlineAfterSaveRow",b,I,z,q);S.removeClass("jqgrid-new-row").unbind("keydown")}}},restoreRow:function(b,c){var e=a.makeArray(arguments).slice(1),d={};"object"===a.type(e[0])?d=e[0]:a.isFunction(c)&&(d.afterrestorefunc=c);return this.each(function(){var c=this,e=a(c),h=c.p,n=-1,u={},q;if(c.grid){var y=a.extend(!0,{},p.inlineEdit,h.inlineEditing||{},d),
E=e.jqGrid("getInd",b,!0);if(!1!==E&&f.call(c,y,"beforeCancelRow",y,b)){for(q=0;q<h.savedRow.length;q++)if(String(h.savedRow[q].id)===String(b)){n=q;break}if(0<=n){if(a.isFunction(a.fn.datepicker))try{a("input.hasDatepicker","#"+p.jqID(E.id)).datepicker("hide")}catch(C){}a.each(h.colModel,function(){var b=this.name;h.savedRow[n].hasOwnProperty(b)&&(u[b]=h.savedRow[n][b],!this.formatter||"date"!==this.formatter||null!=this.formatoptions&&!0===this.formatoptions.sendFormatted||(u[b]=a.unformat.date.call(c,
u[b],this)))});e.jqGrid("setRowData",b,u);a(E).attr("editable","0").unbind("keydown");h.savedRow.splice(n,1);a("#"+p.jqID(b),c).hasClass("jqgrid-new-row")&&setTimeout(function(){e.jqGrid("delRowData",b);e.jqGrid("showAddEditButtons",!1)},0)}r.call(c,y.afterrestorefunc,"jqGridInlineAfterRestoreRow",b)}}})},addRow:function(b){return this.each(function(){if(this.grid){var c=this,e=a(c),d=c.p,h=a.extend(!0,{rowID:null,initdata:{},position:"first",useDefValues:!0,useFormatter:!1,beforeAddRow:null,addRowParams:{extraparam:{}}},
p.inlineEdit,d.inlineEditing||{},b||{});f.call(c,h,"beforeAddRow",h.addRowParams)&&(h.rowID=a.isFunction(h.rowID)?h.rowID.call(c,h):null!=h.rowID?h.rowID:p.randId(),!0===h.useDefValues&&a(d.colModel).each(function(){if(this.editoptions&&this.editoptions.defaultValue){var b=this.editoptions.defaultValue;h.initdata[this.name]=a.isFunction(b)?b.call(c):b}}),h.rowID=d.idPrefix+h.rowID,e.jqGrid("addRowData",h.rowID,h.initdata,h.position),a("#"+p.jqID(h.rowID),c).addClass("jqgrid-new-row"),h.useFormatter?
a("#"+p.jqID(h.rowID)+" .ui-inline-edit",c).click():(d=d.prmNames,h.addRowParams.extraparam[d.oper]=d.addoper,e.jqGrid("editRow",h.rowID,h.addRowParams),e.jqGrid("setSelection",h.rowID)))}})},inlineNav:function(b,c){"object"===typeof b&&(c=b,b=void 0);return this.each(function(){var e=this,d=a(e),f=e.p;if(this.grid&&null!=f){var g,t=b===f.toppager?f.idSel+"_top":f.idSel,n=b===f.toppager?f.id+"_top":f.id,r=h.call(e,"disabled"),q=a.extend(!0,{edit:!0,editicon:"ui-icon-pencil",add:!0,addicon:"ui-icon-plus",
save:!0,saveicon:"ui-icon-disk",cancel:!0,cancelicon:"ui-icon-cancel",commonIconClass:"ui-icon",iconsOverText:!1,addParams:{addRowParams:{extraparam:{}}},editParams:{},restoreAfterSelect:!0},d.jqGrid("getGridRes","nav"),p.nav||{},f.navOptions||{},c||{});if(void 0===b)if(f.pager)if(d.jqGrid("inlineNav",f.pager,q),f.toppager)b=f.toppager,t=f.idSel+"_top",n=f.id+"_top";else return;else f.toppager&&(b=f.toppager,t=f.idSel+"_top",n=f.id+"_top");if(void 0!==b&&(g=a(b),!(0>=g.length))){0>=g.find(".navtable").length&&
d.jqGrid("navGrid",b,{add:!1,edit:!1,del:!1,search:!1,refresh:!1,view:!1});f._inlinenav=!0;if(!0===q.addParams.useFormatter){g=f.colModel;var y,E;for(y=0;y<g.length;y++)if(g[y].formatter&&"actions"===g[y].formatter){g[y].formatoptions&&(E={keys:!1,onEdit:null,onSuccess:null,afterSave:null,onError:null,afterRestore:null,extraparam:{},url:null},g=a.extend(E,g[y].formatoptions),q.addParams.addRowParams={keys:g.keys,oneditfunc:g.onEdit,successfunc:g.onSuccess,url:g.url,extraparam:g.extraparam,aftersavefunc:g.afterSave,
errorfunc:g.onError,afterrestorefunc:g.afterRestore});break}}q.add&&d.jqGrid("navButtonAdd",b,{caption:q.addtext,title:q.addtitle,commonIconClass:q.commonIconClass,buttonicon:q.addicon,iconsOverText:q.iconsOverText,id:n+"_iladd",onClickButton:function(){u(this,r)||d.jqGrid("addRow",q.addParams)}});q.edit&&d.jqGrid("navButtonAdd",b,{caption:q.edittext,title:q.edittitle,commonIconClass:q.commonIconClass,buttonicon:q.editicon,iconsOverText:q.iconsOverText,id:n+"_iledit",onClickButton:function(){if(!u(this,
r)){var a=f.selrow;a?d.jqGrid("editRow",a,q.editParams):e.modalAlert()}}});q.save&&(d.jqGrid("navButtonAdd",b,{caption:q.savetext||"",title:q.savetitle||"Save row",commonIconClass:q.commonIconClass,buttonicon:q.saveicon,iconsOverText:q.iconsOverText,id:n+"_ilsave",onClickButton:function(){if(!u(this,r)){var b=f.savedRow[0].id;if(b){var c=f.prmNames,g=c.oper,h=q.editParams;a("#"+p.jqID(b),e).hasClass("jqgrid-new-row")?(q.addParams.addRowParams.extraparam[g]=c.addoper,h=q.addParams.addRowParams):(q.editParams.extraparam||
(q.editParams.extraparam={}),q.editParams.extraparam[g]=c.editoper);d.jqGrid("saveRow",b,h)}else e.modalAlert()}}}),a(t+"_ilsave").addClass(r));q.cancel&&(d.jqGrid("navButtonAdd",b,{caption:q.canceltext||"",title:q.canceltitle||"Cancel row editing",commonIconClass:q.commonIconClass,buttonicon:q.cancelicon,iconsOverText:q.iconsOverText,id:n+"_ilcancel",onClickButton:function(){if(!u(this,r)){var b=f.savedRow[0].id,c=q.editParams;b?(a("#"+p.jqID(b),e).hasClass("jqgrid-new-row")&&(c=q.addParams.addRowParams),
d.jqGrid("restoreRow",b,c)):e.modalAlert()}}}),a(t+"_ilcancel").addClass(r));!0===q.restoreAfterSelect&&d.bind("jqGridSelectRow",function(a,b){if(0<f.savedRow.length&&!0===f._inlinenav){var c=f.savedRow[0].id;b!==c&&"number"!==typeof c&&d.jqGrid("restoreRow",c,q.editParams)}});d.bind("jqGridInlineAfterRestoreRow jqGridInlineAfterSaveRow",function(){d.jqGrid("showAddEditButtons",!1)});d.bind("jqGridInlineEditRow",function(a,b){d.jqGrid("showAddEditButtons",!0,b)})}}})},showAddEditButtons:function(b){return this.each(function(){if(this.grid){var c=
this.p,e=c.idSel,d=h.call(this,"disabled"),f=e+"_ilsave,"+e+"_ilcancel"+(c.toppager?","+e+"_top_ilsave,"+e+"_top_ilcancel":""),c=e+"_iladd,"+e+"_iledit"+(c.toppager?","+e+"_top_iladd,"+e+"_top_iledit":"");a(b?c:f).addClass(d);a(b?f:c).removeClass(d)}})}})})(jQuery);
(function(a){var p=a.jgrid,r=null!=a.ui?a.ui.multiselect:null,u=p.jqID;p.msie&&8===p.msiever()&&(a.expr[":"].hidden=function(a){return 0===a.offsetWidth||0===a.offsetHeight||"none"===a.style.display});p._multiselect=!1;if(a.ui&&r){if(r.prototype._setSelected){var n=r.prototype._setSelected;r.prototype._setSelected=function(d,f){var h=this,b=n.call(h,d,f);if(f&&h.selectedList){var c=h.element;h.selectedList.find("li").each(function(){a(h).data("optionLink")&&a(h).data("optionLink").remove().appendTo(c)})}return b}}r.prototype.destroy&&
(r.prototype.destroy=function(){this.element.show();this.container.remove();void 0===a.Widget?a.widget.prototype.destroy.apply(this,arguments):a.Widget.prototype.destroy.apply(this,arguments)});p._multiselect=!0}p.extend({sortableColumns:function(d){return this.each(function(){function f(){b.disableClick=!0}var h=this,b=h.p,c=u(b.id),c={tolerance:"pointer",axis:"x",scrollSensitivity:"1",items:">th:not(:has(#jqgh_"+c+"_cb,#jqgh_"+c+"_rn,#jqgh_"+c+"_subgrid),:hidden)",placeholder:{element:function(b){return a(document.createElement(b[0].nodeName)).addClass(b[0].className+
" ui-sortable-placeholder ui-state-highlight").removeClass("ui-sortable-helper")[0]},update:function(a,b){b.height(a.currentItem.innerHeight()-parseInt(a.currentItem.css("paddingTop")||0,10)-parseInt(a.currentItem.css("paddingBottom")||0,10));b.width(a.currentItem.innerWidth()-parseInt(a.currentItem.css("paddingLeft")||0,10)-parseInt(a.currentItem.css("paddingRight")||0,10))}},update:function(c,e){var d=a(">th",a(e.item).parent()),f=b.id+"_",p=[];d.each(function(){var c=a(">div",this).get(0).id.replace(/^jqgh_/,
"").replace(f,""),c=b.iColByName[c];void 0!==c&&p.push(c)});a(h).jqGrid("remapColumns",p,!0,!0);a.isFunction(b.sortable.update)&&b.sortable.update(p);setTimeout(function(){b.disableClick=!1},50)}};b.sortable.options?a.extend(c,b.sortable.options):a.isFunction(b.sortable)&&(b.sortable={update:b.sortable});if(c.start){var e=c.start;c.start=function(a,b){f();e.call(this,a,b)}}else c.start=f;b.sortable.exclude&&(c.items+=":not("+b.sortable.exclude+")");c=d.sortable(c);c=c.data("sortable")||c.data("uiSortable")||
c.data("ui-sortable");null!=c&&(c.floating=!0)})},columnChooser:function(d){function f(b,c){b&&("string"===typeof b?a.fn[b]&&a.fn[b].apply(c,a.makeArray(arguments).slice(2)):a.isFunction(b)&&b.apply(c,a.makeArray(arguments).slice(2)))}var h=this,b=h[0].p,c,e,l={},m=[],g,t,n=b.colModel;g=n.length;t=b.colNames;var A=function(a){return r&&r.prototype&&a.data(r.prototype.widgetFullName||r.prototype.widgetName)||a.data("ui-multiselect")||a.data("multiselect")};if(!a("#colchooser_"+u(b.id)).length){c=a('<div id="colchooser_'+
b.id+'" style="position:relative;overflow:hidden"><div><select multiple="multiple"></select></div></div>');e=a("select",c);d=a.extend({width:400,height:240,classname:null,done:function(a){a&&null==b.groupHeader&&h.jqGrid("remapColumns",a,!0)},msel:"multiselect",dlog:"dialog",dialog_opts:{minWidth:470,dialogClass:"ui-jqdialog"},dlog_opts:function(b){var c={};c[b.bSubmit]=function(){b.apply_perm();b.cleanup(!1)};c[b.bCancel]=function(){b.cleanup(!0)};return a.extend(!0,{buttons:c,close:function(){b.cleanup(!0)},
modal:b.modal||!1,resizable:b.resizable||!0,width:b.width+70,resize:function(){var a=A(e),b=a.container.closest(".ui-dialog-content");0<b.length&&"object"===typeof b[0].style?b[0].style.width="":b.css("width","");a.selectedList.height(Math.max(a.selectedContainer.height()-a.selectedActions.outerHeight()-1,1));a.availableList.height(Math.max(a.availableContainer.height()-a.availableActions.outerHeight()-1,1))}},b.dialog_opts||{})},apply_perm:function(){var c=[];a("option",e).each(function(){a(this).is(":selected")?
h.jqGrid("showCol",n[this.value].name):h.jqGrid("hideCol",n[this.value].name)});a("option",e).filter(":selected").each(function(){c.push(parseInt(this.value,10))});a.each(c,function(){delete l[n[parseInt(this,10)].name]});a.each(l,function(){var a=parseInt(this,10);var b=c,e=a,d,g;0<=e?(d=b.slice(),g=d.splice(e,Math.max(b.length-e,e)),e>b.length&&(e=b.length),d[e]=a,c=d.concat(g)):c=b});d.done&&d.done.call(h,c);h.jqGrid("setGridWidth",b.autowidth||void 0!==b.widthOrg&&"auto"!==b.widthOrg&&"100%"!==
b.widthOrg?b.width:b.tblwidth,b.shrinkToFit)},cleanup:function(a){f(d.dlog,c,"destroy");f(d.msel,e,"destroy");c.remove();a&&d.done&&d.done.call(h)},msel_opts:{}},h.jqGrid("getGridRes","col"),p.col,d||{});if(a.ui&&r&&r.defaults){if(!p._multiselect){alert("Multiselect plugin loaded after jqGrid. Please load the plugin before the jqGrid!");return}d.msel_opts=a.extend(r.defaults,d.msel_opts)}d.caption&&c.attr("title",d.caption);d.classname&&(c.addClass(d.classname),e.addClass(d.classname));d.width&&(a(">div",
c).css({width:d.width,margin:"0 auto"}),e.css("width",d.width));d.height&&(a(">div",c).css("height",d.height),e.css("height",d.height-10));e.empty();var q=b.groupHeader,y={},E,C,B,D,z;if(null!=q&&null!=q.groupHeaders)for(E=0,B=q.groupHeaders.length;E<B;E++)for(z=q.groupHeaders[E],C=0;C<z.numberOfColumns;C++)D=b.iColByName[z.startColumnName]+C,y[D]=a.isFunction(d.buildItemText)?d.buildItemText.call(h[0],{iCol:D,cm:n[D],cmName:n[D].name,colName:t[D],groupTitleText:z.titleText}):a.jgrid.stripHtml(z.titleText)+
": "+a.jgrid.stripHtml(""===t[D]?n[D].name:t[D]);for(D=0;D<g;D++)void 0===y[D]&&(y[D]=a.isFunction(d.buildItemText)?d.buildItemText.call(h[0],{iCol:D,cm:n[D],cmName:n[D].name,colName:t[D],groupTitleText:null}):a.jgrid.stripHtml(t[D]));a.each(n,function(a){l[this.name]=a;this.hidedlg?this.hidden||m.push(a):e.append("<option value='"+a+"'"+(b.headertitles||this.headerTitle?' title="'+p.stripHtml("string"===typeof this.headerTitle?this.headerTitle:y[a])+'"':"")+(this.hidden?"":" selected='selected'")+
">"+y[a]+"</option>")});g=a.isFunction(d.dlog_opts)?d.dlog_opts.call(h,d):d.dlog_opts;f(d.dlog,c,g);g=a.isFunction(d.msel_opts)?d.msel_opts.call(h,d):d.msel_opts;f(d.msel,e,g);g=a("#colchooser_"+u(b.id));g.css({margin:"auto"});g.find(">div").css({width:"100%",height:"100%",margin:"auto"});if(g=A(e))g.container.css({width:"100%",height:"100%",margin:"auto"}),g.selectedContainer.css({width:100*g.options.dividerLocation+"%",height:"100%",margin:"auto",boxSizing:"border-box"}),g.availableContainer.css({width:100-
100*g.options.dividerLocation+"%",height:"100%",margin:"auto",boxSizing:"border-box"}),g.selectedList.css("height","auto"),g.availableList.css("height","auto"),t=Math.max(g.selectedList.height(),g.availableList.height()),t=Math.min(t,a(window).height()),g.selectedList.css("height",t),g.availableList.css("height",t)}},sortableRows:function(d){return this.each(function(){var f=this,h=f.grid,b=f.p;h&&!b.treeGrid&&a.fn.sortable&&(d=a.extend({cursor:"move",axis:"y",items:">.jqgrow"},d||{}),d.start&&a.isFunction(d.start)?
(d._start_=d.start,delete d.start):d._start_=!1,d.update&&a.isFunction(d.update)?(d._update_=d.update,delete d.update):d._update_=!1,d.start=function(c,e){a(e.item).css("border-width","0");a("td",e.item).each(function(a){this.style.width=h.cols[a].style.width});if(b.subGrid){var l=a(e.item).attr("id");try{a(f).jqGrid("collapseSubGridRow",l)}catch(m){}}d._start_&&d._start_.apply(this,[c,e])},d.update=function(c,e){a(e.item).css("border-width","");!0===b.rownumbers&&a("td.jqgrid-rownum",f.rows).each(function(c){a(this).html(c+
1+(parseInt(b.page,10)-1)*parseInt(b.rowNum,10))});d._update_&&d._update_.apply(this,[c,e])},a("tbody:first",f).sortable(d),a.isFunction(a.fn.disableSelection)&&a("tbody:first>.jqgrow",f).disableSelection())})},gridDnD:function(d){return this.each(function(){function f(){var b=a.data(h,"dnd");a("tr.jqgrow:not(.ui-draggable)",h).draggable(a.isFunction(b.drag)?b.drag.call(a(h),b):b.drag)}var h=this,b,c;if(h.grid&&!h.p.treeGrid&&a.fn.draggable&&a.fn.droppable)if(void 0===a("#jqgrid_dnd")[0]&&a("body").append("<table id='jqgrid_dnd' class='ui-jqgrid-dnd'></table>"),
"string"===typeof d&&"updateDnD"===d&&!0===h.p.jqgdnd)f();else if(d=a.extend({drag:function(b){return a.extend({start:function(c,d){var g;if(h.p.subGrid){g=a(d.helper).attr("id");try{a(h).jqGrid("collapseSubGridRow",g)}catch(f){}}for(g=0;g<a.data(h,"dnd").connectWith.length;g++)0===a(a.data(h,"dnd").connectWith[g]).jqGrid("getGridParam","reccount")&&a(a.data(h,"dnd").connectWith[g]).jqGrid("addRowData","jqg_empty_row",{});d.helper.addClass("ui-state-highlight");a("td",d.helper).each(function(a){this.style.width=
h.grid.headers[a].width+"px"});b.onstart&&a.isFunction(b.onstart)&&b.onstart.call(a(h),c,d)},stop:function(c,d){var g;d.helper.dropped&&!b.dragcopy&&(g=a(d.helper).attr("id"),void 0===g&&(g=a(this).attr("id")),a(h).jqGrid("delRowData",g));for(g=0;g<a.data(h,"dnd").connectWith.length;g++)a(a.data(h,"dnd").connectWith[g]).jqGrid("delRowData","jqg_empty_row");b.onstop&&a.isFunction(b.onstop)&&b.onstop.call(a(h),c,d)}},b.drag_opts||{})},drop:function(b){return a.extend({accept:function(b){if(!a(b).hasClass("jqgrow"))return b;
b=a(b).closest("table.ui-jqgrid-btable");return 0<b.length&&void 0!==a.data(b[0],"dnd")?(b=a.data(b[0],"dnd").connectWith,-1!==a.inArray("#"+u(this.id),b)?!0:!1):!1},drop:function(c,d){if(a(d.draggable).hasClass("jqgrow")){var g=a(d.draggable).attr("id"),g=d.draggable.parent().parent().jqGrid("getRowData",g);if(!b.dropbyname){var f=0,p={},n,q,r=a("#"+u(this.id)).jqGrid("getGridParam","colModel");try{for(q in g)g.hasOwnProperty(q)&&(n=r[f].name,"cb"!==n&&"rn"!==n&&"subgrid"!==n&&g.hasOwnProperty(q)&&
r[f]&&(p[n]=g[q]),f++);g=p}catch(E){}}d.helper.dropped=!0;b.beforedrop&&a.isFunction(b.beforedrop)&&(n=b.beforedrop.call(this,c,d,g,a("#"+u(h.p.id)),a(this)),void 0!==n&&null!==n&&"object"===typeof n&&(g=n));if(d.helper.dropped){var C;b.autoid&&(a.isFunction(b.autoid)?C=b.autoid.call(this,g):(C=Math.ceil(1E3*Math.random()),C=b.autoidprefix+C));a("#"+u(this.id)).jqGrid("addRowData",C,g,b.droppos);g[h.p.localReader.id]=C}b.ondrop&&a.isFunction(b.ondrop)&&b.ondrop.call(this,c,d,g)}}},b.drop_opts||{})},
onstart:null,onstop:null,beforedrop:null,ondrop:null,drop_opts:{},drag_opts:{revert:"invalid",helper:"clone",cursor:"move",appendTo:"#jqgrid_dnd",zIndex:5E3},dragcopy:!1,dropbyname:!1,droppos:"first",autoid:!0,autoidprefix:"dnd_"},d||{}),d.connectWith)for(d.connectWith=d.connectWith.split(","),d.connectWith=a.map(d.connectWith,function(b){return a.trim(b)}),a.data(h,"dnd",d),0===h.p.reccount||h.p.jqgdnd||f(),h.p.jqgdnd=!0,b=0;b<d.connectWith.length;b++)c=d.connectWith[b],a(c).droppable(a.isFunction(d.drop)?
d.drop.call(a(h),d):d.drop)})},gridResize:function(d){return this.each(function(){var f=this,h=f.grid,b=f.p,c=b.gView+">.ui-jqgrid-bdiv",e=!1,l,m=b.height;if(h&&a.fn.resizable){d=a.extend({},d||{});d.alsoResize?(d._alsoResize_=d.alsoResize,delete d.alsoResize):d._alsoResize_=!1;d.stop&&a.isFunction(d.stop)?(d._stop_=d.stop,delete d.stop):d._stop_=!1;d.stop=function(g,n){a(f).jqGrid("setGridWidth",n.size.width,d.shrinkToFit);a(b.gView+">.ui-jqgrid-titlebar").css("width","");e?(a(l).each(function(){a(this).css("height",
"")}),"auto"!==m&&"100%"!==m||a(h.bDiv).css("height",m)):a(f).jqGrid("setGridParam",{height:a(c).height()});f.fixScrollOffsetAndhBoxPadding&&f.fixScrollOffsetAndhBoxPadding();d._stop_&&d._stop_.call(f,g,n)};l=c;"auto"!==m&&"100%"!==m||void 0!==d.handles||(d.handles="e,w");if(d.handles){var g=a.map(String(d.handles).split(","),function(b){return a.trim(b)});2===g.length&&("e"===g[0]&&"w"===g[1]||"e"===g[1]&&"w"===g[1])&&(l=b.gView+">div:not(.frozen-div)",e=!0,b.pager&&(l+=","+b.pager))}d.alsoResize=
d._alsoResize_?l+","+d._alsoResize_:l;delete d._alsoResize_;a(b.gBox).resizable(d)}})}})})(jQuery);
(function(a){function p(a,d,f){if(!(this instanceof p))return new p(a);this.aggregator=a;this.finilized=!1;this.context=d;this.pivotOptions=f}function r(n,d,f,h,b){var c=h.length,e=function(a,b){var c=a,e=b;null==c&&(c="");null==e&&(e="");c=String(c);e=String(e);this.caseSensitive||(c=c.toUpperCase(),e=e.toUpperCase());if(c===e){if(a===b)return 0;if(void 0===a)return-1;if(void 0===b)return 1;if(null===a)return-1;if(null===b)return 1}return c<e?-1:1},l=function(a,b){a=Number(a);b=Number(b);return a===
b?0:a<b?-1:1},m=function(a,b){a=Math.floor(Number(a));b=Math.floor(Number(b));return a===b?0:a<b?-1:1};this.items=[];this.indexesOfSourceData=[];this.trimByCollect=n;this.caseSensitive=d;this.skipSort=f;this.fieldLength=c;this.fieldNames=Array(c);this.fieldSortDirection=Array(c);this.fieldCompare=Array(c);for(n=0;n<c;n++){d=h[n];this.fieldNames[n]=d[b||"dataName"];switch(d.sorttype){case "integer":case "int":this.fieldCompare[n]=m;break;case "number":case "currency":case "float":this.fieldCompare[n]=
l;break;default:this.fieldCompare[n]=a.isFunction(d.compare)?d.compare:e}this.fieldSortDirection[n]="desc"===d.sortorder?-1:1}}p.prototype.calc=function(n,d,f,h,b){if(void 0!==n)switch(this.result=this.result||0,n=parseFloat(n),this.aggregator){case "sum":this.result+=n;break;case "count":this.result++;break;case "avg":this.finilized?(this.count=this.count||0,this.result=(this.result*this.count+n)/(this.count+1)):(this.result+=n,this.count=this.count||0);this.count++;break;case "min":this.result=
Math.min(this.result,n);break;case "max":this.result=Math.max(this.result,n);break;default:a.isFunction(this.aggregator)&&(this.result=this.aggregator.call(this.context,{previousResult:this.result,value:n,fieldName:d,item:f,iItem:h,items:b}))}};p.prototype.getResult=function(a,d,f){if(void 0!==this.result||f)f&&void 0!==this.result&&(this.count=this.result=0),void 0===this.result||this.finilized||"avg"!==this.aggregator||(this.result/=this.count,this.finilized=!0),a[d]=this.result};r.prototype.compareVectorsEx=
function(a,d){var f=this.fieldLength,h,b;for(h=0;h<f;h++)if(b=this.fieldCompare[h](a[h],d[h]),0!==b)return{index:h,result:b};return{index:-1,result:0}};r.prototype.getIndexOfDifferences=function(a,d){return null===d||null===a?0:this.compareVectorsEx(a,d).index};r.prototype.compareVectors=function(a,d){var f=this.compareVectorsEx(a,d);return 0<(0<=f.index?this.fieldSortDirection[f.index]:1)?f.result:-f.result};r.prototype.getItem=function(a){return this.items[a]};r.prototype.getIndexLength=function(){return this.items.length};
r.prototype.getIndexesOfSourceData=function(a){return this.indexesOfSourceData[a]};r.prototype.createDataIndex=function(p){var d,f=p.length,h=this.fieldLength,b,c,e=this.fieldNames,l=this.indexesOfSourceData,m,g,t=this.items,w;for(d=0;d<f;d++){g=p[d];b=Array(h);for(m=0;m<h;m++)c=g[e[m]],void 0!==c&&("string"===typeof c&&this.trimByCollect&&(c=a.trim(c)),b[m]=c);g=0;w=t.length-1;if(0>w)t.push(b),l.push([d]);else if(c=this.compareVectors(b,t[w]),0===c)l[w].push(d);else if(1===c||this.skipSort)t.push(b),
l.push([d]);else if(c=this.compareVectors(t[0],b),1===c)t.unshift(b),l.unshift([d]);else if(0===c)l[0].push(d);else for(;;){if(2>w-g){t.splice(w,0,b);l.splice(w,0,[d]);break}m=Math.floor((g+w)/2);c=this.compareVectors(t[m],b);if(0===c){l[m].push(d);break}1===c?w=m:g=m}}};var u=a.jgrid;u.extend({pivotSetup:function(n,d){var f=this[0],h=a.isArray,b={},c={groupField:[],groupSummary:[],groupSummaryPos:[]},e={grouping:!0,groupingView:c},l=a.extend({totals:!1,useColSpanStyle:!1,trimByCollect:!0,skipSortByX:!1,
skipSortByY:!1,caseSensitive:!1,footerTotals:!1,groupSummary:!0,groupSummaryPos:"header",frozenStaticCols:!1,defaultFormatting:!0,data:n},d||{}),m,g,t,w=n.length,A,q,y,E,C,B,D=l.xDimension,z=l.yDimension,v=l.aggregates,V,w=l.totalText||l.totals||l.rowTotals||l.totalHeader,I,G=h(D)?D.length:0;E=h(z)?z.length:0;var S=h(v)?v.length:0,U=E-(1===S?1:0),F=[],J=[],H=[],h=[],N=Array(S),Y=Array(E),X,T,x,O,aa,Q,K,L,k,R,W;g=function(b,c,e){b=new r(l.trimByCollect,l.caseSensitive,c,b);a.isFunction(e)&&(b.compareVectorsEx=
e);b.createDataIndex(n);return b};var ba=function(b,c,e,d,g){var h,k;switch(b){case 1:h=z[d].totalText||"{0} {1} {2}";k="y"+g+"t"+d;break;case 2:h=l.totalText||"{0}";k="t";break;default:h=1<S?c.label||"{0}":W.getItem(g)[d],k="y"+g}b=a.extend({},c,{name:k+(1<S?"a"+e:""),label:a.isFunction(h)?h.call(f,2===b?{aggregate:c,iAggregate:e,pivotOptions:l}:{yIndex:W.getItem(g),aggregate:c,iAggregate:e,yLevel:d,pivotOptions:l}):u.template.apply(f,2===b?[h,c.aggregator,c.member,e]:[h,c.aggregator,c.member,W.getItem(g)[d],
d])});delete b.member;delete b.aggregator;return b};C=function(a,b,c){var e,d;for(e=0;e<S;e++)d=v[e],void 0===d.template&&void 0===d.formatter&&l.defaultFormatting&&(d.template="count"===d.aggregator?"integer":"number"),H.push(ba(a,d,e,b,c))};X=function(b,c,e){var d,g,l,h;for(d=U-1;d>=c;d--)if(J[d]){for(g=0;g<=d;g++)k=F[g].groupHeaders,k[k.length-1].numberOfColumns+=S;A=z[d];l=A.totalHeader;h=A.headerOnTop;for(g=d+1;g<=U-1;g++)F[g].groupHeaders.push({titleText:h&&g===d+1||!h&&g===U-1?a.isFunction(l)?
l.call(f,e,d):u.template.call(f,l||"",e[d],d):"",startColumnName:"y"+(b-1)+"t"+d+(1===S?"":"a0"),numberOfColumns:S})}};var ca=function(a){a=new p("count"===v[a].aggregator?"sum":v[a].aggregator,f,d);a.groupInfo={iRows:[],rows:[],ys:[],iYs:[]};return a},ha=function(){var a,b;for(a=U-1;0<=a;a--)if(J[a])for(null==Y[a]&&(Y[a]=Array(S)),b=0;b<S;b++)Y[a][b]=ca(b)},ja=function(a,b,c,e){var d,g=W.getIndexOfDifferences(b,c),f,l;if(null!==c)for(g=Math.max(g,0),d=U-1;d>=g;d--)f="y"+a+"t"+d+(1<S?"a"+e:""),J[d]&&
void 0===K[f]&&(l=Y[d][e],l.getResult(K,f),K.pivotInfos[f]={colType:1,iA:e,a:v[e],level:d,iRows:l.groupInfo.iRows,rows:l.groupInfo.rows,ys:l.groupInfo.ys,iYs:l.groupInfo.iYs},b!==c&&(Y[d][e]=ca(e)))},da=function(b,c,e,d,g,f,l){var h;if(b!==c)for(c=U-1;0<=c;c--)J[c]&&(h=Y[c][d],h.calc(g[e.member],e.member,g,f,n),h=h.groupInfo,0>a.inArray(l,h.iYs)&&(h.iYs.push(l),h.ys.push(b)),0>a.inArray(f,h.iRows)&&(h.iRows.push(f),h.rows.push(g)))};if(0===G||0===S)throw"xDimension or aggregates options are not set!";
R=g(D,l.skipSortByX,l.compareVectorsByX);W=g(z,l.skipSortByY,l.compareVectorsByY);d.xIndex=R;d.yIndex=W;for(g=0;g<G;g++)t=D[g],q={name:"x"+g,label:null!=t.label?a.isFunction(t.label)?t.label.call(f,t,g,l):t.label:t.dataName,frozen:l.frozenStaticCols},g<G-1&&(c.groupField.push(q.name),c.groupSummary.push(l.groupSummary),c.groupSummaryPos.push(l.groupSummaryPos)),q=a.extend(q,t),delete q.dataName,delete q.footerText,H.push(q);2>G&&(e.grouping=!1);e.sortname=H[G-1].name;c.hideFirstGroupCol=!0;for(g=
0;g<E;g++)A=z[g],J.push(A.totals||A.rowTotals||A.totalText||A.totalHeader?!0:!1);L=W.getItem(0);C(0,E-1,0);c=W.getIndexLength();for(q=1;q<c;q++){x=W.getItem(q);g=W.getIndexOfDifferences(x,L);for(t=U-1;t>=g;t--)J[t]&&C(1,t,q-1);L=x;C(0,E-1,q)}for(g=U-1;0<=g;g--)J[g]&&C(1,g,c-1);w&&C(2);L=W.getItem(0);for(t=0;t<U;t++)F.push({useColSpanStyle:l.useColSpanStyle,groupHeaders:[{titleText:L[t],startColumnName:1===S?"y0":"y0a0",numberOfColumns:S}]});for(q=1;q<c;q++){x=W.getItem(q);g=W.getIndexOfDifferences(x,
L);X(q,g,L);for(t=U-1;t>=g;t--)F[t].groupHeaders.push({titleText:x[t],startColumnName:"y"+q+(1===S?"":"a0"),numberOfColumns:S});for(t=0;t<g;t++)k=F[t].groupHeaders,k[k.length-1].numberOfColumns+=S;L=x}X(c,0,L);if(w)for(g=0;g<U;g++)F[g].groupHeaders.push({titleText:g<U-1?"":l.totalHeader||"",startColumnName:"t"+(1===S?"":"a0"),numberOfColumns:S});X=R.getIndexLength();for(E=0;E<X;E++){t=R.getItem(E);C={iX:E,x:t};K={pivotInfos:C};for(g=0;g<G;g++)K["x"+g]=t[g];T=R.getIndexesOfSourceData(E);if(w)for(t=
0;t<S;t++)N[t]=ca(t);L=null;ha();for(q=0;q<c;q++){x=W.getItem(q);O=W.getIndexesOfSourceData(q);for(t=0;t<S;t++){null!==L&&ja(q-1,x,L,t);aa=[];for(g=0;g<O.length;g++)y=O[g],0<=a.inArray(y,T)&&aa.push(y);if(0<aa.length){B=Array(aa.length);Q=v[t];V=new p(Q.aggregator,f,d);for(y=0;y<aa.length;y++)g=aa[y],m=n[g],B[y]=m,V.calc(m[Q.member],Q.member,m,g,n),w&&(I=N[t],I.calc(m[Q.member],Q.member,m,g,n),I=I.groupInfo,0>a.inArray(g,I.iYs)&&(I.iYs.push(q),I.ys.push(x)),0>a.inArray(g,I.iRows)&&(I.iRows.push(g),
I.rows.push(m))),da(x,L,Q,t,m,g,q);m="y"+q+(1===S?"":"a"+t);V.getResult(K,m);C[m]={colType:0,iY:q,y:x,iA:t,a:Q,iRows:aa,rows:B}}}L=x}if(null!==L)for(t=0;t<S;t++)ja(c-1,L,L,t);if(w)for(t=0;t<S;t++)m="t"+(1===S?"":"a"+t),I=N[t],I.getResult(K,m),I=I.groupInfo,C[m]={colType:2,iA:t,a:v[t],iRows:I.iRows,rows:I.rows,iYs:I.iYs,ys:I.ys};h.push(K)}if(l.footerTotals||l.colTotals){w=h.length;for(g=0;g<G;g++)b["x"+g]=D[g].footerText||"";for(g=G;g<H.length;g++){m=H[g].name;V=new p(l.footerAggregator||"sum",f,d);
for(y=0;y<w;y++)K=h[y],V.calc(K[m],m,K,y,h);V.getResult(b,m)}}d.colHeaders=F;return{colModel:H,options:d,rows:h,groupOptions:e,groupHeaders:F,summary:b}},jqPivot:function(p,d,f,h){return this.each(function(){function b(b){var g=l.pivotSetup.call(e,b,d),h=g.groupHeaders,p=g.summary,n=0,q;for(q in p)p.hasOwnProperty(q)&&n++;p=0<n?!0:!1;n=g.groupOptions.groupingView;q=u.from.call(c,g.rows);var r;if(d.skipSortByX)for(r=0;r<n.groupField.length;r++)q.orderBy(n.groupField[r],null!=f&&f.groupingView&&null!=
f.groupingView.groupOrder&&"desc"===f.groupingView.groupOrder[r]?"d":"a","text","");d.data=b;l.call(e,a.extend(!0,{datastr:a.extend(q.select(),p?{userdata:g.summary}:{}),datatype:"jsonstring",footerrow:p,userDataOnFooter:p,colModel:g.colModel,pivotOptions:g.options,additionalProperties:["pivotInfos"],viewrecords:!0,sortname:d.xDimension[0].dataName},g.groupOptions,f||{}));if(h.length)for(r=0;r<h.length;r++)h[r]&&h[r].groupHeaders.length&&l.setGroupHeaders.call(e,h[r]);d.frozenStaticCols&&l.setFrozenColumns.call(e)}
var c=this,e=a(c),l=a.fn.jqGrid;"string"===typeof p?a.ajax(a.extend({url:p,dataType:"json",success:function(a){b(u.getAccessor(a,h&&h.reader?h.reader:"rows"))}},h||{})):b(p)})}})})(jQuery);
(function(a){var p=a.jgrid,r=p.jqID,u=a.fn.jqGrid,n=function(){var d=a.makeArray(arguments);d[0]="subGrid"+d[0].charAt(0).toUpperCase()+d[0].substring(1);d.unshift("");d.unshift("");d.unshift(this.p);return p.feedback.apply(this,d)};p.extend({setSubGrid:function(){return this.each(function(){var d=this.p,f=d.subGridModel[0];d.subGridOptions=a.extend({expandOnLoad:!1,delayOnLoad:50,selectOnExpand:!1,selectOnCollapse:!1,reloadOnExpand:!0},d.subGridOptions||{});d.colNames.unshift("");d.colModel.unshift({name:"subgrid",
width:p.cell_width?d.subGridWidth+d.cellLayout:d.subGridWidth,labelClasses:"jqgh_subgrid",sortable:!1,resizable:!1,hidedlg:!0,search:!1,fixed:!0,frozen:!0});if(f)for(f.align=a.extend([],f.align||[]),d=0;d<f.name.length;d++)f.align[d]=f.align[d]||"left"})},addSubGridCell:function(a,f){var h=this[0],b=h.p.subGridOptions;return null==h||null==h.p||null==b?"":'<td role="gridcell" aria-describedby="'+h.p.id+"_subgrid\" class='"+u.getGuiStyles.call(this,"subgrid.tdStart","ui-sgcollapsed sgcollapsed")+"' "+
h.formatCol(a,f)+"><a style='cursor:pointer;'><span class='"+p.mergeCssClasses(b.commonIconClass,b.plusicon)+"'></span></a></td>"},addSubGrid:function(d,f){return this.each(function(){var h=this,b=h.p,c=function(a,b){return u.getGuiStyles.call(h,"subgrid."+a,b||"")},e=c("thSubgrid","ui-th-subgrid ui-th-column ui-th-"+b.direction),l=c("rowSubTable","ui-subtblcell"),m=c("row","ui-subgrid ui-row-"+b.direction),g=c("tdWithIcon","subgrid-cell"),t=c("tdData","subgrid-data"),w=function(c,e,d){e=a("<td align='"+
b.subGridModel[0].align[d]+"'></td>").html(e);a(c).append(e)},A=function(c,d){var g,f,m,q,t=a("<table"+(p.msie&&8>p.msiever()?" cellspacing='0'":"")+"><tbody></tbody></table>"),n=a("<tr></tr>");for(f=0;f<b.subGridModel[0].name.length;f++)g=a("<th class='"+e+"'></th>"),a(g).html(b.subGridModel[0].name[f]),a(g).width(b.subGridModel[0].width[f]),a(n).append(g);a(t).append(n);c&&(m=b.xmlReader.subgrid,a(m.root+" "+m.row,c).each(function(){n=a("<tr class='"+l+"'></tr>");if(!0===m.repeatitems)a(m.cell,
this).each(function(b){w(n,a(this).text()||" ",b)});else if(q=b.subGridModel[0].mapping||b.subGridModel[0].name)for(f=0;f<q.length;f++)w(n,a(q[f],this).text()||" ",f);a(t).append(n)}));a("#"+r(b.id+"_"+d)).append(t);h.grid.hDiv.loading=!1;a("#load_"+r(b.id)).hide();return!1},q=function(c,d){var g,f,m,q,t,n,u=a("<table"+(p.msie&&8>p.msiever()?" cellspacing='0'":"")+"><tbody></tbody></table>"),A=a("<tr></tr>");for(f=0;f<b.subGridModel[0].name.length;f++)g=a("<th class='"+e+"'></th>"),a(g).html(b.subGridModel[0].name[f]),
a(g).width(b.subGridModel[0].width[f]),a(A).append(g);a(u).append(A);if(c&&(q=b.jsonReader.subgrid,g=p.getAccessor(c,q.root),void 0!==g))for(f=0;f<g.length;f++){m=g[f];A=a("<tr class='"+l+"'></tr>");if(!0===q.repeatitems)for(q.cell&&(m=m[q.cell]),t=0;t<m.length;t++)w(A,m[t]||" ",t);else if(n=b.subGridModel[0].mapping||b.subGridModel[0].name,n.length)for(t=0;t<n.length;t++)w(A,m[n[t]]||" ",t);a(u).append(A)}a("#"+r(b.id+"_"+d)).append(u);h.grid.hDiv.loading=!1;a("#load_"+r(b.id)).hide();
return!1},y=function(c){var e=a(c).attr("id"),d={nd_:(new Date).getTime()},g,f;d[b.prmNames.subgridid]=e;if(!b.subGridModel[0])return!1;if(b.subGridModel[0].params)for(f=0;f<b.subGridModel[0].params.length;f++)g=b.iColByName[b.subGridModel[0].params[f]],void 0!==g&&(d[b.colModel[g].name]=a(c.cells[g]).text().replace(/\ \;/ig,""));if(!h.grid.hDiv.loading)switch(h.grid.hDiv.loading=!0,a("#load_"+r(b.id)).show(),b.subgridtype||(b.subgridtype=b.datatype),a.isFunction(b.subgridtype)?b.subgridtype.call(h,
d):b.subgridtype=b.subgridtype.toLowerCase(),b.subgridtype){case "xml":case "json":a.ajax(a.extend({type:b.mtype,url:a.isFunction(b.subGridUrl)?b.subGridUrl.call(h,d):b.subGridUrl,dataType:b.subgridtype,data:p.serializeFeedback.call(h,b.serializeSubGridData,"jqGridSerializeSubGridData",d),complete:function(a){"xml"===b.subgridtype?A(a.responseXML,e):q(p.parse(a.responseText),e)}},p.ajaxOptions,b.ajaxSubgridOptions||{}))}return!1},c=function(){var c=a(this).parent("tr")[0],e=c.nextSibling,f=c.id,l=
b.id+"_"+f,q=function(a){return[b.subGridOptions.commonIconClass,b.subGridOptions[a]].join(" ")},p=1;a.each(b.colModel,function(){!0!==this.hidden&&"rn"!==this.name&&"cb"!==this.name||p++});if(a(this).hasClass("sgcollapsed")){if(!0===b.subGridOptions.reloadOnExpand||!1===b.subGridOptions.reloadOnExpand&&!a(e).hasClass("ui-subgrid")){e=1<=d?"<td colspan='"+d+"'> </td>":"";if(!n.call(h,"beforeExpand",l,f))return;a(c).after("<tr role='row' class='"+m+"'>"+e+"<td class='"+g+"'><span class='"+q("openicon")+
"'></span></td><td colspan='"+parseInt(b.colNames.length-p,10)+"' class='"+t+"'><div id="+l+" class='tablediv'></div></td></tr>");a(h).triggerHandler("jqGridSubGridRowExpanded",[l,f]);a.isFunction(b.subGridRowExpanded)?b.subGridRowExpanded.call(h,l,f):y(c)}else a(e).show();a(this).html("<a style='cursor:pointer;'><span class='"+q("minusicon")+"'></span></a>").removeClass("sgcollapsed").addClass("sgexpanded");b.subGridOptions.selectOnExpand&&a(h).jqGrid("setSelection",f)}else if(a(this).hasClass("sgexpanded")){if(!n.call(h,
"beforeCollapse",l,f))return;!0===b.subGridOptions.reloadOnExpand?a(e).remove(".ui-subgrid"):a(e).hasClass("ui-subgrid")&&a(e).hide();a(this).html("<a style='cursor:pointer;'><span class='"+q("plusicon")+"'></span></a>").removeClass("sgexpanded").addClass("sgcollapsed");b.subGridOptions.selectOnCollapse&&a(h).jqGrid("setSelection",f)}return!1},E,C=1;if(h.grid){E=h.rows.length;void 0!==f&&0<f&&(C=f,E=f+1);for(;C<E;)a(h.rows[C]).hasClass("jqgrow")&&(b.scroll&&a(h.rows[C].cells[d]).unbind("click"),a(h.rows[C].cells[d]).bind("click",
c)),C++;!0===b.subGridOptions.expandOnLoad&&a(h.rows).filter(".jqgrow").each(function(b,c){a(c.cells[0]).click()});h.subGridXml=function(a,b){A(a,b)};h.subGridJson=function(a,b){q(a,b)}}})},expandSubGridRow:function(d){return this.each(function(){var f;(this.grid||d)&&!0===this.p.subGrid&&(f=a(this).jqGrid("getInd",d,!0),a(f).find(">td.sgcollapsed").trigger("click"))})},collapseSubGridRow:function(d){return this.each(function(){var f;(this.grid||d)&&!0===this.p.subGrid&&(f=a(this).jqGrid("getInd",
d,!0),a(f).find(">td.sgexpanded").trigger("click"))})},toggleSubGridRow:function(d){return this.each(function(){var f;(this.grid||d)&&!0===this.p.subGrid&&(f=a(this).jqGrid("getInd",d,!0),a(f).find(">td.ui-sgcollapsed").trigger("click"))})}})})(jQuery);
(function(a){window.tableToGrid=function(p,r){a(p).each(function(){var p=a(this),n,d,f,h,b=[],c=[],e=[],l=[],m=[];if(!this.grid){p.width("99%");n=p.width();d=a("tr td:first-child input[type=checkbox]:first",p);f=a("tr td:first-child input[type=radio]:first",p);d=0<d.length;f=!d&&0<f.length;h=d||f;a("th",p).each(function(){0===b.length&&h?(b.push({name:"__selection__",index:"__selection__",width:0,hidden:!0}),c.push("__selection__")):(b.push({name:a(this).attr("id")||a.trim(a.jgrid.stripHtml(a(this).html())).split(" ").join("_"),
index:a(this).attr("id")||a.trim(a.jgrid.stripHtml(a(this).html())).split(" ").join("_"),width:a(this).width()||150}),c.push(a(this).html()))});a("tbody > tr",p).each(function(){var c={},d=0;a("td",a(this)).each(function(){if(0===d&&h){var f=a("input",a(this)),p=f.attr("value");l.push(p||e.length);f.is(":checked")&&m.push(p);c[b[d].name]=f.attr("value")}else c[b[d].name]=a(this).html();d++});0<d&&e.push(c)});p.empty();p.jqGrid(a.extend({datatype:"local",width:n,colNames:c,colModel:b,multiselect:d},
r||{}));for(n=0;n<e.length;n++)f=null,0<l.length&&(f=l[n])&&f.replace&&(f=encodeURIComponent(f).replace(/[.\-%]/g,"_")),null===f&&(f=a.jgrid.randId()),p.jqGrid("addRowData",f,e[n]);for(n=0;n<m.length;n++)p.jqGrid("setSelection",m[n])}})}})(jQuery);
(function(a){var p=a.jgrid,r=p.getAccessor,u=p.stripPref,n=p.jqID,d=a.fn.jqGrid,f=function(){var d=a.makeArray(arguments);d[0]="treeGrid"+d[0].charAt(0).toUpperCase()+d[0].substring(1);d.unshift("");d.unshift("");d.unshift(this.p);return p.feedback.apply(this,d)};p.extend({setTreeNode:function(){return this.each(function(){var f=a(this),b=this.p;if(this.grid&&b.treeGrid){var c=b.treeReader.expanded_field,e=b.treeReader.leaf_field,l=function(l,g,p){if(null!=p){l=a(p.target);p=l.closest("tr.jqgrow>td");
var n=p.parent(),r=function(a){a=b.data[b._index[u(b.idPrefix,a)]];var g=a[c]?"collapse":"expand";a[e]||(d[g+"Row"].call(f,a,n),d[g+"Node"].call(f,a,n))};l.is("div.treeclick")?r(g):b.ExpandColClick&&0<p.length&&0<l.closest("span.ui-jqgrid-cell-wrapper",p).length&&r(g);return!0}};f.unbind("jqGridBeforeSelectRow.setTreeNode",l);f.bind("jqGridBeforeSelectRow.setTreeNode",l)}})},setTreeGrid:function(){return this.each(function(){var d=this.p,b,c,e,f=[],m=["leaf_field","expanded_field","loaded"];if(d.treeGrid){d.treedatatype||
a.extend(this.p,{treedatatype:d.datatype});d.subGrid=!1;d.altRows=!1;d.pgbuttons=!1;d.pginput=!1;d.gridview=!0;null===d.rowTotal&&(d.rowNum=d.maxRowNum);d.rowList=[];d.treeIcons.plus="rtl"===d.direction?d.treeIcons.plusRtl:d.treeIcons.plusLtr;"nested"===d.treeGridModel?d.treeReader=a.extend({level_field:"level",left_field:"lft",right_field:"rgt",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},d.treeReader):"adjacency"===d.treeGridModel&&(d.treeReader=a.extend({level_field:"level",
parent_id_field:"parent",leaf_field:"isLeaf",expanded_field:"expanded",loaded:"loaded",icon_field:"icon"},d.treeReader));for(c in d.colModel)if(d.colModel.hasOwnProperty(c))for(e in b=d.colModel[c].name,d.treeReader)d.treeReader.hasOwnProperty(e)&&d.treeReader[e]===b&&f.push(b);a.each(d.treeReader,function(b){var c=String(this);c&&-1===a.inArray(c,f)&&(0<=a.inArray(b,m)?d.additionalProperties.push({name:c,convert:function(a){return!0===a||"true"===String(a).toLowerCase()||"1"===String(a)?!0:a}}):
d.additionalProperties.push(c))})}})},expandRow:function(h){this.each(function(){var b=a(this),c=this.p;if(this.grid&&c.treeGrid){var e=c.treeReader.expanded_field,l=h[c.localReader.id];if(f.call(this,"beforeExpandRow",{rowid:l,item:h})){var m=d.getNodeChildren.call(b,h);a(m).each(function(){var g=c.idPrefix+r(this,c.localReader.id);a(d.getGridRowById.call(b,g)).css("display","");this[e]&&d.expandRow.call(b,this)});f.call(this,"afterExpandRow",{rowid:l,item:h})}}})},collapseRow:function(h){this.each(function(){var b=
a(this),c=this.p;if(this.grid&&c.treeGrid){var e=c.treeReader.expanded_field,l=h[c.localReader.id];if(f.call(this,"beforeCollapseRow",{rowid:l,item:h})){var m=d.getNodeChildren.call(b,h);a(m).each(function(){var g=c.idPrefix+r(this,c.localReader.id);a(d.getGridRowById.call(b,g)).css("display","none");this[e]&&d.collapseRow.call(b,this)});f.call(this,"afterCollapseRow",{rowid:l,item:h})}}})},getRootNodes:function(){var d=[];this.each(function(){var b=this.p;if(this.grid&&b.treeGrid)switch(b.treeGridModel){case "nested":var c=
b.treeReader.level_field;a(b.data).each(function(){parseInt(this[c],10)===parseInt(b.tree_root_level,10)&&d.push(this)});break;case "adjacency":var e=b.treeReader.parent_id_field;a(b.data).each(function(){null!==this[e]&&"null"!==String(this[e]).toLowerCase()||d.push(this)})}});return d},getNodeDepth:function(f){var b=null;this.each(function(){var c=this.p;if(this.grid&&c.treeGrid)switch(c.treeGridModel){case "nested":b=parseInt(f[c.treeReader.level_field],10)-parseInt(c.tree_root_level,10);break;
case "adjacency":b=d.getNodeAncestors.call(a(this),f).length}});return b},getNodeParent:function(d){var b=this[0];if(!b||!b.grid||null==b.p||!b.p.treeGrid||null==d)return null;var b=b.p,c=b.treeReader,e=d[c.parent_id_field];if("nested"===b.treeGridModel){var f=null,m=c.left_field,g=c.right_field,p=c.level_field,n=parseInt(d[m],10),r=parseInt(d[g],10),q=parseInt(d[p],10);a(b.data).each(function(){if(parseInt(this[p],10)===q-1&&parseInt(this[m],10)<n&&parseInt(this[g],10)>r)return f=this,!1});return f}if(null===
e||"null"===e)return null;d=b._index[e];return void 0!=d?b.data[d]:null},getNodeChildren:function(d){var b=[];this.each(function(){var c=this.p;if(this.grid&&c.treeGrid)switch(c.treeGridModel){case "nested":var e=c.treeReader.left_field,f=c.treeReader.right_field,m=c.treeReader.level_field,g=parseInt(d[e],10),p=parseInt(d[f],10),n=parseInt(d[m],10);a(c.data).each(function(){parseInt(this[m],10)===n+1&&parseInt(this[e],10)>g&&parseInt(this[f],10)<p&&b.push(this)});break;case "adjacency":var r=c.treeReader.parent_id_field,
q=c.localReader.id;a(c.data).each(function(){String(this[r])===String(d[q])&&b.push(this)})}});return b},getFullTreeNode:function(d){var b=[];this.each(function(){var c=this.p,e;if(this.grid&&c.treeGrid)switch(c.treeGridModel){case "nested":var f=c.treeReader.left_field,m=c.treeReader.right_field,g=c.treeReader.level_field,p=parseInt(d[f],10),n=parseInt(d[m],10),r=parseInt(d[g],10);a(c.data).each(function(){parseInt(this[g],10)>=r&&parseInt(this[f],10)>=p&&parseInt(this[f],10)<=n&&b.push(this)});
break;case "adjacency":if(d){b.push(d);var q=c.treeReader.parent_id_field,u=c.localReader.id;a(c.data).each(function(){var a;e=b.length;for(a=0;a<e;a++)if(b[a][u]===this[q]){b.push(this);break}})}}});return b},getNodeAncestors:function(f){var b=[];this.each(function(){var c=a(this),e=d.getNodeParent;if(this.grid&&this.p.treeGrid)for(var l=e.call(c,f);l;)b.push(l),l=e.call(c,l)});return b},isVisibleNode:function(f){var b=!0;this.each(function(){var c=this.p;if(this.grid&&c.treeGrid){var e=d.getNodeAncestors.call(a(this),
f),l=c.treeReader.expanded_field;a(e).each(function(){b=b&&this[l];if(!b)return!1})}});return b},isNodeLoaded:function(f){var b;this.each(function(){var c=this.p;if(this.grid&&c.treeGrid){var e=c.treeReader.leaf_field,c=c.treeReader.loaded;b=void 0!==f?void 0!==f[c]?f[c]:f[e]||0<d.getNodeChildren.call(a(this),f).length?!0:!1:!1}});return b},expandNode:function(h){return this.each(function(){var b=this.p;if(this.grid&&b.treeGrid){var c=b.treeReader.expanded_field,e=b.treeReader.parent_id_field,l=b.treeReader.loaded,
m=b.treeReader.level_field,g=b.treeReader.left_field,p=b.treeReader.right_field;if(!h[c]){var w=r(h,b.localReader.id);if(f.call(this,"beforeExpandNode",{rowid:w,item:h})){var u=a("#"+b.idPrefix+n(w),this.grid.bDiv)[0],q=b._index[w];"local"===b.treedatatype||d.isNodeLoaded.call(a(this),b.data[q])?(h[c]=!0,a("div.treeclick",u).removeClass(b.treeIcons.plus+" tree-plus").addClass(b.treeIcons.commonIconClass).addClass(b.treeIcons.minus+" tree-minus")):this.grid.hDiv.loading||(h[c]=!0,a("div.treeclick",
u).removeClass(b.treeIcons.plus+" tree-plus").addClass(b.treeIcons.commonIconClass).addClass(b.treeIcons.minus+" tree-minus"),b.treeANode=u.rowIndex,b.datatype=b.treedatatype,d.setGridParam.call(a(this),{postData:"nested"===b.treeGridModel?{nodeid:w,n_level:h[m],n_left:h[g],n_right:h[p]}:{nodeid:w,n_level:h[m],parentid:h[e]}}),a(this).trigger("reloadGrid"),h[l]=!0,d.setGridParam.call(a(this),{postData:"nested"===b.treeGridModel?{nodeid:"",n_level:"",n_left:"",n_right:""}:{nodeid:"",n_level:"",parentid:""}}));
f.call(this,"afterExpandNode",{rowid:w,item:h})}}}})},collapseNode:function(d){return this.each(function(){var b=this.p;if(this.grid&&b.treeGrid){var c=b.treeReader.expanded_field;if(d[c]){var e=r(d,b.localReader.id);f.call(this,"beforeCollapseNode",{rowid:e,item:d})&&(d[c]=!1,c=a("#"+b.idPrefix+n(e),this.grid.bDiv)[0],a("div.treeclick",c).removeClass(b.treeIcons.minus+" tree-minus").addClass(b.treeIcons.commonIconClass).addClass(b.treeIcons.plus+" tree-plus"),f.call(this,"afterCollapseNode",{rowid:e,
item:d}))}}})},SortTree:function(f,b,c,e){return this.each(function(){var l=this,m=l.p,g=a(l);if(l.grid&&m.treeGrid){var t,u,A,q=[];t=d.getRootNodes.call(g);t=p.from.call(l,t);t.orderBy(f,b,c,e);var y=t.select();t=0;for(u=y.length;t<u;t++)A=y[t],q.push(A),d.collectChildrenSortTree.call(g,q,A,f,b,c,e);a.each(q,function(b){var c=r(this,m.localReader.id);a(l.rows[b]).after(g.find(">tbody>tr#"+n(c)))})}})},collectChildrenSortTree:function(f,b,c,e,l,m){return this.each(function(){var g=a(this);if(this.grid&&
this.p.treeGrid){var n,r,u;n=d.getNodeChildren.call(g,b);n=p.from.call(this,n);n.orderBy(c,e,l,m);var q=n.select();n=0;for(r=q.length;n<r;n++)u=q[n],f.push(u),d.collectChildrenSortTree.call(g,f,u,c,e,l,m)}})},setTreeRow:function(f,b){var c=!1;this.each(function(){this.grid&&this.p.treeGrid&&(c=d.setRowData.call(a(this),f,b))});return c},delTreeNode:function(f){return this.each(function(){var b=this.p,c,e,l,m;l=b.localReader.id;var g,n=a(this),r=b.treeReader.left_field,u=b.treeReader.right_field;if(this.grid&&
b.treeGrid&&(g=b._index[f],void 0!==g)){c=parseInt(b.data[g][u],10);e=c-parseInt(b.data[g][r],10)+1;var q=d.getFullTreeNode.call(n,b.data[g]);if(0<q.length)for(g=0;g<q.length;g++)d.delRowData.call(n,q[g][l]);if("nested"===b.treeGridModel){l=p.from.call(this,b.data).greater(r,c,{stype:"integer"}).select();if(l.length)for(m in l)l.hasOwnProperty(m)&&(l[m][r]=parseInt(l[m][r],10)-e);l=p.from.call(this,b.data).greater(u,c,{stype:"integer"}).select();if(l.length)for(m in l)l.hasOwnProperty(m)&&(l[m][u]=
parseInt(l[m][u],10)-e)}}})},addChildNode:function(f,b,c,e){var l=a(this),m=l[0],g=m.p,n=d.getInd;if(c){var r,u,q,y,E;r=0;var C=b,B,D,z=g.treeReader.expanded_field;D=g.treeReader.leaf_field;var v=g.treeReader.level_field,V=g.treeReader.parent_id_field,I=g.treeReader.left_field,G=g.treeReader.right_field,S=g.treeReader.loaded;void 0===e&&(e=!1);if(null==f){E=g.data.length-1;if(0<=E)for(;0<=E;)r=Math.max(r,parseInt(g.data[E][g.localReader.id],10)),E--;f=r+1}var U=n.call(l,b);B=!1;void 0===b||null===
b||""===b?(C=b=null,r="last",y=g.tree_root_level,E=g.data.length+1):(r="after",u=g._index[b],q=g.data[u],b=q[g.localReader.id],y=parseInt(q[v],10)+1,E=d.getFullTreeNode.call(l,q),E.length?(C=E=E[E.length-1][g.localReader.id],E=n.call(l,C)+1):E=n.call(l,b)+1,q[D]&&(B=!0,q[z]=!0,a(m.rows[U]).find("span.cell-wrapperleaf").removeClass("cell-wrapperleaf").addClass("cell-wrapper").end().find("div.tree-leaf").removeClass(g.treeIcons.leaf+" tree-leaf").addClass(g.treeIcons.commonIconClass).addClass(g.treeIcons.minus+
" tree-minus"),g.data[u][D]=!1,q[S]=!0));n=E+1;void 0===c[z]&&(c[z]=!1);void 0===c[S]&&(c[S]=!1);c[v]=y;void 0===c[D]&&(c[D]=!0);"adjacency"===g.treeGridModel&&(c[V]=b);if("nested"===g.treeGridModel){var F;if(null!==b){D=parseInt(q[G],10);g=p.from.call(m,g.data);g=g.greaterOrEquals(G,D,{stype:"integer"});v=g.select();if(v.length)for(F in v)v.hasOwnProperty(F)&&(v[F][I]=v[F][I]>D?parseInt(v[F][I],10)+2:v[F][I],v[F][G]=v[F][G]>=D?parseInt(v[F][G],10)+2:v[F][G]);c[I]=D;c[G]=D+1}else{D=parseInt(d.getCol.call(l,
G,!1,"max"),10);v=p.from.call(m,g.data).greater(I,D,{stype:"integer"}).select();if(v.length)for(F in v)v.hasOwnProperty(F)&&(v[F][I]=parseInt(v[F][I],10)+2);v=p.from.call(m,g.data).greater(G,D,{stype:"integer"}).select();if(v.length)for(F in v)v.hasOwnProperty(F)&&(v[F][G]=parseInt(v[F][G],10)+2);c[I]=D+1;c[G]=D+2}}if(null===b||d.isNodeLoaded.call(l,q)||B)d.addRowData.call(l,f,c,r,C),d.setTreeNode.call(l,E,n);q&&!q[z]&&e&&a(m.rows[U]).find("div.treeclick").click()}}})})(jQuery);
(function(a){var p="mousedown",r="mousemove",u="mouseup",n=function(a){var b=a.originalEvent.targetTouches;return b?(b=b[0],{x:b.pageX,y:b.pageY}):{x:a.pageX,y:a.pageY}},d={drag:function(a){var b=a.data,c=b.e,e=b.dnr,d=b.ar,b=b.dnrAr;a=n(a);"move"===e.k?c.css({left:e.X+a.x-e.pX,top:e.Y+a.y-e.pY}):(c.css({width:Math.max(a.x-e.pX+e.W,0),height:Math.max(a.y-e.pY+e.H,0)}),b&&d.css({width:Math.max(a.x-b.pX+b.W,0),height:Math.max(a.y-b.pY+b.H,0)}));return!1},stop:function(){a(document).unbind(r,d.drag).unbind(u,
d.stop)}},f=function(f,b,c,e){return f.each(function(){b=b?a(b,f):f;b.bind(p,{e:f,k:c},function(b){var c=b.data,g={},f,h,p=function(a,b){return parseInt(a.css(b),10)||!1},q=n(b);if(a(b.target).hasClass("ui-jqdialog-titlebar-close")||a(b.target).parent().hasClass("ui-jqdialog-titlebar-close"))a(b.target).click();else{b=c.e;h=e?a(e):!1;if("relative"!==b.css("position"))try{b.position(g)}catch(y){}f={X:g.left||p(b,"left")||0,Y:g.top||p(b,"top")||0,W:p(b,"width")||b[0].scrollWidth||0,H:p(b,"height")||
b[0].scrollHeight||0,pX:q.x,pY:q.y,k:c.k};g=h&&"move"!==c.k?{X:g.left||p(h,"left")||0,Y:g.top||p(h,"top")||0,W:h[0].offsetWidth||p(h,"width")||0,H:h[0].offsetHeight||p(h,"height")||0,pX:q.x,pY:q.y,k:c.k}:!1;c=b.find("input.hasDatepicker");if(0<c.length)try{c.datepicker("hide")}catch(E){}b={e:b,dnr:f,ar:h,dnrAr:g};a(document).bind(r,b,d.drag);a(document).bind(u,b,d.stop);return!1}})})};window.PointerEvent?(p+=".jqGrid pointerdown.jqGrid",r+=".jqGrid pointermove.jqGrid",u+=".jqGrid pointerup.jqGrid"):
window.MSPointerEvent?(p+=".jqGrid mspointerdown.jqGrid",r+=".jqGrid mspointermove.jqGrid",u+=".jqGrid mspointerup"):(p+=".jqGrid touchstart.jqGrid",r+=".jqGrid touchmove.jqGrid",u+=".jqGrid touchend.jqGrid");a.jqDnR=d;a.fn.jqDrag=function(a){return f(this,a,"move")};a.fn.jqResize=function(a,b){return f(this,a,"resize",b)}})(jQuery);
(function(a){var p=0,r,u=[],n=function(b){try{a(":input:visible",b.w).first().focus()}catch(c){}},d=function(b){var c=r[u[u.length-1]],e=!a(b.target).parents(".jqmID"+c.s)[0],d=a(b.target).offset(),f=void 0!==b.pageX?b.pageX:d.left,g=void 0!==b.pageY?b.pageY:d.top,d=function(){var b=!1;a(".jqmID"+c.s).each(function(){var c=a(this),e=c.offset();if(e.top<=g&&g<=e.top+c.height()&&e.left<=f&&f<=e.left+c.width())return b=!0,!1});return b};if("mousedown"!==b.type&&d())return!0;"mousedown"===b.type&&e&&
(d()&&(e=!1),e&&!a(b.target).is(":input")&&n(c));return!e},f=function(b){a(document)[b]("keypress keydown mousedown",d)},h=function(b,c,e){return b.each(function(){var b=this._jqm;a(c).each(function(){this[e]||(this[e]=[],a(this).click(function(){var a,b,c,e=["jqmShow","jqmHide"];for(a=0;a<e.length;a++)for(c in b=e[a],this[b])if(this[b].hasOwnProperty(c)&&r[this[b][c]])r[this[b][c]].w[b](this);return!1}));this[e].push(b)})})};a.fn.jqm=function(b){var c={overlay:50,closeoverlay:!1,overlayClass:"jqmOverlay",
closeClass:"jqmClose",trigger:".jqModal",ajax:!1,ajaxText:"",target:!1,modal:!1,toTop:!1,onShow:!1,onHide:!1,onLoad:!1};return this.each(function(){if(this._jqm)return r[this._jqm].c=a.extend({},r[this._jqm].c,b),r[this._jqm].c;p++;this._jqm=p;r[p]={c:a.extend(c,a.jqm.params,b),a:!1,w:a(this).addClass("jqmID"+p),s:p};c.trigger&&a(this).jqmAddTrigger(c.trigger)})};a.fn.jqmAddClose=function(a){return h(this,a,"jqmHide")};a.fn.jqmAddTrigger=function(a){return h(this,a,"jqmShow")};a.fn.jqmShow=function(b){return this.each(function(){a.jqm.open(this._jqm,
b)})};a.fn.jqmHide=function(b){return this.each(function(){a.jqm.close(this._jqm,b)})};a.jqm={hash:{},open:function(b,c){var e=r[b],d,h,g=e.c;d=e.w.parent().offset();var p,w="."+g.closeClass;h=parseInt(e.w.css("z-index"),10);h=0<h?h:3E3;d=a("<div></div>").css({height:"100%",width:"100%",position:"fixed",left:0,top:0,"z-index":h-1,opacity:g.overlay/100});if(e.a)return!1;e.t=c;e.a=!0;e.w.css("z-index",h);g.modal?(u[0]||setTimeout(function(){f("bind")},1),u.push(b)):0<g.overlay?g.closeoverlay&&e.w.jqmAddClose(d):
d=!1;e.o=d?d.addClass(g.overlayClass).prependTo("body"):!1;g.ajax?(d=g.target||e.w,h=g.ajax,d="string"===typeof d?a(d,e.w):a(d),h="@"===h.substr(0,1)?a(c).attr(h.substring(1)):h,d.html(g.ajaxText).load(h,function(){g.onLoad&&g.onLoad.call(this,e);w&&e.w.jqmAddClose(a(w,e.w));n(e)})):w&&e.w.jqmAddClose(a(w,e.w));g.toTop&&e.o&&(d=e.w.parent().offset(),h=parseFloat(e.w.css("left")||0),p=parseFloat(e.w.css("top")||0),e.w.before('<span id="jqmP'+e.w[0]._jqm+'"></span>').insertAfter(e.o),e.w.css({top:d.top+
p,left:d.left+h}));if(g.onShow)g.onShow(e);else e.w.show();n(e);return!1},close:function(b){b=r[b];if(!b.a)return!1;b.a=!1;u[0]&&(u.pop(),u[0]||f("unbind"));b.c.toTop&&b.o&&a("#jqmP"+b.w[0]._jqm).after(b.w).remove();if(b.c.onHide)b.c.onHide(b);else b.w.hide(),b.o&&b.o.remove();return!1},params:{}};r=a.jqm.hash})(jQuery);
(function(a){a.fmatter=a.fmatter||{};a.jgrid=a.jgrid||{};var p=a.fmatter,r=a.jgrid,u=r.getMethod("getGridRes");a.extend(!0,r,{formatter:{date:{parseRe:/[#%\\\/:_;.,\t\s\-]/,masks:{ISO8601Long:"Y-m-d H:i:s",ISO8601Short:"Y-m-d",SortableDateTime:"Y-m-d\\TH:i:s",UniversalSortableDateTime:"Y-m-d H:i:sO"},reformatAfterEdit:!0,userLocalTime:!1},baseLinkUrl:"",showAction:"",target:"",checkbox:{disabled:!0},idName:"id"},cmTemplate:{integerStr:{formatter:"integer",align:"right",sorttype:"integer",searchoptions:{sopt:"eq ne lt le gt ge".split(" ")}},
integer:{formatter:"integer",align:"right",sorttype:"integer",convertOnSave:function(a){a=a.newValue;return isNaN(a)?a:parseInt(a,10)},searchoptions:{sopt:"eq ne lt le gt ge".split(" ")}},numberStr:{formatter:"number",align:"right",sorttype:"number",searchoptions:{sopt:"eq ne lt le gt ge".split(" ")}},number:{formatter:"number",align:"right",sorttype:"number",convertOnSave:function(a){a=a.newValue;return isNaN(a)?a:parseFloat(a)},searchoptions:{sopt:"eq ne lt le gt ge".split(" ")}},booleanCheckbox:{align:"center",
formatter:"checkbox",edittype:"checkbox",editoptions:{value:"true:false",defaultValue:"false"},convertOnSave:function(b){var e=b.newValue,d=b.cm;b=String(e).toLowerCase();d=null!=d.editoptions&&"string"===typeof d.editoptions.value?d.editoptions.value.split(":"):["yes","no"];0<=a.inArray(b,["1","true",d[0].toLowerCase()])?e=!0:0<=a.inArray(b,["0","false",d[1].toLowerCase()])&&(e=!1);return e},stype:"select",searchoptions:{sopt:["eq","ne"],value:":Any;true:Yes;false:No"}},booleanCheckboxFa:{align:"center",
formatter:"checkboxFontAwesome4",edittype:"checkbox",editoptions:{value:"true:false",defaultValue:"false"},convertOnSave:function(b){var e=b.newValue,d=b.cm;b=String(e).toLowerCase();d=null!=d.editoptions&&"string"===typeof d.editoptions.value?d.editoptions.value.split(":"):["yes","no"];0<=a.inArray(b,["1","true",d[0].toLowerCase()])?e=!0:0<=a.inArray(b,["0","false",d[1].toLowerCase()])&&(e=!1);return e},stype:"select",searchoptions:{sopt:["eq","ne"],value:":Any;true:Yes;false:No"}},actions:function(){return{formatter:"actions",
width:(null!=this.p&&this.p.fontAwesomeIcons?33:36)+(r.cellWidth()?5:0),align:"center",label:"",autoResizable:!1,frozen:!0,fixed:!0,hidedlg:!0,resizable:!1,sortable:!1,search:!1,editable:!1,viewable:!1}}}});a.extend(p,{isObject:function(b){return b&&("object"===typeof b||a.isFunction(b))||!1},isNumber:function(a){return"number"===typeof a&&isFinite(a)},isValue:function(a){return this.isObject(a)||"string"===typeof a||this.isNumber(a)||"boolean"===typeof a},isEmpty:function(b){if("string"!==typeof b&&
this.isValue(b))return!1;if(!this.isValue(b))return!0;b=a.trim(b).replace(/\ \;/ig,"").replace(/\ \;/ig,"");return""===b},NumberFormat:function(a,b){var d=p.isNumber;d(a)||(a*=1);if(d(a)){var f=0>a,g=String(a),h=b.decimalSeparator||".";if(d(b.decimalPlaces)){var n=b.decimalPlaces,g=Math.pow(10,n),g=String(Math.round(a*g)/g),d=g.lastIndexOf(".");if(0<n)for(0>d?(g+=h,d=g.length-1):"."!==h&&(g=g.replace(".",h));g.length-1-d<n;)g+="0"}if(b.thousandsSeparator){var n=b.thousandsSeparator,d=g.lastIndexOf(h),
d=-1<d?d:g.length,h=void 0===b.decimalSeparator?"":g.substring(d),r=-1,q;for(q=d;0<q;q--)r++,0===r%3&&q!==d&&(!f||1<q)&&(h=n+h),h=g.charAt(q-1)+h;g=h}return g}return a}});var n=function(b,e,d,f,g){var h=e;d=a.extend({},u.call(a(this),"formatter"),d);try{h=a.fn.fmatter[b].call(this,e,d,f,g)}catch(p){}return h};a.fn.fmatter=n;n.getCellBuilder=function(b,e,d){b=null!=a.fn.fmatter[b]?a.fn.fmatter[b].getCellBuilder:null;return a.isFunction(b)?b.call(this,a.extend({},u.call(a(this),"formatter"),e),d):null};
n.defaultFormat=function(a,b){return p.isValue(a)&&""!==a?a:b.defaultValue||" "};var d=n.defaultFormat;n.email=function(a,b){return p.isEmpty(a)?d(a,b):'<a href="mailto:'+a+'">'+a+"</a>"};n.checkbox=function(b,e){var f=e.colModel,h=a.extend({},e.checkbox);null!=f&&(h=a.extend({},h,f.formatoptions||{}));f=!0===h.disabled?'disabled="disabled"':"";if(p.isEmpty(b)||void 0===b)b=d(b,h);b=String(b);b=String(b).toLowerCase();return'<input type="checkbox" '+(0>b.search(/(false|f|0|no|n|off|undefined)/i)?
" checked='checked' ":"")+' value="'+b+'" data-offval="no" '+f+"/>"};n.checkbox.getCellBuilder=function(b){var e=b.colModel,f=a.extend({},b.checkbox),h;null!=e&&(f=a.extend({},f,e.formatoptions||{}));h='" data-offval="no" '+(!0===f.disabled?'disabled="disabled"':"")+"/>";return function(a){if(p.isEmpty(a)||void 0===a)a=d(a,f);a=String(a).toLowerCase();return'<input type="checkbox" '+(0>a.search(/(false|f|0|no|n|off|undefined)/i)?" checked='checked' ":"")+' value="'+a+h}};n.checkboxFontAwesome4=function(a,
b){var d=b.colModel,f=!1!==d.title?' title="'+(b.colName||d.label||d.name)+'"':"",g=String(a).toLowerCase(),d=d.editoptions||{},d="string"===typeof d.value?d.value.split(":")[0]:"yes";return 1===a||"1"===g||"x"===g||!0===a||"true"===g||"yes"===g||g===d?'<i class="fa fa-check-square-o fa-lg"'+f+"></i>":'<i class="fa fa-square-o fa-lg"'+f+"></i>"};n.checkboxFontAwesome4.getCellBuilder=function(a){var b=a.colModel;a=!1!==b.title?' title="'+(a.colName||b.label||b.name)+'"':"";var b=b.editoptions||{},
d="string"===typeof b.value?b.value.split(":")[0]:"yes",f='<i class="fa fa-check-square-o fa-lg"'+a+"></i>",g='<i class="fa fa-square-o fa-lg"'+a+"></i>";return function(a){var b=String(a).toLowerCase();return!0===a||1===a||"1"===b||"x"===b||"true"===b||"yes"===b||b===d?f:g}};n.checkboxFontAwesome4.unformat=function(b,d,f){b=d.colModel.editoptions||{};b="string"===typeof b.value?b.value.split(":"):["Yes","No"];return a(">i",f).hasClass("fa-check-square-o")?b[0]:b[1]};n.link=function(b,e){var f=e.colModel,
h="",g={target:e.target};null!=f&&(g=a.extend({},g,f.formatoptions||{}));g.target&&(h="target="+g.target);return p.isEmpty(b)?d(b,g):"<a "+h+' href="'+b+'">'+b+"</a>"};n.showlink=function(b,e,f){var h=this,g=e.colModel,n={baseLinkUrl:e.baseLinkUrl,showAction:e.showAction,addParam:e.addParam||"",target:e.target,idName:e.idName,hrefDefaultValue:"#"},r="",u,q,y=function(d){return a.isFunction(d)?d.call(h,{cellValue:b,rowid:e.rowId,rowData:f,options:n}):d||""};null!=g&&(n=a.extend({},n,g.formatoptions||
{}));n.target&&(r="target="+y(n.target));g=y(n.baseLinkUrl)+y(n.showAction);u=n.idName?encodeURIComponent(y(n.idName))+"="+encodeURIComponent(y(n.rowId)||e.rowId):"";q=y(n.addParam);"object"===typeof q&&null!==q&&(q=(""!==u?"&":"")+a.param(q));g+=u||q?"?"+u+q:"";""===g&&(g=y(n.hrefDefaultValue));return"string"===typeof b||p.isNumber(b)||a.isFunction(n.cellValue)?"<a "+r+' href="'+g+'">'+(a.isFunction(n.cellValue)?y(n.cellValue):b)+"</a>":d(b,n)};n.showlink.getCellBuilder=function(b){var e={baseLinkUrl:b.baseLinkUrl,
showAction:b.showAction,addParam:b.addParam||"",target:b.target,idName:b.idName,hrefDefaultValue:"#"};b=b.colModel;null!=b&&(e=a.extend({},e,b.formatoptions||{}));return function(b,c,f){var h=this,n=c.rowId,r="",q,u,E=function(c){return a.isFunction(c)?c.call(h,{cellValue:b,rowid:n,rowData:f,options:e}):c||""};e.target&&(r="target="+E(e.target));q=E(e.baseLinkUrl)+E(e.showAction);c=e.idName?encodeURIComponent(E(e.idName))+"="+encodeURIComponent(E(n)||c.rowId):"";u=E(e.addParam);"object"===typeof u&&
null!==u&&(u=(""!==c?"&":"")+a.param(u));q+=c||u?"?"+c+u:"";""===q&&(q=E(e.hrefDefaultValue));return"string"===typeof b||p.isNumber(b)||a.isFunction(e.cellValue)?"<a "+r+' href="'+q+'">'+(a.isFunction(e.cellValue)?E(e.cellValue):b)+"</a>":d(b,e)}};n.showlink.pageFinalization=function(b){var d=a(this),f=this.p,h=f.colModel[b],g,p=this.rows,n=p.length,r,q=function(f){var g=a(this).closest(".jqgrow");if(0<g.length)return h.formatoptions.onClick.call(d[0],{iCol:b,iRow:g[0].rowIndex,rowid:g.attr("id"),
cm:h,cmName:h.name,cellValue:a(this).text(),a:this,event:f})};if(null!=h.formatoptions&&a.isFunction(h.formatoptions.onClick))for(g=0;g<n;g++)r=p[g],a(r).hasClass("jqgrow")&&(r=r.cells[b],h.autoResizable&&null!=r&&a(r.firstChild).hasClass(f.autoResizing.wrapperClassName)&&(r=r.firstChild),a(r.firstChild).bind("click",q))};var f=function(a,b){a=b.prefix?b.prefix+a:a;return b.suffix?a+b.suffix:a},h=function(b,d,h){var m=d.colModel;d=a.extend({},d[h]);null!=m&&(d=a.extend({},d,m.formatoptions||{}));
return p.isEmpty(b)?f(d.defaultValue,d):f(p.NumberFormat(b,d),d)};n.integer=function(a,b){return h(a,b,"integer")};n.number=function(a,b){return h(a,b,"number")};n.currency=function(a,b){return h(a,b,"currency")};var b=function(b,d){var h=b.colModel,m=a.extend({},b[d]);null!=h&&(m=a.extend({},m,h.formatoptions||{}));var g=p.NumberFormat,n=m.defaultValue?f(m.defaultValue,m):"";return function(a){return p.isEmpty(a)?n:f(g(a,m),m)}};n.integer.getCellBuilder=function(a){return b(a,"integer")};n.number.getCellBuilder=
function(a){return b(a,"number")};n.currency.getCellBuilder=function(a){return b(a,"currency")};n.date=function(b,e,f,h){f=e.colModel;e=a.extend({},e.date);null!=f&&(e=a.extend({},e,f.formatoptions||{}));return e.reformatAfterEdit||"edit"!==h?p.isEmpty(b)?d(b,e):r.parseDate.call(this,e.srcformat,b,e.newformat,e):d(b,e)};n.date.getCellBuilder=function(b,e){var f=a.extend({},b.date);null!=b.colModel&&(f=a.extend({},f,b.colModel.formatoptions||{}));var h=r.parseDate,g=f.srcformat,n=f.newformat;return f.reformatAfterEdit||
"edit"!==e?function(a){return p.isEmpty(a)?d(a,f):h.call(this,g,a,n,f)}:function(a){return d(a,f)}};n.select=function(b,e){var f=[],h=e.colModel,g,h=a.extend({},h.editoptions||{},h.formatoptions||{}),n=h.value,r=h.separator||":",u=h.delimiter||";";if(n){var q=!0===h.multiple?!0:!1,y=[],E=function(a,b){if(0<b)return a};q&&(y=a.map(String(b).split(","),function(b){return a.trim(b)}));if("string"===typeof n){var C=n.split(u),B,D;for(B=0;B<C.length;B++)if(u=C[B].split(r),2<u.length&&(u[1]=a.map(u,E).join(r)),
D=a.trim(u[0]),h.defaultValue===D&&(g=u[1]),q)-1<a.inArray(D,y)&&f.push(u[1]);else if(D===a.trim(b)){f=[u[1]];break}}else p.isObject(n)&&(g=n[h.defaultValue],f=q?a.map(y,function(a){return n[a]}):[void 0===n[b]?"":n[b]])}b=f.join(", ");return""!==b?b:void 0!==h.defaultValue?g:d(b,h)};n.select.getCellBuilder=function(b){b=b.colModel;var d=n.defaultFormat,f=a.extend({},b.editoptions||{},b.formatoptions||{}),h=f.value;b=f.separator||":";var g=f.delimiter||";",t,r=void 0!==f.defaultValue,u=!0===f.multiple?
!0:!1,q,y={},E=function(a,b){if(0<b)return a};if("string"===typeof h)for(h=h.split(g),g=h.length,q=g-1;0<=q;q--)g=h[q].split(b),2<g.length&&(g[1]=a.map(g,E).join(b)),y[a.trim(g[0])]=g[1];else if(p.isObject(h))y=h;else return function(a){return a?String(a):d(a,f)};r&&(t=y[f.defaultValue]);return u?function(b){var c=[],g,h=a.map(String(b).split(","),function(b){return a.trim(b)});for(g=0;g<h.length;g++)b=h[g],y.hasOwnProperty(b)&&c.push(y[b]);b=c.join(", ");return""!==b?b:r?t:d(b,f)}:function(a){var b=
y[String(a)];return""!==b&&void 0!==b?b:r?t:d(a,f)}};n.rowactions=function(b,d){var f=a(this).closest("tr.jqgrow"),h=f.attr("id"),g=a(this).closest("table.ui-jqgrid-btable").attr("id").replace(/_frozen([^_]*)$/,"$1"),n=a("#"+r.jqID(g)),g=n[0],p=g.p,u=p.colModel[r.getCellIndex(this)],u=a.extend(!0,{extraparam:{}},r.actionsNav||{},p.actionsNavOptions||{},u.formatoptions||{});void 0!==p.editOptions&&(u.editOptions=p.editOptions);void 0!==p.delOptions&&(u.delOptions=p.delOptions);f.hasClass("jqgrid-new-row")&&
(u.extraparam[p.prmNames.oper]=p.prmNames.addoper);var q={keys:u.keys,oneditfunc:u.onEdit,successfunc:u.onSuccess,url:u.url,extraparam:u.extraparam,aftersavefunc:u.afterSave,errorfunc:u.onError,afterrestorefunc:u.afterRestore,restoreAfterError:u.restoreAfterError,mtype:u.mtype};!p.multiselect&&h!==p.selrow||p.multiselect&&0>a.inArray(h,p.selarrrow)?n.jqGrid("setSelection",h,!0,b):r.fullBoolFeedback.call(g,"onSelectRow","jqGridSelectRow",h,!0,b);switch(d){case "edit":n.jqGrid("editRow",h,q);break;
case "save":n.jqGrid("saveRow",h,q);break;case "cancel":n.jqGrid("restoreRow",h,u.afterRestore);break;case "del":u.delOptions=u.delOptions||{};void 0===u.delOptions.top&&(u.delOptions.top=f.offset().top+f.outerHeight()-n.closest(".ui-jqgrid").offset().top);n.jqGrid("delGridRow",h,u.delOptions);break;case "formedit":u.editOptions=u.editOptions||{};void 0===u.editOptions.top&&(u.editOptions.top=f.offset().top+f.outerHeight()-n.closest(".ui-jqgrid").offset().top,u.editOptions.recreateForm=!0);n.jqGrid("editGridRow",
h,u.editOptions);break;default:if(null!=u.custom&&0<u.custom.length)for(n=u.custom.length,f=0;f<n;f++)p=u.custom[f],p.action===d&&a.isFunction(p.onClick)&&p.onClick.call(g,{rowid:h,event:b,action:d,options:p})}b.stopPropagation&&b.stopPropagation();return!1};n.actions=function(b,d,f,h){b=d.rowId;var g="",n=this.p,w=a(this),A={},q=u.call(w,"edit")||{},w=a.extend({editbutton:!0,delbutton:!0,editformbutton:!1,commonIconClass:"ui-icon",editicon:"ui-icon-pencil",delicon:"ui-icon-trash",saveicon:"ui-icon-disk",
cancelicon:"ui-icon-cancel",savetitle:q.bSubmit||"",canceltitle:q.bCancel||""},u.call(w,"nav")||{},r.nav||{},n.navOptions||{},u.call(w,"actionsNav")||{},r.actionsNav||{},n.actionsNavOptions||{},d.colModel.formatoptions||{}),q=r.mergeCssClasses,n=q(r.getRes(r.guiStyles[n.guiStyle],"states.hover")),n="onmouseover=jQuery(this).addClass('"+n+"'); onmouseout=jQuery(this).removeClass('"+n+"'); ",y=[{action:"edit",actionName:"formedit",display:w.editformbutton},{action:"edit",display:!w.editformbutton&&
w.editbutton},{action:"del",idPrefix:"Delete",display:w.delbutton},{action:"save",display:w.editformbutton||w.editbutton,hidden:!0},{action:"cancel",display:w.editformbutton||w.editbutton,hidden:!0}],E=null!=w.custom?w.custom.length-1:-1;if(void 0===b||p.isEmpty(b))return"";if(a.isFunction(w.isDisplayButtons))try{A=w.isDisplayButtons.call(this,d,f,h)||{}}catch(C){}for(;0<=E;)d=w.custom[E--],y["first"===d.position?"unshift":"push"](d);d=0;for(E=y.length;d<E;d++)if(f=a.extend({},y[d],A[y[d].action]||
{}),!1!==f.display){h=f.action;var B=f.actionName||h,D=void 0!==f.idPrefix?f.idPrefix:h.charAt(0).toUpperCase()+h.substring(1);f="<div title='"+w[h+"title"]+(f.hidden?"' style='display:none;":"")+"' class='ui-pg-div ui-inline-"+h+"' "+(null!==D?"id='j"+D+"Button_"+b:"")+"' onclick=\"return jQuery.fn.fmatter.rowactions.call(this,event,'"+B+"');\" "+(f.noHovering?"":n)+"><span class='"+q(w.commonIconClass,w[h+"icon"])+"'></span></div>";g+=f}return"<div class='ui-jqgrid-actions'>"+g+"</div>"};n.actions.pageFinalization=
function(b){var d=a(this),f=this.p,h=f.colModel,g=h[b],n=function(n,p){var u=0,t,r;t=h.length;for(r=0;r<t&&!0===h[r].frozen;r++)u=r;t=d.jqGrid("getGridRowById",p);null!=t&&null!=t.cells&&(b=f.iColByName[g.name],r=a(t.cells[b]).children(".ui-jqgrid-actions"),g.frozen&&f.frozenColumns&&b<=u&&(r=r.add(a(d[0].grid.fbRows[t.rowIndex].cells[b]).children(".ui-jqgrid-actions"))),n?(r.find(">.ui-inline-edit,>.ui-inline-del").show(),r.find(">.ui-inline-save,>.ui-inline-cancel").hide()):(r.find(">.ui-inline-edit,>.ui-inline-del").hide(),
r.find(">.ui-inline-save,>.ui-inline-cancel").show()))},p=function(a,b){n(!0,b);return!1},u=function(a,b){n(!1,b);return!1};null!=g.formatoptions&&g.formatoptions.editformbutton||(d.unbind("jqGridInlineAfterRestoreRow.jqGridFormatter jqGridInlineAfterSaveRow.jqGridFormatter",p),d.bind("jqGridInlineAfterRestoreRow.jqGridFormatter jqGridInlineAfterSaveRow.jqGridFormatter",p),d.unbind("jqGridInlineEditRow.jqGridFormatter",u),d.bind("jqGridInlineEditRow.jqGridFormatter",u))};a.unformat=function(b,d,f,
h){var g,p=d.colModel,w=p.formatter,A=this.p,q=p.formatoptions||{},y=p.unformat||n[w]&&n[w].unformat;b instanceof jQuery&&0<b.length&&(b=b[0]);A.treeGrid&&null!=b&&a(b.firstChild).hasClass("tree-wrap")&&(a(b.lastChild).hasClass("cell-wrapper")||a(b.lastChild).hasClass("cell-wrapperleaf"))&&(b=b.lastChild);p.autoResizable&&null!=b&&a(b.firstChild).hasClass(A.autoResizing.wrapperClassName)&&(b=b.firstChild);if(void 0!==y&&a.isFunction(y))g=y.call(this,a(b).text(),d,b);else if(void 0!==w&&"string"===
typeof w){var E=a(this),C=function(a,b){return void 0!==q[b]?q[b]:u.call(E,"formatter."+a+"."+b)},A=function(a,b){var c=C(a,"thousandsSeparator").replace(/([\.\*\_\'\(\)\{\}\+\?\\])/g,"\\$1");return b.replace(new RegExp(c,"g"),"")};switch(w){case "integer":g=A("integer",a(b).text());break;case "number":g=A("number",a(b).text()).replace(C("number","decimalSeparator"),".");break;case "currency":g=a(b).text();d=C("currency","prefix");f=C("currency","suffix");d&&d.length&&(g=g.substr(d.length));f&&f.length&&
(g=g.substr(0,g.length-f.length));g=A("number",g).replace(C("number","decimalSeparator"),".");break;case "checkbox":g=null!=p.editoptions&&"string"===typeof p.editoptions.value?p.editoptions.value.split(":"):["Yes","No"];g=a("input",b).is(":checked")?g[0]:g[1];break;case "select":g=a.unformat.select(b,d,f,h);break;case "actions":return"";default:g=a(b).text()}}return g=void 0!==g?g:!0===h?a(b).text():r.htmlDecode(a(b).html())};a.unformat.select=function(b,d,f,h){f=[];b=a(b).text();d=d.colModel;if(!0===
h)return b;d=a.extend({},d.editoptions||{},d.formatoptions||{});h=void 0===d.separator?":":d.separator;var g=void 0===d.delimiter?";":d.delimiter;if(d.value){var n=d.value;d=!0===d.multiple?!0:!1;var r=[],u=function(a,b){if(0<b)return a};d&&(r=b.split(","),r=a.map(r,function(b){return a.trim(b)}));if("string"===typeof n){var q=n.split(g),y=0,E;for(E=0;E<q.length;E++)if(g=q[E].split(h),2<g.length&&(g[1]=a.map(g,u).join(h)),d)-1<a.inArray(a.trim(g[1]),r)&&(f[y]=g[0],y++);else if(a.trim(g[1])===a.trim(b)){f[0]=
g[0];break}}else if(p.isObject(n)||a.isArray(n))d||(r[0]=b),f=a.map(r,function(b){var c;a.each(n,function(a,d){if(d===b)return c=a,!1});if(void 0!==c)return c});return f.join(", ")}return b||""};a.unformat.date=function(b,d){var f=a.extend(!0,{},u.call(a(this),"formatter.date"),r.formatter.date||{},d.formatoptions||{});return p.isEmpty(b)?"":r.parseDate.call(this,f.newformat,b,f.srcformat,f)}})(jQuery);
(function(){window.xmlJsonClass={xml2json:function(a,p){9===a.nodeType&&(a=a.documentElement);var r=this.removeWhite(a),r=this.toObj(r),r=this.toJson(r,a.nodeName,"\t");return"{\n"+p+(p?r.replace(/\t/g,p):r.replace(/\t|\n/g,""))+"\n}"},json2xml:function(a,p){var r=function(a,f,h){var b="",c,e,l;if(a instanceof Array)if(0===a.length)b+=h+"<"+f+">__EMPTY_ARRAY_</"+f+">\n";else for(c=0,e=a.length;c<e;c+=1)l=h+r(a[c],f,h+"\t")+"\n",b+=l;else if("object"===typeof a){c=!1;b+=h+"<"+f;for(e in a)a.hasOwnProperty(e)&&
("@"===e.charAt(0)?b+=" "+e.substr(1)+'="'+a[e].toString()+'"':c=!0);b+=c?">":"/>";if(c){for(e in a)a.hasOwnProperty(e)&&("#text"===e?b+=a[e]:"#cdata"===e?b+="<![CDATA["+a[e]+"]]\x3e":"@"!==e.charAt(0)&&(b+=r(a[e],e,h+"\t")));b+=("\n"===b.charAt(b.length-1)?h:"")+"</"+f+">"}}else"function"===typeof a?b+=h+"<"+f+"><![CDATA["+a+"]]\x3e</"+f+">":(void 0===a&&(a=""),b='""'===a.toString()||0===a.toString().length?b+(h+"<"+f+">__EMPTY_STRING_</"+f+">"):b+(h+"<"+f+">"+a.toString()+"</"+f+">"));return b},
u="",n;for(n in a)a.hasOwnProperty(n)&&(u+=r(a[n],n,""));return p?u.replace(/\t/g,p):u.replace(/\t|\n/g,"")},toObj:function(a){var p={},r=/function/i,u,n=0,d=0,f=!1;if(1===a.nodeType){if(a.attributes.length)for(u=0;u<a.attributes.length;u+=1)p["@"+a.attributes[u].nodeName]=(a.attributes[u].nodeValue||"").toString();if(a.firstChild){for(u=a.firstChild;u;u=u.nextSibling)1===u.nodeType?f=!0:3===u.nodeType&&u.nodeValue.match(/[^ \f\n\r\t\v]/)?n+=1:4===u.nodeType&&(d+=1);if(f)if(2>n&&2>d)for(this.removeWhite(a),
u=a.firstChild;u;u=u.nextSibling)3===u.nodeType?p["#text"]=this.escape(u.nodeValue):4===u.nodeType?r.test(u.nodeValue)?p[u.nodeName]=[p[u.nodeName],u.nodeValue]:p["#cdata"]=this.escape(u.nodeValue):p[u.nodeName]?p[u.nodeName]instanceof Array?p[u.nodeName][p[u.nodeName].length]=this.toObj(u):p[u.nodeName]=[p[u.nodeName],this.toObj(u)]:p[u.nodeName]=this.toObj(u);else a.attributes.length?p["#text"]=this.escape(this.innerXml(a)):p=this.escape(this.innerXml(a));else if(n)a.attributes.length?p["#text"]=
this.escape(this.innerXml(a)):(p=this.escape(this.innerXml(a)),"__EMPTY_ARRAY_"===p?p="[]":"__EMPTY_STRING_"===p&&(p=""));else if(d)if(1<d)p=this.escape(this.innerXml(a));else for(u=a.firstChild;u;u=u.nextSibling){if(r.test(a.firstChild.nodeValue)){p=a.firstChild.nodeValue;break}p["#cdata"]=this.escape(u.nodeValue)}}a.attributes.length||a.firstChild||(p=null)}else 9===a.nodeType?p=this.toObj(a.documentElement):alert("unhandled node type: "+a.nodeType);return p},toJson:function(a,p,r,u){void 0===u&&
(u=!0);var n=p?'"'+p+'"':"",d="\t",f="\n",h,b,c=[];h=[];u||(f=d="");if("[]"===a)n+=p?":[]":"[]";else if(a instanceof Array){b=0;for(h=a.length;b<h;b+=1)c[b]=this.toJson(a[b],"",r+d,u);n+=(p?":[":"[")+(1<c.length?f+r+d+c.join(","+f+r+d)+f+r:c.join(""))+"]"}else if(null===a)n+=(p&&":")+"null";else if("object"===typeof a){for(b in a)a.hasOwnProperty(b)&&(h[h.length]=this.toJson(a[b],b,r+d,u));n+=(p?":{":"{")+(1<h.length?f+r+d+h.join(","+f+r+d)+f+r:h.join(""))+"}"}else n="string"===typeof a?n+((p&&":")+
'"'+a.replace(/\\/g,"\\\\").replace(/\"/g,'\\"')+'"'):n+((p&&":")+a.toString());return n},innerXml:function(a){var p="",r=function(a){var n="",d;if(1===a.nodeType){n+="<"+a.nodeName;for(d=0;d<a.attributes.length;d+=1)n+=" "+a.attributes[d].nodeName+'="'+(a.attributes[d].nodeValue||"").toString()+'"';if(a.firstChild){n+=">";for(d=a.firstChild;d;d=d.nextSibling)n+=r(d);n+="</"+a.nodeName+">"}else n+="/>"}else 3===a.nodeType?n+=a.nodeValue:4===a.nodeType&&(n+="<![CDATA["+a.nodeValue+"]]\x3e");return n};
if(a.hasOwnProperty("innerHTML"))p=a.innerHTML;else for(a=a.firstChild;a;a=a.nextSibling)p+=r(a);return p},escape:function(a){return a.replace(/[\\]/g,"\\\\").replace(/[\"]/g,'\\"').replace(/[\n]/g,"\\n").replace(/[\r]/g,"\\r")},removeWhite:function(a){a.normalize();for(var p=a.firstChild,r;p;)3===p.nodeType?p.nodeValue.match(/[^ \f\n\r\t\v]/)?p=p.nextSibling:(r=p.nextSibling,a.removeChild(p),p=r):(1===p.nodeType&&this.removeWhite(p),p=p.nextSibling);return a}}})();
//@ sourceMappingURL=jquery.jqgrid.min.map
|
// TinyMCE helper, checks to see if TinyMCE editors in the given form are dirty
// Support for UMD: https://github.com/umdjs/umd/blob/master/jqueryPluginCommonjs.js
// This allows for tools such as Browserify to compose the components together into a single HTTP request.
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
// Create a new object, with an isDirty method
var tinymce = {
ignoreAnchorSelector: '.mceEditor a,.mceMenu a',
isDirty: function (form) {
var isDirty = false;
if (formHasTinyMCE(form)) {
//..alert('in finder');
// Search for all tinymce elements inside the given form
$(form).find(':tinymce').each(function () {
$.DirtyForms.dirtylog('Checking node ' + $(this).attr('id'));
if ($(this).tinymce().isDirty()) {
isDirty = true;
$.DirtyForms.dirtylog('Node was totally dirty.');
// Return false to break out of the .each() function
return false;
}
});
}
return isDirty;
},
setClean: function (form) {
if (formHasTinyMCE(form)) {
// Search for all tinymce elements inside the given form
$(form).find(':tinymce').each(function () {
if ($(this).tinymce().isDirty()) {
$.DirtyForms.dirtylog('Resetting isDirty on node ' + $(this).attr('id'));
$(this).tinymce().isNotDirty = 1; //Force not dirty state
}
});
}
}
};
// Fix: tinymce throws an error if the selector doesn't match anything
// (such as when there are no textareas on the current page)
var formHasTinyMCE = function (form) {
try {
return $(form).find(':tinymce').length > 0;
}
catch (e) {
return false;
}
};
// Push the new object onto the helpers array
$.DirtyForms.helpers.push(tinymce);
// Create a pre refire binding to trigger the tinymce save
//$(document).bind('beforeRefire.dirtyforms', function(){
// This is no longer needed, but kept here to remind me.
// tinyMCE.triggerSave();
//});
}));
|
/**
* @fileoverview A rule to disallow negated left operands of the `in` operator
* @author Michael Ficarra
* @deprecated in ESLint v3.3.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow negating the left operand in `in` expressions",
category: "Possible Errors",
recommended: true,
replacedBy: ["no-unsafe-negation"]
},
deprecated: true,
schema: []
},
create(context) {
return {
BinaryExpression(node) {
if (node.operator === "in" && node.left.type === "UnaryExpression" && node.left.operator === "!") {
context.report({ node, message: "The 'in' expression's left operand is negated." });
}
}
};
}
};
|
module.exports = function (obj, opts) {
if (!opts) opts = {};
if (typeof opts === 'function') opts = { cmp: opts };
var space = opts.space || '';
if (typeof space === 'number') space = Array(space+1).join(' ');
var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
var replacer = opts.replacer || function(key, value) { return value; };
var cmp = opts.cmp && (function (f) {
return function (node) {
return function (a, b) {
var aobj = { key: a, value: node[a] };
var bobj = { key: b, value: node[b] };
return f(aobj, bobj);
};
};
})(opts.cmp);
var seen = [];
return (function stringify (parent, key, node, level) {
var indent = space ? ('\n' + new Array(level + 1).join(space)) : '';
var colonSeparator = space ? ': ' : ':';
if (node && node.toJSON && typeof node.toJSON === 'function') {
node = node.toJSON();
}
node = replacer.call(parent, key, node);
if (node === undefined) {
return;
}
if (typeof node !== 'object' || node === null) {
return JSON.stringify(node);
}
if (isArray(node)) {
var out = [];
for (var i = 0; i < node.length; i++) {
var item = stringify(node, i, node[i], level+1) || JSON.stringify(null);
out.push(indent + space + item);
}
return '[' + out.join(',') + indent + ']';
}
else {
if (seen.indexOf(node) !== -1) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
else seen.push(node);
var keys = objectKeys(node).sort(cmp && cmp(node));
var out = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var value = stringify(node, key, node[key], level+1);
if(!value) continue;
var keyValue = JSON.stringify(key)
+ colonSeparator
+ value;
;
out.push(indent + space + keyValue);
}
seen.splice(seen.indexOf(node), 1);
return '{' + out.join(',') + indent + '}';
}
})({ '': obj }, '', obj, 0);
};
var isArray = Array.isArray || function (x) {
return {}.toString.call(x) === '[object Array]';
};
var objectKeys = Object.keys || function (obj) {
var has = Object.prototype.hasOwnProperty || function () { return true };
var keys = [];
for (var key in obj) {
if (has.call(obj, key)) keys.push(key);
}
return keys;
};
|
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
if (typeof define !== 'function') {
var define = require('amdefine')(module, require);
}
define(function (require, exports, module) {
/**
* This is a helper function for getting values from parameter/options
* objects.
*
* @param args The object we are extracting values from
* @param name The name of the property we are getting.
* @param defaultValue An optional value to return if the property is missing
* from the object. If this is not specified and the property is missing, an
* error will be thrown.
*/
function getArg(aArgs, aName, aDefaultValue) {
if (aName in aArgs) {
return aArgs[aName];
} else if (arguments.length === 3) {
return aDefaultValue;
} else {
throw new Error('"' + aName + '" is a required argument.');
}
}
exports.getArg = getArg;
var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
var dataUrlRegexp = /^data:.+\,.+/;
function urlParse(aUrl) {
var match = aUrl.match(urlRegexp);
if (!match) {
return null;
}
return {
scheme: match[1],
auth: match[3],
host: match[4],
port: match[6],
path: match[7]
};
}
exports.urlParse = urlParse;
function urlGenerate(aParsedUrl) {
var url = aParsedUrl.scheme + "://";
if (aParsedUrl.auth) {
url += aParsedUrl.auth + "@"
}
if (aParsedUrl.host) {
url += aParsedUrl.host;
}
if (aParsedUrl.port) {
url += ":" + aParsedUrl.port
}
if (aParsedUrl.path) {
url += aParsedUrl.path;
}
return url;
}
exports.urlGenerate = urlGenerate;
function join(aRoot, aPath) {
var url;
if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
return aPath;
}
if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
url.path = aPath;
return urlGenerate(url);
}
return aRoot.replace(/\/$/, '') + '/' + aPath;
}
exports.join = join;
/**
* Because behavior goes wacky when you set `__proto__` on objects, we
* have to prefix all the strings in our set with an arbitrary character.
*
* See https://github.com/mozilla/source-map/pull/31 and
* https://github.com/mozilla/source-map/issues/30
*
* @param String aStr
*/
function toSetString(aStr) {
return '$' + aStr;
}
exports.toSetString = toSetString;
function fromSetString(aStr) {
return aStr.substr(1);
}
exports.fromSetString = fromSetString;
function relative(aRoot, aPath) {
aRoot = aRoot.replace(/\/$/, '');
var url = urlParse(aRoot);
if (aPath.charAt(0) == "/" && url && url.path == "/") {
return aPath.slice(1);
}
return aPath.indexOf(aRoot + '/') === 0
? aPath.substr(aRoot.length + 1)
: aPath;
}
exports.relative = relative;
function strcmp(aStr1, aStr2) {
var s1 = aStr1 || "";
var s2 = aStr2 || "";
return (s1 > s2) - (s1 < s2);
}
/**
* Comparator between two mappings where the original positions are compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same original source/line/column, but different generated
* line and column the same. Useful when searching for a mapping with a
* stubbed out mapping.
*/
function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
var cmp;
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp || onlyCompareOriginal) {
return cmp;
}
cmp = strcmp(mappingA.name, mappingB.name);
if (cmp) {
return cmp;
}
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
return mappingA.generatedColumn - mappingB.generatedColumn;
};
exports.compareByOriginalPositions = compareByOriginalPositions;
/**
* Comparator between two mappings where the generated positions are
* compared.
*
* Optionally pass in `true` as `onlyCompareGenerated` to consider two
* mappings with the same generated line and column, but different
* source/name/original line and column the same. Useful when searching for a
* mapping with a stubbed out mapping.
*/
function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
var cmp;
cmp = mappingA.generatedLine - mappingB.generatedLine;
if (cmp) {
return cmp;
}
cmp = mappingA.generatedColumn - mappingB.generatedColumn;
if (cmp || onlyCompareGenerated) {
return cmp;
}
cmp = strcmp(mappingA.source, mappingB.source);
if (cmp) {
return cmp;
}
cmp = mappingA.originalLine - mappingB.originalLine;
if (cmp) {
return cmp;
}
cmp = mappingA.originalColumn - mappingB.originalColumn;
if (cmp) {
return cmp;
}
return strcmp(mappingA.name, mappingB.name);
};
exports.compareByGeneratedPositions = compareByGeneratedPositions;
});
|
var WritableStream = require('stream').Writable
|| require('readable-stream').Writable,
inherits = require('util').inherits;
var StreamSearch = require('streamsearch');
var PartStream = require('./PartStream'),
HeaderParser = require('./HeaderParser');
var B_ONEDASH = new Buffer('-'),
B_CRLF = new Buffer('\r\n');
function Dicer(cfg) {
if (!(this instanceof Dicer))
return new Dicer(cfg);
WritableStream.call(this, cfg);
if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string'))
throw new TypeError('Boundary required');
if (typeof cfg.boundary === 'string')
this.setBoundary(cfg.boundary);
else
this._bparser = undefined;
this._headerFirst = cfg.headerFirst;
var self = this;
this._dashes = 0;
this._parts = 0;
this._finished = false;
this._isPreamble = true;
this._justMatched = false;
this._firstWrite = true;
this._inHeader = true;
this._part = undefined;
this._cb = undefined;
this._partOpts = (typeof cfg.partHwm === 'number'
? { highWaterMark: cfg.partHwm }
: {});
this._pause = false;
this._hparser = new HeaderParser(cfg);
this._hparser.on('header', function(header) {
self._inHeader = false;
self._part.emit('header', header);
});
}
inherits(Dicer, WritableStream);
Dicer.prototype._write = function(data, encoding, cb) {
var self = this;
if (this._headerFirst && this._isPreamble) {
if (!this._part) {
this._part = new PartStream(this._partOpts);
this.emit('preamble', this._part);
}
var r = this._hparser.push(data);
if (!this._inHeader && r !== undefined && r < data.length)
data = data.slice(r);
else
return cb();
}
// allows for "easier" testing
if (this._firstWrite) {
this._bparser.push(B_CRLF);
this._firstWrite = false;
}
this._bparser.push(data);
if (this._pause)
this._cb = cb;
else
cb();
};
Dicer.prototype.reset = function() {
this._part = undefined;
this._bparser = undefined;
this._hparser = undefined;
};
Dicer.prototype.setBoundary = function(boundary) {
var self = this;
this._bparser = new StreamSearch('\r\n--' + boundary);
this._bparser.on('info', function(isMatch, data, start, end) {
self._oninfo(isMatch, data, start, end);
});
};
Dicer.prototype._oninfo = function(isMatch, data, start, end) {
var buf, self = this, i = 0, r, shouldWriteMore = true;
if (!this._part && this._justMatched && data) {
while (this._dashes < 2 && (start + i) < end) {
if (data[start + i] === 45) {
++i;
++this._dashes;
} else {
if (this._dashes)
buf = B_ONEDASH;
this._dashes = 0;
break;
}
}
if (this._dashes === 2) {
if ((start + i) < end && this._events.trailer)
this.emit('trailer', data.slice(start + i, end));
this.reset();
this._finished = true;
//process.nextTick(function() { self.emit('end'); });
}
if (this._dashes)
return;
}
if (this._justMatched)
this._justMatched = false;
if (!this._part) {
this._part = new PartStream(this._partOpts);
this._part._read = function(n) {
if (!self._pause)
return;
self._pause = false;
if (self._cb) {
var cb = self._cb;
self._cb = undefined;
cb();
}
};
this.emit(this._isPreamble ? 'preamble' : 'part', this._part);
if (!this._isPreamble)
this._inHeader = true;
}
if (data && start < end) {
if (this._isPreamble || !this._inHeader) {
if (buf)
shouldWriteMore = this._part.push(buf);
shouldWriteMore = this._part.push(data.slice(start, end));
if (!shouldWriteMore)
this._pause = true;
} else if (!this._isPreamble && this._inHeader) {
if (buf)
this._hparser.push(buf);
r = this._hparser.push(data.slice(start, end));
if (!this._inHeader && r !== undefined && r < end)
this._oninfo(false, data, start + r, end);
}
}
if (isMatch) {
this._hparser.reset();
if (this._isPreamble)
this._isPreamble = false;
else {
++this._parts;
this._part.on('end', function() {
if (--self._parts === 0 && self._finished) {
self._finished = false;
self.emit('end');
}
});
}
this._part.push(null);
this._part = undefined;
this._justMatched = true;
this._dashes = 0;
}
};
module.exports = Dicer;
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'newpage', 'hu', {
toolbar: 'Új oldal'
});
|
"use strict";
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
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) subClass.__proto__ = superClass; };
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var Dispatcher = require("flux").Dispatcher;
var EventEmitter = _interopRequire(require("eventemitter3"));
var Symbol = _interopRequire(require("es-symbol"));
var assign = _interopRequire(require("object-assign"));
var ACTION_HANDLER = Symbol("action creator handler");
var ACTION_KEY = Symbol("holds the actions uid symbol for listening");
var ACTION_UID = Symbol("the actions uid name");
var EE = Symbol("event emitter instance");
var INIT_SNAPSHOT = Symbol("init snapshot storage");
var LAST_SNAPSHOT = Symbol("last snapshot storage");
var LIFECYCLE = Symbol("store lifecycle listeners");
var LISTENERS = Symbol("stores action listeners storage");
var PUBLIC_METHODS = Symbol("store public method storage");
var STATE_CONTAINER = Symbol("the state container");
function formatAsConstant(name) {
return name.replace(/[a-z]([A-Z])/g, function (i) {
return "" + i[0] + "_" + i[1].toLowerCase();
}).toUpperCase();
}
function uid(container, name) {
var count = 0;
var key = name;
while (Object.hasOwnProperty.call(container, key)) {
key = name + String(++count);
}
return key;
}
/* istanbul ignore next */
function NoopClass() {}
var builtIns = Object.getOwnPropertyNames(NoopClass);
var builtInProto = Object.getOwnPropertyNames(NoopClass.prototype);
var getInternalMethods = function (obj, excluded) {
return Object.getOwnPropertyNames(obj).reduce(function (value, m) {
if (excluded.indexOf(m) !== -1) {
return value;
}
value[m] = obj[m];
return value;
}, {});
};
var AltStore = (function () {
function AltStore(dispatcher, model, state) {
var _this8 = this;
_classCallCheck(this, AltStore);
this[EE] = new EventEmitter();
this[LIFECYCLE] = {};
this[STATE_CONTAINER] = state || model;
assign(this[LIFECYCLE], model[LIFECYCLE]);
assign(this, model[PUBLIC_METHODS]);
// Register dispatcher
this.dispatchToken = dispatcher.register(function (payload) {
if (model[LISTENERS][payload.action]) {
var result = model[LISTENERS][payload.action](payload.data);
if (result !== false) {
_this8.emitChange();
}
}
});
if (this[LIFECYCLE].init) {
this[LIFECYCLE].init();
}
}
_createClass(AltStore, {
getEventEmitter: {
value: function getEventEmitter() {
return this[EE];
}
},
emitChange: {
value: function emitChange() {
this[EE].emit("change", this[STATE_CONTAINER]);
}
},
listen: {
value: function listen(cb) {
this[EE].on("change", cb);
}
},
unlisten: {
value: function unlisten(cb) {
this[EE].removeListener("change", cb);
}
},
getState: {
value: function getState() {
// Copy over state so it's RO.
return assign({}, this[STATE_CONTAINER]);
}
}
});
return AltStore;
})();
var ActionCreator = (function () {
function ActionCreator(alt, name, action, actions) {
_classCallCheck(this, ActionCreator);
this[ACTION_UID] = name;
this[ACTION_HANDLER] = action.bind(this);
this.actions = actions;
this.alt = alt;
}
_createClass(ActionCreator, {
dispatch: {
value: function dispatch(data) {
this.alt.dispatch(this[ACTION_UID], data);
}
}
});
return ActionCreator;
})();
var StoreMixinListeners = {
on: function on(lifecycleEvent, handler) {
this[LIFECYCLE][lifecycleEvent] = handler.bind(this);
},
bindAction: function bindAction(symbol, handler) {
if (!symbol) {
throw new ReferenceError("Invalid action reference passed in");
}
if (typeof handler !== "function") {
throw new TypeError("bindAction expects a function");
}
if (handler.length > 1) {
throw new TypeError("Action handler in store " + this._storeName + " for " + ("" + (symbol[ACTION_KEY] || symbol).toString() + " was defined with 2 ") + "parameters. Only a single parameter is passed through the " + "dispatcher, did you mean to pass in an Object instead?");
}
// You can pass in the constant or the function itself
if (symbol[ACTION_KEY]) {
this[LISTENERS][symbol[ACTION_KEY]] = handler.bind(this);
} else {
this[LISTENERS][symbol] = handler.bind(this);
}
},
bindActions: function bindActions(actions) {
var _this8 = this;
Object.keys(actions).forEach(function (action) {
var symbol = actions[action];
var matchFirstCharacter = /./;
var assumedEventHandler = action.replace(matchFirstCharacter, function (x) {
return "on" + x[0].toUpperCase();
});
var handler = null;
if (_this8[action] && _this8[assumedEventHandler]) {
// If you have both action and onAction
throw new ReferenceError("You have multiple action handlers bound to an action: " + ("" + action + " and " + assumedEventHandler));
} else if (_this8[action]) {
// action
handler = _this8[action];
} else if (_this8[assumedEventHandler]) {
// onAction
handler = _this8[assumedEventHandler];
}
if (handler) {
_this8.bindAction(symbol, handler);
}
});
},
bindListeners: function bindListeners(obj) {
var _this8 = this;
Object.keys(obj).forEach(function (methodName) {
var symbol = obj[methodName];
var listener = _this8[methodName];
if (!listener) {
throw new ReferenceError("" + methodName + " defined but does not exist in " + _this8._storeName);
}
if (Array.isArray(symbol)) {
symbol.forEach(function (action) {
_this8.bindAction(action, listener);
});
} else {
_this8.bindAction(symbol, listener);
}
});
}
};
var StoreMixinEssentials = {
waitFor: function waitFor(sources) {
if (!sources) {
throw new ReferenceError("Dispatch tokens not provided");
}
if (arguments.length === 1) {
sources = Array.isArray(sources) ? sources : [sources];
} else {
sources = Array.prototype.slice.call(arguments);
}
var tokens = sources.map(function (source) {
return source.dispatchToken || source;
});
this.dispatcher.waitFor(tokens);
},
exportPublicMethods: function exportPublicMethods(methods) {
var _this8 = this;
Object.keys(methods).forEach(function (methodName) {
if (typeof methods[methodName] !== "function") {
throw new TypeError("exportPublicMethods expects a function");
}
_this8[PUBLIC_METHODS][methodName] = methods[methodName];
});
},
emitChange: function emitChange() {
this.getInstance().emitChange();
}
};
var setAppState = function (instance, data, onStore) {
var obj = JSON.parse(data);
Object.keys(obj).forEach(function (key) {
var store = instance.stores[key];
if (store[LIFECYCLE].deserialize) {
obj[key] = store[LIFECYCLE].deserialize(obj[key]) || obj[key];
}
assign(store[STATE_CONTAINER], obj[key]);
onStore(store);
});
};
var snapshot = function (instance) {
return JSON.stringify(Object.keys(instance.stores).reduce(function (obj, key) {
var store = instance.stores[key];
var customSnapshot = store[LIFECYCLE].serialize && store[LIFECYCLE].serialize();
obj[key] = customSnapshot ? customSnapshot : store.getState();
return obj;
}, {}));
};
var saveInitialSnapshot = function (instance, key) {
var state = instance.stores[key][STATE_CONTAINER];
var initial = JSON.parse(instance[INIT_SNAPSHOT]);
initial[key] = state;
instance[INIT_SNAPSHOT] = JSON.stringify(initial);
};
var filterSnapshotOfStores = function (serializedSnapshot, storeNames) {
var stores = JSON.parse(serializedSnapshot);
var storesToReset = storeNames.reduce(function (obj, name) {
if (!stores[name]) {
throw new ReferenceError("" + name + " is not a valid store");
}
obj[name] = stores[name];
return obj;
}, {});
return JSON.stringify(storesToReset);
};
var createStoreFromObject = function (alt, StoreModel, key, saveStore) {
var storeInstance = undefined;
var StoreProto = {};
StoreProto[LIFECYCLE] = {};
StoreProto[LISTENERS] = {};
assign(StoreProto, {
_storeName: key,
alt: alt,
dispatcher: alt.dispatcher,
getInstance: function getInstance() {
return storeInstance;
},
setState: function setState() {
var values = arguments[0] === undefined ? {} : arguments[0];
assign(this.state, values);
this.emitChange();
return false;
}
}, StoreMixinListeners, StoreMixinEssentials, StoreModel);
// bind the store listeners
/* istanbul ignore else */
if (StoreProto.bindListeners) {
StoreMixinListeners.bindListeners.call(StoreProto, StoreProto.bindListeners);
}
// bind the lifecycle events
/* istanbul ignore else */
if (StoreProto.lifecycle) {
Object.keys(StoreProto.lifecycle).forEach(function (event) {
StoreMixinListeners.on.call(StoreProto, event, StoreProto.lifecycle[event]);
});
}
// create the instance and assign the public methods to the instance
storeInstance = assign(new AltStore(alt.dispatcher, StoreProto, StoreProto.state), StoreProto.publicMethods);
/* istanbul ignore else */
if (saveStore) {
alt.stores[key] = storeInstance;
saveInitialSnapshot(alt, key);
}
return storeInstance;
};
var Alt = (function () {
function Alt() {
_classCallCheck(this, Alt);
this.dispatcher = new Dispatcher();
this.actions = {};
this.stores = {};
this[LAST_SNAPSHOT] = null;
this[INIT_SNAPSHOT] = "{}";
}
_createClass(Alt, {
dispatch: {
value: function dispatch(action, data) {
this.dispatcher.dispatch({ action: action, data: data });
}
},
createStore: {
value: function createStore(StoreModel, iden) {
var saveStore = arguments[2] === undefined ? true : arguments[2];
var storeInstance = undefined;
var key = iden || StoreModel.name || StoreModel.displayName || "";
if (saveStore && (this.stores[key] || !key)) {
/* istanbul ignore else */
if (typeof console !== "undefined") {
if (this.stores[key]) {
console.warn(new ReferenceError("A store named " + key + " already exists, double check your store " + "names or pass in your own custom identifier for each store"));
} else {
console.warn(new ReferenceError("Store name was not specified"));
}
}
key = uid(this.stores, key);
}
if (typeof StoreModel === "object") {
return createStoreFromObject(this, StoreModel, key, saveStore);
}
// Creating a class here so we don't overload the provided store's
// prototype with the mixin behaviour and I'm extending from StoreModel
// so we can inherit any extensions from the provided store.
var Store = (function (_StoreModel) {
function Store(alt) {
_classCallCheck(this, Store);
_get(Object.getPrototypeOf(Store.prototype), "constructor", this).call(this, alt);
}
_inherits(Store, _StoreModel);
return Store;
})(StoreModel);
assign(Store.prototype, StoreMixinListeners, StoreMixinEssentials, {
_storeName: key,
alt: this,
dispatcher: this.dispatcher,
getInstance: function getInstance() {
return storeInstance;
},
setState: function setState() {
var values = arguments[0] === undefined ? {} : arguments[0];
assign(this, values);
this.emitChange();
return false;
}
});
Store.prototype[LIFECYCLE] = {};
Store.prototype[LISTENERS] = {};
Store.prototype[PUBLIC_METHODS] = {};
var store = new Store(this);
storeInstance = assign(new AltStore(this.dispatcher, store), getInternalMethods(StoreModel, builtIns));
if (saveStore) {
this.stores[key] = storeInstance;
saveInitialSnapshot(this, key);
}
return storeInstance;
}
},
generateActions: {
value: function generateActions() {
for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) {
actionNames[_key] = arguments[_key];
}
return this.createActions(function () {
this.generateActions.apply(this, actionNames);
});
}
},
createActions: {
value: function createActions(ActionsClass) {
var _this8 = this;
var exportObj = arguments[1] === undefined ? {} : arguments[1];
var actions = assign({}, getInternalMethods(ActionsClass.prototype, builtInProto));
var key = ActionsClass.name || ActionsClass.displayName || "";
var ActionsGenerator = (function (_ActionsClass) {
function ActionsGenerator(alt) {
_classCallCheck(this, ActionsGenerator);
_get(Object.getPrototypeOf(ActionsGenerator.prototype), "constructor", this).call(this, alt);
}
_inherits(ActionsGenerator, _ActionsClass);
_createClass(ActionsGenerator, {
generateActions: {
value: function generateActions() {
for (var _len = arguments.length, actionNames = Array(_len), _key = 0; _key < _len; _key++) {
actionNames[_key] = arguments[_key];
}
actionNames.forEach(function (actionName) {
// This is a function so we can later bind this to ActionCreator
actions[actionName] = function (x) {
for (var _len2 = arguments.length, a = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
a[_key2 - 1] = arguments[_key2];
}
this.dispatch(a.length ? [x].concat(a) : x);
};
});
}
}
});
return ActionsGenerator;
})(ActionsClass);
new ActionsGenerator(this);
return Object.keys(actions).reduce(function (obj, action) {
var constant = formatAsConstant(action);
var actionName = Symbol("" + key + "#" + action);
// Wrap the action so we can provide a dispatch method
var newAction = new ActionCreator(_this8, actionName, actions[action], obj);
// Set all the properties on action
obj[action] = newAction[ACTION_HANDLER];
obj[action].defer = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
setTimeout(function () {
newAction[ACTION_HANDLER].apply(null, args);
});
};
obj[action][ACTION_KEY] = actionName;
obj[constant] = actionName;
return obj;
}, exportObj);
}
},
takeSnapshot: {
value: function takeSnapshot() {
var state = snapshot(this);
this[LAST_SNAPSHOT] = state;
return state;
}
},
rollback: {
value: function rollback() {
setAppState(this, this[LAST_SNAPSHOT], function (store) {
if (store[LIFECYCLE].rollback) {
store[LIFECYCLE].rollback();
}
});
}
},
recycle: {
value: function recycle() {
for (var _len = arguments.length, storeNames = Array(_len), _key = 0; _key < _len; _key++) {
storeNames[_key] = arguments[_key];
}
var initialSnapshot = storeNames.length ? filterSnapshotOfStores(this[INIT_SNAPSHOT], storeNames) : this[INIT_SNAPSHOT];
setAppState(this, initialSnapshot, function (store) {
if (store[LIFECYCLE].init) {
store[LIFECYCLE].init();
}
});
}
},
flush: {
value: function flush() {
var state = snapshot(this);
this.recycle();
return state;
}
},
bootstrap: {
value: function bootstrap(data) {
setAppState(this, data, function (store) {
if (store[LIFECYCLE].bootstrap) {
store[LIFECYCLE].bootstrap();
}
});
}
},
addActions: {
// Instance type methods for injecting alt into your application as context
value: function addActions(name, ActionsClass) {
this.actions[name] = this.createActions(ActionsClass);
}
},
addStore: {
value: function addStore(name, StoreModel, saveStore) {
this.createStore(StoreModel, name, saveStore);
}
},
getActions: {
value: function getActions(name) {
return this.actions[name];
}
},
getStore: {
value: function getStore(name) {
return this.stores[name];
}
}
});
return Alt;
})();
module.exports = Alt;
|
var a: [] = [];
var a: [Foo<T>] = [foo];
var a: [number] = [123];
var a: [number, string] = [123, "duck"];
|
/*!
* Qoopido.js library v3.4.3, 2014-6-11
* https://github.com/dlueth/qoopido.js
* (c) 2014 Dirk Lueth
* Dual licensed under MIT and GPL
*//*!
* Qoopido.js library
*
* version: 3.4.3
* date: 2014-6-11
* author: Dirk Lueth <info@qoopido.com>
* website: https://github.com/dlueth/qoopido.js
*
* Copyright (c) 2014 Dirk Lueth
*
* Dual licensed under the MIT and GPL licenses.
* - http://www.opensource.org/licenses/mit-license.php
* - http://www.gnu.org/copyleft/gpl.html
*/
!function(t){window.qoopido.register("support/element/canvas/todataurl",t,["../../../support","../canvas"])}(function(t,e,n,o,a,s,r){"use strict";var c=t.support;return c.addTest("/element/canvas/todataurl",function(e){t["support/element/canvas"]().then(function(){var t=c.pool?c.pool.obtain("canvas"):s.createElement("canvas");t.toDataURL!==r?e.resolve():e.reject(),t.dispose&&t.dispose()},function(){e.reject()}).done()})});
|
var a = {
echo(c) {
return c;
}
};
assert.strictEqual(a.echo(1), 1);
|
/*==================================================
Copyright (c) 2013-2015 司徒正美 and other contributors
http://www.cnblogs.com/rubylouvre/
https://github.com/RubyLouvre
http://weibo.com/jslouvre/
Released under the MIT license
avalon.modern.shim.js(无加载器版本) 1.44 built in 2015.6.17
support IE10+ and other browsers
==================================================*/
(function(global, factory) {
if (typeof module === "object" && typeof module.exports === "object") {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get avalon.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var avalon = require("avalon")(window);
module.exports = global.document ? factory(global, true) : function(w) {
if (!w.document) {
throw new Error("Avalon requires a window with a document")
}
return factory(w)
}
} else {
factory(global)
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function(window, noGlobal){
/*********************************************************************
* 全局变量及方法 *
**********************************************************************/
var expose = Date.now()
//http://stackoverflow.com/questions/7290086/javascript-use-strict-and-nicks-find-global-function
var DOC = window.document
var head = DOC.head //HEAD元素
head.insertAdjacentHTML("afterBegin", '<avalon ms-skip class="avalonHide"><style id="avalonStyle">.avalonHide{ display: none!important }</style></avalon>')
var ifGroup = head.firstChild
function log() {
if (avalon.config.debug) {
// http://stackoverflow.com/questions/8785624/how-to-safely-wrap-console-log
console.log.apply(console, arguments)
}
}
/**
* Creates a new object without a prototype. This object is useful for lookup without having to
* guard against prototypically inherited properties via hasOwnProperty.
*
* Related micro-benchmarks:
* - http://jsperf.com/object-create2
* - http://jsperf.com/proto-map-lookup/2
* - http://jsperf.com/for-in-vs-object-keys2
*/
function createMap() {
return Object.create(null)
}
var subscribers = "$" + expose
var otherRequire = window.require
var otherDefine = window.define
var innerRequire
var stopRepeatAssign = false
var rword = /[^, ]+/g //切割字符串为一个个小块,以空格或豆号分开它们,结合replace实现字符串的forEach
var rcomplexType = /^(?:object|array)$/
var rsvg = /^\[object SVG\w*Element\]$/
var rwindow = /^\[object (?:Window|DOMWindow|global)\]$/
var oproto = Object.prototype
var ohasOwn = oproto.hasOwnProperty
var serialize = oproto.toString
var ap = Array.prototype
var aslice = ap.slice
var Registry = {} //将函数曝光到此对象上,方便访问器收集依赖
var W3C = window.dispatchEvent
var root = DOC.documentElement
var avalonFragment = DOC.createDocumentFragment()
var cinerator = DOC.createElement("div")
var class2type = {}
"Boolean Number String Function Array Date RegExp Object Error".replace(rword, function(name) {
class2type["[object " + name + "]"] = name.toLowerCase()
})
function noop() {
}
function oneObject(array, val) {
if (typeof array === "string") {
array = array.match(rword) || []
}
var result = {},
value = val !== void 0 ? val : 1
for (var i = 0, n = array.length; i < n; i++) {
result[array[i]] = value
}
return result
}
//生成UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
var generateID = function(prefix) {
prefix = prefix || "avalon"
return String(Math.random() + Math.random()).replace(/\d\.\d{4}/, prefix)
}
function IE() {
if (window.VBArray) {
var mode = document.documentMode
return mode ? mode : window.XMLHttpRequest ? 7 : 6
} else {
return 0
}
}
var IEVersion = IE()
avalon = function(el) { //创建jQuery式的无new 实例化结构
return new avalon.init(el)
}
/*视浏览器情况采用最快的异步回调*/
avalon.nextTick = new function() {// jshint ignore:line
var tickImmediate = window.setImmediate
var tickObserver = window.MutationObserver
var tickPost = W3C && window.postMessage
if (tickImmediate) {
return tickImmediate.bind(window)
}
var queue = []
function callback() {
var n = queue.length
for (var i = 0; i < n; i++) {
queue[i]()
}
queue = queue.slice(n)
}
if (tickObserver) {
var node = document.createTextNode("avalon")
new tickObserver(callback).observe(node, {characterData: true})// jshint ignore:line
return function(fn) {
queue.push(fn)
node.data = Math.random()
}
}
if (tickPost) {
window.addEventListener("message", function(e) {
var source = e.source
if ((source === window || source === null) && e.data === "process-tick") {
e.stopPropagation()
callback()
}
})
return function(fn) {
queue.push(fn)
window.postMessage('process-tick', '*')
}
}
return function(fn) {
setTimeout(fn, 0)
}
}// jshint ignore:line
/*********************************************************************
* avalon的静态方法定义区 *
**********************************************************************/
avalon.init = function(el) {
this[0] = this.element = el
}
avalon.fn = avalon.prototype = avalon.init.prototype
avalon.type = function(obj) { //取得目标的类型
if (obj == null) {
return String(obj)
}
// 早期的webkit内核浏览器实现了已废弃的ecma262v4标准,可以将正则字面量当作函数使用,因此typeof在判定正则时会返回function
return typeof obj === "object" || typeof obj === "function" ?
class2type[serialize.call(obj)] || "object" :
typeof obj
}
var isFunction = function(fn) {
return serialize.call(fn) === "[object Function]"
}
avalon.isFunction = isFunction
avalon.isWindow = function(obj) {
return rwindow.test(serialize.call(obj))
}
/*判定是否是一个朴素的javascript对象(Object),不是DOM对象,不是BOM对象,不是自定义类的实例*/
avalon.isPlainObject = function(obj) {
// 简单的 typeof obj === "object"检测,会致使用isPlainObject(window)在opera下通不过
return serialize.call(obj) === "[object Object]" && Object.getPrototypeOf(obj) === oproto
}
//与jQuery.extend方法,可用于浅拷贝,深拷贝
avalon.mix = avalon.fn.mix = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false
// 如果第一个参数为布尔,判定是否深拷贝
if (typeof target === "boolean") {
deep = target
target = arguments[1] || {}
i++
}
//确保接受方为一个复杂的数据类型
if (typeof target !== "object" && !isFunction(target)) {
target = {}
}
//如果只有一个参数,那么新成员添加于mix所在的对象上
if (i === length) {
target = this
i--
}
for (; i < length; i++) {
//只处理非空参数
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name]
copy = options[name]
// 防止环引用
if (target === copy) {
continue
}
if (deep && copy && (avalon.isPlainObject(copy) || (copyIsArray = Array.isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false
clone = src && Array.isArray(src) ? src : []
} else {
clone = src && avalon.isPlainObject(src) ? src : {}
}
target[name] = avalon.mix(deep, clone, copy)
} else if (copy !== void 0) {
target[name] = copy
}
}
}
}
return target
}
function _number(a, len) { //用于模拟slice, splice的效果
a = Math.floor(a) || 0
return a < 0 ? Math.max(len + a, 0) : Math.min(a, len);
}
avalon.mix({
rword: rword,
subscribers: subscribers,
version: 1.44,
ui: {},
log: log,
slice: function(nodes, start, end) {
return aslice.call(nodes, start, end)
},
noop: noop,
/*如果不用Error对象封装一下,str在控制台下可能会乱码*/
error: function(str, e) {
throw new (e || Error)(str)// jshint ignore:line
},
/*将一个以空格或逗号隔开的字符串或数组,转换成一个键值都为1的对象*/
oneObject: oneObject,
/* avalon.range(10)
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
avalon.range(1, 11)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
avalon.range(0, 30, 5)
=> [0, 5, 10, 15, 20, 25]
avalon.range(0, -10, -1)
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
avalon.range(0)
=> []*/
range: function(start, end, step) { // 用于生成整数数组
step || (step = 1)
if (end == null) {
end = start || 0
start = 0
}
var index = -1,
length = Math.max(0, Math.ceil((end - start) / step)),
result = new Array(length)
while (++index < length) {
result[index] = start
start += step
}
return result
},
eventHooks: {},
/*绑定事件*/
bind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, type, fn, phase)
}
}
if (!fn.unbind)
el.addEventListener(type, fn, !!phase)
return fn
},
/*卸载事件*/
unbind: function(el, type, fn, phase) {
var hooks = avalon.eventHooks
var hook = hooks[type]
var callback = fn || noop
if (typeof hook === "object") {
type = hook.type
if (hook.deel) {
fn = hook.deel(el, type, fn, false)
}
}
el.removeEventListener(type, callback, !!phase)
},
/*读写删除元素节点的样式*/
css: function(node, name, value) {
if (node instanceof avalon) {
node = node[0]
}
var prop = /[_-]/.test(name) ? camelize(name) : name, fn
name = avalon.cssName(prop) || prop
if (value === void 0 || typeof value === "boolean") { //获取样式
fn = cssHooks[prop + ":get"] || cssHooks["@:get"]
if (name === "background") {
name = "backgroundColor"
}
var val = fn(node, name)
return value === true ? parseFloat(val) || 0 : val
} else if (value === "") { //请除样式
node.style[name] = ""
} else { //设置样式
if (value == null || value !== value) {
return
}
if (isFinite(value) && !avalon.cssNumber[prop]) {
value += "px"
}
fn = cssHooks[prop + ":set"] || cssHooks["@:set"]
fn(node, name, value)
}
},
/*遍历数组与对象,回调的第一个参数为索引或键名,第二个或元素或键值*/
each: function(obj, fn) {
if (obj) { //排除null, undefined
var i = 0
if (isArrayLike(obj)) {
for (var n = obj.length; i < n; i++) {
if (fn(i, obj[i]) === false)
break
}
} else {
for (i in obj) {
if (obj.hasOwnProperty(i) && fn(i, obj[i]) === false) {
break
}
}
}
}
},
//收集元素的data-{{prefix}}-*属性,并转换为对象
getWidgetData: function(elem, prefix) {
var raw = avalon(elem).data()
var result = {}
for (var i in raw) {
if (i.indexOf(prefix) === 0) {
result[i.replace(prefix, "").replace(/\w/, function(a) {
return a.toLowerCase()
})] = raw[i]
}
}
return result
},
Array: {
/*只有当前数组不存在此元素时只添加它*/
ensure: function(target, item) {
if (target.indexOf(item) === -1) {
return target.push(item)
}
},
/*移除数组中指定位置的元素,返回布尔表示成功与否*/
removeAt: function(target, index) {
return !!target.splice(index, 1).length
},
/*移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否*/
remove: function(target, item) {
var index = target.indexOf(item)
if (~index)
return avalon.Array.removeAt(target, index)
return false
}
}
})
var bindingHandlers = avalon.bindingHandlers = {}
var bindingExecutors = avalon.bindingExecutors = {}
/*判定是否类数组,如节点集合,纯数组,arguments与拥有非负整数的length属性的纯JS对象*/
function isArrayLike(obj) {
if (obj && typeof obj === "object") {
var n = obj.length,
str = serialize.call(obj)
if (/(Array|List|Collection|Map|Arguments)\]$/.test(str)) {
return true
} else if (str === "[object Object]" && n === (n >>> 0)) {
return true //由于ecma262v5能修改对象属性的enumerable,因此不能用propertyIsEnumerable来判定了
}
}
return false
}
// https://github.com/rsms/js-lru
var Cache = new function() {// jshint ignore:line
function LRU(maxLength) {
this.size = 0
this.limit = maxLength
this.head = this.tail = void 0
this._keymap = {}
}
var p = LRU.prototype
p.put = function(key, value) {
var entry = {
key: key,
value: value
}
this._keymap[key] = entry
if (this.tail) {
this.tail.newer = entry
entry.older = this.tail
} else {
this.head = entry
}
this.tail = entry
if (this.size === this.limit) {
this.shift()
} else {
this.size++
}
return value
}
p.shift = function() {
var entry = this.head
if (entry) {
this.head = this.head.newer
this.head.older =
entry.newer =
entry.older =
this._keymap[entry.key] = void 0
}
}
p.get = function(key) {
var entry = this._keymap[key]
if (entry === void 0)
return
if (entry === this.tail) {
return entry.value
}
// HEAD--------------TAIL
// <.older .newer>
// <--- add direction --
// A B C <D> E
if (entry.newer) {
if (entry === this.head) {
this.head = entry.newer
}
entry.newer.older = entry.older // C <-- E.
}
if (entry.older) {
entry.older.newer = entry.newer // C. --> E
}
entry.newer = void 0 // D --x
entry.older = this.tail // D. --> E
if (this.tail) {
this.tail.newer = entry // E. <-- D
}
this.tail = entry
return entry.value
}
return LRU
}// jshint ignore:line
/*********************************************************************
* DOM 底层补丁 *
**********************************************************************/
//safari5+是把contains方法放在Element.prototype上而不是Node.prototype
if (!DOC.contains) {
Node.prototype.contains = function (arg) {
return !!(this.compareDocumentPosition(arg) & 16)
}
}
avalon.contains = function (root, el) {
try {
while ((el = el.parentNode))
if (el === root)
return true
return false
} catch (e) {
return false
}
}
if (window.SVGElement) {
var svgns = "http://www.w3.org/2000/svg"
var svg = DOC.createElementNS(svgns, "svg")
svg.innerHTML = '<circle cx="50" cy="50" r="40" fill="red" />'
if (!rsvg.test(svg.firstChild)) {// #409
/* jshint ignore:start */
function enumerateNode(node, targetNode) {
if (node && node.childNodes) {
var nodes = node.childNodes
for (var i = 0, el; el = nodes[i++]; ) {
if (el.tagName) {
var svg = DOC.createElementNS(svgns,
el.tagName.toLowerCase())
// copy attrs
ap.forEach.call(el.attributes, function (attr) {
svg.setAttribute(attr.name, attr.value)
})
// 递归处理子节点
enumerateNode(el, svg)
targetNode.appendChild(svg)
}
}
}
}
/* jshint ignore:end */
Object.defineProperties(SVGElement.prototype, {
"outerHTML": {//IE9-11,firefox不支持SVG元素的innerHTML,outerHTML属性
enumerable: true,
configurable: true,
get: function () {
return new XMLSerializer().serializeToString(this)
},
set: function (html) {
var tagName = this.tagName.toLowerCase(),
par = this.parentNode,
frag = avalon.parseHTML(html)
// 操作的svg,直接插入
if (tagName === "svg") {
par.insertBefore(frag, this)
// svg节点的子节点类似
} else {
var newFrag = DOC.createDocumentFragment()
enumerateNode(frag, newFrag)
par.insertBefore(newFrag, this)
}
par.removeChild(this)
}
},
"innerHTML": {
enumerable: true,
configurable: true,
get: function () {
var s = this.outerHTML
var ropen = new RegExp("<" + this.nodeName + '\\b(?:(["\'])[^"]*?(\\1)|[^>])*>', "i")
var rclose = new RegExp("<\/" + this.nodeName + ">$", "i")
return s.replace(ropen, "").replace(rclose, "")
},
set: function (html) {
if (avalon.clearHTML) {
avalon.clearHTML(this)
var frag = avalon.parseHTML(html)
enumerateNode(frag, this)
}
}
}
})
}
}
//========================= event binding ====================
var eventHooks = avalon.eventHooks
//针对firefox, chrome修正mouseenter, mouseleave(chrome30+)
if (!("onmouseenter" in root)) {
avalon.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function (origType, fixType) {
eventHooks[origType] = {
type: fixType,
deel: function (elem, _, fn) {
return function (e) {
var t = e.relatedTarget
if (!t || (t !== elem && !(elem.compareDocumentPosition(t) & 16))) {
delete e.type
e.type = origType
return fn.call(elem, e)
}
}
}
}
})
}
//针对IE9+, w3c修正animationend
avalon.each({
AnimationEvent: "animationend",
WebKitAnimationEvent: "webkitAnimationEnd"
}, function (construct, fixType) {
if (window[construct] && !eventHooks.animationend) {
eventHooks.animationend = {
type: fixType
}
}
})
if (DOC.onmousewheel === void 0) {
/* IE6-11 chrome mousewheel wheelDetla 下 -120 上 120
firefox DOMMouseScroll detail 下3 上-3
firefox wheel detlaY 下3 上-3
IE9-11 wheel deltaY 下40 上-40
chrome wheel deltaY 下100 上-100 */
eventHooks.mousewheel = {
type: "wheel",
deel: function (elem, _, fn) {
return function (e) {
e.wheelDeltaY = e.wheelDelta = e.deltaY > 0 ? -120 : 120
e.wheelDeltaX = 0
Object.defineProperty(e, "type", {
value: "mousewheel"
})
fn.call(elem, e)
}
}
}
}
/*********************************************************************
* 配置系统 *
**********************************************************************/
function kernel(settings) {
for (var p in settings) {
if (!ohasOwn.call(settings, p))
continue
var val = settings[p]
if (typeof kernel.plugins[p] === "function") {
kernel.plugins[p](val)
} else if (typeof kernel[p] === "object") {
avalon.mix(kernel[p], val)
} else {
kernel[p] = val
}
}
return this
}
var openTag, closeTag, rexpr, rexprg, rbind, rregexp = /[-.*+?^${}()|[\]\/\\]/g
function escapeRegExp(target) {
//http://stevenlevithan.com/regex/xregexp/
//将字符串安全格式化为正则表达式的源码
return (target + "").replace(rregexp, "\\$&")
}
var plugins = {
loader: function (builtin) {
var flag = innerRequire && builtin
window.require = flag ? innerRequire : otherRequire
window.define = flag ? innerRequire.define : otherDefine
},
interpolate: function (array) {
openTag = array[0]
closeTag = array[1]
if (openTag === closeTag) {
throw new SyntaxError("openTag!==closeTag")
} else if (array + "" === "<!--,-->") {
kernel.commentInterpolate = true
} else {
var test = openTag + "test" + closeTag
cinerator.innerHTML = test
if (cinerator.innerHTML !== test && cinerator.innerHTML.indexOf("<") > -1) {
throw new SyntaxError("此定界符不合法")
}
cinerator.innerHTML = ""
}
var o = escapeRegExp(openTag),
c = escapeRegExp(closeTag)
rexpr = new RegExp(o + "(.*?)" + c)
rexprg = new RegExp(o + "(.*?)" + c, "g")
rbind = new RegExp(o + ".*?" + c + "|\\sms-")
}
}
kernel.debug = true
kernel.plugins = plugins
kernel.plugins['interpolate'](["{{", "}}"])
kernel.paths = {}
kernel.shim = {}
kernel.maxRepeatSize = 100
avalon.config = kernel
var ravalon = /(\w+)\[(avalonctrl)="(\S+)"\]/
var findNodes = function(str) {
return DOC.querySelectorAll(str)
}
/*********************************************************************
* 事件总线 *
**********************************************************************/
var EventBus = {
$watch: function (type, callback) {
if (typeof callback === "function") {
var callbacks = this.$events[type]
if (callbacks) {
callbacks.push(callback)
} else {
this.$events[type] = [callback]
}
} else { //重新开始监听此VM的第一重简单属性的变动
this.$events = this.$watch.backup
}
return this
},
$unwatch: function (type, callback) {
var n = arguments.length
if (n === 0) { //让此VM的所有$watch回调无效化
this.$watch.backup = this.$events
this.$events = {}
} else if (n === 1) {
this.$events[type] = []
} else {
var callbacks = this.$events[type] || []
var i = callbacks.length
while (~--i < 0) {
if (callbacks[i] === callback) {
return callbacks.splice(i, 1)
}
}
}
return this
},
$fire: function (type) {
var special, i, v, callback
if (/^(\w+)!(\S+)$/.test(type)) {
special = RegExp.$1
type = RegExp.$2
}
var events = this.$events
if (!events)
return
var args = aslice.call(arguments, 1)
var detail = [type].concat(args)
if (special === "all") {
for (i in avalon.vmodels) {
v = avalon.vmodels[i]
if (v !== this) {
v.$fire.apply(v, detail)
}
}
} else if (special === "up" || special === "down") {
var elements = events.expr ? findNodes(events.expr) : []
if (elements.length === 0)
return
for (i in avalon.vmodels) {
v = avalon.vmodels[i]
if (v !== this) {
if (v.$events.expr) {
var eventNodes = findNodes(v.$events.expr)
if (eventNodes.length === 0) {
continue
}
//循环两个vmodel中的节点,查找匹配(向上匹配或者向下匹配)的节点并设置标识
/* jshint ignore:start */
ap.forEach.call(eventNodes, function (node) {
ap.forEach.call(elements, function (element) {
var ok = special === "down" ? element.contains(node) : //向下捕获
node.contains(element) //向上冒泡
if (ok) {
node._avalon = v //符合条件的加一个标识
}
});
})
/* jshint ignore:end */
}
}
}
var nodes = DOC.getElementsByTagName("*") //实现节点排序
var alls = []
ap.forEach.call(nodes, function (el) {
if (el._avalon) {
alls.push(el._avalon)
el._avalon = ""
el.removeAttribute("_avalon")
}
})
if (special === "up") {
alls.reverse()
}
for (i = 0; callback = alls[i++]; ) {
if (callback.$fire.apply(callback, detail) === false) {
break
}
}
} else {
var callbacks = events[type] || []
var all = events.$all || []
for (i = 0; callback = callbacks[i++]; ) {
if (isFunction(callback))
callback.apply(this, args)
}
for (i = 0; callback = all[i++]; ) {
if (isFunction(callback))
callback.apply(this, arguments)
}
}
}
}
/*********************************************************************
* modelFactory *
**********************************************************************/
//avalon最核心的方法的两个方法之一(另一个是avalon.scan),返回一个ViewModel(VM)
var VMODELS = avalon.vmodels = {} //所有vmodel都储存在这里
avalon.define = function (id, factory) {
var $id = id.$id || id
if (!$id) {
log("warning: vm必须指定$id")
}
if (VMODELS[$id]) {
log("warning: " + $id + " 已经存在于avalon.vmodels中")
}
if (typeof id === "object") {
var model = modelFactory(id)
} else {
var scope = {
$watch: noop
}
factory(scope) //得到所有定义
model = modelFactory(scope) //偷天换日,将scope换为model
stopRepeatAssign = true
factory(model)
stopRepeatAssign = false
}
model.$id = $id
return VMODELS[$id] = model
}
//一些不需要被监听的属性
var $$skipArray = String("$id,$watch,$unwatch,$fire,$events,$model,$skipArray,$proxy").match(rword)
function modelFactory(source, $special, $model) {
if (Array.isArray(source)) {
var arr = source.concat()
source.length = 0
var collection = arrayFactory(source)// jshint ignore:line
collection.pushArray(arr)
return collection
}
//0 null undefined || Node || VModel(fix IE6-8 createWithProxy $val: val引发的BUG)
if (!source || source.nodeType > 0 || (source.$id && source.$events)) {
return source
}
var $skipArray = Array.isArray(source.$skipArray) ? source.$skipArray : []
$skipArray.$special = $special || createMap() //强制要监听的属性
var $vmodel = {} //要返回的对象, 它在IE6-8下可能被偷龙转凤
$model = $model || {} //vmodels.$model属性
var $events = createMap() //vmodel.$events属性
var accessors = createMap() //监控属性
var computed = []
$$skipArray.forEach(function (name) {
delete source[name]
})
for (var i in source) {
(function (name, val, accessor) {
$model[name] = val
if (!isObservable(name, val, $skipArray)) {
return //过滤所有非监控属性
}
//总共产生三种accessor
$events[name] = []
var valueType = avalon.type(val)
//总共产生三种accessor
if (valueType === "object" && isFunction(val.get) && Object.keys(val).length <= 2) {
accessor = makeComputedAccessor(name, val)
computed.push(accessor)
} else if (rcomplexType.test(valueType)) {
accessor = makeComplexAccessor(name, val, valueType, $events[name])
} else {
accessor = makeSimpleAccessor(name, val)
}
accessors[name] = accessor
})(i, source[i])// jshint ignore:line
}
$vmodel = Object.defineProperties($vmodel, descriptorFactory(accessors)) //生成一个空的ViewModel
for (var name in source) {
if (!accessors[name]) {
$vmodel[name] = source[name]
}
}
//添加$id, $model, $events, $watch, $unwatch, $fire
$vmodel.$id = generateID()
$vmodel.$model = $model
$vmodel.$events = $events
for (i in EventBus) {
$vmodel[i] = EventBus[i]
}
Object.defineProperty($vmodel, "hasOwnProperty", {
value: function (name) {
return name in this.$model
},
writable: false,
enumerable: false,
configurable: true
})
$vmodel.$compute = function () {
computed.forEach(function (accessor) {
dependencyDetection.begin({
callback: function (vm, dependency) {//dependency为一个accessor
var name = dependency._name
if (dependency !== accessor) {
var list = vm.$events[name]
accessor.vm = $vmodel
injectDependency(list, accessor.digest)
}
}
})
try {
accessor.get.call($vmodel)
} finally {
dependencyDetection.end()
}
})
}
$vmodel.$compute()
return $vmodel
}
//创建一个简单访问器
function makeSimpleAccessor(name, value) {
function accessor(value) {
var oldValue = accessor._value
if (arguments.length > 0) {
if (!stopRepeatAssign && !isEqual(value, oldValue)) {
accessor.updateValue(this, value)
accessor.notify(this, value, oldValue)
}
return this
} else {
dependencyDetection.collectDependency(this, accessor)
return oldValue
}
}
accessorFactory(accessor, name)
accessor._value = value
return accessor;
}
///创建一个计算访问器
function makeComputedAccessor(name, options) {
options.set = options.set || noop
function accessor(value) {//计算属性
var oldValue = accessor._value
var init = "_value" in accessor
if (arguments.length > 0) {
if (stopRepeatAssign) {
return this
}
accessor.set.call(this, value)
return this
} else {
//将依赖于自己的高层访问器或视图刷新函数(以绑定对象形式)放到自己的订阅数组中
value = accessor.get.call(this)
if (oldValue !== value) {
accessor.updateValue(this, value)
init && accessor.notify(this, value, oldValue) //触发$watch回调
}
//将自己注入到低层访问器的订阅数组中
return value
}
}
accessor.set = options.set || noop
accessor.get = options.get
accessorFactory(accessor, name)
var id
accessor.digest = function () {
accessor.updateValue = globalUpdateModelValue
accessor.notify = noop
accessor.call(accessor.vm)
clearTimeout(id)//如果计算属性存在多个依赖项,那么等它们都更新了才更新视图
id = setTimeout(function () {
accessorFactory(accessor, accessor._name)
accessor.call(accessor.vm)
})
}
return accessor
}
//创建一个复杂访问器
function makeComplexAccessor(name, initValue, valueType, list) {
function accessor(value) {
var oldValue = accessor._value
var son = accessor._vmodel
if (arguments.length > 0) {
if (stopRepeatAssign) {
return this
}
if (valueType === "array") {
var old = son._
son._ = []
son.clear()
son._ = old
son.pushArray(value)
} else if (valueType === "object") {
var $proxy = son.$proxy
var observes = this.$events[name] || []
son = accessor._vmodel = modelFactory(value)
son.$proxy = $proxy
if (observes.length) {
observes.forEach(function (data) {
if (data.rollback) {
data.rollback() //还原 ms-with ms-on
}
bindingHandlers[data.type](data, data.vmodels)
})
son.$events[name] = observes
}
}
accessor.updateValue(this, son.$model)
accessor.notify(this, this._value, oldValue)
return this
} else {
dependencyDetection.collectDependency(this, accessor)
return son
}
}
accessorFactory(accessor, name)
var son = accessor._vmodel = modelFactory(initValue)
son.$events[subscribers] = list
return accessor
}
function globalUpdateValue(vmodel, value) {
vmodel.$model[this._name] = this._value = value
}
function globalUpdateModelValue(vmodel, value) {
vmodel.$model[this._name] = value
}
function globalNotify(vmodel, value, oldValue) {
var name = this._name
var array = vmodel.$events[name] //刷新值
if (array) {
fireDependencies(array) //同步视图
EventBus.$fire.call(vmodel, name, value, oldValue) //触发$watch回调
}
}
function accessorFactory(accessor, name) {
accessor._name = name
//同时更新_value与model
accessor.updateValue = globalUpdateValue
accessor.notify = globalNotify
}
//比较两个值是否相等
var isEqual = Object.is || function (v1, v2) {
if (v1 === 0 && v2 === 0) {
return 1 / v1 === 1 / v2
} else if (v1 !== v1) {
return v2 !== v2
} else {
return v1 === v2
}
}
function isObservable(name, value, $skipArray) {
if (isFunction(value) || value && value.nodeType) {
return false
}
if ($skipArray.indexOf(name) !== -1) {
return false
}
var $special = $skipArray.$special
if (name && name.charAt(0) === "$" && !$special[name]) {
return false
}
return true
}
var descriptorFactory = function (obj) {
var descriptors = {}
for (var i in obj) {
descriptors[i] = {
get: obj[i],
set: obj[i],
enumerable: true,
configurable: true
}
}
return descriptors
}
/*********************************************************************
* 监控数组(与ms-each, ms-repeat配合使用) *
**********************************************************************/
function arrayFactory(model) {
var array = []
array.$id = generateID()
array.$model = model //数据模型
array.$events = {}
array.$events[subscribers] = []
array._ = modelFactory({
length: model.length
})
array._.$watch("length", function (a, b) {
array.$fire("length", a, b)
})
for (var i in EventBus) {
array[i] = EventBus[i]
}
array.$map = {
el: 1
}
array.$proxy = []
avalon.mix(array, arrayPrototype)
return array
}
function mutateArray(method, pos, n, index, method2, pos2, n2) {
var oldLen = this.length, loop = 2
while (--loop) {
switch (method) {
case "add":
/* jshint ignore:start */
var m = pos + n
var array = this.$model.slice(pos, m).map(function (el) {
if (rcomplexType.test(avalon.type(el))) {//转换为VM
return el.$id ? el : modelFactory(el, 0, el)
} else {
return el
}
})
_splice.apply(this, [pos, 0].concat(array))
/* jshint ignore:end */
for (var i = pos; i < m; i++) {//生成代理VM
var proxy = eachProxyAgent(i, this)
this.$proxy.splice(i, 0, proxy)
}
this._fire("add", pos, n)
break
case "del":
var ret = this._splice(pos, n)
var removed = this.$proxy.splice(pos, n) //回收代理VM
eachProxyRecycler(removed, "each")
this._fire("del", pos, n)
break
}
if (method2) {
method = method2
pos = pos2
n = n2
loop = 2
method2 = 0
}
}
resetIndex(this.$proxy, index)
if (this.length !== oldLen) {
this._.length = this.length
}
return ret
}
var _splice = ap.splice
var arrayPrototype = {
_splice: _splice,
_fire: function (method, a, b) {
fireDependencies(this.$events[subscribers], method, a, b)
},
size: function () { //取得数组长度,这个函数可以同步视图,length不能
return this._.length
},
pushArray: function (array) {
var m = array.length, n = this.length
if (m) {
ap.push.apply(this.$model, array)
mutateArray.call(this, "add", n, m, Math.max(0, n - 1))
}
return m + n
},
push: function () {
//http://jsperf.com/closure-with-arguments
var array = []
var i, n = arguments.length
for (i = 0; i < n; i++) {
array[i] = arguments[i]
}
return this.pushArray(array)
},
unshift: function () {
var m = arguments.length, n = this.length
if (m) {
ap.unshift.apply(this.$model, arguments)
mutateArray.call(this, "add", 0, m, 0)
}
return m + n //IE67的unshift不会返回长度
},
shift: function () {
if (this.length) {
var el = this.$model.shift()
mutateArray.call(this, "del", 0, 1, 0)
return el //返回被移除的元素
}
},
pop: function () {
var n = this.length
if (n) {
var el = this.$model.pop()
mutateArray.call(this, "del", n - 1, 1, Math.max(0, n - 2))
return el //返回被移除的元素
}
},
splice: function (start) {
var m = arguments.length, args = [], change
var removed = _splice.apply(this.$model, arguments)
if (removed.length) { //如果用户删掉了元素
args.push("del", start, removed.length, 0)
change = true
}
if (m > 2) { //如果用户添加了元素
if (change) {
args.splice(3, 1, 0, "add", start, m - 2)
} else {
args.push("add", start, m - 2, 0)
}
change = true
}
if (change) { //返回被移除的元素
return mutateArray.apply(this, args)
} else {
return []
}
},
contains: function (el) { //判定是否包含
return this.indexOf(el) !== -1
},
remove: function (el) { //移除第一个等于给定值的元素
return this.removeAt(this.indexOf(el))
},
removeAt: function (index) { //移除指定索引上的元素
if (index >= 0) {
this.$model.splice(index, 1)
return mutateArray.call(this, "del", index, 1, 0)
}
return []
},
clear: function () {
eachProxyRecycler(this.$proxy, "each")
this.$model.length = this.$proxy.length = this.length = this._.length = 0 //清空数组
this._fire("clear", 0)
return this
},
removeAll: function (all) { //移除N个元素
if (Array.isArray(all)) {
for (var i = this.length - 1; i >= 0; i--) {
if (all.indexOf(this[i]) !== -1) {
this.removeAt(i)
}
}
} else if (typeof all === "function") {
for (i = this.length - 1; i >= 0; i--) {
if (all(this[i], i)) {
this.removeAt(i)
}
}
} else {
this.clear()
}
},
ensure: function (el) {
if (!this.contains(el)) { //只有不存在才push
this.push(el)
}
return this
},
set: function (index, val) {
if (index >= 0) {
var valueType = avalon.type(val)
if (val && val.$model) {
val = val.$model
}
var target = this[index]
if (valueType === "object") {
for (var i in val) {
if (target.hasOwnProperty(i)) {
target[i] = val[i]
}
}
} else if (valueType === "array") {
target.clear().push.apply(target, val)
} else if (target !== val) {
this[index] = val
this.$model[index] = val
var proxy = this.$proxy[index]
if (proxy) {
fireDependencies(proxy.$events.$index)
}
}
}
return this
}
}
//相当于原来bindingExecutors.repeat 的index分支
function resetIndex(array, pos) {
var last = array.length - 1
for (var el; el = array[pos]; pos++) {
el.$index = pos
el.$first = pos === 0
el.$last = pos === last
}
}
function sortByIndex(array, indexes) {
var map = {};
for (var i = 0, n = indexes.length; i < n; i++) {
map[i] = array[i] // preserve
var j = indexes[i]
if (j in map) {
array[i] = map[j]
delete map[j]
} else {
array[i] = array[j]
}
}
}
"sort,reverse".replace(rword, function (method) {
arrayPrototype[method] = function () {
var newArray = this.$model//这是要排序的新数组
var oldArray = newArray.concat() //保持原来状态的旧数组
var mask = Math.random()
var indexes = []
var hasSort
ap[method].apply(newArray, arguments) //排序
for (var i = 0, n = oldArray.length; i < n; i++) {
var neo = newArray[i]
var old = oldArray[i]
if (isEqual(neo, old)) {
indexes.push(i)
} else {
var index = oldArray.indexOf(neo)
indexes.push(index)//得到新数组的每个元素在旧数组对应的位置
oldArray[index] = mask //屏蔽已经找过的元素
hasSort = true
}
}
if (hasSort) {
sortByIndex(this, indexes)
sortByIndex(this.$proxy, indexes)
this._fire("move", indexes)
resetIndex(this.$proxy, 0)
}
return this
}
})
var eachProxyPool = []
function eachProxyFactory() {
var source = {
$index: NaN,
$first: NaN,
$last: NaN,
$map: {},
$host: {},
$outer: {},
$remove: avalon.noop,
el: {
get: function () {
//avalon1.4.4中,计算属性的订阅数组不再添加绑定对象
return this.$host[this.$index]
},
set: function (val) {
this.$host.set(this.$index, val)
}
}
}
var second = {
$last: 1,
$first: 1,
$index: 1
}
var proxy = modelFactory(source, second)
proxy.$id = generateID("$proxy$each")
return proxy
}
function eachProxyAgent(index, host) {
var proxy = eachProxyPool.shift()
if (!proxy) {
proxy = eachProxyFactory( )
}else{
proxy.$compute()
}
var last = host.length - 1
proxy.$host = host
proxy.$index = index
proxy.$first = index === 0
proxy.$last = index === last
proxy.$map = host.$map
proxy.$remove = function () {
return host.removeAt(proxy.$index)
}
return proxy
}
/*********************************************************************
* 依赖调度系统 *
**********************************************************************/
//检测两个对象间的依赖关系
var dependencyDetection = (function () {
var outerFrames = []
var currentFrame
return {
begin: function (accessorObject) {
//accessorObject为一个拥有callback的对象
outerFrames.push(currentFrame)
currentFrame = accessorObject
},
end: function () {
currentFrame = outerFrames.pop()
},
collectDependency: function (vmodel, accessor) {
if (currentFrame) {
//被dependencyDetection.begin调用
currentFrame.callback(vmodel, accessor);
}
}
};
})()
//将绑定对象注入到其依赖项的订阅数组中
var ronduplex = /^(duplex|on)$/
avalon.injectBinding = function (data) {
var fn = data.evaluator
if (fn) { //如果是求值函数
dependencyDetection.begin({
callback: function (vmodel, dependency) {
injectDependency(vmodel.$events[dependency._name], data)
}
})
try {
var c = ronduplex.test(data.type) ? data : fn.apply(0, data.args)
data.handler(c, data.element, data)
} catch (e) {
//log("warning:exception throwed in [avalon.injectBinding] " + e)
delete data.evaluator
var node = data.element
if (node.nodeType === 3) {
var parent = node.parentNode
if (kernel.commentInterpolate) {
parent.replaceChild(DOC.createComment(data.value), node)
} else {
node.data = openTag + data.value + closeTag
}
}
} finally {
dependencyDetection.end()
}
}
}
//将依赖项(比它高层的访问器或构建视图刷新函数的绑定对象)注入到订阅者数组
function injectDependency(list, data) {
data = data || Registry[expose]
if (list && data && avalon.Array.ensure(list, data) && data.element) {
injectDisposeQueue(data, list)
}
}
//通知依赖于这个访问器的订阅者更新自身
function fireDependencies(list) {
if (list && list.length) {
if (new Date() - beginTime > 444 && typeof list[0] === "object") {
rejectDisposeQueue()
}
var args = aslice.call(arguments, 1)
for (var i = list.length, fn; fn = list[--i]; ) {
var el = fn.element
if (el && el.parentNode) {
if (fn.$repeat) {
fn.handler.apply(fn, args) //处理监控数组的方法
} else if (fn.type !== "on") { //事件绑定只能由用户触发,不能由程序触发
var fun = fn.evaluator || noop
fn.handler(fun.apply(0, fn.args || []), el, fn)
}
}
}
}
}
/*********************************************************************
* 定时GC回收机制 *
**********************************************************************/
var disposeCount = 0
var disposeQueue = avalon.$$subscribers = []
var beginTime = new Date()
var oldInfo = {}
function getUid(obj) { //IE9+,标准浏览器
return obj.uniqueNumber || (obj.uniqueNumber = ++disposeCount)
}
//添加到回收列队中
function injectDisposeQueue(data, list) {
var elem = data.element
if (!data.uuid) {
if (elem.nodeType !== 1) {
data.uuid = data.type + (data.pos || 0) + "-" + getUid(elem.parentNode)
} else {
data.uuid = data.name + "-" + getUid(elem)
}
}
var lists = data.lists || (data.lists = [])
avalon.Array.ensure(lists, list)
list.$uuid = list.$uuid || generateID()
if (!disposeQueue[data.uuid]) {
disposeQueue[data.uuid] = 1
disposeQueue.push(data)
}
}
function rejectDisposeQueue(data) {
var i = disposeQueue.length
var n = i
var allTypes = []
var iffishTypes = {}
var newInfo = {}
//对页面上所有绑定对象进行分门别类, 只检测个数发生变化的类型
while (data = disposeQueue[--i]) {
var type = data.type
if (newInfo[type]) {
newInfo[type]++
} else {
newInfo[type] = 1
allTypes.push(type)
}
}
var diff = false
allTypes.forEach(function (type) {
if (oldInfo[type] !== newInfo[type]) {
iffishTypes[type] = 1
diff = true
}
})
i = n
if (diff) {
while (data = disposeQueue[--i]) {
if (!data.element)
continue
if (iffishTypes[data.type] && shouldDispose(data.element)) { //如果它没有在DOM树
disposeQueue.splice(i, 1)
delete disposeQueue[data.uuid]
var lists = data.lists
for (var k = 0, list; list = lists[k++]; ) {
avalon.Array.remove(lists, list)
avalon.Array.remove(list, data)
}
disposeData(data)
}
}
}
oldInfo = newInfo
beginTime = new Date()
}
function disposeData(data) {
data.element = null
data.rollback && data.rollback()
for (var key in data) {
data[key] = null
}
}
function shouldDispose(el) {
try {//IE下,如果文本节点脱离DOM树,访问parentNode会报错
if (!el.parentNode) {
return true
}
} catch (e) {
return true
}
return el.msRetain ? 0 : (el.nodeType === 1 ? !root.contains(el) : !avalon.contains(root, el))
}
/************************************************************************
* HTML处理(parseHTML, innerHTML, clearHTML) *
**************************************************************************/
//parseHTML的辅助变量
var tagHooks = new function() {// jshint ignore:line
avalon.mix(this, {
option: DOC.createElement("select"),
thead: DOC.createElement("table"),
td: DOC.createElement("tr"),
area: DOC.createElement("map"),
tr: DOC.createElement("tbody"),
col: DOC.createElement("colgroup"),
legend: DOC.createElement("fieldset"),
_default: DOC.createElement("div"),
"g": DOC.createElementNS("http://www.w3.org/2000/svg", "svg")
})
this.optgroup = this.option
this.tbody = this.tfoot = this.colgroup = this.caption = this.thead
this.th = this.td
}// jshint ignore:line
String("circle,defs,ellipse,image,line,path,polygon,polyline,rect,symbol,text,use").replace(rword, function(tag) {
tagHooks[tag] = tagHooks.g //处理SVG
})
var rtagName = /<([\w:]+)/
var rxhtml = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig
var scriptTypes = oneObject(["", "text/javascript", "text/ecmascript", "application/ecmascript", "application/javascript"])
var script = DOC.createElement("script")
var rhtml = /<|&#?\w+;/
avalon.parseHTML = function(html) {
var fragment = avalonFragment.cloneNode(false)
if (typeof html !== "string" ) {
return fragment
}
if (!rhtml.test(html)) {
fragment.appendChild(DOC.createTextNode(html))
return fragment
}
html = html.replace(rxhtml, "<$1></$2>").trim()
var tag = (rtagName.exec(html) || ["", ""])[1].toLowerCase(),
//取得其标签名
wrapper = tagHooks[tag] || tagHooks._default,
firstChild
wrapper.innerHTML = html
var els = wrapper.getElementsByTagName("script")
if (els.length) { //使用innerHTML生成的script节点不会发出请求与执行text属性
for (var i = 0, el; el = els[i++]; ) {
if (scriptTypes[el.type]) {
var neo = script.cloneNode(false) //FF不能省略参数
ap.forEach.call(el.attributes, function(attr) {
neo.setAttribute(attr.name, attr.value)
})// jshint ignore:line
neo.text = el.text
el.parentNode.replaceChild(neo, el)
}
}
}
while (firstChild = wrapper.firstChild) { // 将wrapper上的节点转移到文档碎片上!
fragment.appendChild(firstChild)
}
return fragment
}
avalon.innerHTML = function(node, html) {
var a = this.parseHTML(html)
this.clearHTML(node).appendChild(a)
}
avalon.clearHTML = function(node) {
node.textContent = ""
while (node.firstChild) {
node.removeChild(node.firstChild)
}
return node
}
/*********************************************************************
* avalon的原型方法定义区 *
**********************************************************************/
function hyphen(target) {
//转换为连字符线风格
return target.replace(/([a-z\d])([A-Z]+)/g, "$1-$2").toLowerCase()
}
function camelize(target) {
//转换为驼峰风格
if (target.indexOf("-") < 0 && target.indexOf("_") < 0) {
return target //提前判断,提高getStyle等的效率
}
return target.replace(/[-_][^-_]/g, function(match) {
return match.charAt(1).toUpperCase()
})
}
"add,remove".replace(rword, function(method) {
avalon.fn[method + "Class"] = function(cls) {
var el = this[0]
//https://developer.mozilla.org/zh-CN/docs/Mozilla/Firefox/Releases/26
if (cls && typeof cls === "string" && el && el.nodeType === 1) {
cls.replace(/\S+/g, function(c) {
el.classList[method](c)
})
}
return this
}
})
avalon.fn.mix({
hasClass: function(cls) {
var el = this[0] || {} //IE10+, chrome8+, firefox3.6+, safari5.1+,opera11.5+支持classList,chrome24+,firefox26+支持classList2.0
return el.nodeType === 1 && el.classList.contains(cls)
},
toggleClass: function(value, stateVal) {
var className, i = 0
var classNames = String(value).split(/\s+/)
var isBool = typeof stateVal === "boolean"
while ((className = classNames[i++])) {
var state = isBool ? stateVal : !this.hasClass(className)
this[state ? "addClass" : "removeClass"](className)
}
return this
},
attr: function(name, value) {
if (arguments.length === 2) {
this[0].setAttribute(name, value)
return this
} else {
return this[0].getAttribute(name)
}
},
data: function(name, value) {
name = "data-" + hyphen(name || "")
switch (arguments.length) {
case 2:
this.attr(name, value)
return this
case 1:
var val = this.attr(name)
return parseData(val)
case 0:
var ret = {}
ap.forEach.call(this[0].attributes, function(attr) {
if (attr) {
name = attr.name
if (!name.indexOf("data-")) {
name = camelize(name.slice(5))
ret[name] = parseData(attr.value)
}
}
})
return ret
}
},
removeData: function(name) {
name = "data-" + hyphen(name)
this[0].removeAttribute(name)
return this
},
css: function(name, value) {
if (avalon.isPlainObject(name)) {
for (var i in name) {
avalon.css(this, i, name[i])
}
} else {
var ret = avalon.css(this, name, value)
}
return ret !== void 0 ? ret : this
},
position: function() {
var offsetParent, offset,
elem = this[0],
parentOffset = {
top: 0,
left: 0
};
if (!elem) {
return
}
if (this.css("position") === "fixed") {
offset = elem.getBoundingClientRect()
} else {
offsetParent = this.offsetParent() //得到真正的offsetParent
offset = this.offset() // 得到正确的offsetParent
if (offsetParent[0].tagName !== "HTML") {
parentOffset = offsetParent.offset()
}
parentOffset.top += avalon.css(offsetParent[0], "borderTopWidth", true)
parentOffset.left += avalon.css(offsetParent[0], "borderLeftWidth", true)
// Subtract offsetParent scroll positions
parentOffset.top -= offsetParent.scrollTop()
parentOffset.left -= offsetParent.scrollLeft()
}
return {
top: offset.top - parentOffset.top - avalon.css(elem, "marginTop", true),
left: offset.left - parentOffset.left - avalon.css(elem, "marginLeft", true)
}
},
offsetParent: function() {
var offsetParent = this[0].offsetParent
while (offsetParent && avalon.css(offsetParent, "position") === "static") {
offsetParent = offsetParent.offsetParent;
}
return avalon(offsetParent || root)
},
bind: function(type, fn, phase) {
if (this[0]) { //此方法不会链
return avalon.bind(this[0], type, fn, phase)
}
},
unbind: function(type, fn, phase) {
if (this[0]) {
avalon.unbind(this[0], type, fn, phase)
}
return this
},
val: function(value) {
var node = this[0]
if (node && node.nodeType === 1) {
var get = arguments.length === 0
var access = get ? ":get" : ":set"
var fn = valHooks[getValType(node) + access]
if (fn) {
var val = fn(node, value)
} else if (get) {
return (node.value || "").replace(/\r/g, "")
} else {
node.value = value
}
}
return get ? val : this
}
})
if (root.dataset) {
avalon.fn.data = function(name, val) {
name = name && camelize(name)
var dataset = this[0].dataset
switch (arguments.length) {
case 2:
dataset[name] = val
return this
case 1:
val = dataset[name]
return parseData(val)
case 0:
var ret = createMap()
for (name in dataset) {
ret[name] = parseData(dataset[name])
}
return ret
}
}
}
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/
avalon.parseJSON = JSON.parse
function parseData(data) {
try {
if (typeof data === "object")
return data
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null : +data + "" === data ? +data : rbrace.test(data) ? JSON.parse(data) : data
} catch (e) {}
return data
}
avalon.each({
scrollLeft: "pageXOffset",
scrollTop: "pageYOffset"
}, function(method, prop) {
avalon.fn[method] = function(val) {
var node = this[0] || {}, win = getWindow(node),
top = method === "scrollTop"
if (!arguments.length) {
return win ? win[prop] : node[method]
} else {
if (win) {
win.scrollTo(!top ? val : win[prop], top ? val : win[prop])
} else {
node[method] = val
}
}
}
})
function getWindow(node) {
return node.window && node.document ? node : node.nodeType === 9 ? node.defaultView : false
}
//=============================css相关==================================
var cssHooks = avalon.cssHooks = createMap()
var prefixes = ["", "-webkit-", "-moz-", "-ms-"] //去掉opera-15的支持
var cssMap = {
"float": "cssFloat"
}
avalon.cssNumber = oneObject("columnCount,order,fillOpacity,fontWeight,lineHeight,opacity,orphans,widows,zIndex,zoom")
avalon.cssName = function(name, host, camelCase) {
if (cssMap[name]) {
return cssMap[name]
}
host = host || root.style
for (var i = 0, n = prefixes.length; i < n; i++) {
camelCase = camelize(prefixes[i] + name)
if (camelCase in host) {
return (cssMap[name] = camelCase)
}
}
return null
}
cssHooks["@:set"] = function(node, name, value) {
node.style[name] = value
}
cssHooks["@:get"] = function(node, name) {
if (!node || !node.style) {
throw new Error("getComputedStyle要求传入一个节点 " + node)
}
var ret, computed = getComputedStyle(node)
if (computed) {
ret = name === "filter" ? computed.getPropertyValue(name) : computed[name]
if (ret === "") {
ret = node.style[name] //其他浏览器需要我们手动取内联样式
}
}
return ret
}
cssHooks["opacity:get"] = function(node) {
var ret = cssHooks["@:get"](node, "opacity")
return ret === "" ? "1" : ret
}
"top,left".replace(rword, function(name) {
cssHooks[name + ":get"] = function(node) {
var computed = cssHooks["@:get"](node, name)
return /px$/.test(computed) ? computed :
avalon(node).position()[name] + "px"
}
})
var cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}
var rdisplayswap = /^(none|table(?!-c[ea]).+)/
function showHidden(node, array) {
//http://www.cnblogs.com/rubylouvre/archive/2012/10/27/2742529.html
if (node.offsetWidth <= 0) { //opera.offsetWidth可能小于0
var styles = getComputedStyle(node, null)
if (rdisplayswap.test(styles["display"])) {
var obj = {
node: node
}
for (var name in cssShow) {
obj[name] = styles[name]
node.style[name] = cssShow[name]
}
array.push(obj)
}
var parent = node.parentNode
if (parent && parent.nodeType === 1) {
showHidden(parent, array)
}
}
}
"Width,Height".replace(rword, function(name) { //fix 481
var method = name.toLowerCase(),
clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name
cssHooks[method + ":get"] = function(node, which, override) {
var boxSizing = -4
if (typeof override === "number") {
boxSizing = override
}
which = name === "Width" ? ["Left", "Right"] : ["Top", "Bottom"]
var ret = node[offsetProp] // border-box 0
if (boxSizing === 2) { // margin-box 2
return ret + avalon.css(node, "margin" + which[0], true) + avalon.css(node, "margin" + which[1], true)
}
if (boxSizing < 0) { // padding-box -2
ret = ret - avalon.css(node, "border" + which[0] + "Width", true) - avalon.css(node, "border" + which[1] + "Width", true)
}
if (boxSizing === -4) { // content-box -4
ret = ret - avalon.css(node, "padding" + which[0], true) - avalon.css(node, "padding" + which[1], true)
}
return ret
}
cssHooks[method + "&get"] = function(node) {
var hidden = [];
showHidden(node, hidden);
var val = cssHooks[method + ":get"](node)
for (var i = 0, obj; obj = hidden[i++];) {
node = obj.node
for (var n in obj) {
if (typeof obj[n] === "string") {
node.style[n] = obj[n]
}
}
}
return val;
}
avalon.fn[method] = function(value) { //会忽视其display
var node = this[0]
if (arguments.length === 0) {
if (node.setTimeout) { //取得窗口尺寸,IE9后可以用node.innerWidth /innerHeight代替
return node["inner" + name]
}
if (node.nodeType === 9) { //取得页面尺寸
var doc = node.documentElement
//FF chrome html.scrollHeight< body.scrollHeight
//IE 标准模式 : html.scrollHeight> body.scrollHeight
//IE 怪异模式 : html.scrollHeight 最大等于可视窗口多一点?
return Math.max(node.body[scrollProp], doc[scrollProp], node.body[offsetProp], doc[offsetProp], doc[clientProp])
}
return cssHooks[method + "&get"](node)
} else {
return this.css(method, value)
}
}
avalon.fn["inner" + name] = function() {
return cssHooks[method + ":get"](this[0], void 0, -2)
}
avalon.fn["outer" + name] = function(includeMargin) {
return cssHooks[method + ":get"](this[0], void 0, includeMargin === true ? 2 : 0)
}
})
avalon.fn.offset = function() { //取得距离页面左右角的坐标
var node = this[0]
try {
var rect = node.getBoundingClientRect()
// Make sure element is not hidden (display: none) or disconnected
// https://github.com/jquery/jquery/pull/2043/files#r23981494
if (rect.width || rect.height || node.getClientRects().length) {
var doc = node.ownerDocument
var root = doc.documentElement
var win = doc.defaultView
return {
top: rect.top + win.pageYOffset - root.clientTop,
left: rect.left + win.pageXOffset - root.clientLeft
}
}
} catch (e) {
return {
left: 0,
top: 0
}
}
}
//=============================val相关=======================
function getValType(elem) {
var ret = elem.tagName.toLowerCase()
return ret === "input" && /checkbox|radio/.test(elem.type) ? "checked" : ret
}
var valHooks = {
"select:get": function(node, value) {
var option, options = node.options,
index = node.selectedIndex,
one = node.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ? max : one ? index : 0
for (; i < max; i++) {
option = options[i]
//旧式IE在reset后不会改变selected,需要改用i === index判定
//我们过滤所有disabled的option元素,但在safari5下,如果设置select为disable,那么其所有孩子都disable
//因此当一个元素为disable,需要检测其是否显式设置了disable及其父节点的disable情况
if ((option.selected || i === index) && !option.disabled) {
value = option.value
if (one) {
return value
}
//收集所有selected值组成数组返回
values.push(value)
}
}
return values
},
"select:set": function(node, values, optionSet) {
values = [].concat(values) //强制转换为数组
for (var i = 0, el; el = node.options[i++];) {
if ((el.selected = values.indexOf(el.value) > -1)) {
optionSet = true
}
}
if (!optionSet) {
node.selectedIndex = -1
}
}
}
/*********************************************************************
* 编译系统 *
**********************************************************************/
var quote = JSON.stringify
var keywords = [
"break,case,catch,continue,debugger,default,delete,do,else,false",
"finally,for,function,if,in,instanceof,new,null,return,switch,this",
"throw,true,try,typeof,var,void,while,with", /* 关键字*/
"abstract,boolean,byte,char,class,const,double,enum,export,extends",
"final,float,goto,implements,import,int,interface,long,native",
"package,private,protected,public,short,static,super,synchronized",
"throws,transient,volatile", /*保留字*/
"arguments,let,yield,undefined" /* ECMA 5 - use strict*/].join(",")
var rrexpstr = /\/\*[\w\W]*?\*\/|\/\/[^\n]*\n|\/\/[^\n]*$|"(?:[^"\\]|\\[\w\W])*"|'(?:[^'\\]|\\[\w\W])*'|[\s\t\n]*\.[\s\t\n]*[$\w\.]+/g
var rsplit = /[^\w$]+/g
var rkeywords = new RegExp(["\\b" + keywords.replace(/,/g, '\\b|\\b') + "\\b"].join('|'), 'g')
var rnumber = /\b\d[^,]*/g
var rcomma = /^,+|,+$/g
var variablePool = new Cache(512)
var getVariables = function (code) {
var key = "," + code.trim()
var ret = variablePool.get(key)
if (ret) {
return ret
}
var match = code
.replace(rrexpstr, "")
.replace(rsplit, ",")
.replace(rkeywords, "")
.replace(rnumber, "")
.replace(rcomma, "")
.split(/^$|,+/)
return variablePool.put(key, uniqSet(match))
}
/*添加赋值语句*/
function addAssign(vars, scope, name, data) {
var ret = [],
prefix = " = " + name + "."
var isProxy = /\$proxy\$each/.test(scope.$id)
for (var i = vars.length, prop; prop = vars[--i]; ) {
var el = isProxy && scope.$map[prop] ? "el" : prop
if (scope.hasOwnProperty(el)) {
ret.push(prop + prefix + el)
data.vars.push(prop)
if (data.type === "duplex") {
vars.get = name + "." + el
}
vars.splice(i, 1)
}
}
return ret
}
function uniqSet(array) {
var ret = [],
unique = {}
for (var i = 0; i < array.length; i++) {
var el = array[i]
var id = el && typeof el.$id === "string" ? el.$id : el
if (!unique[id]) {
unique[id] = ret.push(el)
}
}
return ret
}
//缓存求值函数,以便多次利用
var evaluatorPool = new Cache(128)
//取得求值函数及其传参
var rduplex = /\w\[.*\]|\w\.\w/
var rproxy = /(\$proxy\$[a-z]+)\d+$/
var rthimRightParentheses = /\)\s*$/
var rthimOtherParentheses = /\)\s*\|/g
var rquoteFilterName = /\|\s*([$\w]+)/g
var rpatchBracket = /"\s*\["/g
var rthimLeftParentheses = /"\s*\(/g
function parseFilter(val, filters) {
filters = filters
.replace(rthimRightParentheses, "")//处理最后的小括号
.replace(rthimOtherParentheses, function () {//处理其他小括号
return "],|"
})
.replace(rquoteFilterName, function (a, b) { //处理|及它后面的过滤器的名字
return "[" + quote(b)
})
.replace(rpatchBracket, function () {
return '"],["'
})
.replace(rthimLeftParentheses, function () {
return '",'
}) + "]"
return "return avalon.filters.$filter(" + val + ", " + filters + ")"
}
function parseExpr(code, scopes, data) {
var dataType = data.type
var filters = data.filters || ""
var exprId = scopes.map(function (el) {
return String(el.$id).replace(rproxy, "$1")
}) + code + dataType + filters
var vars = getVariables(code).concat(),
assigns = [],
names = [],
args = [],
prefix = ""
//args 是一个对象数组, names 是将要生成的求值函数的参数
scopes = uniqSet(scopes)
data.vars = []
for (var i = 0, sn = scopes.length; i < sn; i++) {
if (vars.length) {
var name = "vm" + expose + "_" + i
names.push(name)
args.push(scopes[i])
assigns.push.apply(assigns, addAssign(vars, scopes[i], name, data))
}
}
if (!assigns.length && dataType === "duplex") {
return
}
if (dataType !== "duplex" && (code.indexOf("||") > -1 || code.indexOf("&&") > -1)) {
//https://github.com/RubyLouvre/avalon/issues/583
data.vars.forEach(function (v) {
var reg = new RegExp("\\b" + v + "(?:\\.\\w+|\\[\\w+\\])+", "ig")
code = code.replace(reg, function (_) {
var c = _.charAt(v.length)
var r = IEVersion ? code.slice(arguments[1] + _.length) : RegExp.rightContext
var method = /^\s*\(/.test(r)
if (c === "." || c === "[" || method) {//比如v为aa,我们只匹配aa.bb,aa[cc],不匹配aaa.xxx
var name = "var" + String(Math.random()).replace(/^0\./, "")
if (method) {//array.size()
var array = _.split(".")
if (array.length > 2) {
var last = array.pop()
assigns.push(name + " = " + array.join("."))
return name + "." + last
} else {
return _
}
}
assigns.push(name + " = " + _)
return name
} else {
return _
}
})
})
}
//---------------args----------------
data.args = args
//---------------cache----------------
delete data.vars
var fn = evaluatorPool.get(exprId) //直接从缓存,免得重复生成
if (fn) {
data.evaluator = fn
return
}
prefix = assigns.join(", ")
if (prefix) {
prefix = "var " + prefix
}
if (/\S/.test(filters)) { //文本绑定,双工绑定才有过滤器
if (!/text|html/.test(data.type)) {
throw Error("ms-" + data.type + "不支持过滤器")
}
code = "\nvar ret" + expose + " = " + code + ";\r\n"
code += parseFilter("ret" + expose, filters)
} else if (dataType === "duplex") { //双工绑定
var _body = "'use strict';\nreturn function(vvv){\n\t" +
prefix +
";\n\tif(!arguments.length){\n\t\treturn " +
code +
"\n\t}\n\t" + (!rduplex.test(code) ? vars.get : code) +
"= vvv;\n} "
try {
fn = Function.apply(noop, names.concat(_body))
data.evaluator = evaluatorPool.put(exprId, fn)
} catch (e) {
log("debug: parse error," + e.message)
}
return
} else if (dataType === "on") { //事件绑定
if (code.indexOf("(") === -1) {
code += ".call(this, $event)"
} else {
code = code.replace("(", ".call(this,")
}
names.push("$event")
code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
var lastIndex = code.lastIndexOf("\nreturn")
var header = code.slice(0, lastIndex)
var footer = code.slice(lastIndex)
code = header + "\n" + footer
} else { //其他绑定
code = "\nreturn " + code + ";" //IE全家 Function("return ")出错,需要Function("return ;")
}
try {
fn = Function.apply(noop, names.concat("'use strict';\n" + prefix + code))
data.evaluator = evaluatorPool.put(exprId, fn)
} catch (e) {
log("debug: parse error," + e.message)
} finally {
vars = assigns = names = null //释放内存
}
}
//parseExpr的智能引用代理
function parseExprProxy(code, scopes, data, tokens, noRegister) {
if (Array.isArray(tokens)) {
code = tokens.map(function (el) {
return el.expr ? "(" + el.value + ")" : quote(el.value)
}).join(" + ")
}
parseExpr(code, scopes, data)
if (data.evaluator && !noRegister) {
data.handler = bindingExecutors[data.handlerName || data.type]
//方便调试
//这里非常重要,我们通过判定视图刷新函数的element是否在DOM树决定
//将它移出订阅者列表
avalon.injectBinding(data)
}
}
avalon.parseExprProxy = parseExprProxy
/*********************************************************************
* 扫描系统 *
**********************************************************************/
avalon.scan = function(elem, vmodel) {
elem = elem || root
var vmodels = vmodel ? [].concat(vmodel) : []
scanTag(elem, vmodels)
}
//http://www.w3.org/TR/html5/syntax.html#void-elements
var stopScan = oneObject("area,base,basefont,br,col,command,embed,hr,img,input,link,meta,param,source,track,wbr,noscript,script,style,textarea".toUpperCase())
function checkScan(elem, callback, innerHTML) {
var id = setTimeout(function() {
var currHTML = elem.innerHTML
clearTimeout(id)
if (currHTML === innerHTML) {
callback()
} else {
checkScan(elem, callback, currHTML)
}
})
}
function createSignalTower(elem, vmodel) {
var id = elem.getAttribute("avalonctrl") || vmodel.$id
elem.setAttribute("avalonctrl", id)
vmodel.$events.expr = elem.tagName + '[avalonctrl="' + id + '"]'
}
var getBindingCallback = function(elem, name, vmodels) {
var callback = elem.getAttribute(name)
if (callback) {
for (var i = 0, vm; vm = vmodels[i++]; ) {
if (vm.hasOwnProperty(callback) && typeof vm[callback] === "function") {
return vm[callback]
}
}
}
}
function executeBindings(bindings, vmodels) {
for (var i = 0, data; data = bindings[i++]; ) {
data.vmodels = vmodels
bindingHandlers[data.type](data, vmodels)
if (data.evaluator && data.element && data.element.nodeType === 1) { //移除数据绑定,防止被二次解析
//chrome使用removeAttributeNode移除不存在的特性节点时会报错 https://github.com/RubyLouvre/avalon/issues/99
data.element.removeAttribute(data.name)
}
}
bindings.length = 0
}
//https://github.com/RubyLouvre/avalon/issues/636
var mergeTextNodes = IEVersion && window.MutationObserver ? function (elem) {
var node = elem.firstChild, text
while (node) {
var aaa = node.nextSibling
if (node.nodeType === 3) {
if (text) {
text.nodeValue += node.nodeValue
elem.removeChild(node)
} else {
text = node
}
} else {
text = null
}
node = aaa
}
} : 0
var rmsAttr = /ms-(\w+)-?(.*)/
var priorityMap = {
"if": 10,
"repeat": 90,
"data": 100,
"widget": 110,
"each": 1400,
"with": 1500,
"duplex": 2000,
"on": 3000
}
var events = oneObject("animationend,blur,change,input,click,dblclick,focus,keydown,keypress,keyup,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,mouseup,scan,scroll,submit")
var obsoleteAttrs = oneObject("value,title,alt,checked,selected,disabled,readonly,enabled")
function bindingSorter(a, b) {
return a.priority - b.priority
}
function scanAttr(elem, vmodels, match) {
var scanNode = true
if (vmodels.length) {
var attributes = elem.attributes
var bindings = []
var fixAttrs = []
var msData = createMap()
for (var i = 0, attr; attr = attributes[i++]; ) {
if (attr.specified) {
if (match = attr.name.match(rmsAttr)) {
//如果是以指定前缀命名的
var type = match[1]
var param = match[2] || ""
var value = attr.value
var name = attr.name
if (events[type]) {
param = type
type = "on"
} else if (obsoleteAttrs[type]) {
if (type === "enabled") {//吃掉ms-enabled绑定,用ms-disabled代替
log("warning!ms-enabled或ms-attr-enabled已经被废弃")
type = "disabled"
value = "!(" + value + ")"
}
param = type
type = "attr"
name = "ms-" + type +"-" +param
fixAttrs.push([attr.name, name, value])
}
msData[name] = value
if (typeof bindingHandlers[type] === "function") {
var binding = {
type: type,
param: param,
element: elem,
name: name,
value: value,
priority: (priorityMap[type] || type.charCodeAt(0) * 10 )+ (Number(param.replace(/\D/g, "")) || 0)
}
if (type === "html" || type === "text") {
var token = getToken(value)
avalon.mix(binding, token)
binding.filters = binding.filters.replace(rhasHtml, function () {
binding.type = "html"
binding.group = 1
return ""
})// jshint ignore:line
} else if (type === "duplex") {
var hasDuplex = name
} else if (name === "ms-if-loop") {
binding.priority += 100
}
bindings.push(binding)
if (type === "widget") {
elem.msData = elem.msData || msData
}
}
}
}
}
if (bindings.length) {
bindings.sort(bindingSorter)
fixAttrs.forEach(function (arr) {
log("warning!请改用" + arr[1] + "代替" + arr[0] + "!")
elem.removeAttribute(arr[0])
elem.setAttribute(arr[1], arr[2])
})
var control = elem.type
if (control && hasDuplex) {
if (msData["ms-attr-checked"]) {
log("warning!" + control + "控件不能同时定义ms-attr-checked与" + hasDuplex)
}
if (msData["ms-attr-value"]) {
log("warning!" + control + "控件不能同时定义ms-attr-value与" + hasDuplex)
}
}
for (i = 0; binding = bindings[i]; i++) {
type = binding.type
if (rnoscanAttrBinding.test(type)) {
return executeBindings(bindings.slice(0, i + 1), vmodels)
} else if (scanNode) {
scanNode = !rnoscanNodeBinding.test(type)
}
}
executeBindings(bindings, vmodels)
}
}
if (scanNode && !stopScan[elem.tagName] && rbind.test(elem.innerHTML + elem.textContent)) {
mergeTextNodes && mergeTextNodes(elem)
scanNodeList(elem, vmodels) //扫描子孙元素
}
}
var rnoscanAttrBinding = /^if|widget|repeat$/
var rnoscanNodeBinding = /^each|with|html|include$/
//function scanNodeList(parent, vmodels) {
// var node = parent.firstChild
// while (node) {
// var nextNode = node.nextSibling
// scanNode(node, node.nodeType, vmodels)
// node = nextNode
// }
//}
function scanNodeList(parent, vmodels) {
var nodes = avalon.slice(parent.childNodes)
scanNodeArray(nodes, vmodels)
}
function scanNodeArray(nodes, vmodels) {
for (var i = 0, node; node = nodes[i++]; ) {
scanNode(node, node.nodeType, vmodels)
}
}
function scanNode(node, nodeType, vmodels) {
if (nodeType === 1) {
scanTag(node, vmodels) //扫描元素节点
if( node.msCallback){
node.msCallback()
node.msCallback = void 0
}
} else if (nodeType === 3 && rexpr.test(node.data)){
scanText(node, vmodels) //扫描文本节点
} else if (kernel.commentInterpolate && nodeType === 8 && !rexpr.test(node.nodeValue)) {
scanText(node, vmodels) //扫描注释节点
}
}
function scanTag(elem, vmodels, node) {
//扫描顺序 ms-skip(0) --> ms-important(1) --> ms-controller(2) --> ms-if(10) --> ms-repeat(100)
//--> ms-if-loop(110) --> ms-attr(970) ...--> ms-each(1400)-->ms-with(1500)--〉ms-duplex(2000)垫后
var a = elem.getAttribute("ms-skip")
var b = elem.getAttributeNode("ms-important")
var c = elem.getAttributeNode("ms-controller")
if (typeof a === "string") {
return
} else if (node = b || c) {
var newVmodel = avalon.vmodels[node.value]
if (!newVmodel) {
return
}
//ms-important不包含父VM,ms-controller相反
vmodels = node === b ? [newVmodel] : [newVmodel].concat(vmodels)
elem.removeAttribute(node.name) //removeAttributeNode不会刷新[ms-controller]样式规则
elem.classList.remove(node.name)
createSignalTower(elem, newVmodel)
}
scanAttr(elem, vmodels) //扫描特性节点
}
var rhasHtml = /\|\s*html\s*/,
r11a = /\|\|/g,
rlt = /</g,
rgt = />/g,
rstringLiteral = /(['"])(\\\1|.)+?\1/g
function getToken(value, pos) {
if (value.indexOf("|") > 0) {
var scapegoat = value.replace( rstringLiteral, function(_){
return Array(_.length+1).join("1")// jshint ignore:line
})
var index = scapegoat.replace(r11a, "\u1122\u3344").indexOf("|") //干掉所有短路或
if (index > -1) {
return {
filters: value.slice(index),
value: value.slice(0, index),
pos: pos || 0,
expr: true
}
}
}
return {
value: value,
filters: "",
expr: true
}
}
function scanExpr(str) {
var tokens = [],
value, start = 0,
stop
do {
stop = str.indexOf(openTag, start)
if (stop === -1) {
break
}
value = str.slice(start, stop)
if (value) { // {{ 左边的文本
tokens.push({
value: value,
filters: "",
expr: false
})
}
start = stop + openTag.length
stop = str.indexOf(closeTag, start)
if (stop === -1) {
break
}
value = str.slice(start, stop)
if (value) { //处理{{ }}插值表达式
tokens.push(getToken(value, start))
}
start = stop + closeTag.length
} while (1)
value = str.slice(start)
if (value) { //}} 右边的文本
tokens.push({
value: value,
expr: false,
filters: ""
})
}
return tokens
}
function scanText(textNode, vmodels) {
var bindings = []
if (textNode.nodeType === 8) {
var token = getToken(textNode.nodeValue)
var tokens = [token]
} else {
tokens = scanExpr(textNode.data)
}
if (tokens.length) {
for (var i = 0; token = tokens[i++]; ) {
var node = DOC.createTextNode(token.value) //将文本转换为文本节点,并替换原来的文本节点
if (token.expr) {
token.type = "text"
token.element = node
token.filters = token.filters.replace(rhasHtml, function() {
token.type = "html"
return ""
})// jshint ignore:line
bindings.push(token) //收集带有插值表达式的文本
}
avalonFragment.appendChild(node)
}
textNode.parentNode.replaceChild(avalonFragment, textNode)
if (bindings.length)
executeBindings(bindings, vmodels)
}
}
var bools = ["autofocus,autoplay,async,allowTransparency,checked,controls",
"declare,disabled,defer,defaultChecked,defaultSelected",
"contentEditable,isMap,loop,multiple,noHref,noResize,noShade",
"open,readOnly,selected"
].join(",")
var boolMap = {}
bools.replace(rword, function(name) {
boolMap[name.toLowerCase()] = name
})
var propMap = { //属性名映射
"accept-charset": "acceptCharset",
"char": "ch",
"charoff": "chOff",
"class": "className",
"for": "htmlFor",
"http-equiv": "httpEquiv"
}
var anomaly = ["accessKey,bgColor,cellPadding,cellSpacing,codeBase,codeType,colSpan",
"dateTime,defaultValue,frameBorder,longDesc,maxLength,marginWidth,marginHeight",
"rowSpan,tabIndex,useMap,vSpace,valueType,vAlign"
].join(",")
anomaly.replace(rword, function(name) {
propMap[name.toLowerCase()] = name
})
var rnoscripts = /<noscript.*?>(?:[\s\S]+?)<\/noscript>/img
var rnoscriptText = /<noscript.*?>([\s\S]+?)<\/noscript>/im
var getXHR = function() {
return new(window.XMLHttpRequest || ActiveXObject)("Microsoft.XMLHTTP") // jshint ignore:line
}
var templatePool = avalon.templateCache = {}
bindingHandlers.attr = function(data, vmodels) {
var text = data.value.trim(),
simple = true
if (text.indexOf(openTag) > -1 && text.indexOf(closeTag) > 2) {
simple = false
if (rexpr.test(text) && RegExp.rightContext === "" && RegExp.leftContext === "") {
simple = true
text = RegExp.$1
}
}
if (data.type === "include") {
var elem = data.element
data.includeRendered = getBindingCallback(elem, "data-include-rendered", vmodels)
data.includeLoaded = getBindingCallback(elem, "data-include-loaded", vmodels)
var outer = data.includeReplace = !! avalon(elem).data("includeReplace")
if (avalon(elem).data("includeCache")) {
data.templateCache = {}
}
data.startInclude = DOC.createComment("ms-include")
data.endInclude = DOC.createComment("ms-include-end")
if (outer) {
data.element = data.startInclude
elem.parentNode.insertBefore(data.startInclude, elem)
elem.parentNode.insertBefore(data.endInclude, elem.nextSibling)
} else {
elem.insertBefore(data.startInclude, elem.firstChild)
elem.appendChild(data.endInclude)
}
}
data.handlerName = "attr" //handleName用于处理多种绑定共用同一种bindingExecutor的情况
parseExprProxy(text, vmodels, data, (simple ? 0 : scanExpr(data.value)))
}
bindingExecutors.attr = function(val, elem, data) {
var method = data.type,
attrName = data.param
if (method === "css") {
avalon(elem).css(attrName, val)
} else if (method === "attr") {
// ms-attr-class="xxx" vm.xxx="aaa bbb ccc"将元素的className设置为aaa bbb ccc
// ms-attr-class="xxx" vm.xxx=false 清空元素的所有类名
// ms-attr-name="yyy" vm.yyy="ooo" 为元素设置name属性
var toRemove = (val === false) || (val === null) || (val === void 0)
if (!W3C && propMap[attrName]) { //旧式IE下需要进行名字映射
attrName = propMap[attrName]
}
var bool = boolMap[attrName]
if (typeof elem[bool] === "boolean") {
elem[bool] = !! val //布尔属性必须使用el.xxx = true|false方式设值
if (!val) { //如果为false, IE全系列下相当于setAttribute(xxx,''),会影响到样式,需要进一步处理
toRemove = true
}
}
if (toRemove) {
return elem.removeAttribute(attrName)
}
//SVG只能使用setAttribute(xxx, yyy), VML只能使用elem.xxx = yyy ,HTML的固有属性必须elem.xxx = yyy
var isInnate = rsvg.test(elem) ? false : (DOC.namespaces && isVML(elem)) ? true : attrName in elem.cloneNode(false)
if (isInnate) {
elem[attrName] = val
} else {
elem.setAttribute(attrName, val)
}
} else if (method === "include" && val) {
var vmodels = data.vmodels
var rendered = data.includeRendered
var loaded = data.includeLoaded
var replace = data.includeReplace
var target = replace ? elem.parentNode : elem
var scanTemplate = function(text) {
if (loaded) {
var newText = loaded.apply(target, [text].concat(vmodels))
if (typeof newText === "string")
text = newText
}
if (rendered) {
checkScan(target, function() {
rendered.call(target)
}, NaN)
}
var lastID = data.includeLastID
if (data.templateCache && lastID && lastID !== val) {
var lastTemplate = data.templateCache[lastID]
if (!lastTemplate) {
lastTemplate = data.templateCache[lastID] = DOC.createElement("div")
ifGroup.appendChild(lastTemplate)
}
}
data.includeLastID = val
while (true) {
var node = data.startInclude.nextSibling
if (node && node !== data.endInclude) {
target.removeChild(node)
if (lastTemplate)
lastTemplate.appendChild(node)
} else {
break
}
}
var dom = getTemplateNodes(data, val, text)
var nodes = avalon.slice(dom.childNodes)
target.insertBefore(dom, data.endInclude)
scanNodeArray(nodes, vmodels)
}
if (data.param === "src") {
if (typeof templatePool[val] === "string") {
avalon.nextTick(function() {
scanTemplate(templatePool[val])
})
} else if (Array.isArray(templatePool[val])) { //#805 防止在循环绑定中发出许多相同的请求
templatePool[val].push(scanTemplate)
} else {
var xhr = getXHR()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var s = xhr.status
if (s >= 200 && s < 300 || s === 304 || s === 1223) {
var text = xhr.responseText
for (var f = 0, fn; fn = templatePool[val][f++];) {
fn(text)
}
templatePool[val] = text
}
}
}
templatePool[val] = [scanTemplate]
xhr.open("GET", val, true)
if ("withCredentials" in xhr) {
xhr.withCredentials = true
}
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")
xhr.send(null)
}
} else {
//IE系列与够新的标准浏览器支持通过ID取得元素(firefox14+)
//http://tjvantoll.com/2012/07/19/dom-element-references-as-global-variables/
var el = val && val.nodeType === 1 ? val : DOC.getElementById(val)
if (el) {
if (el.tagName === "NOSCRIPT" && !(el.innerHTML || el.fixIE78)) { //IE7-8 innerText,innerHTML都无法取得其内容,IE6能取得其innerHTML
xhr = getXHR() //IE9-11与chrome的innerHTML会得到转义的内容,它们的innerText可以
xhr.open("GET", location, false) //谢谢Nodejs 乱炖群 深圳-纯属虚构
xhr.send(null)
//http://bbs.csdn.net/topics/390349046?page=1#post-393492653
var noscripts = DOC.getElementsByTagName("noscript")
var array = (xhr.responseText || "").match(rnoscripts) || []
var n = array.length
for (var i = 0; i < n; i++) {
var tag = noscripts[i]
if (tag) { //IE6-8中noscript标签的innerHTML,innerText是只读的
tag.style.display = "none" //http://haslayout.net/css/noscript-Ghost-Bug
tag.fixIE78 = (array[i].match(rnoscriptText) || ["", " "])[1]
}
}
}
avalon.nextTick(function() {
scanTemplate(el.fixIE78 || el.value || el.innerText || el.innerHTML)
})
}
}
} else {
if (!root.hasAttribute && typeof val === "string" && (method === "src" || method === "href")) {
val = val.replace(/&/g, "&") //处理IE67自动转义的问题
}
elem[method] = val
if (window.chrome && elem.tagName === "EMBED") {
var parent = elem.parentNode //#525 chrome1-37下embed标签动态设置src不能发生请求
var comment = document.createComment("ms-src")
parent.replaceChild(comment, elem)
parent.replaceChild(elem, comment)
}
}
}
function getTemplateNodes(data, id, text) {
var div = data.templateCache && data.templateCache[id]
if (div) {
var dom = DOC.createDocumentFragment(),
firstChild
while (firstChild = div.firstChild) {
dom.appendChild(firstChild)
}
return dom
}
return avalon.parseHTML(text)
}
//这几个指令都可以使用插值表达式,如ms-src="aaa/{{b}}/{{c}}.html"
"title,alt,src,value,css,include,href".replace(rword, function(name) {
bindingHandlers[name] = bindingHandlers.attr
})
//根据VM的属性值或表达式的值切换类名,ms-class="xxx yyy zzz:flag"
//http://www.cnblogs.com/rubylouvre/archive/2012/12/17/2818540.html
bindingHandlers["class"] = function(data, vmodels) {
var oldStyle = data.param,
text = data.value,
rightExpr
data.handlerName = "class"
if (!oldStyle || isFinite(oldStyle)) {
data.param = "" //去掉数字
var noExpr = text.replace(rexprg, function(a) {
return a.replace(/./g, "0")
//return Math.pow(10, a.length - 1) //将插值表达式插入10的N-1次方来占位
})
var colonIndex = noExpr.indexOf(":") //取得第一个冒号的位置
if (colonIndex === -1) { // 比如 ms-class="aaa bbb ccc" 的情况
var className = text
} else { // 比如 ms-class-1="ui-state-active:checked" 的情况
className = text.slice(0, colonIndex)
rightExpr = text.slice(colonIndex + 1)
parseExpr(rightExpr, vmodels, data) //决定是添加还是删除
if (!data.evaluator) {
log("debug: ms-class '" + (rightExpr || "").trim() + "' 不存在于VM中")
return false
} else {
data._evaluator = data.evaluator
data._args = data.args
}
}
var hasExpr = rexpr.test(className) //比如ms-class="width{{w}}"的情况
if (!hasExpr) {
data.immobileClass = className
}
parseExprProxy("", vmodels, data, (hasExpr ? scanExpr(className) : 0))
} else {
data.immobileClass = data.oldStyle = data.param
parseExprProxy(text, vmodels, data)
}
}
bindingExecutors["class"] = function(val, elem, data) {
var $elem = avalon(elem),
method = data.type
if (method === "class" && data.oldStyle) { //如果是旧风格
$elem.toggleClass(data.oldStyle, !! val)
} else {
//如果存在冒号就有求值函数
data.toggleClass = data._evaluator ? !! data._evaluator.apply(elem, data._args) : true
data.newClass = data.immobileClass || val
if (data.oldClass && data.newClass !== data.oldClass) {
$elem.removeClass(data.oldClass)
}
data.oldClass = data.newClass
switch (method) {
case "class":
$elem.toggleClass(data.newClass, data.toggleClass)
break
case "hover":
case "active":
if (!data.hasBindEvent) { //确保只绑定一次
var activate = "mouseenter" //在移出移入时切换类名
var abandon = "mouseleave"
if (method === "active") { //在聚焦失焦中切换类名
elem.tabIndex = elem.tabIndex || -1
activate = "mousedown"
abandon = "mouseup"
var fn0 = $elem.bind("mouseleave", function() {
data.toggleClass && $elem.removeClass(data.newClass)
})
}
var fn1 = $elem.bind(activate, function() {
data.toggleClass && $elem.addClass(data.newClass)
})
var fn2 = $elem.bind(abandon, function() {
data.toggleClass && $elem.removeClass(data.newClass)
})
data.rollback = function() {
$elem.unbind("mouseleave", fn0)
$elem.unbind(activate, fn1)
$elem.unbind(abandon, fn2)
}
data.hasBindEvent = true
}
break;
}
}
}
"hover,active".replace(rword, function(method) {
bindingHandlers[method] = bindingHandlers["class"]
})
//ms-controller绑定已经在scanTag 方法中实现
//ms-css绑定已由ms-attr绑定实现
// bindingHandlers.data 定义在if.js
bindingExecutors.data = function(val, elem, data) {
var key = "data-" + data.param
if (val && typeof val === "object") {
elem[key] = val
} else {
elem.setAttribute(key, String(val))
}
}
//双工绑定
var duplexBinding = bindingHandlers.duplex = function(data, vmodels) {
var elem = data.element,
hasCast
parseExprProxy(data.value, vmodels, data, 0, 1)
data.changed = getBindingCallback(elem, "data-duplex-changed", vmodels) || noop
if (data.evaluator && data.args) {
var params = []
var casting = oneObject("string,number,boolean,checked")
if (elem.type === "radio" && data.param === "") {
data.param = "checked"
}
if (elem.msData) {
elem.msData["ms-duplex"] = data.value
}
data.param.replace(/\w+/g, function(name) {
if (/^(checkbox|radio)$/.test(elem.type) && /^(radio|checked)$/.test(name)) {
if (name === "radio")
log("ms-duplex-radio已经更名为ms-duplex-checked")
name = "checked"
data.isChecked = true
}
if (name === "bool") {
name = "boolean"
log("ms-duplex-bool已经更名为ms-duplex-boolean")
} else if (name === "text") {
name = "string"
log("ms-duplex-text已经更名为ms-duplex-string")
}
if (casting[name]) {
hasCast = true
}
avalon.Array.ensure(params, name)
})
if (!hasCast) {
params.push("string")
}
data.param = params.join("-")
data.bound = function(type, callback) {
if (elem.addEventListener) {
elem.addEventListener(type, callback, false)
} else {
elem.attachEvent("on" + type, callback)
}
var old = data.rollback
data.rollback = function() {
elem.avalonSetter = null
avalon.unbind(elem, type, callback)
old && old()
}
}
for (var i in avalon.vmodels) {
var v = avalon.vmodels[i]
v.$fire("avalon-ms-duplex-init", data)
}
var cpipe = data.pipe || (data.pipe = pipe)
cpipe(null, data, "init")
var tagName = elem.tagName
duplexBinding[tagName] && duplexBinding[tagName](elem, data.evaluator.apply(null, data.args), data)
}
}
//不存在 bindingExecutors.duplex
function fixNull(val) {
return val == null ? "" : val
}
avalon.duplexHooks = {
checked: {
get: function(val, data) {
return !data.element.oldValue
}
},
string: {
get: function(val) { //同步到VM
return val
},
set: fixNull
},
"boolean": {
get: function(val) {
return val === "true"
},
set: fixNull
},
number: {
get: function(val, data) {
var number = parseFloat(val)
if (-val === -number) {
return number
}
var arr = /strong|medium|weak/.exec(data.element.getAttribute("data-duplex-number")) || ["medium"]
switch (arr[0]) {
case "strong":
return 0
case "medium":
return val === "" ? "" : 0
case "weak":
return val
}
},
set: fixNull
}
}
function pipe(val, data, action, e) {
data.param.replace(/\w+/g, function(name) {
var hook = avalon.duplexHooks[name]
if (hook && typeof hook[action] === "function") {
val = hook[action](val, data)
}
})
return val
}
var TimerID, ribbon = []
avalon.tick = function(fn) {
if (ribbon.push(fn) === 1) {
TimerID = setInterval(ticker, 60)
}
}
function ticker() {
for (var n = ribbon.length - 1; n >= 0; n--) {
var el = ribbon[n]
if (el() === false) {
ribbon.splice(n, 1)
}
}
if (!ribbon.length) {
clearInterval(TimerID)
}
}
var watchValueInTimer = noop
var rmsinput = /text|password|hidden/
new function() { // jshint ignore:line
try { //#272 IE9-IE11, firefox
var setters = {}
var aproto = HTMLInputElement.prototype
var bproto = HTMLTextAreaElement.prototype
function newSetter(value) { // jshint ignore:line
if (avalon.contains(root, this)) {
setters[this.tagName].call(this, value)
if (!rmsinput.test(this.type))
return
if (!this.msFocus && this.avalonSetter) {
this.avalonSetter()
}
}
}
var inputProto = HTMLInputElement.prototype
Object.getOwnPropertyNames(inputProto) //故意引发IE6-8等浏览器报错
setters["INPUT"] = Object.getOwnPropertyDescriptor(aproto, "value").set
Object.defineProperty(aproto, "value", {
set: newSetter
})
setters["TEXTAREA"] = Object.getOwnPropertyDescriptor(bproto, "value").set
Object.defineProperty(bproto, "value", {
set: newSetter
})
} catch (e) {
//在chrome 43中 ms-duplex终于不需要使用定时器实现双向绑定了
// http://updates.html5rocks.com/2015/04/DOM-attributes-now-on-the-prototype
// https://docs.google.com/document/d/1jwA8mtClwxI-QJuHT7872Z0pxpZz8PBkf2bGAbsUtqs/edit?pli=1
watchValueInTimer = avalon.tick
}
} // jshint ignore:line
//处理radio, checkbox, text, textarea, password
duplexBinding.INPUT = function(element, evaluator, data) {
var $type = element.type,
bound = data.bound,
$elem = avalon(element),
composing = false
function callback(value) {
data.changed.call(this, value, data)
}
function compositionStart() {
composing = true
}
function compositionEnd() {
composing = false
}
//当value变化时改变model的值
var updateVModel = function() {
if (composing) //处理中文输入法在minlengh下引发的BUG
return
var val = element.oldValue = element.value //防止递归调用形成死循环
var lastValue = data.pipe(val, data, "get")
if ($elem.data("duplexObserve") !== false) {
evaluator(lastValue)
callback.call(element, lastValue)
if ($elem.data("duplex-focus")) {
avalon.nextTick(function() {
element.focus()
})
}
}
}
//当model变化时,它就会改变value的值
data.handler = function() {
var val = data.pipe(evaluator(), data, "set") + ""
if (val !== element.oldValue) {
element.value = val
}
}
if (data.isChecked || $type === "radio") {
updateVModel = function() {
if ($elem.data("duplexObserve") !== false) {
var lastValue = data.pipe(element.value, data, "get")
evaluator(lastValue)
callback.call(element, lastValue)
}
}
data.handler = function() {
var val = evaluator()
var checked = data.isChecked ? !! val : val + "" === element.value
element.checked = element.oldValue = checked
}
bound("click", updateVModel)
} else if ($type === "checkbox") {
updateVModel = function() {
if ($elem.data("duplexObserve") !== false) {
var method = element.checked ? "ensure" : "remove"
var array = evaluator()
if (!Array.isArray(array)) {
log("ms-duplex应用于checkbox上要对应一个数组")
array = [array]
}
avalon.Array[method](array, data.pipe(element.value, data, "get"))
callback.call(element, array)
}
}
data.handler = function() {
var array = [].concat(evaluator()) //强制转换为数组
element.checked = array.indexOf(data.pipe(element.value, data, "get")) > -1
}
bound("change", updateVModel)
} else {
var events = element.getAttribute("data-duplex-event") || "input"
if (element.attributes["data-event"]) {
log("data-event指令已经废弃,请改用data-duplex-event")
}
events.replace(rword, function(name) {
switch (name) {
case "input":
bound("input", updateVModel)
bound("DOMAutoComplete", updateVModel)
if (!IEVersion) {
bound("compositionstart", compositionStart)
bound("compositionend", compositionEnd)
}
break
default:
bound(name, updateVModel)
break
}
})
bound("focus", function() {
element.msFocus = true
})
bound("blur", function() {
element.msFocus = false
})
if (rmsinput.test($type)) {
watchValueInTimer(function() {
if (root.contains(element)) {
if (!element.msFocus && element.oldValue !== element.value) {
updateVModel()
}
} else if (!element.msRetain) {
return false
}
})
}
element.avalonSetter = updateVModel
}
element.oldValue = element.value
avalon.injectBinding(data)
callback.call(element, element.value)
}
duplexBinding.TEXTAREA = duplexBinding.INPUT
duplexBinding.SELECT = function(element, evaluator, data) {
var $elem = avalon(element)
function updateVModel() {
if ($elem.data("duplexObserve") !== false) {
var val = $elem.val() //字符串或字符串数组
if (Array.isArray(val)) {
val = val.map(function(v) {
return data.pipe(v, data, "get")
})
} else {
val = data.pipe(val, data, "get")
}
if (val + "" !== element.oldValue) {
evaluator(val)
}
data.changed.call(element, val, data)
}
}
data.handler = function() {
var val = evaluator()
val = val && val.$model || val
if (Array.isArray(val)) {
if (!element.multiple) {
log("ms-duplex在<select multiple=true>上要求对应一个数组")
}
} else {
if (element.multiple) {
log("ms-duplex在<select multiple=false>不能对应一个数组")
}
}
//必须变成字符串后才能比较
val = Array.isArray(val) ? val.map(String) : val + ""
if (val + "" !== element.oldValue) {
$elem.val(val)
element.oldValue = val + ""
}
}
data.bound("change", updateVModel)
element.msCallback = function() {
avalon.injectBinding(data)
data.changed.call(element, evaluator(), data)
}
}
// bindingHandlers.html 定义在if.js
bindingExecutors.html = function (val, elem, data) {
var isHtmlFilter = elem.nodeType !== 1
var parent = isHtmlFilter ? elem.parentNode : elem
if (!parent)
return
val = val == null ? "" : val
if (data.oldText !== val) {
data.oldText = val
} else {
return
}
if (elem.nodeType === 3) {
var signature = generateID("html")
parent.insertBefore(DOC.createComment(signature), elem)
data.element = DOC.createComment(signature + ":end")
parent.replaceChild(data.element, elem)
elem = data.element
}
if (typeof val !== "object") {//string, number, boolean
var fragment = avalon.parseHTML(String(val))
} else if (val.nodeType === 11) { //将val转换为文档碎片
fragment = val
} else if (val.nodeType === 1 || val.item) {
var nodes = val.nodeType === 1 ? val.childNodes : val.item
fragment = avalonFragment.cloneNode(true)
while (nodes[0]) {
fragment.appendChild(nodes[0])
}
}
nodes = avalon.slice(fragment.childNodes)
//插入占位符, 如果是过滤器,需要有节制地移除指定的数量,如果是html指令,直接清空
if (isHtmlFilter) {
var endValue = elem.nodeValue.slice(0, -4)
while (true) {
var node = elem.previousSibling
if (!node || node.nodeType === 8 && node.nodeValue === endValue) {
break
} else {
parent.removeChild(node)
}
}
parent.insertBefore(fragment, elem)
} else {
avalon.clearHTML(elem).appendChild(fragment)
}
scanNodeArray(nodes, data.vmodels)
}
bindingHandlers["if"] =
bindingHandlers.data =
bindingHandlers.text =
bindingHandlers.html =
function(data, vmodels) {
parseExprProxy(data.value, vmodels, data)
}
bindingExecutors["if"] = function(val, elem, data) {
try {
if(!elem.parentNode) return
} catch(e) {return}
if (val) { //插回DOM树
if (elem.nodeType === 8) {
elem.parentNode.replaceChild(data.template, elem)
// animate.enter(data.template, elem.parentNode)
elem = data.element = data.template //这时可能为null
}
if (elem.getAttribute(data.name)) {
elem.removeAttribute(data.name)
scanAttr(elem, data.vmodels)
}
data.rollback = null
} else { //移出DOM树,并用注释节点占据原位置
if (elem.nodeType === 1) {
var node = data.element = DOC.createComment("ms-if")
elem.parentNode.replaceChild(node, elem)
// animate.leave(elem, node.parentNode, node)
data.template = elem //元素节点
ifGroup.appendChild(elem)
data.rollback = function() {
if (elem.parentNode === ifGroup) {
ifGroup.removeChild(elem)
}
}
}
}
}
//ms-important绑定已经在scanTag 方法中实现
//ms-include绑定已由ms-attr绑定实现
var rdash = /\(([^)]*)\)/
bindingHandlers.on = function(data, vmodels) {
var value = data.value
data.type = "on"
var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
if (typeof bindingHandlers.on[eventType + "Hook"] === "function") {
bindingHandlers.on[eventType + "Hook"](data)
}
if (value.indexOf("(") > 0 && value.indexOf(")") > -1) {
var matched = (value.match(rdash) || ["", ""])[1].trim()
if (matched === "" || matched === "$event") { // aaa() aaa($event)当成aaa处理
value = value.replace(rdash, "")
}
}
parseExprProxy(value, vmodels, data)
}
bindingExecutors.on = function(callback, elem, data) {
callback = function(e) {
var fn = data.evaluator || noop
return fn.apply(this, data.args.concat(e))
}
var eventType = data.param.replace(/-\d+$/, "") // ms-on-mousemove-10
if (eventType === "scan") {
callback.call(elem, {
type: eventType
})
} else if (typeof data.specialBind === "function") {
data.specialBind(elem, callback)
} else {
var removeFn = avalon.bind(elem, eventType, callback)
}
data.rollback = function() {
if (typeof data.specialUnbind === "function") {
data.specialUnbind()
} else {
avalon.unbind(elem, eventType, removeFn)
}
}
}
bindingHandlers.repeat = function (data, vmodels) {
var type = data.type
parseExprProxy(data.value, vmodels, data, 0, 1)
var freturn = false
try {
var $repeat = data.$repeat = data.evaluator.apply(0, data.args || [])
var xtype = avalon.type($repeat)
if (xtype !== "object" && xtype !== "array") {
freturn = true
avalon.log("warning:" + data.value + "只能是对象或数组")
}
} catch (e) {
freturn = true
}
var arr = data.value.split(".") || []
if (arr.length > 1) {
arr.pop()
var n = arr[0]
for (var i = 0, v; v = vmodels[i++]; ) {
if (v && v.hasOwnProperty(n)) {
var events = v[n].$events || {}
events[subscribers] = events[subscribers] || []
events[subscribers].push(data)
break
}
}
}
var elem = data.element
if (elem.nodeType === 1) {
elem.removeAttribute(data.name)
data.sortedCallback = getBindingCallback(elem, "data-with-sorted", vmodels)
data.renderedCallback = getBindingCallback(elem, "data-" + type + "-rendered", vmodels)
var signature = generateID(type)
var start = DOC.createComment(signature)
var end = DOC.createComment(signature + ":end")
data.signature = signature
data.template = avalonFragment.cloneNode(false)
if (type === "repeat") {
var parent = elem.parentNode
parent.replaceChild(end, elem)
parent.insertBefore(start, end)
data.template.appendChild(elem)
} else {
while (elem.firstChild) {
data.template.appendChild(elem.firstChild)
}
elem.appendChild(start)
elem.appendChild(end)
}
data.element = end
data.handler = bindingExecutors.repeat
data.rollback = function () {
var elem = data.element
if (!elem)
return
data.handler("clear")
}
}
if (freturn) {
return
}
data.$outer = {}
var check0 = "$key"
var check1 = "$val"
if (Array.isArray($repeat)) {
if (!$repeat.$map) {
$repeat.$map = {
el: 1
}
var m = $repeat.length
var $proxy = []
for (i = 0; i < m; i++) {//生成代理VM
$proxy.push(eachProxyAgent(i, $repeat))
}
$repeat.$proxy = $proxy
}
$repeat.$map[data.param || "el"] = 1
check0 = "$first"
check1 = "$last"
}
for (i = 0; v = vmodels[i++]; ) {
if (v.hasOwnProperty(check0) && v.hasOwnProperty(check1)) {
data.$outer = v
break
}
}
var $events = $repeat.$events
var $list = ($events || {})[subscribers]
injectDependency($list, data)
if (xtype === "object") {
data.$with = true
$repeat.$proxy || ($repeat.$proxy = {})
data.handler("append", $repeat)
} else if ($repeat.length) {
data.handler("add", 0, $repeat.length)
}
}
bindingExecutors.repeat = function (method, pos, el) {
if (method) {
var data = this, start, fragment
var end = data.element
var comments = getComments(data)
var parent = end.parentNode
var transation = avalonFragment.cloneNode(false)
switch (method) {
case "add": //在pos位置后添加el数组(pos为插入位置,el为要插入的个数)
var n = pos + el
var fragments = []
var array = data.$repeat
for (var i = pos; i < n; i++) {
var proxy = array.$proxy[i]
proxy.$outer = data.$outer
shimController(data, transation, proxy, fragments)
}
parent.insertBefore(transation, comments[pos] || end)
for (i = 0; fragment = fragments[i++]; ) {
scanNodeArray(fragment.nodes, fragment.vmodels)
fragment.nodes = fragment.vmodels = null
}
break
case "del": //将pos后的el个元素删掉(pos, el都是数字)
sweepNodes(comments[pos], comments[pos + el] || end)
break
case "clear":
start = comments[0]
if (start) {
sweepNodes(start, end)
}
break
case "move":
start = comments[0]
if (start) {
var signature = start.nodeValue
var rooms = []
var room = [],
node
sweepNodes(start, end, function () {
room.unshift(this)
if (this.nodeValue === signature) {
rooms.unshift(room)
room = []
}
})
sortByIndex(rooms, pos)
while (room = rooms.shift()) {
while (node = room.shift()) {
transation.appendChild(node)
}
}
parent.insertBefore(transation, end)
}
break
case "append":
var object = pos //原来第2参数, 被循环对象
var pool = object.$proxy //代理对象组成的hash
var keys = []
fragments = []
for (var key in pool) {
if (!object.hasOwnProperty(key)) {
proxyRecycler(pool[key], withProxyPool) //去掉之前的代理VM
delete(pool[key])
}
}
for (key in object) { //得到所有键名
if (object.hasOwnProperty(key) && key !== "hasOwnProperty" && key !== "$proxy") {
keys.push(key)
}
}
if (data.sortedCallback) { //如果有回调,则让它们排序
var keys2 = data.sortedCallback.call(parent, keys)
if (keys2 && Array.isArray(keys2) && keys2.length) {
keys = keys2
}
}
for (i = 0; key = keys[i++]; ) {
if (key !== "hasOwnProperty") {
pool[key] = withProxyAgent(pool[key], key, data)
shimController(data, transation, pool[key], fragments)
}
}
parent.insertBefore(transation, end)
for (i = 0; fragment = fragments[i++]; ) {
scanNodeArray(fragment.nodes, fragment.vmodels)
fragment.nodes = fragment.vmodels = null
}
break
}
if (method === "clear")
method = "del"
var callback = data.renderedCallback || noop,
args = arguments
checkScan(parent, function () {
callback.apply(parent, args)
if (parent.oldValue && parent.tagName === "SELECT") { //fix #503
avalon(parent).val(parent.oldValue.split(","))
}
}, NaN)
}
}
"with,each".replace(rword, function (name) {
bindingHandlers[name] = bindingHandlers.repeat
})
avalon.pool = eachProxyPool
function shimController(data, transation, proxy, fragments) {
var content = data.template.cloneNode(true)
var nodes = avalon.slice(content.childNodes)
if (!data.$with) {
content.insertBefore(DOC.createComment(data.signature), content.firstChild)
}
transation.appendChild(content)
var nv = [proxy].concat(data.vmodels)
var fragment = {
nodes: nodes,
vmodels: nv
}
fragments.push(fragment)
}
function getComments(data) {
var end = data.element
var signature = end.nodeValue.replace(":end", "")
var node = end.previousSibling
var array = []
while (node) {
if (node.nodeValue === signature) {
array.unshift(node)
}
node = node.previousSibling
}
return array
}
//移除掉start与end之间的节点(保留end)
function sweepNodes(start, end, callback) {
while (true) {
var node = end.previousSibling
if (!node)
break
node.parentNode.removeChild(node)
callback && callback.call(node)
if (node === start) {
break
}
}
}
// 为ms-each,ms-with, ms-repeat会创建一个代理VM,
// 通过它们保持一个下上文,让用户能调用$index,$first,$last,$remove,$key,$val,$outer等属性与方法
// 所有代理VM的产生,消费,收集,存放通过xxxProxyFactory,xxxProxyAgent, recycleProxies,xxxProxyPool实现
var withProxyPool = []
function withProxyFactory() {
var proxy = modelFactory({
$key: "",
$outer: {},
$host: {},
$val: {
get: function () {
return this.$host[this.$key]
},
set: function (val) {
this.$host[this.$key] = val
}
}
}, {
$val: 1
})
proxy.$id = generateID("$proxy$with")
return proxy
}
function withProxyAgent(proxy, key, data) {
proxy = proxy || withProxyPool.pop()
if (!proxy) {
proxy = withProxyFactory()
}
var host = data.$repeat
proxy.$key = key
proxy.$host = host
proxy.$outer = data.$outer
if (host.$events) {
proxy.$events.$val = host.$events[key]
} else {
proxy.$events = {}
}
return proxy
}
function eachProxyRecycler(proxies) {
proxies.forEach(function (proxy) {
proxyRecycler(proxy, eachProxyPool)
})
proxies.length = 0
}
function proxyRecycler(proxy, proxyPool) {
for (var i in proxy.$events) {
if (Array.isArray(proxy.$events[i])) {
proxy.$events[i].forEach(function (data) {
if (typeof data === "object")
disposeData(data)
})// jshint ignore:line
proxy.$events[i].length = 0
}
}
proxy.$host = proxy.$outer = {}
if (proxyPool.unshift(proxy) > kernel.maxRepeatSize) {
proxyPool.pop()
}
}
/*********************************************************************
* 各种指令 *
**********************************************************************/
//ms-skip绑定已经在scanTag 方法中实现
// bindingHandlers.text 定义在if.js
bindingExecutors.text = function(val, elem) {
val = val == null ? "" : val //不在页面上显示undefined null
if (elem.nodeType === 3) { //绑定在文本节点上
try { //IE对游离于DOM树外的节点赋值会报错
elem.data = val
} catch (e) {}
} else { //绑定在特性节点上
elem.textContent = val
}
}
function parseDisplay(nodeName, val) {
//用于取得此类标签的默认display值
var key = "_" + nodeName
if (!parseDisplay[key]) {
var node = DOC.createElement(nodeName)
root.appendChild(node)
if (W3C) {
val = getComputedStyle(node, null).display
} else {
val = node.currentStyle.display
}
root.removeChild(node)
parseDisplay[key] = val
}
return parseDisplay[key]
}
avalon.parseDisplay = parseDisplay
bindingHandlers.visible = function(data, vmodels) {
var elem = avalon(data.element)
var display = elem.css("display")
if (display === "none") {
var style = elem[0].style
var has = /visibility/i.test(style.cssText)
var visible = elem.css("visibility")
style.display = ""
style.visibility = "hidden"
display = elem.css("display")
if (display === "none") {
display = parseDisplay(elem[0].nodeName)
}
style.visibility = has ? visible : ""
}
data.display = display
parseExprProxy(data.value, vmodels, data)
}
bindingExecutors.visible = function(val, elem, data) {
elem.style.display = val ? data.display : "none"
}
bindingHandlers.widget = function(data, vmodels) {
var args = data.value.match(rword)
var elem = data.element
var widget = args[0]
var id = args[1]
if (!id || id === "$") { //没有定义或为$时,取组件名+随机数
id = generateID(widget)
}
var optName = args[2] || widget //没有定义,取组件名
var constructor = avalon.ui[widget]
if (typeof constructor === "function") { //ms-widget="tabs,tabsAAA,optname"
vmodels = elem.vmodels || vmodels
for (var i = 0, v; v = vmodels[i++];) {
if (v.hasOwnProperty(optName) && typeof v[optName] === "object") {
var vmOptions = v[optName]
vmOptions = vmOptions.$model || vmOptions
break
}
}
if (vmOptions) {
var wid = vmOptions[widget + "Id"]
if (typeof wid === "string") {
log("warning!不再支持" + widget + "Id")
id = wid
}
}
//抽取data-tooltip-text、data-tooltip-attr属性,组成一个配置对象
var widgetData = avalon.getWidgetData(elem, widget)
data.value = [widget, id, optName].join(",")
data[widget + "Id"] = id
data.evaluator = noop
elem.msData["ms-widget-id"] = id
var options = data[widget + "Options"] = avalon.mix({}, constructor.defaults, vmOptions || {}, widgetData)
elem.removeAttribute("ms-widget")
var vmodel = constructor(elem, data, vmodels) || {} //防止组件不返回VM
if (vmodel.$id) {
avalon.vmodels[id] = vmodel
createSignalTower(elem, vmodel)
try {
vmodel.$init(function() {
avalon.scan(elem, [vmodel].concat(vmodels))
if (typeof options.onInit === "function") {
options.onInit.call(elem, vmodel, options, vmodels)
}
})
} catch (e) {}
data.rollback = function() {
try {
vmodel.widgetElement = null
vmodel.$remove()
} catch (e) {}
elem.msData = {}
delete avalon.vmodels[vmodel.$id]
}
injectDisposeQueue(data, widgetList)
if (window.chrome) {
elem.addEventListener("DOMNodeRemovedFromDocument", function() {
setTimeout(rejectDisposeQueue)
})
}
} else {
avalon.scan(elem, vmodels)
}
} else if (vmodels.length) { //如果该组件还没有加载,那么保存当前的vmodels
elem.vmodels = vmodels
}
}
var widgetList = []
//不存在 bindingExecutors.widget
/*********************************************************************
* 自带过滤器 *
**********************************************************************/
var rscripts = /<script[^>]*>([\S\s]*?)<\/script\s*>/gim
var ron = /\s+(on[^=\s]+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g
var ropen = /<\w+\b(?:(["'])[^"]*?(\1)|[^>])*>/ig
var rsanitize = {
a: /\b(href)\=("javascript[^"]*"|'javascript[^']*')/ig,
img: /\b(src)\=("javascript[^"]*"|'javascript[^']*')/ig,
form: /\b(action)\=("javascript[^"]*"|'javascript[^']*')/ig
}
var rsurrogate = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g
var rnoalphanumeric = /([^\#-~| |!])/g;
function numberFormat(number, decimals, point, thousands) {
//form http://phpjs.org/functions/number_format/
//number 必需,要格式化的数字
//decimals 可选,规定多少个小数位。
//point 可选,规定用作小数点的字符串(默认为 . )。
//thousands 可选,规定用作千位分隔符的字符串(默认为 , ),如果设置了该参数,那么所有其他参数都是必需的。
number = (number + '')
.replace(/[^0-9+\-Ee.]/g, '')
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 3 : Math.abs(decimals),
sep = thousands || ",",
dec = point || ".",
s = '',
toFixedFix = function(n, prec) {
var k = Math.pow(10, prec)
return '' + (Math.round(n * k) / k)
.toFixed(prec)
}
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
.split('.')
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
}
if ((s[1] || '')
.length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1)
.join('0')
}
return s.join(dec)
}
var filters = avalon.filters = {
uppercase: function(str) {
return str.toUpperCase()
},
lowercase: function(str) {
return str.toLowerCase()
},
truncate: function(str, length, truncation) {
//length,新字符串长度,truncation,新字符串的结尾的字段,返回新字符串
length = length || 30
truncation = typeof truncation === "string" ? truncation : "..."
return str.length > length ? str.slice(0, length - truncation.length) + truncation : String(str)
},
$filter: function(val) {
for (var i = 1, n = arguments.length; i < n; i++) {
var array = arguments[i]
var fn = avalon.filters[array.shift()]
if (typeof fn === "function") {
var arr = [val].concat(array)
val = fn.apply(null, arr)
}
}
return val
},
camelize: camelize,
//https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// <a href="javasc
ript:alert('XSS')">chrome</a>
// <a href="data:text/html;base64, PGltZyBzcmM9eCBvbmVycm9yPWFsZXJ0KDEpPg==">chrome</a>
// <a href="jav ascript:alert('XSS');">IE67chrome</a>
// <a href="jav	ascript:alert('XSS');">IE67chrome</a>
// <a href="jav
ascript:alert('XSS');">IE67chrome</a>
sanitize: function(str) {
return str.replace(rscripts, "").replace(ropen, function(a, b) {
var match = a.toLowerCase().match(/<(\w+)\s/)
if (match) { //处理a标签的href属性,img标签的src属性,form标签的action属性
var reg = rsanitize[match[1]]
if (reg) {
a = a.replace(reg, function(s, name, value) {
var quote = value.charAt(0)
return name + "=" + quote + "javascript:void(0)" + quote// jshint ignore:line
})
}
}
return a.replace(ron, " ").replace(/\s+/g, " ") //移除onXXX事件
})
},
escape: function(str) {
//将字符串经过 str 转义得到适合在页面中显示的内容, 例如替换 < 为 <
return String(str).
replace(/&/g, '&').
replace(rsurrogate, function(value) {
var hi = value.charCodeAt(0)
var low = value.charCodeAt(1)
return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';'
}).
replace(rnoalphanumeric, function(value) {
return '&#' + value.charCodeAt(0) + ';'
}).
replace(/</g, '<').
replace(/>/g, '>')
},
currency: function(amount, symbol, fractionSize) {
return (symbol || "\uFFE5") + numberFormat(amount, isFinite(fractionSize) ? fractionSize : 2)
},
number: numberFormat
}
/*
'yyyy': 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
'yy': 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
'y': 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
'MMMM': Month in year (January-December)
'MMM': Month in year (Jan-Dec)
'MM': Month in year, padded (01-12)
'M': Month in year (1-12)
'dd': Day in month, padded (01-31)
'd': Day in month (1-31)
'EEEE': Day in Week,(Sunday-Saturday)
'EEE': Day in Week, (Sun-Sat)
'HH': Hour in day, padded (00-23)
'H': Hour in day (0-23)
'hh': Hour in am/pm, padded (01-12)
'h': Hour in am/pm, (1-12)
'mm': Minute in hour, padded (00-59)
'm': Minute in hour (0-59)
'ss': Second in minute, padded (00-59)
's': Second in minute (0-59)
'a': am/pm marker
'Z': 4 digit (+sign) representation of the timezone offset (-1200-+1200)
format string can also be one of the following predefined localizable formats:
'medium': equivalent to 'MMM d, y h:mm:ss a' for en_US locale (e.g. Sep 3, 2010 12:05:08 pm)
'short': equivalent to 'M/d/yy h:mm a' for en_US locale (e.g. 9/3/10 12:05 pm)
'fullDate': equivalent to 'EEEE, MMMM d,y' for en_US locale (e.g. Friday, September 3, 2010)
'longDate': equivalent to 'MMMM d, y' for en_US locale (e.g. September 3, 2010
'mediumDate': equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)
'shortDate': equivalent to 'M/d/yy' for en_US locale (e.g. 9/3/10)
'mediumTime': equivalent to 'h:mm:ss a' for en_US locale (e.g. 12:05:08 pm)
'shortTime': equivalent to 'h:mm a' for en_US locale (e.g. 12:05 pm)
*/
new function() {// jshint ignore:line
function toInt(str) {
return parseInt(str, 10) || 0
}
function padNumber(num, digits, trim) {
var neg = ""
if (num < 0) {
neg = '-'
num = -num
}
num = "" + num
while (num.length < digits)
num = "0" + num
if (trim)
num = num.substr(num.length - digits)
return neg + num
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date["get" + name]()
if (offset > 0 || value > -offset)
value += offset
if (value === 0 && offset === -12) {
value = 12
}
return padNumber(value, size, trim)
}
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date["get" + name]()
var get = (shortForm ? ("SHORT" + name) : name).toUpperCase()
return formats[get][value]
}
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset()
var paddedZone = (zone >= 0) ? "+" : ""
paddedZone += padNumber(Math[zone > 0 ? "floor" : "ceil"](zone / 60), 2) + padNumber(Math.abs(zone % 60), 2)
return paddedZone
}
//取得上午下午
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1]
}
var DATE_FORMATS = {
yyyy: dateGetter("FullYear", 4),
yy: dateGetter("FullYear", 2, 0, true),
y: dateGetter("FullYear", 1),
MMMM: dateStrGetter("Month"),
MMM: dateStrGetter("Month", true),
MM: dateGetter("Month", 2, 1),
M: dateGetter("Month", 1, 1),
dd: dateGetter("Date", 2),
d: dateGetter("Date", 1),
HH: dateGetter("Hours", 2),
H: dateGetter("Hours", 1),
hh: dateGetter("Hours", 2, -12),
h: dateGetter("Hours", 1, -12),
mm: dateGetter("Minutes", 2),
m: dateGetter("Minutes", 1),
ss: dateGetter("Seconds", 2),
s: dateGetter("Seconds", 1),
sss: dateGetter("Milliseconds", 3),
EEEE: dateStrGetter("Day"),
EEE: dateStrGetter("Day", true),
a: ampmGetter,
Z: timeZoneGetter
}
var rdateFormat = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/
var raspnetjson = /^\/Date\((\d+)\)\/$/
filters.date = function(date, format) {
var locate = filters.date.locate,
text = "",
parts = [],
fn, match
format = format || "mediumDate"
format = locate[format] || format
if (typeof date === "string") {
if (/^\d+$/.test(date)) {
date = toInt(date)
} else if (raspnetjson.test(date)) {
date = +RegExp.$1
} else {
var trimDate = date.trim()
var dateArray = [0, 0, 0, 0, 0, 0, 0]
var oDate = new Date(0)
//取得年月日
trimDate = trimDate.replace(/^(\d+)\D(\d+)\D(\d+)/, function(_, a, b, c) {
var array = c.length === 4 ? [c, a, b] : [a, b, c]
dateArray[0] = toInt(array[0]) //年
dateArray[1] = toInt(array[1]) - 1 //月
dateArray[2] = toInt(array[2]) //日
return ""
})
var dateSetter = oDate.setFullYear
var timeSetter = oDate.setHours
trimDate = trimDate.replace(/[T\s](\d+):(\d+):?(\d+)?\.?(\d)?/, function(_, a, b, c, d) {
dateArray[3] = toInt(a) //小时
dateArray[4] = toInt(b) //分钟
dateArray[5] = toInt(c) //秒
if (d) { //毫秒
dateArray[6] = Math.round(parseFloat("0." + d) * 1000)
}
return ""
})
var tzHour = 0
var tzMin = 0
trimDate = trimDate.replace(/Z|([+-])(\d\d):?(\d\d)/, function(z, symbol, c, d) {
dateSetter = oDate.setUTCFullYear
timeSetter = oDate.setUTCHours
if (symbol) {
tzHour = toInt(symbol + c)
tzMin = toInt(symbol + d)
}
return ""
})
dateArray[3] -= tzHour
dateArray[4] -= tzMin
dateSetter.apply(oDate, dateArray.slice(0, 3))
timeSetter.apply(oDate, dateArray.slice(3))
date = oDate
}
}
if (typeof date === "number") {
date = new Date(date)
}
if (avalon.type(date) !== "date") {
return
}
while (format) {
match = rdateFormat.exec(format)
if (match) {
parts = parts.concat(match.slice(1))
format = parts.pop()
} else {
parts.push(format)
format = null
}
}
parts.forEach(function(value) {
fn = DATE_FORMATS[value]
text += fn ? fn(date, locate) : value.replace(/(^'|'$)/g, "").replace(/''/g, "'")
})
return text
}
var locate = {
AMPMS: {
0: "上午",
1: "下午"
},
DAY: {
0: "星期日",
1: "星期一",
2: "星期二",
3: "星期三",
4: "星期四",
5: "星期五",
6: "星期六"
},
MONTH: {
0: "1月",
1: "2月",
2: "3月",
3: "4月",
4: "5月",
5: "6月",
6: "7月",
7: "8月",
8: "9月",
9: "10月",
10: "11月",
11: "12月"
},
SHORTDAY: {
"0": "周日",
"1": "周一",
"2": "周二",
"3": "周三",
"4": "周四",
"5": "周五",
"6": "周六"
},
fullDate: "y年M月d日EEEE",
longDate: "y年M月d日",
medium: "yyyy-M-d H:mm:ss",
mediumDate: "yyyy-M-d",
mediumTime: "H:mm:ss",
"short": "yy-M-d ah:mm",
shortDate: "yy-M-d",
shortTime: "ah:mm"
}
locate.SHORTMONTH = locate.MONTH
filters.date.locate = locate
}// jshint ignore:line
/*********************************************************************
* END *
**********************************************************************/
new function () {
avalon.config({
loader: false
})
var fns = [], loaded = DOC.readyState === "complete", fn
function flush(f) {
loaded = 1
while (f = fns.shift())
f()
}
avalon.bind(DOC, "DOMContentLoaded", fn = function () {
avalon.unbind(DOC, "DOMContentLoaded", fn)
flush()
})
var id = setInterval(function () {
if (document.readyState === "complete" && document.body) {
clearInterval(id)
flush()
}
}, 50)
avalon.ready = function (fn) {
loaded ? fn(avalon) : fns.push(fn)
}
avalon.ready(function () {
avalon.scan(DOC.body)
})
}
// Register as a named AMD module, since avalon can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase avalon is used because AMD module names are
// derived from file names, and Avalon is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of avalon, it will work.
// Note that for maximum portability, libraries that are not avalon should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. avalon is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if (typeof define === "function" && define.amd) {
define("avalon", [], function() {
return avalon
})
}
// Map over avalon in case of overwrite
var _avalon = window.avalon
avalon.noConflict = function(deep) {
if (deep && window.avalon === avalon) {
window.avalon = _avalon
}
return avalon
}
// Expose avalon identifiers, even in AMD
// and CommonJS for browser emulators
if (noGlobal === void 0) {
window.avalon = avalon
}
return avalon
}));
|
jQuery.keyboard.language.pt={language:"Portuguese",display:{a:"✔:Aceitar (Shift+Enter)",accept:"Aceitar:Concluir (Shift+Enter)",alt:"AltGr:Carateres Adicionais/CTRL+ALT",b:"←:Retroceder",bksp:"← Bksp:Retroceder",c:"✖:Cancelar/Escape (Esc)",cancel:"Cancel:Cancelar/Escape(Esc)",clear:"C:Limpar",combo:"ö:Acentuação Automática",dec:".:Decimal",e:"↵:Introduzir/Mudar de Linha",enter:"Enter↵:Introduzir/Mudar de Linha",lock:"⇪ Lock:CapsLock/Maiúsculas",s:"⇧:Shift/Maiúsculas",shift:"⇪ Shift:Maiúsculas-Minúsculas",sign:"±:Mudar Sinal",space:" :Espaço",t:"⇥:Tab/Tabela/Avançar",tab:"⇥ Tab:Tabela/Avançar"},wheelMessage:"Use a roda do rato/navegador para ver mais teclas",comboRegex:/([`\'~\^\"ao\u00b4])([a-z])/gim,combos:{"´":{a:"á",A:"Á",e:"é",E:"É",i:"í",I:"Í",o:"ó",O:"Ó",u:"ú",U:"Ú",y:"ý",Y:"Ý"},"'":{}}};
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleDependencyTemplateAsRequireId {
apply(dep, source, outputOptions, requestShortener) {
if(!dep.range) return;
const comment = outputOptions.pathinfo ?
`/*! ${requestShortener.shorten(dep.request)} */ ` : "";
let content;
if(dep.module)
content = `__webpack_require__(${comment}${JSON.stringify(dep.module.id)})`;
else
content = require("./WebpackMissingModule").module(dep.request);
source.replace(dep.range[0], dep.range[1] - 1, content);
}
}
module.exports = ModuleDependencyTemplateAsRequireId;
|
/**
* @author alteredq / http://alteredqualia.com/
*
* AudioObject
*
* - 3d spatialized sound with Doppler-shift effect
*
* - uses Audio API (currently supported in WebKit-based browsers)
* https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
*
* - based on Doppler effect demo from Chromium
* http://chromium.googlecode.com/svn/trunk/samples/audio/doppler.html
*
* - parameters
*
* - listener
* dopplerFactor // A constant used to determine the amount of pitch shift to use when rendering a doppler effect.
* speedOfSound // The speed of sound used for calculating doppler shift. The default value is 343.3 meters / second.
*
* - panner
* refDistance // A reference distance for reducing volume as source move further from the listener.
* maxDistance // The maximum distance between source and listener, after which the volume will not be reduced any further.
* rolloffFactor // Describes how quickly the volume is reduced as source moves away from listener.
* coneInnerAngle // An angle inside of which there will be no volume reduction.
* coneOuterAngle // An angle outside of which the volume will be reduced to a constant value of coneOuterGain.
* coneOuterGain // Amount of volume reduction outside of the coneOuterAngle.
*/
THREE.AudioObject = function ( url, volume, playbackRate, loop ) {
THREE.Object3D.call( this );
if ( playbackRate === undefined ) playbackRate = 1;
if ( volume === undefined ) volume = 1;
if ( loop === undefined ) loop = true;
if ( ! this.context ) {
try {
THREE.AudioObject.prototype.context = new webkitAudioContext();
} catch ( error ) {
console.warn( "THREE.AudioObject: webkitAudioContext not found" );
return this;
}
}
this.directionalSource = false;
this.listener = this.context.listener;
this.panner = this.context.createPanner();
this.source = this.context.createBufferSource();
this.masterGainNode = this.context.createGainNode();
this.dryGainNode = this.context.createGainNode();
// Setup initial gains
this.masterGainNode.gain.value = volume;
this.dryGainNode.gain.value = 3.0;
// Connect dry mix
this.source.connect( this.panner );
this.panner.connect( this.dryGainNode );
this.dryGainNode.connect( this.masterGainNode );
// Connect master gain
this.masterGainNode.connect( this.context.destination );
// Set source parameters and load sound
this.source.playbackRate.value = playbackRate;
this.source.loop = loop;
loadBufferAndPlay( url );
// private properties
var soundPosition = new THREE.Vector3(),
cameraPosition = new THREE.Vector3(),
oldSoundPosition = new THREE.Vector3(),
oldCameraPosition = new THREE.Vector3(),
soundDelta = new THREE.Vector3(),
cameraDelta = new THREE.Vector3(),
soundFront = new THREE.Vector3(),
cameraFront = new THREE.Vector3(),
soundUp = new THREE.Vector3(),
cameraUp = new THREE.Vector3();
var _this = this;
// API
this.setVolume = function ( volume ) {
this.masterGainNode.gain.value = volume;
};
this.update = function ( camera ) {
oldSoundPosition.copy( soundPosition );
oldCameraPosition.copy( cameraPosition );
soundPosition.setFromMatrixPosition( this.matrixWorld );
cameraPosition.setFromMatrixPosition( camera.matrixWorld );
soundDelta.subVectors( soundPosition, oldSoundPosition );
cameraDelta.subVectors( cameraPosition, oldCameraPosition );
cameraUp.copy( camera.up );
cameraFront.set( 0, 0, -1 );
cameraFront.transformDirection( camera.matrixWorld );
this.listener.setPosition( cameraPosition.x, cameraPosition.y, cameraPosition.z );
this.listener.setVelocity( cameraDelta.x, cameraDelta.y, cameraDelta.z );
this.listener.setOrientation( cameraFront.x, cameraFront.y, cameraFront.z, cameraUp.x, cameraUp.y, cameraUp.z );
this.panner.setPosition( soundPosition.x, soundPosition.y, soundPosition.z );
this.panner.setVelocity( soundDelta.x, soundDelta.y, soundDelta.z );
if ( this.directionalSource ) {
soundFront.set( 0, 0, -1 );
soundFront.transformDirection( this.matrixWorld );
soundUp.copy( this.up );
this.panner.setOrientation( soundFront.x, soundFront.y, soundFront.z, soundUp.x, soundUp.y, soundUp.z );
}
};
function loadBufferAndPlay( url ) {
// Load asynchronously
var request = new XMLHttpRequest();
request.open( "GET", url, true );
request.responseType = "arraybuffer";
request.onload = function() {
_this.source.buffer = _this.context.createBuffer( request.response, true );
_this.source.noteOn( 0 );
}
request.send();
}
};
THREE.AudioObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.AudioObject.prototype.constructor = THREE.AudioObject;
THREE.AudioObject.prototype.context = null;
THREE.AudioObject.prototype.type = null;
|
/*!
* tablesorter pager plugin
* updated 5/3/2012
*/
;(function($) {
$.extend({tablesorterPager: new function() {
this.defaults = {
// target the pager markup
container: null,
// use this format: "http:/mydatabase.com?page={page}&size={size}"
// where {page} is replaced by the page number and {size} is replaced by the number of records to show
ajaxUrl: null,
// process ajax so that the following information is returned:
// [ total_rows (number), rows (array of arrays), headers (array; optional) ]
// example:
// [
// 100, // total rows
// [
// [ "row1cell1", "row1cell2", ... "row1cellN" ],
// [ "row2cell1", "row2cell2", ... "row2cellN" ],
// ...
// [ "rowNcell1", "rowNcell2", ... "rowNcellN" ]
// ],
// [ "header1", "header2", ... "headerN" ] // optional
// ]
ajaxProcessing: function(ajax){ return [ 0, [], null ]; },
// output default: '{page}/{totalPages}'
output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}'
// apply disabled classname to the pager arrows when the rows at either extreme is visible
updateArrows: true,
// starting page of the pager (zero based index)
page: 0,
// Number of visible rows
size: 10,
// if true, the table will remain the same height no matter how many records are displayed. The space is made up by an empty
// table row set to a height to compensate; default is false
fixedHeight: false,
// remove rows from the table to speed up the sort of large tables.
// setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
removeRows: true, // removing rows in larger tables speeds up the sort
// css class names of pager arrows
cssNext: '.next', // next page arrow
cssPrev: '.prev', // previous page arrow
cssFirst: '.first', // first page arrow
cssLast: '.last', // last page arrow
cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed
cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option
// class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page)
cssDisabled: 'disabled', // Note there is no period "." in front of this class name
// stuff not set by the user
totalRows: 0,
totalPages: 0
};
var $this = this,
// hide arrows at extremes
pagerArrows = function(c, disable) {
var a = 'addClass', r = 'removeClass',
d = c.cssDisabled, dis = !!disable;
if (c.updateArrows) {
c.container[(c.totalRows < c.size) ? a : r](d);
$(c.cssFirst + ',' + c.cssPrev, c.container)[(dis || c.page === 0) ? a : r](d);
$(c.cssNext + ',' + c.cssLast, c.container)[(dis || c.page === c.totalPages - 1) ? a : r](d);
}
},
updatePageDisplay = function(table, c) {
if (c.totalPages > 0) {
c.startRow = c.size * (c.page) + 1;
c.endRow = Math.min(c.totalRows, c.size * (c.page+1));
var out = $(c.cssPageDisplay, c.container),
// form the output string
s = c.output.replace(/\{(page|totalPages|startRow|endRow|totalRows)\}/gi, function(m){
return {
'{page}' : c.page + 1,
'{totalPages}' : c.totalPages,
'{startRow}' : c.startRow,
'{endRow}' : c.endRow,
'{totalRows}' : c.totalRows
}[m];
});
if (out[0]) {
out[ (out[0].tagName === 'INPUT') ? 'val' : 'html' ](s);
}
}
pagerArrows(c);
$(table).trigger('pagerComplete', c);
},
fixHeight = function(table, c) {
var d, h, $b = $(table.tBodies[0]);
if (c.fixedHeight) {
$b.find('tr.pagerSavedHeightSpacer').remove();
h = $.data(table, 'pagerSavedHeight');
if (h) {
d = h - $b.height();
if (d > 5 && $.data(table, 'pagerLastSize') === c.size && $b.find('tr:visible').length < c.size) {
$b.append('<tr class="pagerSavedHeightSpacer remove-me" style="height:' + d + 'px;"></tr>');
}
}
}
},
changeHeight = function(table, c) {
var $b = $(table.tBodies[0]);
$b.find('tr.pagerSavedHeightSpacer').remove();
$.data(table, 'pagerSavedHeight', $b.height());
fixHeight(table, c);
$.data(table, 'pagerLastSize', c.size);
},
hideRows = function(table, c){
var i, rows = $('tr:not(.' + table.config.cssChildRow + ')', table.tBodies[0]),
l = rows.length,
s = (c.page * c.size),
e = (s + c.size);
if (e > l) { e = l; }
for (i = 0; i < l; i++){
rows[i].style.display = (i >= s && i < e) ? '' : 'none';
}
},
hideRowsSetup = function(table, c){
c.size = parseInt($(c.cssPageSize, c.container).val(), 10) || c.size;
$.data(table, 'pagerLastSize', c.size);
pagerArrows(c);
if (!c.removeRows) {
hideRows(table, c);
$(table).bind('sortEnd.pager', function(){
hideRows(table, c);
});
}
},
renderAjax = function(data, table, c, exception){
// process data
if (typeof(c.ajaxProcessing) === "function") {
// ajaxProcessing result: [ total, rows, headers ]
var i, j, k, hsh, $f, $sh, $t = $(table), $b = $(table.tBodies[0]),
hl = $t.find('thead th').length, tds = '',
err = '<tr class="remove-me"><td style="text-align: center;" colspan="' + hl + '">' +
(exception ? exception.message + ' (' + exception.name + ')' : 'No rows found') + '</td></tr>',
result = c.ajaxProcessing(data) || [ 0, [] ],
d = result[1] || [], l = d.length, th = result[2];
if (l > 0) {
for ( i=0; i < l; i++ ) {
tds += '<tr>';
for (j=0; j < d[i].length; j++) {
// build tbody cells
tds += '<td>' + d[i][j] + '</td>';
}
tds += '</tr>';
}
}
// only add new header text if the length matches
if (th && th.length === hl) {
hsh = $t.hasClass('hasStickyHeaders');
$sh = $t.find('.' + ((c.widgetOptions && c.widgetOptions.stickyHeaders) || 'tablesorter-stickyheader'));
$f = $t.find('tfoot tr:first').children();
$t.find('thead tr.tablesorter-header th').each(function(j){
var $t = $(this),
// add new test within the first span it finds, or just in the header
tar = ($t.find('span').length) ? $t.find('span:first') : $t;
tar.html(th[j]);
$f.eq(j).html(th[j]);
// update sticky headers
if (hsh && $sh.length){
tar = $sh.find('th').eq(j);
tar = (tar.find('span').length) ? tar.find('span:first') : tar;
tar.html(th[j]);
}
});
}
if (exception) {
// add error row to thead instead of tbody, or clicking on the header will result in a parser error
$t.find('thead').append(err);
} else {
$b.html(tds); // add tbody
}
c.temp.remove(); // remove loading icon
$t.trigger('update');
c.totalRows = result[0] || 0;
c.totalPages = Math.ceil(c.totalRows / c.size);
updatePageDisplay(table, c);
fixHeight(table, c);
$t.trigger('pagerChange', c);
}
},
getAjax = function(table, c){
var $t = $(table),
url = c.ajaxUrl.replace(/\{page\}/g, c.page).replace(/\{size\}/g, c.size);
if (url !== '') {
// loading icon
c.temp = $('<div/>', {
id : 'tablesorterPagerLoading',
width : $t.outerWidth(true),
height: $t.outerHeight(true)
});
$t.before(c.temp);
$(document).ajaxError(function(e, xhr, settings, exception) {
renderAjax(null, table, c, exception);
});
$.getJSON(url, function(data) {
renderAjax(data, table, c);
});
}
},
renderTable = function(table, rows, c) {
var i, j, o,
f = document.createDocumentFragment(),
l = rows.length,
s = (c.page * c.size),
e = (s + c.size);
if (l < 1) { return; } // empty table, abort!
$(table).trigger('pagerChange', c);
if (!c.removeRows) {
hideRows(table, c);
} else {
if (e > rows.length ) {
e = rows.length;
}
$.tablesorter.clearTableBody(table);
for (i = s; i < e; i++) {
o = rows[i];
l = o.length;
for (j = 0; j < l; j++) {
f.appendChild(o[j]);
}
}
table.tBodies[0].appendChild(f);
}
if ( c.page >= c.totalPages ) {
moveToLastPage(table, c);
}
updatePageDisplay(table, c);
if (!c.isDisabled) { fixHeight(table, c); }
},
showAllRows = function(table, c){
if (c.ajax) {
pagerArrows(c, true);
} else {
c.isDisabled = true;
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.page = 0;
c.size = c.totalRows;
c.totalPages = 1;
$('tr.pagerSavedHeightSpacer', table.tBodies[0]).remove();
renderTable(table, table.config.rowsCopy, c);
}
// disable size selector
$(c.cssPageSize, c.container).addClass(c.cssDisabled)[0].disabled = true;
},
moveToPage = function(table, c) {
if (c.isDisabled) { return; }
if (c.page < 0 || c.page > (c.totalPages-1)) {
c.page = 0;
}
$.data(table, 'pagerLastPage', c.page);
if (c.ajax) {
getAjax(table, c);
} else {
renderTable(table, table.config.rowsCopy, c);
}
},
setPageSize = function(table, size, c) {
c.size = size;
$.data(table, 'pagerLastPage', c.page);
$.data(table, 'pagerLastSize', c.size);
c.totalPages = Math.ceil(c.totalRows / c.size);
moveToPage(table, c);
},
moveToFirstPage = function(table, c) {
c.page = 0;
moveToPage(table, c);
},
moveToLastPage = function(table, c) {
c.page = (c.totalPages-1);
moveToPage(table, c);
},
moveToNextPage = function(table, c) {
c.page++;
if (c.page >= (c.totalPages-1)) {
c.page = (c.totalPages-1);
}
moveToPage(table, c);
},
moveToPrevPage = function(table, c) {
c.page--;
if (c.page <= 0) {
c.page = 0;
}
moveToPage(table, c);
},
destroyPager = function(table, c){
showAllRows(table, c);
c.container.hide(); // hide pager
table.config.appender = null; // remove pager appender function
$(table).unbind('destroy.pager sortEnd.pager enable.pager disable.pager');
},
enablePager = function(table, c, triggered){
var p = $(c.cssPageSize, c.container).removeClass(c.cssDisabled).removeAttr('disabled');
c.isDisabled = false;
c.page = $.data(table, 'pagerLastPage') || c.page || 0;
c.size = $.data(table, 'pagerLastSize') || parseInt(p.val(), 10) || c.size;
c.totalPages = Math.ceil(c.totalRows / c.size);
if (triggered) {
$(table).trigger('update');
setPageSize(table, c.size, c);
hideRowsSetup(table, c);
fixHeight(table, c);
}
};
$this.appender = function(table, rows) {
var c = table.config.pager;
if (!c.ajax) {
table.config.rowsCopy = rows;
c.totalRows = rows.length;
c.size = $.data(table, 'pagerLastSize') || c.size;
c.totalPages = Math.ceil(c.totalRows / c.size);
renderTable(table, rows, c);
}
};
$this.construct = function(settings) {
return this.each(function() {
var config = this.config,
c = config.pager = $.extend({}, $.tablesorterPager.defaults, settings),
table = this,
$t = $(table),
pager = $(c.container).show(); // added in case the pager is reinitialized after being destroyed.
config.appender = $this.appender;
enablePager(table, c, false);
if (typeof(c.ajaxUrl) === 'string') {
// ajax pager; interact with database
c.ajax = true;
getAjax(table, c);
} else {
c.ajax = false;
// Regular pager; all rows stored in memory
$(this).trigger("appendCache");
hideRowsSetup(table, c);
}
$(c.cssFirst,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToFirstPage(table, c); }
return false;
});
$(c.cssNext,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToNextPage(table, c); }
return false;
});
$(c.cssPrev,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToPrevPage(table, c); }
return false;
});
$(c.cssLast,pager).unbind('click.pager').bind('click.pager', function() {
if (!$(this).hasClass(c.cssDisabled)) { moveToLastPage(table, c); }
return false;
});
$(c.cssPageSize,pager).unbind('change.pager').bind('change.pager', function() {
$(c.cssPageSize,pager).val( $(this).val() ); // in case there are more than one pagers
if (!$(this).hasClass(c.cssDisabled)) {
setPageSize(table, parseInt($(this).val(), 10), c);
changeHeight(table, c);
}
return false;
});
$t
.unbind('disable.pager enable.pager destroy.pager')
.bind('disable.pager', function(){
showAllRows(table, c);
})
.bind('enable.pager', function(){
enablePager(table, c, true);
})
.bind('destroy.pager', function(){
destroyPager(table, c);
});
});
};
}
});
// extend plugin scope
$.fn.extend({
tablesorterPager: $.tablesorterPager.construct
});
})(jQuery);
|
(function(definition) {
// RequireJS.
if (typeof define === 'function') {
define(definition);
// CommonJS and <script>.
} else {
definition();
}
})(function() {
'use strict';
var globall = (typeof global === 'undefined') ? window : global;
var global_isNaN = globall.isNaN;
var global_isFinite = globall.isFinite;
var defineProperty = function(object, name, method) {
if (!object[name]) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: method
});
}
};
var defineProperties = function(object, map) {
Object.keys(map).forEach(function(name) {
defineProperty(object, name, map[name]);
});
};
var sign = function(n) {
return (n < 0) ? -1 : 1;
};
var unique = function(iterable) {
return Array.from(Set.from(iterable));
};
// http://wiki.ecmascript.org/doku.php?id=harmony:string.prototype.repeat
// http://wiki.ecmascript.org/doku.php?id=harmony:string_extras
defineProperties(String.prototype, {
repeat: function(times) {
return new Array(times + 1).join(this);
},
startsWith: function(substring) {
return this.indexOf(substring) === 0;
},
endsWith: function(s) {
var t = String(s);
return this.lastIndexOf(t) === this.length - t.length;
},
contains: function(s) {
return this.indexOf(s) !== -1;
},
toArray: function() {
return this.split('');
}
});
// https://gist.github.com/1074126
defineProperties(Array, {
from: function(iterable) {
var object = Object(iterable);
var array = [];
for (var key = 0, length = object.length >>> 0; key < length; key++) {
if (key in object) {
array[key] = object[key];
}
}
return array;
},
of: function() {
return Array.prototype.slice.call(arguments);
}
});
defineProperties(Number, {
isInteger: function(value) {
return typeof value === 'number' && global_isFinite(value) &&
value > -9007199254740992 && value < 9007199254740992 &&
Math.floor(value) === value;
},
isNaN: function(value) {
return typeof value === 'number' && global_isNaN(value);
},
toInteger: function(value) {
var n = +value;
if (isNaN(n)) return +0;
if (n === 0 || !global_isFinite(n)) return n;
return sign(n) * Math.floor(Math.abs(n));
}
});
defineProperties(Object, {
getOwnPropertyDescriptors: function(subject) {
var descs = {};
Object.getOwnPropertyNames(subject).forEach(function(propName) {
descs[propName] = Object.getOwnPropertyDescriptor(subject, propName);
});
return descs;
},
getPropertyDescriptor: function(subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (pd === undefined && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
},
getPropertyNames: function(subject, name) {
var set = Set.from(Object.getOwnPropertyNames(subject));
var proto = Object.getPrototypeOf(subject);
while (proto !== null) {
Object.getOwnPropertyNames(proto).forEach(set.add);
proto = Object.getPrototypeOf(proto);
}
return Array.from(set);
},
is: function(x, y) {
if (x === y) {
// 0 === -0, but they are not identical
return x !== 0 || 1 / x === 1 / y;
}
// NaN !== NaN, but they are identical.
// NaNs are the only non-reflexive value, i.e., if x !== x,
// then x is a NaN.
// isNaN is broken: it converts its argument to number, so
// isNaN("foo") => true
return x !== x && y !== y;
}
});
defineProperties(globall, {
Map: (function() {
var indexOfIdentical = function(keys, key) {
for (var i = 0, length = keys.length; i < length; i++) {
if (Object.is(keys[i], key)) return i;
}
return -1;
};
function Map() {
if (!(this instanceof Map)) return new Map;
defineProperty(this, 'keys', []);
defineProperty(this, 'values', []);
}
defineProperties(Map.prototype, {
get: function(key) {
var index = indexOfIdentical(this.keys, key);
return index < 0 ? undefined : this.values[index];
},
has: function(key) {
return indexOfIdentical(this.keys, key) >= 0;
},
set: function(key, value) {
var keys = this.keys;
var values = this.values;
var index = indexOfIdentical(keys, key);
if (index < 0) index = keys.length;
keys[index] = key;
values[index] = value;
},
'delete': function(key) {
var keys = this.keys;
var values = this.values;
var index = indexOfIdentical(keys, key);
if (index < 0) return false;
keys.splice(index, 1);
values.splice(index, 1);
return true;
}
});
return Map;
// TODO: iteration.
})(),
Set: (function() {
function Set() {
if (!(this instanceof Set)) return new Set;
defineProperty(this, 'map', Map());
}
defineProperties(Set.prototype, {
has: function(key) {
return this.map.has(key);
},
add: function(key) {
this.map.set(key, true);
},
'delete': function(key) {
return this.map.delete(key);
}
});
return Set;
// TODO: iteration.
})()
});
defineProperties(globall.Set, {
from: function(iterable) {
var object = Object(iterable);
var set = Set();
for (var key = 0, length = object.length >>> 0; key < length; key++) {
if (key in object && !(set.has(key))) {
set.add(object[key]);
}
}
return set;
},
of: function() {
return Set.from(arguments);
}
});
});
|
import baseGet from './_baseGet.js';
/**
* Gets the value at `path` of `object`. If the resolved value is
* `undefined`, the `defaultValue` is returned in its place.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned for `undefined` resolved values.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : baseGet(object, path);
return result === undefined ? defaultValue : result;
}
export default get;
|
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var stdin = require('get-stdin');
var pkg = require('./package.json');
var stripIndent = require('./');
var argv = process.argv.slice(2);
var input = argv[0];
function help() {
console.log([
'',
' ' + pkg.description,
'',
' Usage',
' strip-indent <file>',
' echo <string> | strip-indent',
'',
' Example',
' echo \'\\tunicorn\\n\\t\\tcake\' | strip-indent',
' unicorn',
' \tcake'
].join('\n'));
}
function init(data) {
console.log(stripIndent(data));
}
if (argv.indexOf('--help') !== -1) {
help();
return;
}
if (argv.indexOf('--version') !== -1) {
console.log(pkg.version);
return;
}
if (process.stdin.isTTY) {
if (!input) {
help();
return;
}
init(fs.readFileSync(input, 'utf8'));
} else {
stdin(init);
}
|
YUI.add('oop', function(Y) {
/**
* Supplies object inheritance and manipulation utilities. This adds
* additional functionaity to what is provided in yui-base, and the
* methods are applied directly to the YUI instance. This module
* is required for most YUI components.
* @module oop
*/
var L = Y.Lang,
A = Y.Array,
OP = Object.prototype,
CLONE_MARKER = "_~yuim~_",
EACH = 'each',
SOME = 'some',
dispatch = function(o, f, c, proto, action) {
if (o && o[action] && o !== Y) {
return o[action].call(o, f, c);
} else {
switch (A.test(o)) {
case 1:
return A[action](o, f, c);
case 2:
return A[action](Y.Array(o, 0, true), f, c);
default:
return Y.Object[action](o, f, c, proto);
}
}
};
/**
* The following methods are added to the YUI instance
* @class YUI~oop
*/
/**
* Applies prototype properties from the supplier to the receiver.
* The receiver can be a constructor or an instance.
* @method augment
* @param {Function} r the object to receive the augmentation
* @param {Function} s the object that supplies the properties to augment
* @param ov {boolean} if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param wl {string[]} a whitelist. If supplied, only properties in
* this list will be applied to the receiver.
* @param args {Array | Any} arg or arguments to apply to the supplier
* constructor when initializing.
* @return {object} the augmented object
*
* @todo constructor optional?
* @todo understanding what an instance is augmented with
* @TODO best practices for overriding sequestered methods.
*/
Y.augment = function(r, s, ov, wl, args) {
var sProto = s.prototype,
newProto = null,
construct = s,
a = (args) ? Y.Array(args) : [],
rProto = r.prototype,
target = rProto || r,
applyConstructor = false,
sequestered, replacements, i;
// working on a class, so apply constructor infrastructure
if (rProto && construct) {
sequestered = {};
replacements = {};
newProto = {};
// sequester all of the functions in the supplier and replace with
// one that will restore all of them.
Y.Object.each(sProto, function(v, k) {
replacements[k] = function() {
// Y.log('sequestered function "' + k + '" executed. Initializing EventTarget');
// overwrite the prototype with all of the sequestered functions,
// but only if it hasn't been overridden
for (i in sequestered) {
if (sequestered.hasOwnProperty(i) && (this[i] === replacements[i])) {
// Y.log('... restoring ' + k);
this[i] = sequestered[i];
}
}
// apply the constructor
construct.apply(this, a);
// apply the original sequestered function
return sequestered[k].apply(this, arguments);
};
if ((!wl || (k in wl)) && (ov || !(k in this))) {
// Y.log('augment: ' + k);
if (L.isFunction(v)) {
// sequester the function
sequestered[k] = v;
// replace the sequestered function with a function that will
// restore all sequestered functions and exectue the constructor.
this[k] = replacements[k];
} else {
// Y.log('augment() applying non-function: ' + k);
this[k] = v;
}
}
}, newProto, true);
// augmenting an instance, so apply the constructor immediately
} else {
applyConstructor = true;
}
Y.mix(target, newProto || sProto, ov, wl);
if (applyConstructor) {
s.apply(target, a);
}
return r;
};
/**
* Applies object properties from the supplier to the receiver. If
* the target has the property, and the property is an object, the target
* object will be augmented with the supplier's value. If the property
* is an array, the suppliers value will be appended to the target.
* @method aggregate
* @param {Function} r the object to receive the augmentation
* @param {Function} s the object that supplies the properties to augment
* @param ov {boolean} if true, properties already on the receiver
* will be overwritten if found on the supplier.
* @param wl {string[]} a whitelist. If supplied, only properties in
* this list will be applied to the receiver.
* @return {object} the extended object
*/
Y.aggregate = function(r, s, ov, wl) {
return Y.mix(r, s, ov, wl, 0, true);
};
/**
* Utility to set up the prototype, constructor and superclass properties to
* support an inheritance strategy that can chain constructors and methods.
* Static members will not be inherited.
*
* @method extend
* @param {Function} r the object to modify
* @param {Function} s the object to inherit
* @param {Object} px prototype properties to add/override
* @param {Object} sx static properties to add/override
* @return {YUI} the YUI instance
*/
Y.extend = function(r, s, px, sx) {
if (!s||!r) {
// @TODO error symbols
Y.error("extend failed, verify dependencies");
}
var sp = s.prototype, rp=Y.Object(sp);
r.prototype=rp;
rp.constructor=r;
r.superclass=sp;
// assign constructor property
if (s != Object && sp.constructor == OP.constructor) {
sp.constructor=s;
}
// add prototype overrides
if (px) {
Y.mix(rp, px, true);
}
// add object overrides
if (sx) {
Y.mix(r, sx, true);
}
return r;
};
/**
* Executes the supplied function for each item in
* a collection. Supports arrays, objects, and
* Y.NodeLists
* @method each
* @param o the object to iterate
* @param f the function to execute. This function
* receives the value, key, and object as parameters
* @param proto if true, prototype properties are
* iterated on objects
* @return {YUI} the YUI instance
*/
Y.each = function(o, f, c, proto) {
return dispatch(o, f, c, proto, EACH);
};
/*
* Executes the supplied function for each item in
* a collection. The operation stops if the function
* returns true. Supports arrays, objects, and
* Y.NodeLists.
* @method some
* @param o the object to iterate
* @param f the function to execute. This function
* receives the value, key, and object as parameters
* @param proto if true, prototype properties are
* iterated on objects
* @return {boolean} true if the function ever returns true, false otherwise
*/
Y.some = function(o, f, c, proto) {
return dispatch(o, f, c, proto, SOME);
};
/**
* Deep obj/array copy. Function clones are actually
* wrappers around the original function.
* Array-like objects are treated as arrays.
* Primitives are returned untouched. Optionally, a
* function can be provided to handle other data types,
* filter keys, validate values, etc.
*
* @method clone
* @param o what to clone
* @param safe {boolean} if true, objects will not have prototype
* items from the source. If false, they will. In this case, the
* original is initially protected, but the clone is not completely immune
* from changes to the source object prototype. Also, cloned prototype
* items that are deleted from the clone will result in the value
* of the source prototype being exposed. If operating on a non-safe
* clone, items should be nulled out rather than deleted.
* @param f optional function to apply to each item in a collection;
* it will be executed prior to applying the value to
* the new object. Return false to prevent the copy.
* @param c optional execution context for f
* @param owner Owner object passed when clone is iterating an
* object. Used to set up context for cloned functions.
* @return {Array|Object} the cloned object
*/
Y.clone = function(o, safe, f, c, owner, cloned) {
if (!L.isObject(o)) {
return o;
}
// @TODO cloning YUI instances doesn't currently work
if (o instanceof YUI) {
return o;
}
var o2, marked = cloned || {}, stamp,
each = Y.each || Y.Object.each;
switch (L.type(o)) {
case 'date':
return new Date(o);
case 'regexp':
// return new RegExp(o.source); // if we do this we need to set the flags too
return o;
case 'function':
// o2 = Y.bind(o, owner);
// break;
return o;
case 'array':
o2 = [];
break;
default:
// #2528250 only one clone of a given object should be created.
if (o[CLONE_MARKER]) {
return marked[o[CLONE_MARKER]];
}
stamp = Y.guid();
o2 = (safe) ? {} : Y.Object(o);
o[CLONE_MARKER] = stamp;
marked[stamp] = o;
}
// #2528250 don't try to clone element properties
if (!o.addEventListener && !o.attachEvent) {
each(o, function(v, k) {
if (!f || (f.call(c || this, v, k, this, o) !== false)) {
if (k !== CLONE_MARKER) {
if (k == 'prototype') {
// skip the prototype
// } else if (o[k] === o) {
// this[k] = this;
} else {
this[k] = Y.clone(v, safe, f, c, owner || o, marked);
}
}
}
}, o2);
}
if (!cloned) {
Y.Object.each(marked, function(v, k) {
delete v[CLONE_MARKER];
});
marked = null;
}
return o2;
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the beginning of the arguments collection the
* supplied to the function.
*
* @method bind
* @param f {Function|String} the function to bind, or a function name
* to execute on the context object
* @param c the execution context
* @param args* 0..n arguments to include before the arguments the
* function is executed with.
* @return {function} the wrapped function
*/
Y.bind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function () {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments;
return fn.apply(c || fn, args);
};
};
/**
* Returns a function that will execute the supplied function in the
* supplied object's context, optionally adding any additional
* supplied parameters to the end of the arguments the function
* is executed with.
*
* @method rbind
* @param f {Function|String} the function to bind, or a function name
* to execute on the context object
* @param c the execution context
* @param args* 0..n arguments to append to the end of arguments collection
* supplied to the function
* @return {function} the wrapped function
*/
Y.rbind = function(f, c) {
var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null;
return function () {
var fn = L.isString(f) ? c[f] : f,
args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments;
return fn.apply(c || fn, args);
};
};
}, '@VERSION@' );
|
require('../modules/es6.object.to-string');
require('../modules/web.dom.iterable');
require('../modules/es6.weak-map');
module.exports = require('../modules/$.core').WeakMap;
|
import mod1770 from './mod1770';
var value=mod1770+1;
export default value;
|
$().ready(function () {
var $likeDislikeTripButton = $('#likeDislikeTripButton'),
$likesCount = $('#likesCount'),
ajaxAFT = $('#ajaxAFT input[name="__RequestVerificationToken"]:first').val();
$likeDislikeTripButton.on('click', function () {
var $this = $(this),
valueAsString = $this.attr('data-value'),
value = false
if (valueAsString == 'like') {
value = true;
}
$.ajax({
type: "POST",
url: '/TripAjax/LikeDislikeTrip',
data: {
__RequestVerificationToken: ajaxAFT,
tripId: tripId,
value: value
},
success: function (response) {
if (response.Status) {
if (value) {
addDislikeButton();
} else {
addLikeButton();
}
updateLikeCounts(response.Data);
toastr.success("You have successfully " + valueAsString + " this trip.");
} else {
if (response.ErrorMessage) {
toastr.error(response.ErrorMessage);
} else {
toastr.error("Unable to " + valueAsString + " this trip.");
}
}
}
})
});
function updateLikeCounts(likesCount) {
$likesCount.text(likesCount);
}
function addDislikeButton() {
$likeDislikeTripButton.removeClass('likeButton');
$likeDislikeTripButton.addClass('dislikeButton');
$likeDislikeTripButton.attr('data-value', 'dislike');
}
function addLikeButton() {
$likeDislikeTripButton.removeClass('dislikeButton');
$likeDislikeTripButton.addClass('likeButton');
$likeDislikeTripButton.attr('data-value', 'like');
}
})
|
'use strict';
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var Module = require('module');
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var glob = require('glob');
var minimatch = require('minimatch');
var babel = require('babel');
var Istanbul = require('istanbul');
var Mocha = require('mocha');
var run;
function padRight(str, length) {
return str + Array(length - str.length + 1).join(' ');
}
function addSourceComments(source) {
var sourceComment;
var sourceMap;
var originalLines;
var generatedSource;
var line;
var lines = [];
var longestLine = 0;
var longestLineNumber = 0;
var outputItems = [];
var output = [];
var tmp;
var i;
var j;
generatedSource = source.split('\n');
sourceComment = source.match(/\n\/\/# sourceMappingURL=data:application\/json;base64,(.+)/);
if (!sourceComment) {
return source;
}
sourceMap = new SourceMapConsumer(new Buffer(sourceComment[1], 'base64').toString('utf8'));
originalLines = sourceMap.sourceContentFor(sourceMap.sources[0]).split('\n');
for (i = 1; i <= generatedSource.length; i++) {
lines.push([]);
}
sourceMap.eachMapping(function sourceMapIterator(mapping) {
if (lines[mapping.generatedLine].indexOf(mapping.originalLine) === -1) {
lines[mapping.generatedLine].push(mapping.originalLine);
}
});
for (i = 1; i < generatedSource.length; i++) {
tmp = {
generated: generatedSource[i - 1],
original: false
};
line = '';
for (j = 0; j < lines[i].length; j++) {
line += originalLines[lines[i][j] - 1];
}
if (line !== '') {
tmp.original = line;
if (lines[i].length === 1) {
tmp.lineNumbers = '// Line: ' + lines[i][0];
}
else {
tmp.lineNumbers = '// Lines: ' + lines[i].join(',');
}
if (tmp.lineNumbers.length > longestLineNumber) {
longestLineNumber = tmp.lineNumbers.length;
}
}
// get the longest line length
if (generatedSource[i - 1].length > longestLine) {
longestLine = generatedSource[i - 1].length;
}
outputItems.push(tmp);
}
for (i = 0; i < outputItems.length; i++) {
if (outputItems[i].original) {
output.push(
padRight(outputItems[i].generated, longestLine + 3) +
padRight(outputItems[i].lineNumbers, longestLineNumber + 1) +
'| ' + outputItems[i].original
);
}
else {
output.push(outputItems[i].generated);
}
}
return output.join('\n');
}
function initMocha(mocha, testGlobs, options) {
var i;
var j;
var files;
for (i = 0; i < options.require.length; i++) {
require(options.require[i]);
}
for (i = 0; i < testGlobs.length; i++) {
files = glob.sync(testGlobs[i]);
for (j = 0; j < files.length; j++) {
mocha.addFile(files[j]);
}
}
return mocha;
}
function initIstanbulCallback(sourceStore, collector, options) {
global[options.istanbul.coverageVariable] = {};
function reporterCallback() {
collector.add(global[options.istanbul.coverageVariable]);
_.forOwn(options.istanbul.reporters, function reporterIterator(reporterOptions, name) {
Istanbul.Report
.create(name, _.defaults({
sourceStore: sourceStore, // include this always, not used by every reporter
dir: options.istanbul.directory // most (all?) reporters use this
}, reporterOptions))
.writeReport(collector, true);
});
}
return reporterCallback;
}
function initModuleRequire(instrumenter, sourceStore, options) {
Module._extensions['.js'] = function moduleExtension(module, filename) {
var matcher = minimatch.bind(null, filename);
var src = fs.readFileSync(filename, {
encoding: 'utf8'
});
// replace tabs with spaces
src = src.replace(/^\t+/gm, function tabsReplace(match) {
// hard code to 2 spaces per tabs for now, istanbul uses 2
return match.replace(/\t/g, ' ');
});
if (_.any(options.babelInclude, matcher) && !_.any(options.babelExclude, matcher)) {
options.babel.filename = filename;
try {
src = babel.transform(src, options.babel).code;
} catch (e) {
throw new Error('Error during babel transform - ' + filename + ': \n' + e.message);
}
}
if (!_.any(options.istanbul.exclude, matcher)) {
sourceStore.set(filename, addSourceComments(src));
try {
src = instrumenter.instrumentSync(src, filename);
} catch (e) {
throw new Error('Error during istanbul instrument - ' + filename + ': \n' + e.message);
}
}
module._compile(src, filename);
};
return Module._extensions['.js'];
}
function defaults(options) {
var i;
var opts = {};
opts.tests = options.tests? options.tests: ['test/**/*.js'];
opts.istanbul = _.defaults({}, options.istanbul, {
directory: 'coverage',
reporters: {
html: {},
text: {}
},
collector: {},
instrumenter: {},
coverageVariable: '__istanbul_coverage__',
exclude: []
});
opts.istanbul.instrumenter.coverageVariable = opts.istanbul.coverageVariable;
if (!_.isArray(opts.tests)) {
opts.tests = [opts.tests];
}
if (options.istanbul && options.istanbul.reporters) {
opts.istanbul.reporters = options.istanbul.reporters;
}
// add tests directories and node modules to the istanbul ignore
for (i = 0; i < opts.tests.length; i++) {
if (opts.tests[i][0] !== '/' && opts.tests[i].substr(0, 2) !== '**') {
opts.istanbul.exclude.push('**/' + opts.tests[i]);
}
else {
opts.istanbul.exclude.push(opts.tests[i]);
}
}
opts.istanbul.exclude.push('**/node_modules/**/*');
opts.mocha = _.defaults({}, options.mocha, {
require: []
});
if (!_.isArray(opts.mocha.require)) {
opts.mocha.require = [opts.mocha.require];
}
for (i = 0; i < opts.mocha.require.length; i++) {
opts.mocha.require[i] = path.resolve(opts.mocha.require[i]);
}
// convert greps to regex
if (opts.mocha.grep) {
if (!_.isArray(opts.mocha.grep)) {
opts.mocha.grep = [opts.mocha.grep];
}
for (i = 0; i < opts.mocha.grep.length; i++) {
if (!_.isRegExp(opts.mocha.grep[i])) {
opts.mocha.grep[i] = new RegExp(opts.mocha.grep[i]);
}
}
}
opts.babel = _.defaults({
sourceMap: 'inline'
}, options.babel, {
include: ['**/*.jsx', '**/*.js'],
exclude: []
}
);
opts.babelInclude = opts.babel.include;
opts.babelExclude = opts.babel.exclude;
delete opts.babel.include;
delete opts.babel.exclude;
if (!_.isArray(opts.babelInclude)) {
opts.babelInclude = [opts.babelInclude];
}
if (!_.isArray(opts.babelExclude)) {
opts.babelExclude = [opts.babelExclude];
}
opts.babelExclude.push('**/node_modules/**/*');
return _.cloneDeep(opts);
}
run = function run(options) {
var mocha;
var istanbulCallback;
var instrumenter;
var collector;
var sourceStore = Istanbul.Store.create('memory');
var opts = defaults(options);
instrumenter = new Istanbul.Instrumenter(opts.istanbul.instrumenter);
collector = new Istanbul.Collector(opts.istanbul.collector);
mocha = new Mocha(opts.mocha);
initMocha(mocha, opts.tests, opts.mocha);
initModuleRequire(instrumenter, sourceStore, opts);
istanbulCallback = initIstanbulCallback(
sourceStore, collector, opts
);
mocha.run(istanbulCallback);
};
module.exports = run;
|
import CDGPlayer from './CDGPlayer'
export default CDGPlayer
|
var structdbs_1_1i_1_1_r1 =
[
[ "nodes", "structdbs_1_1i_1_1_r1.html#a249eb273e89b4e1a053dea78ec1f2a3c", null ]
];
|
'use strict';
import React, { Component, PropTypes } from 'react';
class Package extends Component {
static propTypes = {
children: PropTypes.node,
billItems: PropTypes.object
}
render() {
const { billItems } = this.props;
const { subscriptions } = this.props.billItems.package;
const packages = subscriptions.map((val, key) =>
<tr key={key}>
<td>{val.name}</td>
<td>{val.type}</td>
<td>{val.cost}</td>
</tr>
);
return (
<section>
<h1>Latest Bill</h1>
<h3>Package</h3>
<table>
<thead>
<tr>
<th>Subscription</th>
<th>Type</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{packages}
</tbody>
</table>
<p><strong>Sub Total</strong> {billItems.package.total}</p>
{this.props.children}
</section>
);
}
}
export default Package;
|
'use strict';
require('nightingale-app-console');
var _pool = require('koack/pool');
var _pool2 = _interopRequireDefault(_pool);
var _server = require('koack/server');
var _server2 = _interopRequireDefault(_server);
var _memory = require('koack/storages/memory');
var _memory2 = _interopRequireDefault(_memory);
var _interactiveMessages = require('koack/interactive-messages');
var _interactiveMessages2 = _interopRequireDefault(_interactiveMessages);
var _config = require('../config');
var _config2 = _interopRequireDefault(_config);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pool = new _pool2.default({
size: 100,
path: require.resolve('./bot')
});
const server = new _server2.default({
pool,
scopes: ['bot'],
slackClient: _config2.default.slackClient,
storage: (0, _memory2.default)()
});
server.proxy = true;
server.use((0, _interactiveMessages2.default)({
pool,
token: _config2.default.verificationToken
}));
server.listen({ port: process.env.PORT || 3000 });
//# sourceMappingURL=index.js.map
|
// External modules
var del = require('del');
var critical = require('critical').stream;
// Import config
var config = require('./_config');
// Html module
module.exports = function(gulp, livereload) {
gulp.task('html', function() {
return gulp.src(config.html)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('html--deploy', function() {
return gulp.src(config.html)
.pipe(critical({
base: 'dist/',
inline: true,
css: ['dist/app.css']
}))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function() {
return gulp.src(config.images)
.pipe(gulp.dest('dist/images'))
.pipe(livereload());
});
gulp.task('assets', function() {
return gulp.src(config.assets)
.pipe(gulp.dest('dist/assets'))
.pipe(livereload());
});
gulp.task('fixtures', function() {
return gulp.src(config.fixtures)
.pipe(gulp.dest('dist'))
.pipe(livereload());
});
gulp.task('clean-html-tmp', function () {
return del(['dist/tmp-**']);
});
gulp.task('clean-dist', function () {
return del(['dist/**']);
});
};
|
/** @license ISC License (c) copyright 2017 original and current authors */
/** @author Ian Hofmann-Hicks (evil) */
const Pair = require('../core/types').proxy('Pair')
const isFoldable = require('../core/isFoldable')
const isSameType = require('../core/isSameType')
const isString = require('../core/isString')
function foldPairs(acc, pair) {
if(!isSameType(Pair, pair)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
const key = pair.fst()
const value = pair.snd()
if(!isString(key)) {
throw new TypeError('fromPairs: String required for fst of every Pair')
}
return value !== undefined
? Object.assign(acc, { [key]: value })
: acc
}
/** fromPairs :: Foldable f => f (Pair String a) -> Object */
function fromPairs(xs) {
if(!isFoldable(xs)) {
throw new TypeError('fromPairs: Foldable of Pairs required for argument')
}
return xs.reduce(foldPairs, {})
}
module.exports = fromPairs
|
var fs = require('fs');
var tapOut = require('tap-out');
var through = require('through2');
var duplexer = require('duplexer');
var format = require('chalk');
var prettyMs = require('pretty-ms');
var _ = require('lodash');
var repeat = require('repeat-string');
var symbols = require('./lib/utils/symbols');
var lTrimList = require('./lib/utils/l-trim-list');
module.exports = function (spec) {
spec = spec || {};
// TODO: document
var OUTPUT_PADDING = spec.padding || ' ';
var output = through();
var parser = tapOut();
var stream = duplexer(parser, output);
var startTime = new Date().getTime();
output.push('\n');
parser.on('test', function (test) {
output.push('\n' + pad(test.name) + '\n\n');
});
// Passing assertions
parser.on('pass', function (assertion) {
var glyph = format.green(symbols.ok);
var name = format.dim(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
});
// Failing assertions
parser.on('fail', function (assertion) {
var glyph = format.red(symbols.err);
var name = format.red.bold(assertion.name);
output.push(pad(' ' + glyph + ' ' + name + '\n'));
stream.failed = true;
});
// All done
parser.on('output', function (results) {
output.push('\n\n');
if (results.fail.length > 0) {
output.push(formatErrors(results));
output.push('\n');
}
output.push(formatTotals(results));
output.push('\n\n\n');
});
// Utils
function formatErrors (results) {
var failCount = results.fail.length;
var past = (failCount === 1) ? 'was' : 'were';
var plural = (failCount === 1) ? 'failure' : 'failures';
var out = '\n' + pad(format.red.bold('Failed Tests:') + ' There ' + past + ' ' + format.red.bold(failCount) + ' ' + plural + '\n');
out += formatFailedAssertions(results);
return out;
}
function formatTotals (results) {
return _.filter([
pad('total: ' + results.asserts.length),
pad(format.green('passing: ' + results.pass.length)),
results.fail.length > 0 ? pad(format.red('failing: ' + results.fail.length)) : null,
pad('duration: ' + prettyMs(new Date().getTime() - startTime)) // TODO: actually calculate this
], _.identity).join('\n');
}
function formatFailedAssertions (results) {
var out = '';
var groupedAssertions = _.groupBy(results.fail, function (assertion) {
return assertion.test;
});
_.each(groupedAssertions, function (assertions, testNumber) {
// Wrie failed assertion's test name
var test = _.find(results.tests, {number: parseInt(testNumber)});
out += '\n' + pad(' ' + test.name + '\n\n');
// Write failed assertion
_.each(assertions, function (assertion) {
out += pad(' ' + format.red(symbols.err) + ' ' + format.red(assertion.name)) + '\n';
out += formatFailedAssertionDetail(assertion) + '\n';
});
});
return out;
}
function formatFailedAssertionDetail (assertion) {
var out = '';
var filepath = assertion.error.at.file;
var contents = fs.readFileSync(filepath).toString().split('\n');
var line = contents[assertion.error.at.line - 1];
var previousLine = contents[assertion.error.at.line - 2];
var nextLine = contents[assertion.error.at.line];
var lineNumber = parseInt(assertion.error.at.line);
var previousLineNumber = parseInt(assertion.error.at.line) - 1;
var nextLineNumber = parseInt(assertion.error.at.line) + 1;
var lines = lTrimList([
line,
previousLine,
nextLine
]);
var atCharacterPadding = parseInt(assertion.error.at.character) + parseInt(lineNumber.toString().length) + 2;
out += pad(' ' + format.dim(filepath)) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('v') + "\n");
out += pad(' ' + format.dim(previousLineNumber + '. ' + lines[1])) + '\n';
out += pad(' ' + lineNumber + '. ' + lines[0]) + '\n';
out += pad(' ' + format.dim(nextLineNumber + '. ' + lines[2])) + '\n';
out += pad(' ' + repeat(' ', atCharacterPadding) + format.red('^') + "\n");
return out;
}
function pad (str) {
return OUTPUT_PADDING + str;
}
return stream;
};
|
/*jshint esnext: true */
let plugins;
export default class DevicePlugin {
constructor(_plugins) {
plugins = _plugins;
plugins.registerCommand('Device', 'getDeviceInfo', this.getDeviceInfo);
}
getDeviceInfo(sender) {
return {
platform: sender.device.preset.platform,
version: sender.device.preset.platformVersion,
uuid: sender.device.uuid,
model: sender.device.preset.model
};
}
}
DevicePlugin.$inject = ['plugins'];
|
/**
* Created by larus on 15/2/9.
*/
angular.module('myApp').directive('taginput', function () {
return {
restrict: 'E',
template: '<input name="{{name}}" class="tagsinput tagsinput-primary" ng-value="values" />',
replace: true,
scope: {
tags: '=',
name: '@',
id: '@'
},
link: function ($scope, element, attrs) {
$scope.name = attrs.name;
$scope.id = attrs.id;
$scope.$watch('tags', function (value) {
if (!value)
value = [];
$scope.values = value;
element.tagsInput(value.toString());
});
element.tagsInput({
onAddTag: function (value) {
$scope.values.push(value);
$scope.$apply(function () {
$scope.tags = $scope.values;
});
}
});
},
controller: function ($scope) {
}
}
});
|
/* eslint-disable consistent-this */
var cscript = require('../lib/cscript.js')
describe('cscript', function() {
var mockFs, mockExecFile
it('must be initialized', function() {
(function() {
cscript.path()
}).should.throw('must initialize first')
})
it('if cscript.exe is successfully spawned then no more checks are conducted', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['cscript.exe'].args[0].should.eql('cscript.exe')
done()
})
})
it('initializes only once', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].stdout = cscript.CSCRIPT_EXPECTED_OUTPUT
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(0)
done()
})
})
})
it('if cscript.exe fails to execute, try to run "where cscript.exe"', function(done) {
mockExecFile['cscript.exe'].calls.should.eql(0)
mockExecFile['where cscript.exe'].calls.should.eql(0)
mockExecFile['cscript.exe'].err = new Error()
mockExecFile['cscript.exe'].err.code = 'ENOENT'
mockExecFile['where cscript.exe'].stdout = '123'
cscript.init(function(err) {
if (err) {
return done(err)
}
mockExecFile['cscript.exe'].calls.should.eql(1)
mockExecFile['where cscript.exe'].calls.should.eql(1)
cscript.path().should.eql('123')
done()
})
})
beforeEach(function() {
mockFs = {
err: null,
calls: 0,
stat: function(name, cb) {
this.calls++
var self = this
setImmediate(function() {
cb(self.err, {})
})
},
}
mockExecFile = function(command, args, options, callback) {
if (!mockExecFile[command]) {
throw new Error('unexpected command ' + command)
}
mockExecFile[command].args = arguments
mockExecFile[command].calls++
if (typeof args === 'function') {
callback = args
args = undefined
options = undefined
}
if (typeof options === 'function') {
callback = options
args = undefined
options = undefined
}
if (typeof callback !== 'function') {
throw new Error('missing callback')
}
setImmediate(function() {
callback(mockExecFile[command].err, mockExecFile[command].stdout, mockExecFile[command].stderr)
})
}
mockExecFile['cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
mockExecFile['where cscript.exe'] = { calls: 0, stdout: '', stderr: '', err: null }
cscript._mock(mockFs, mockExecFile, false)
})
afterEach(function() {
cscript._mockReset()
})
})
|
var SpecHelper = function(){};
|
var add = function( part ){
this._value.push(part);
}
var resolved = function( is ){
if( undefined === is ) return this._resolved;
this._resolved = !!is;
return this._resolved;
}
var getValue = function(){
return this._value;
}
var setValue = function( value ){
this._value = value;
}
var Wildcard = function(){
_oop(this,"Espresso/Bag/Resolver/Wildcard");
this._value = [];
this._resolved = false;
this._parent;
}
Wildcard.prototype.add = add;
Wildcard.prototype.resolved = resolved;
Wildcard.prototype.getValue = getValue;
Wildcard.prototype.setValue = setValue;
module.exports = Wildcard;
|
// var knexConfig = require('../knexfile')
// var knex = require('knex')(knexConfig[process.env.NODE_ENV || "development"])
var knex = require('./knexOrigin')
module.exports = {
createEvent: (eventObj, cb) => {
knex('events').insert(eventObj)
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
},
getEventById: (eventId, cb) => {
knex.select().where("id", eventId).table("events")
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
},
getEventsByHostId: (userId, cb) => {
knex('hosts').select()
.join('events', 'hosts.eventId', '=', 'events.id')
.where('hosts.userId', userId)
.then( (data) => cb(null, data) )
.catch( (err) => cb(err) )
},
getEventsByGuestId: (userId, cb) => {
knex('guests').select()
.join('events', 'guests.eventId', '=', 'events.id')
.where('guests.userId', userId)
.then( (data) => cb(null, data) )
.catch( (err) => cb(err) )
},
updateEvent: (eventId, eventChanges, cb) => {
knex('events').update(eventChanges).where('id', eventId)
.then( (data) => cb(null, data[0]) )
.catch( (err) => cb(err) )
}
}
|
(function ($) {
"use strict";
Dropzone.options.myDropzone = {
// Prevents Dropzone from uploading dropped files immediately
autoProcessQueue: false
, init: function () {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
submitButton.addEventListener("click", function () {
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function () {
// Show submit button here and/or inform user to click it.
});
}
};
})(jQuery);
|
// @flow
/* eslint-disable */
import {
periodic,
now,
merge,
never,
newStream,
propagateEventTask
} from '@most/core'
import {disposeBoth, disposeWith} from '@most/disposable'
import {newDefaultScheduler, asap} from '@most/scheduler'
import M from '../m'
import tree from './element'
import type {Pith} from '../vtree/rvnode'
import Counter1 from '../piths/counter1'
import Counter2 from '../piths/counter2'
const elm = document.getElementById('root-node')
if (!elm) throw new Error()
const count = () =>
M.of(periodic(1000))
.scan(a => a + 1, 0)
.skip(1)
.map(i => 'h' + i)
.take(10)
.continueWith(count)
.valueOf()
const ring = pith => pith // (put, on) => pith({...put}, on)
const rez = tree(elm)(Test())
const disposable = M.of(rez).$.run(
{
event: (t, e) => {},
end: t => {},
error: (t, err) => {}
},
newDefaultScheduler()
)
setTimeout(disposable.dispose.bind(disposable), 20000)
function Test() {
return ring((put, on) => {
function f(vnode, cb) {
if (f.patchedNodes.has(vnode)) return
const listener = () => console.log('patch', vnode)
vnode.node.addEventListener('click', listener)
console.log('addEventListener')
f.patchedNodes.set(vnode, () => {
console.log('removeEventListener')
vnode.node.removeEventListener('click', listener)
})
}
f.patchedNodes = new Map()
put.put(
newStream((sink, scheduler) => {
console.log('sink')
return disposeBoth(
asap(propagateEventTask(f, sink), scheduler),
disposeWith(() => {
f.patchedNodes.forEach(d => d())
f.patchedNodes.clear()
}, null)
)
})
)
// put.text('text')
put.node('div')(put => {
put.node('button', {on: {click: 'a'}})(put => put.text('a'))
put.node('button', {on: {click: 'b'}})(put => put.text('b'))
put.node('button', {on: {click: 'o'}})(put => put.text('o'))
})
put.node('h4')(put => put.text(count()))
put.node('div', {}, 'key')(
M.of(on)
.filter(x => typeof x.action === 'string')
.map(x => {
if (x.action === 'a') return Counter1(0)
if (x.action === 'b') return Counter1(1)
return Counter2(1)
})
.startWith(put => put.node('h1')(put => put.text('select')))
.tap(pith => console.timeStamp(pith.toString()))
.valueOf()
)
})
}
function C(): Pith {
return (put, on) => {
put.node('button', {on: {click: 'A'}})(put => {
put.text('A')
})
put.text(
M.of(on)
.map(x => x.action)
.startWith('')
.valueOf()
)
}
}
|
var socket; //socket.io (live engine)
//Variable is set by server later on
var position = {
x: 1,
y: 1
};
var heading; // direction of player
var nameSize = 18; // size of the name label
//Variable is set by server later on
var worldDimensions = {
x: 1,
y: 1
};
var inPlay = false; //whether you have started playing
var currFrameNum = 0;
var prevTimeOfFrame = 0;
function setup() {
createCanvas(windowWidth, windowHeight);
//Load the skins into the array
for (var path in playerImageOptions) {
playerImages.push(loadImage("sprites/players/" + playerImageOptions[path]))
}
imageMode(CENTER)
}
//receive world dimensions from the server
function setWorldDimensions(wd) {
worldDimensions = wd;
}
//reload the page when you die
function iDied() {
location.reload();
}
//draw the grid background
function drawGrid(sqrWidth, border) {
strokeWeight(border);
stroke(25);
for (var x = 0; x < worldDimensions.x - 1; x += (sqrWidth + border)) {
line(x, 0, x, worldDimensions.y);
}
for (var y = 0; y < worldDimensions.y - 1; y += (sqrWidth + border)) {
line(0, y, worldDimensions.x, y);
}
}
//Display the world
function worldUpdate(bodies) {
background(30);
displayBodies(bodies);
}
function displayBodies(bodies) {
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
//Check if the body is a player
if (body.label === 'player') {
//Draw the player image
if (body.socketID === socket.id) {
translate(-body.position.x + width / 2, -body.position.y + height / 2);
break;
}
}
}
drawGrid(60, 20);
//Loop through all the bodies in the world
for (var i = 0; i < bodies.length; i++) {
var body = bodies[i];
//Check if the body is a player
if (body.label === 'player') {
//Draw the player image
push();
translate(body.position.x, body.position.y);
rotate(body.angle);
image(playerImages[body.skinID], 0, 0);
pop();
//Write number of bullets if it is the current player
var bodyColor = color(body.render.fillStyle);
fill(color(255 - red(bodyColor), 255 - green(bodyColor), 255 - blue(bodyColor)));
textSize(nameSize);
text(body.numOfBullets, body.position.x - textWidth(body.numOfBullets) / 2, body.position.y - 60)
text(body.name, body.position.x - textWidth(body.name) / 2, body.position.y)
//Draw the health bar
var barSize = body.maxHealth / 2;
fill(255, 0, 0);
rect(body.position.x - barSize / 2, body.position.y - 45, barSize, 10);
fill(0, 255, 0);
rect(body.position.x - barSize / 2, body.position.y - 45, barSize * body.health / body.maxHealth, 10)
} else {
//Draw shape from its vertices
strokeWeight(body.render.lineWidth);
fill(body.render.fillStyle);
stroke(body.render.strokeStyle);
var vertices;
push();
if (typeof(body.vertices) === 'string') {
translate(body.position.x, body.position.y);
rotate(body.angle);
vertices = objectVertices[body.vertices];
} else {
vertices = body.vertices
}
beginShape();
for (var j = 0; j < vertices.length; j++) {
var v = vertices[j];
vertex(v.x, v.y);
}
endShape(CLOSE);
pop();
}
}
}
function draw() {
if (inPlay) {
heading = {
x: (mouseX - width / 2),
y: (mouseY - height / 2)
};
heading = getUnitVector(heading);
socket.emit('heading', heading)
} else {
var padding = 0;
var imageSize = (width - padding * (playerImages.length - 1)) / playerImages.length;
for (var i = 0; i < playerImages.length; i++) {
push();
translate(i * (imageSize + padding) + imageSize / 2, imageSize / 2);
rotate(Math.PI / 2);
image(playerImages[i], 0, 0, imageSize, imageSize);
pop();
}
}
}
function getUnitVector(v) {
var scale = Math.sqrt(v.x * v.x + v.y * v.y);
if (scale !== 0) {
v.x = v.x / scale;
v.y = v.y / scale
}
return v;
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight)
}
function keyReleased() {
if (key === ' ') {
socket.emit('newBullet')
}
if (key === 'B') {
var bombParams = getBombParams();
try {
if ((bombParams.bullets > 0)) {
socket.emit('newBomb', bombParams.bullets, bombParams.trigger, bombParams.visible)
}
} catch (e) {
}
}
if (key === 'S' && inPlay) {
toggleBombSelector();
}
}
|
// Thai
jQuery.timeago.settings.strings = {
prefixAgo : null,
prefixFromNow: null,
suffixAgo : "ที่แล้ว",
suffixFromNow: "จากตอนนี้",
seconds : "น้อยกว่าหนึ่งนาที",
minute : "ประมาณหนึ่งนาที",
minutes : "%d นาที",
hour : "ประมาณหนึ่งชั่วโมง",
hours : "ประมาณ %d ชั่วโมง",
day : "หนึ่งวัน",
days : "%d วัน",
month : "ประมาณหนึ่งเดือน",
months : "%d เดือน",
year : "ประมาณหนึ่งปี",
years : "%d ปี",
wordSeparator: "",
numbers : []
};
|
// Copyright (c) 2009 by Doug Kearns
//
// This work is licensed for reuse under an MIT license. Details are
// given in the License.txt file included with this file.
const Name = "Vimperator";
/*
* We can't load our modules here, so the following code is sadly
* duplicated: .w !sh
vimdiff ../../*'/components/about-handler.js'
*/
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
const Cc = Components.classes;
const Ci = Components.interfaces;
const name = Name.toLowerCase();
function AboutHandler() {}
AboutHandler.prototype = {
classDescription: "About " + Name + " Page",
classID: Components.ID("81495d80-89ee-4c36-a88d-ea7c4e5ac63f"),
contractID: "@mozilla.org/network/protocol/about;1?what=" + name,
QueryInterface: XPCOMUtils.generateQI([Ci.nsIAboutModule]),
newChannel: function (uri) {
let channel = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newChannel("chrome://" + name + "/content/about.html", null, null);
channel.originalURI = uri;
return channel;
},
getURIFlags: function (uri) Ci.nsIAboutModule.ALLOW_SCRIPT
};
if(XPCOMUtils.generateNSGetFactory)
var NSGetFactory = XPCOMUtils.generateNSGetFactory([AboutHandler]);
else
function NSGetModule(compMgr, fileSpec) XPCOMUtils.generateModule([AboutHandler])
// vim: set fdm=marker sw=4 ts=4 et:
|
export default Ember.ObjectController.extend({
actions: {
cancel: function() {
this.transitionToRoute('books');
}
}
});
|
////////////////////////////////////////////////
/* Provided Code - Please Don't Edit */
////////////////////////////////////////////////
'use strict';
function getInput() {
console.log("Please choose either 'rock', 'paper', or 'scissors'.")
return prompt();
}
function randomPlay() {
var randomNumber = Math.random();
if (randomNumber < 0.33) {
return "rock";
} else if (randomNumber < 0.66) {
return "paper";
} else {
return "scissors";
}
}
////////////////////////////////////////////////
/* Write Your Code Below */
////////////////////////////////////////////////
function getPlayerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `getInput()`.
return move || getInput();
}
function getComputerMove(move) {
// Write an expression that operates on a variable called `move`
// If a `move` has a value, your expression should evaluate to that value.
// However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
return move || randomPlay();
}
function getWinner(playerMove,computerMove) {
var winner;
// Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
// Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
// The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
if (playerMove === computerMove){
winner = 'tie';
} else if(playerMove === 'rock' && computerMove === 'scissors'){
winner = 'player';
} else if(playerMove === 'scissors' && computerMove === 'rock'){
winner = 'computer';
} else if(playerMove === 'paper' && computerMove === 'rock'){
winner = 'player';
} else if(playerMove === 'rock' && computerMove === 'paper'){
winner = 'computer';
} else if(playerMove === 'paper' && computerMove === 'scissors'){
winner = 'computer';
} else if(playerMove === 'scissors' && computerMove === 'paper'){
winner = 'player';
}
return winner;
}
function playToFive() {
console.log("Let's play Rock, Paper, Scissors");
var playerWins = 0;
var computerWins = 0;
// Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
/* YOUR CODE HERE */
while (playerWins < 5 && computerWins < 5) {
var playerMove = getPlayerMove();
var computerMove = getComputerMove();
var winner = getWinner(playerMove,computerMove);
if (winner === 'player') {
playerWins += 1;
} else if ( winner === 'computer') {
computerWins += 1;
} else { playerWins += 0;
computerWins += 0;
console.log("It's a tie!")
}
console.log('Player chose ' + playerMove + ' while Computer chose ' + computerMove);
console.log('The score is currently ' + playerWins + ' to ' + computerWins);
}
if (playerWins > computerWins) {
console.log('Player won! Congrats!')
}
else {
console.log('Computer won....Game Over!')
}
}
//call function
playToFive();
|
var express = require('express'),
server = express();
server.use('/', express.static(__dirname + '/public'));
server.use('/shaders', express.static(__dirname + '/lessons/shaders'));
server.use('/assets', express.static(__dirname + '/lessons/assets'));
server.listen(9000);
console.log('Listening on port 9000');
|
var assert = require('assert');
var _ = require('lodash');
var Client = require('./lib/client');
describe('cgminer-api', function () {
describe('@parser', function () {
});
describe('@client', function () {
var client;
before(function (done) {
client = new Client({
host: process.env.CGMINER_HOST,
port: process.env.CGMINER_PORT
});
client.connect()
.then(function (client) {
assert(client instanceof Client);
done();
})
.catch(function (err) {
done(err);
});
});
it('can double-connect without error', function (done) {
client.connect()
.then(function (client) {
assert(client instanceof Client);
done();
})
.catch(function (err) {
done(err);
});
});
describe('#_commands', function () {
it('should be an object', function () {
//console.log(client._commands);
assert(_.isObject(client._commands));
});
});
describe('#version()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.version), 'client.version() is not a function');
client.version().then(function (result) {
assert(_.isObject(result));
assert(_.isString(result.API));
done();
})
.catch(done);
});
});
describe.skip('#stats()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.stats), 'client.stats() is not a function');
client.stats().then(function (stats) {
assert(_.isObject(stats));
done();
})
.catch(done);
});
});
describe('#summary()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.summary), 'client.summary() is not a function');
client.summary().then(function (summary) {
assert(_.isObject(summary));
done();
})
.catch(done);
});
});
describe('#pools()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.summary), 'client.pools() is not a function');
client.pools().then(function (pools) {
//console.log(pools);
assert(_.isArray(pools));
done();
})
.catch(done);
});
});
describe('#devs()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.summary), 'client.devs() is not a function');
client.devs().then(function (devices) {
console.log(devices);
assert(_.isArray(devices));
done();
})
.catch(done);
});
});
describe('#config()', function (done) {
it('should return a validated object', function (done) {
assert(_.isFunction(client.summary), 'client.config() is not a function');
client.config().then(function (config) {
assert(_.isObject(config));
done();
})
.catch(done);
});
});
describe('#addpool()', function (done) {
var poolCount = 0;
before(function (done) {
client.pools().then(function (pools) {
assert(_.isArray(pools));
poolCount = pools.length;
done();
})
.catch(done);
});
it('should return a validated object', function (done) {
var pool = [
'stratum+tcp://us1.ghash.io:3333',
'abshnasko.ephemeral1',
'x'
];
assert(_.isFunction(client.addpool), 'client.addpool() is not a function');
client.addpool(pool).then(function (status) {
console.log(status);
assert(_.isObject(status));
assert(/added pool/i.test(status.Msg));
done();
})
.catch(done);
});
it('should add a pool', function (done) {
client.pools().then(function (pools) {
assert(_.isArray(pools));
assert(pools.length === poolCount + 1,
'pool count should be ' + (poolCount + 1) + ' but is actually '+ pools.length);
done();
})
.catch(done);
});
});
describe('#enablepool()', function (done) {
it('should return a validated object', function (done) {
client.enablepool(0).then(function (status) {
assert(_.isObject(status));
done();
})
.catch(done);
});
it('should enable pool', function (done) {
client.enablepool(0).then(function (status) {
//console.log(status);
assert(/already enabled/.test(status.Msg), status.Msg);
done();
})
.catch(done);
});
});
describe('#disablepool()', function (done) {
it('should return a validated object', function (done) {
client.disablepool(0)
.then(function (status) {
assert(/Disabling pool/.test(status.Msg), status.Msg);
assert(_.isObject(status));
done();
})
.catch(done);
});
it('should disable pool', function (done) {
client.disablepool(0)
.then(function (status) {
assert(/already disabled/.test(status.Msg), status.Msg);
done();
})
.catch(done);
});
});
describe('#removepool()', function (done) {
it('should disable and remove pool', function (done) {
client.removepool(0)
.then(function (status) {
//console.log(status);
if (/Cannot remove active pool/.test(status.Msg)) {
// should throw a warning here, but this is not an exception
return client.disablepool(0);
}
else {
assert(/Removed pool 0/.test(status.Msg), status.Msg);
}
})
.then(function (status) {
//console.log(status);
done();
})
.catch(done);
});
});
describe('#switchpool()', function (done) {
it('should switch pool 0 to highest priority', function (done) {
client.switchpool(0)
.then(function (status) {
assert(_.isObject(status));
assert(_.any([
/Switching to pool 0/.test(status.Msg),
/Cannot remove active pool/.test(status.Msg)
]), status.Msg
);
done();
})
.catch(done);
});
});
describe('#save()', function (done) {
it('should save config without error', function (done) {
client.save()
.then(function (status) {
assert(/Configuration saved to file/.test(status.Msg));
assert(_.isObject(status));
done();
})
.catch(done);
});
});
describe('#privileged()', function (done) {
it('should return success, indicating we have privileged access', function (done) {
client.privileged()
.then(function (status) {
assert(/Privileged access OK/.test(status.Msg));
assert(_.isObject(status));
done();
})
.catch(done);
});
});
describe('#check()', function (done) {
it('should check summary command', function (done) {
client.check('summary')
.then(function (cmd) {
assert(_.isObject(cmd));
assert(cmd.Exists === 'Y');
assert(cmd.Access === 'Y');
done();
})
.catch(done);
});
it('should check bogus command', function (done) {
client.check('bogus')
.then(function (cmd) {
assert(_.isObject(cmd));
assert(cmd.Exists === 'N');
assert(cmd.Access === 'N');
done();
})
.catch(done);
});
});
describe('#restart()', function (done) {
it('should restart', function (done) {
client.restart()
.then(function (status) {
assert(_.isObject(status));
done();
})
.catch(done);
});
});
});
});
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
name: { type: String, required: true },
position: { type: String },
marketValue: { type: Number },
jerseyNumber: { type: Number },
dateOfBirth: { type: Date },
contractedUntil: { type: Date },
club_id: { type: Schema.Types.ObjectId, ref: 'Club' },
nation_name: { type: String, ref: 'Nation' },
attributes: {
physical: {
Acceleration: { type: Number },
Agility: { type: Number },
Balance: { type: Number },
JumpingReach: { type: Number },
NaturalFitness: { type: Number },
Pace: { type: Number },
Stamina: { type: Number },
Strength: { type: Number },
GoalkeeperRating:{ type: Number }
},
mental: {
Aggression: { type: Number },
Anticipation: { type: Number },
Bravery: { type: Number },
Composure: { type: Number },
Concentration: { type: Number },
Decision: { type: Number },
Determination: { type: Number },
Flair: { type: Number },
Leadership: { type: Number },
OfftheBall: { type: Number },
Positioning: { type: Number },
Teamwork: { type: Number },
Vision: { type: Number },
WorkRate:{ type: Number }
},
technical: {
Crossing: { type: Number },
Dribbling: { type: Number },
Finishing: { type: Number },
FirstTouch: { type: Number },
FreeKickTaking: { type: Number },
Heading: { type: Number },
LongShots: { type: Number },
LongThrows: { type: Number },
Marking: { type: Number },
Passing: { type: Number },
PenaltyTaking: { type: Number },
Tackling: { type: Number },
Technique:{ type: Number }
}
}
})
module.exports = mongoose.model('Player', schema);
|
"use strict";
const filterable = require("@lerna/filter-options");
/**
* @see https://github.com/yargs/yargs/blob/master/docs/advanced.md#providing-a-command-module
*/
exports.command = "bootstrap";
exports.describe = "Link local packages together and install remaining package dependencies";
exports.builder = yargs => {
yargs
.example(
"$0 bootstrap -- --no-optional",
"# execute `npm install --no-optional` in bootstrapped packages"
)
.parserConfiguration({
"populate--": true,
})
.options({
hoist: {
group: "Command Options:",
describe: "Install external dependencies matching [glob] to the repo root",
defaultDescription: "'**'",
},
nohoist: {
group: "Command Options:",
describe: "Don't hoist external dependencies matching [glob] to the repo root",
type: "string",
requiresArg: true,
},
mutex: {
hidden: true,
// untyped and hidden on purpose
},
"ignore-prepublish": {
group: "Command Options:",
describe: "Don't run prepublish lifecycle scripts in bootstrapped packages.",
type: "boolean",
},
"ignore-scripts": {
group: "Command Options:",
describe: "Don't run _any_ lifecycle scripts in bootstrapped packages",
type: "boolean",
},
"npm-client": {
group: "Command Options:",
describe: "Executable used to install dependencies (npm, yarn, pnpm, ...)",
type: "string",
requiresArg: true,
},
registry: {
group: "Command Options:",
describe: "Use the specified registry for all npm client operations.",
type: "string",
requiresArg: true,
},
strict: {
group: "Command Options:",
describe: "Don't allow warnings when hoisting as it causes longer bootstrap times and other issues.",
type: "boolean",
},
"use-workspaces": {
group: "Command Options:",
describe: "Enable integration with Yarn workspaces.",
type: "boolean",
},
"force-local": {
group: "Command Options:",
describe: "Force local sibling links regardless of version range match",
type: "boolean",
},
contents: {
group: "Command Options:",
describe: "Subdirectory to use as the source of any links. Must apply to ALL packages.",
type: "string",
defaultDescription: ".",
},
});
return filterable(yargs);
};
exports.handler = function handler(argv) {
return require(".")(argv);
};
|
/*
* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
( function() {
// Add to collection with DUP examination.
// @param {Object} collection
// @param {Object} element
// @param {Object} database
function addSafely( collection, element, database ) {
// 1. IE doesn't support customData on text nodes;
// 2. Text nodes never get chance to appear twice;
if ( !element.is || !element.getCustomData( 'block_processed' ) ) {
element.is && CKEDITOR.dom.element.setMarker( database, element, 'block_processed', true );
collection.push( element );
}
}
// Dialog reused by both 'creatediv' and 'editdiv' commands.
// @param {Object} editor
// @param {String} command The command name which indicate what the current command is.
function divDialog( editor, command ) {
// Definition of elements at which div operation should stopped.
var divLimitDefinition = ( function() {
// Customzie from specialize blockLimit elements
var definition = CKEDITOR.tools.extend( {}, CKEDITOR.dtd.$blockLimit );
if ( editor.config.div_wrapTable ) {
delete definition.td;
delete definition.th;
}
return definition;
} )();
// DTD of 'div' element
var dtd = CKEDITOR.dtd.div;
// Get the first div limit element on the element's path.
// @param {Object} element
function getDivContainer( element ) {
var container = editor.elementPath( element ).blockLimit;
// Never consider read-only (i.e. contenteditable=false) element as
// a first div limit (https://dev.ckeditor.com/ticket/11083).
if ( container.isReadOnly() )
container = container.getParent();
// Dont stop at 'td' and 'th' when div should wrap entire table.
if ( editor.config.div_wrapTable && container.is( [ 'td', 'th' ] ) ) {
var parentPath = editor.elementPath( container.getParent() );
container = parentPath.blockLimit;
}
return container;
}
// Init all fields' setup/commit function.
// @memberof divDialog
function setupFields() {
this.foreach( function( field ) {
// Exclude layout container elements
if ( /^(?!vbox|hbox)/.test( field.type ) ) {
if ( !field.setup ) {
// Read the dialog fields values from the specified
// element attributes.
field.setup = function( element ) {
field.setValue( element.getAttribute( field.id ) || '', 1 );
};
}
if ( !field.commit ) {
// Set element attributes assigned by the dialog
// fields.
field.commit = function( element ) {
var fieldValue = this.getValue();
// ignore default element attribute values
if ( field.id == 'dir' && element.getComputedStyle( 'direction' ) == fieldValue ) {
return;
}
if ( fieldValue )
element.setAttribute( field.id, fieldValue );
else
element.removeAttribute( field.id );
};
}
}
} );
}
// Wrapping 'div' element around appropriate blocks among the selected ranges.
// @param {Object} editor
function createDiv( editor ) {
// new adding containers OR detected pre-existed containers.
var containers = [];
// node markers store.
var database = {};
// All block level elements which contained by the ranges.
var containedBlocks = [],
block;
// Get all ranges from the selection.
var selection = editor.getSelection(),
ranges = selection.getRanges();
var bookmarks = selection.createBookmarks();
var i, iterator;
// collect all included elements from dom-iterator
for ( i = 0; i < ranges.length; i++ ) {
iterator = ranges[ i ].createIterator();
while ( ( block = iterator.getNextParagraph() ) ) {
// include contents of blockLimit elements.
if ( block.getName() in divLimitDefinition && !block.isReadOnly() ) {
var j,
childNodes = block.getChildren();
for ( j = 0; j < childNodes.count(); j++ )
addSafely( containedBlocks, childNodes.getItem( j ), database );
} else {
while ( !dtd[ block.getName() ] && !block.equals( ranges[ i ].root ) )
block = block.getParent();
addSafely( containedBlocks, block, database );
}
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
var blockGroups = groupByDivLimit( containedBlocks );
var ancestor, divElement;
for ( i = 0; i < blockGroups.length; i++ ) {
// Sometimes we could get empty block group if all elements inside it
// don't have parent's nodes (https://dev.ckeditor.com/ticket/13585).
if ( !blockGroups[ i ].length ) {
continue;
}
var currentNode = blockGroups[ i ][ 0 ];
// Calculate the common parent node of all contained elements.
ancestor = currentNode.getParent();
for ( j = 1; j < blockGroups[ i ].length; j++ ) {
ancestor = ancestor.getCommonAncestor( blockGroups[ i ][ j ] );
}
// If there is no ancestor, mark editable as one (https://dev.ckeditor.com/ticket/13585).
if ( !ancestor ) {
ancestor = editor.editable();
}
divElement = new CKEDITOR.dom.element( 'div', editor.document );
// Normalize the blocks in each group to a common parent.
for ( j = 0; j < blockGroups[ i ].length; j++ ) {
currentNode = blockGroups[ i ][ j ];
// Check if the currentNode has a parent before attempting to operate on it (https://dev.ckeditor.com/ticket/13585).
while ( currentNode.getParent() && !currentNode.getParent().equals( ancestor ) ) {
currentNode = currentNode.getParent();
}
// This could introduce some duplicated elements in array.
blockGroups[ i ][ j ] = currentNode;
}
// Wrapped blocks counting
for ( j = 0; j < blockGroups[ i ].length; j++ ) {
currentNode = blockGroups[ i ][ j ];
// Avoid DUP elements introduced by grouping.
if ( !( currentNode.getCustomData && currentNode.getCustomData( 'block_processed' ) ) ) {
currentNode.is && CKEDITOR.dom.element.setMarker( database, currentNode, 'block_processed', true );
// Establish new container, wrapping all elements in this group.
if ( !j ) {
divElement.insertBefore( currentNode );
}
divElement.append( currentNode );
}
}
CKEDITOR.dom.element.clearAllMarkers( database );
containers.push( divElement );
}
selection.selectBookmarks( bookmarks );
return containers;
}
// Divide a set of nodes to different groups by their path's blocklimit element.
// Note: the specified nodes should be in source order naturally, which mean they are supposed to producea by following class:
// * CKEDITOR.dom.range.Iterator
// * CKEDITOR.dom.domWalker
// @returns {Array[]} the grouped nodes
function groupByDivLimit( nodes ) {
var groups = [],
lastDivLimit = null,
block;
for ( var i = 0; i < nodes.length; i++ ) {
block = nodes[ i ];
var limit = getDivContainer( block );
if ( !limit.equals( lastDivLimit ) ) {
lastDivLimit = limit;
groups.push( [] );
}
// Sometimes we got nodes that are not inside the DOM, which causes error (https://dev.ckeditor.com/ticket/13585).
if ( block.getParent() ) {
groups[ groups.length - 1 ].push( block );
}
}
return groups;
}
// Synchronous field values to other impacted fields is required, e.g. div styles
// change should also alter inline-style text.
function commitInternally( targetFields ) {
var dialog = this.getDialog(),
element = dialog._element && dialog._element.clone() || new CKEDITOR.dom.element( 'div', editor.document );
// Commit this field and broadcast to target fields.
this.commit( element, true );
targetFields = [].concat( targetFields );
var length = targetFields.length,
field;
for ( var i = 0; i < length; i++ ) {
field = dialog.getContentElement.apply( dialog, targetFields[ i ].split( ':' ) );
field && field.setup && field.setup( element, true );
}
}
// Registered 'CKEDITOR.style' instances.
var styles = {};
// Hold a collection of created block container elements.
var containers = [];
// @type divDialog
return {
title: editor.lang.div.title,
minWidth: 400,
minHeight: 165,
contents: [ {
id: 'info',
label: editor.lang.common.generalTab,
title: editor.lang.common.generalTab,
elements: [ {
type: 'hbox',
widths: [ '50%', '50%' ],
children: [ {
id: 'elementStyle',
type: 'select',
style: 'width: 100%;',
label: editor.lang.div.styleSelectLabel,
'default': '',
// Options are loaded dynamically.
items: [
[ editor.lang.common.notSet, '' ]
],
onChange: function() {
commitInternally.call( this, [ 'info:elementStyle', 'info:class', 'advanced:dir', 'advanced:style' ] );
},
setup: function( element ) {
for ( var name in styles )
styles[ name ].checkElementRemovable( element, true, editor ) && this.setValue( name, 1 );
},
commit: function( element ) {
var styleName;
if ( ( styleName = this.getValue() ) ) {
var style = styles[ styleName ];
style.applyToObject( element, editor );
}
else {
element.removeAttribute( 'style' );
}
}
},
{
id: 'class',
type: 'text',
requiredContent: 'div(cke-xyz)', // Random text like 'xyz' will check if all are allowed.
label: editor.lang.common.cssClass,
'default': ''
} ]
} ]
},
{
id: 'advanced',
label: editor.lang.common.advancedTab,
title: editor.lang.common.advancedTab,
elements: [ {
type: 'vbox',
padding: 1,
children: [ {
type: 'hbox',
widths: [ '50%', '50%' ],
children: [ {
type: 'text',
id: 'id',
requiredContent: 'div[id]',
label: editor.lang.common.id,
'default': ''
},
{
type: 'text',
id: 'lang',
requiredContent: 'div[lang]',
label: editor.lang.common.langCode,
'default': ''
} ]
},
{
type: 'hbox',
children: [ {
type: 'text',
id: 'style',
requiredContent: 'div{cke-xyz}', // Random text like 'xyz' will check if all are allowed.
style: 'width: 100%;',
label: editor.lang.common.cssStyle,
'default': '',
commit: function( element ) {
element.setAttribute( 'style', this.getValue() );
}
} ]
},
{
type: 'hbox',
children: [ {
type: 'text',
id: 'title',
requiredContent: 'div[title]',
style: 'width: 100%;',
label: editor.lang.common.advisoryTitle,
'default': ''
} ]
},
{
type: 'select',
id: 'dir',
requiredContent: 'div[dir]',
style: 'width: 100%;',
label: editor.lang.common.langDir,
'default': '',
items: [
[ editor.lang.common.notSet, '' ],
[ editor.lang.common.langDirLtr, 'ltr' ],
[ editor.lang.common.langDirRtl, 'rtl' ]
]
} ] }
]
} ],
onLoad: function() {
setupFields.call( this );
// Preparing for the 'elementStyle' field.
var dialog = this,
stylesField = this.getContentElement( 'info', 'elementStyle' );
// Reuse the 'stylescombo' plugin's styles definition.
editor.getStylesSet( function( stylesDefinitions ) {
var styleName, style;
if ( stylesDefinitions ) {
// Digg only those styles that apply to 'div'.
for ( var i = 0; i < stylesDefinitions.length; i++ ) {
var styleDefinition = stylesDefinitions[ i ];
if ( styleDefinition.element && styleDefinition.element == 'div' ) {
styleName = styleDefinition.name;
styles[ styleName ] = style = new CKEDITOR.style( styleDefinition );
if ( editor.filter.check( style ) ) {
// Populate the styles field options with style name.
stylesField.items.push( [ styleName, styleName ] );
stylesField.add( styleName, styleName );
}
}
}
}
// We should disable the content element
// it if no options are available at all.
stylesField[ stylesField.items.length > 1 ? 'enable' : 'disable' ]();
// Now setup the field value manually if dialog was opened on element. (https://dev.ckeditor.com/ticket/9689)
setTimeout( function() {
dialog._element && stylesField.setup( dialog._element );
}, 0 );
} );
},
onShow: function() {
// Whether always create new container regardless of existed
// ones.
if ( command == 'editdiv' ) {
// Try to discover the containers that already existed in
// ranges
// update dialog field values
this.setupContent( this._element = CKEDITOR.plugins.div.getSurroundDiv( editor ) );
}
},
onOk: function() {
if ( command == 'editdiv' )
containers = [ this._element ];
else
containers = createDiv( editor, true );
// Update elements attributes
var size = containers.length;
for ( var i = 0; i < size; i++ ) {
this.commitContent( containers[ i ] );
// Remove empty 'style' attribute.
!containers[ i ].getAttribute( 'style' ) && containers[ i ].removeAttribute( 'style' );
}
this.hide();
},
onHide: function() {
// Remove style only when editing existing DIV. (https://dev.ckeditor.com/ticket/6315)
if ( command == 'editdiv' )
this._element.removeCustomData( 'elementStyle' );
delete this._element;
}
};
}
CKEDITOR.dialog.add( 'creatediv', function( editor ) {
return divDialog( editor, 'creatediv' );
} );
CKEDITOR.dialog.add( 'editdiv', function( editor ) {
return divDialog( editor, 'editdiv' );
} );
} )();
/**
* Whether to wrap the entire table instead of individual cells when creating a `<div>` in a table cell.
*
* config.div_wrapTable = true;
*
* @cfg {Boolean} [div_wrapTable=false]
* @member CKEDITOR.config
*/
|
if ( true ) import { a as x } from "./abc";
if ( false ) import { b as y } from "./abc";
if ( true ) export function outer() {
import { a as ay } from "./abc";
import { b as bee } from "./abc";
import { c as see } from "./abc";
return [ ay, bee, see ];
}
if ( false ) export { x } from "./foo";
x; // Stay as x
y; // Stay as y
|
/**
@class
<p>Efficient querying of documents containing shapes indexed using the
geo_shape type.</p>
<p>Much like the geo_shape type, the geo_shape query uses a grid square
representation of the query shape to find those documents which have shapes
that relate to the query shape in a specified way. In order to do this, the
field being queried must be of geo_shape type. The query will use the same
PrefixTree configuration as defined for the field.</p>
@name ejs.GeoShapeQuery
@desc
A Query to find documents with a geo_shapes matching a specific shape.
*/
ejs.GeoShapeQuery = function (field) {
/**
The internal query object. <code>Use _self()</code>
@member ejs.GeoShapeQuery
@property {Object} GeoShapeQuery
*/
var query = {
geo_shape: {}
};
query.geo_shape[field] = {};
return {
/**
Sets the field to query against.
@member ejs.GeoShapeQuery
@param {String} f A valid field name.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
field: function (f) {
var oldValue = query.geo_shape[field];
if (f == null) {
return field;
}
delete query.geo_shape[field];
field = f;
query.geo_shape[f] = oldValue;
return this;
},
/**
Sets the shape
@member ejs.GeoShapeQuery
@param {String} shape A valid <code>Shape</code> object.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
shape: function (shape) {
if (shape == null) {
return query.geo_shape[field].shape;
}
if (query.geo_shape[field].indexed_shape != null) {
delete query.geo_shape[field].indexed_shape;
}
query.geo_shape[field].shape = shape._self();
return this;
},
/**
Sets the indexed shape. Use this if you already have shape definitions
already indexed.
@member ejs.GeoShapeQuery
@param {String} indexedShape A valid <code>IndexedShape</code> object.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
indexedShape: function (indexedShape) {
if (indexedShape == null) {
return query.geo_shape[field].indexed_shape;
}
if (query.geo_shape[field].shape != null) {
delete query.geo_shape[field].shape;
}
query.geo_shape[field].indexed_shape = indexedShape._self();
return this;
},
/**
Sets the shape relation type. A relationship between a Query Shape
and indexed Shapes that will be used to determine if a Document
should be matched or not. Valid values are: intersects, disjoint,
and within.
@member ejs.GeoShapeQuery
@param {String} indexedShape A valid <code>IndexedShape</code> object.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
relation: function (relation) {
if (relation == null) {
return query.geo_shape[field].relation;
}
relation = relation.toLowerCase();
if (relation === 'intersects' || relation === 'disjoint' || relation === 'within') {
query.geo_shape[field].relation = relation;
}
return this;
},
/**
<p>Sets the spatial strategy.</p>
<p>Valid values are:</p>
<dl>
<dd><code>recursive</code> - default, recursively traverse nodes in
the spatial prefix tree. This strategy has support for
searching non-point shapes.</dd>
<dd><code>term</code> - uses a large TermsFilter on each node
in the spatial prefix tree. It only supports the search of
indexed Point shapes.</dd>
</dl>
<p>This is an advanced setting, use with care.</p>
@since elasticsearch 0.90
@member ejs.GeoShapeQuery
@param {String} strategy The strategy as a string.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
strategy: function (strategy) {
if (strategy == null) {
return query.geo_shape[field].strategy;
}
strategy = strategy.toLowerCase();
if (strategy === 'recursive' || strategy === 'term') {
query.geo_shape[field].strategy = strategy;
}
return this;
},
/**
Sets the boost value for documents matching the <code>Query</code>.
@member ejs.GeoShapeQuery
@param {Number} boost A positive <code>double</code> value.
@returns {Object} returns <code>this</code> so that calls can be chained.
*/
boost: function (boost) {
if (boost == null) {
return query.geo_shape[field].boost;
}
query.geo_shape[field].boost = boost;
return this;
},
/**
Allows you to serialize this object into a JSON encoded string.
@member ejs.GeoShapeQuery
@returns {String} returns this object as a serialized JSON string.
*/
toString: function () {
return JSON.stringify(query);
},
/**
The type of ejs object. For internal use only.
@member ejs.GeoShapeQuery
@returns {String} the type of object
*/
_type: function () {
return 'query';
},
/**
Retrieves the internal <code>query</code> object. This is typically used by
internal API functions so use with caution.
@member ejs.GeoShapeQuery
@returns {String} returns this object's internal <code>query</code> property.
*/
_self: function () {
return query;
}
};
};
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions/auth'
import './login.css'
import { Container, Grid, Segment, Input, Header, Button, Icon } from 'semantic-ui-react';
const styles = {
loginForm: {
height: '100%'
},
segment: {
maxWidth: '450px'
},
container: {
marginTop: '10px'
},
}
class Login extends Component {
constructor(props) {
super(props)
this.state = {
username: "",
password: "",
isLoading: false
}
}
handleUserChange(e) {
this.setState({
user: e.target.value
});
}
handlePasswordChange(e) {
this.setState({
password: e.target.value
});
}
toggleLoading() {
this.setState({
isLoading: !this.state.isLoading
});
}
handleSubmit() {
this.toggleLoading();
this.props.login(this.state.user, this.state.password,(err,data)=>{
if(err) {
this.toggleLoading();
alert(data.msg);
} else {
this.props.history.push("/dashboard");
}
});
}
handleKeyPress = (e) =>
{
console.log('Key pressed.');
if(e.key === 'Enter')
{
this.handleSubmit();
}
}
componentWillMount() {
document.title = "Login";
}
renderLogin() {
return (
<div style={styles.loginForm}>
<Grid textAlign='center' style={{ height: '100%' }} verticalAlign='middle'>
<Grid.Column style={styles.segment}>
<Segment raised onKeyPress={this.handleKeyPress}>
<Header as='h2' color='teal' textAlign='center'>
Log-in to your account
</Header>
<Input
onChange={this.handleUserChange.bind(this)}
value={this.state.user}
fluid
icon='user'
iconPosition='left'
placeholder='Enter your username' />
<br />
<Input
onChange={this.handlePasswordChange.bind(this)}
value={this.state.password}
fluid
type='password'
icon='lock'
iconPosition='left'
placeholder='Enter your password' />
<Container textAlign='right' style={styles.container}>
<Button animated loading={this.state.isLoading} color='teal' onClick={this.handleSubmit.bind(this)}>
<Button.Content visible>Login</Button.Content>
<Button.Content hidden>
<Icon name='right arrow'/>
</Button.Content>
</Button>
</Container>
</Segment>
</Grid.Column>
</Grid>
</div>
)
}
render() {
return (
<div style={styles.loginForm}>
{this.renderLogin()}
</div>
)
}
}
function mapStateToProps({ auth }) {
return { auth }
}
export default connect(mapStateToProps, actions)(Login);
|
const jsonfile = require('jsonfile')
const stats = require("stats-lite");
const commandLineArgs = require("command-line-args");
const mqtt = require("mqtt");
const stringify = require("csv-stringify");
const fs = require("fs");
const client = mqtt.connect("mqtt://127.0.0.1:1883");
const options = commandLineArgs([
{ name: "sub_qos", type: Number },
{ name: "file", type: String, multiple: false, defaultOption: true }
]);
if (!options.file || options.sub_qos === undefined) {
console.error("You must specify --sub_qos and provide file for dump!");
process.exit(1)
}
let devices = {};
client.on("connect", () => {
client.subscribe("qos_testing/#", {
qos: options.sub_qos
});
});
client.on("message", (topic, message) => {
const device = topic.split("/")[1];
const i = parseInt(message.toString());
const ts = process.hrtime();
if(!devices[device]) {
devices[device] = {
last_i: i,
last_timestamp: ts,
messages: [ [Date.now(), i] ],
intervals: [],
seen: [],
duplicates: [],
out_of_order: []
}
} else {
let diff = process.hrtime(devices[device].last_timestamp);
diff = diff[0]*1000 + diff[1]/1000000.0;
devices[device].intervals.push(diff);
if (devices[device].seen.indexOf(i) > -1) {
devices[device].duplicates.push([Date.now(), i]);
} else if (devices[device].last_i >= i) {
devices[device].out_of_order.push([Date.now(), i]);
}
devices[device].last_i = i;
devices[device].seen.push(i);
devices[device].last_timestamp = ts;
devices[device].messages.push([Date.now(), i]);
}
});
setInterval(function() {
Object.keys(devices).forEach((device) => {
let d = devices[device];
let last_1k = d.intervals.slice(Math.max(0, d.intervals.length - 1000));
console.log("=====");
console.log("Status for device #" + device + " (stats for last 1k msgs)");
console.log("Msgs rcvd:", d.messages.length);
console.log("i:", d.last_i);
console.log("Mean interval:", stats.mean(last_1k));
console.log("stddev interval:", stats.stdev(last_1k));
console.log("95th percentile interval:", stats.percentile(last_1k, 0.95));
console.log("max interval:", Math.max(...last_1k));
console.log("number of duplicates:", d.duplicates.length);
console.log("number of out_of_order:", d.out_of_order.length);
});
}, 2000);
function dump(reason, add) {
console.log("Dumping state to " + options.file + ".json and " + options.file + "_intervals.csv");
jsonfile.writeFileSync(options.file + ".json", devices);
stringify([].concat.apply([], Object.keys(devices).map((device) => {
return devices[device].intervals.map((int) => {
return [device, int];
});
})), (err, out) => {
console.log(err);
fs.writeFileSync(options.file + "_intervals.csv", out);
console.log("Try running octave-cli --eval=\"hist(csvread('"+options.file+"_intervals.csv')(:,2), 25)\" --persist");
if(reason) {
console.log("Quiting because:", reason);
if(reason == "EXCEPTION") {
console.log(add);
}
process.exit();
}
});
}
process.on("SIGINT", dump.bind(null, "SIGINT"));
process.on("SIGHUP", dump.bind(null, false));
process.on("uncaughtException", dump.bind(null, "EXCEPTION"));
|
version https://git-lfs.github.com/spec/v1
oid sha256:7532f5b4891e60d75d6a1d91f80921a3ad8b96ba88a746f05948fc6c6f5a9772
size 137987
|
let spec = {
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.",
"version": "1.0.0",
"title": "Swagger Petstore",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"email": "apiteam@swagger.io"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"tags": [
{
"name": "pet",
"description": "Everything about your Pets",
"externalDocs": {
"description": "Find out more",
"url": "http://swagger.io"
}
},
{
"name": "store",
"description": "Access to Petstore orders"
},
{
"name": "user",
"description": "Operations about user",
"externalDocs": {
"description": "Find out more about our store",
"url": "http://swagger.io"
}
}
],
"schemes": [
"http"
],
"paths": {
"/pet": {
"post": {
"tags": [
"pet"
],
"summary": "Add a new pet to the store",
"description": "",
"operationId": "addPet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": true,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"put": {
"tags": [
"pet"
],
"summary": "Update an existing pet",
"description": "",
"operationId": "updatePet",
"consumes": [
"application/json",
"application/xml"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": true,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
"responses": {
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Pet not found"
},
"405": {
"description": "Validation exception"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByStatus": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by status",
"description": "Multiple status values can be provided with comma seperated strings",
"operationId": "findPetsByStatus",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "status",
"in": "query",
"description": "Status values that need to be considered for filter",
"required": true,
"type": "array",
"items": {
"type": "string",
"enum": [
"available",
"pending",
"sold"
],
"default": "available"
},
"collectionFormat": "csv"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid status value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/findByTags": {
"get": {
"tags": [
"pet"
],
"summary": "Finds Pets by tags",
"description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.",
"operationId": "findPetsByTags",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "tags",
"in": "query",
"description": "Tags to filter by",
"required": true,
"type": "array",
"items": {
"type": "string"
},
"collectionFormat": "csv"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/Pet"
}
}
},
"400": {
"description": "Invalid tag value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}": {
"get": {
"tags": [
"pet"
],
"summary": "Find pet by ID",
"description": "Returns a single pet",
"operationId": "getPetById",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to return",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Pet"
}
},
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Pet not found"
}
},
"security": [
{
"api_key": []
}
]
},
"post": {
"tags": [
"pet"
],
"summary": "Updates a pet in the store with form data",
"description": "",
"operationId": "updatePetWithForm",
"consumes": [
"application/x-www-form-urlencoded"
],
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet that needs to be updated",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "name",
"in": "formData",
"description": "Updated name of the pet",
"required": false,
"type": "string"
},
{
"name": "status",
"in": "formData",
"description": "Updated status of the pet",
"required": false,
"type": "string"
}
],
"responses": {
"405": {
"description": "Invalid input"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
},
"delete": {
"tags": [
"pet"
],
"summary": "Deletes a pet",
"description": "",
"operationId": "deletePet",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "api_key",
"in": "header",
"required": false,
"type": "string"
},
{
"name": "petId",
"in": "path",
"description": "Pet id to delete",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"400": {
"description": "Invalid pet value"
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/pet/{petId}/uploadImage": {
"post": {
"tags": [
"pet"
],
"summary": "uploads an image",
"description": "",
"operationId": "uploadFile",
"consumes": [
"multipart/form-data"
],
"produces": [
"application/json"
],
"parameters": [
{
"name": "petId",
"in": "path",
"description": "ID of pet to update",
"required": true,
"type": "integer",
"format": "int64"
},
{
"name": "additionalMetadata",
"in": "formData",
"description": "Additional data to pass to server",
"required": false,
"type": "string"
},
{
"name": "file",
"in": "formData",
"description": "file to upload",
"required": false,
"type": "file"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/ApiResponse"
}
}
},
"security": [
{
"petstore_auth": [
"write:pets",
"read:pets"
]
}
]
}
},
"/store/inventory": {
"get": {
"tags": [
"store"
],
"summary": "Returns pet inventories by status",
"description": "Returns a map of status codes to quantities",
"operationId": "getInventory",
"produces": [
"application/json"
],
"parameters": [],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "object",
"additionalProperties": {
"type": "integer",
"format": "int32"
}
}
}
},
"security": [
{
"api_key": []
}
]
}
},
"/store/order": {
"post": {
"tags": [
"store"
],
"summary": "Place an order for a pet",
"description": "",
"operationId": "placeOrder",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "order placed for purchasing the pet",
"required": true,
"schema": {
"$ref": "#/definitions/Order"
}
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid Order"
}
}
}
},
"/store/order/{orderId}": {
"get": {
"tags": [
"store"
],
"summary": "Find purchase order by ID",
"description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions",
"operationId": "getOrderById",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of pet that needs to be fetched",
"required": true,
"type": "integer",
"maximum": 5.0,
"minimum": 1.0,
"format": "int64"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/Order"
}
},
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Order not found"
}
}
},
"delete": {
"tags": [
"store"
],
"summary": "Delete purchase order by ID",
"description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",
"operationId": "deleteOrder",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "orderId",
"in": "path",
"description": "ID of the order that needs to be deleted",
"required": true,
"type": "string",
"minimum": 1.0
}
],
"responses": {
"400": {
"description": "Invalid ID supplied"
},
"404": {
"description": "Order not found"
}
}
}
},
"/user": {
"post": {
"tags": [
"user"
],
"summary": "Create user",
"description": "This can only be done by the logged in user.",
"operationId": "createUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "Created user object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithArray": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithArrayInput",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/createWithList": {
"post": {
"tags": [
"user"
],
"summary": "Creates list of users with given input array",
"description": "",
"operationId": "createUsersWithListInput",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"in": "body",
"name": "body",
"description": "List of user object",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/User"
}
}
}
],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/login": {
"get": {
"tags": [
"user"
],
"summary": "Logs user into the system",
"description": "",
"operationId": "loginUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "query",
"description": "The user name for login",
"required": true,
"type": "string"
},
{
"name": "password",
"in": "query",
"description": "The password for login in clear text",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"type": "string"
},
"headers": {
"X-Rate-Limit": {
"type": "integer",
"format": "int32",
"description": "calls per hour allowed by the user"
},
"X-Expires-After": {
"type": "string",
"format": "date-time",
"description": "date in UTC when toekn expires"
}
}
},
"400": {
"description": "Invalid username/password supplied"
}
}
}
},
"/user/logout": {
"get": {
"tags": [
"user"
],
"summary": "Logs out current logged in user session",
"description": "",
"operationId": "logoutUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [],
"responses": {
"default": {
"description": "successful operation"
}
}
}
},
"/user/{username}": {
"get": {
"tags": [
"user"
],
"summary": "Get user by user name",
"description": "",
"operationId": "getUserByName",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be fetched. Use user1 for testing. ",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "successful operation",
"schema": {
"$ref": "#/definitions/User"
}
},
"400": {
"description": "Invalid username supplied"
},
"404": {
"description": "User not found"
}
}
},
"put": {
"tags": [
"user"
],
"summary": "Updated user",
"description": "This can only be done by the logged in user.",
"operationId": "updateUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "name that need to be deleted",
"required": true,
"type": "string"
},
{
"in": "body",
"name": "body",
"description": "Updated user object",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"400": {
"description": "Invalid user supplied"
},
"404": {
"description": "User not found"
}
}
},
"delete": {
"tags": [
"user"
],
"summary": "Delete user",
"description": "This can only be done by the logged in user.",
"operationId": "deleteUser",
"produces": [
"application/xml",
"application/json"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "The name that needs to be deleted",
"required": true,
"type": "string"
}
],
"responses": {
"400": {
"description": "Invalid username supplied"
},
"404": {
"description": "User not found"
}
}
}
}
},
"securityDefinitions": {
"petstore_auth": {
"type": "oauth2",
"authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog",
"flow": "implicit",
"scopes": {
"write:pets": "modify pets in your account",
"read:pets": "read your pets"
}
},
"api_key": {
"type": "apiKey",
"name": "api_key",
"in": "header"
}
},
"definitions": {
"Order": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"petId": {
"type": "integer",
"format": "int64"
},
"quantity": {
"type": "integer",
"format": "int32"
},
"shipDate": {
"type": "string",
"format": "date-time"
},
"status": {
"type": "string",
"description": "Order Status",
"enum": [
"placed",
"approved",
"delivered"
]
},
"complete": {
"type": "boolean",
"default": false
}
},
"xml": {
"name": "Order"
}
},
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"username": {
"type": "string"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"email": {
"type": "string"
},
"password": {
"type": "string"
},
"phone": {
"type": "string"
},
"userStatus": {
"type": "integer",
"format": "int32",
"description": "User Status"
}
},
"xml": {
"name": "User"
}
},
"Category": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Category"
}
},
"Tag": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
}
},
"xml": {
"name": "Tag"
}
},
"Pet": {
"type": "object",
"required": [
"name",
"photoUrls"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"category": {
"$ref": "#/definitions/Category"
},
"name": {
"type": "string",
"example": "doggie"
},
"photoUrls": {
"type": "array",
"xml": {
"name": "photoUrl",
"wrapped": true
},
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"xml": {
"name": "tag",
"wrapped": true
},
"items": {
"$ref": "#/definitions/Tag"
}
},
"status": {
"type": "string",
"description": "pet status in the store",
"enum": [
"available",
"pending",
"sold"
]
}
},
"xml": {
"name": "Pet"
}
},
"ApiResponse": {
"type": "object",
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"type": {
"type": "string"
},
"message": {
"type": "string"
}
}
}
},
"externalDocs": {
"description": "Find out more about Swagger",
"url": "http://swagger.io"
}
};
export default spec;
|
import style from './style';
const s = Object.create(style);
s.root = {
fontFamily: 'helvetica, sans-serif',
fontWeight: '300',
fontSize: '16px',
letterSpacing: '0.025em',
padding: '3vh 0 12vh 0',
width: '500px',
// use responsive max-width to simulate padding/margin to allow
// space for vertical scroll bar without creating horizontal scroll bar
// (if there is padding, the window will scroll horizontally to show the padding)
maxWidth: 'calc(100vw - 40px)',
// center based on vw to prevent content jump when vertical scroll bar show/hide
// note: vw/vh include the width of scroll bars. Note that centering using margin auto
// or % (which doesn't include scroll bars, so changes when scroll bars shown) causes a page jump
position: 'relative',
left: '50vw',
WebkitTransform: 'translate(-50%, 0)',
MozTransform: 'translate(-50%, 0)',
msTransform: 'translate(-50%, 0)',
OTransform: 'translate(-50%, 0)',
transform: 'translate(-50%, 0)',
WebkitTextSizeAdjust: 'none',
MozTextSizeAdjust: 'none',
msTextSizeAdjust: 'none',
textSizeAdjust: 'none',
};
s.title = {
fontSize: '20px',
marginBottom: '0.5vh',
};
s.repoLink = {
fontSize: '14px',
};
s.breadcrumbs = {
margin: '3vh 0',
};
s.creditLine = {
color: '#A0A0A0',
fontSize: '14px',
marginTop: '50px',
};
s.App = {
textAlign: 'center',
backgroundColor: '#F7F0F0',
};
s.Appheader = {
backgroundColor: '#18A999',
height: 'auto',
padding: '20px',
color: '#484349',
};
s.button = {
backgroundColor: '#18a999',
borderRadius: '10px',
color: '#F7F0F0',
display: 'inline-block',
marginBottom: '5px',
padding: '10px 10px',
textDecoration: 'none',
};
s.Links = {
paddingTop: '20px',
};
s.Icons = {
paddingLeft: '5px',
paddingRight: '5px',
color: '#484349',
};
export default s;
|
'use strict';
module.exports = {
SET_COUNTRY: function(state, value) {
state.countryCode = value;
},
SET_PERIOD: function(state, value) {
state.period = value;
}
};
|
var app = angular.module('Zespol', []);
//Filtr umożliwiający wstawienie scope jako link url
app.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}]);
app.controller('MusicCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/music.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.mysrctest = "http://tolmax.type.pl/uploads/music/01.Rehab.mp3";
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
//Filtr zamieniajacy podłogi na spacje dla bezpieczenstwa bazy danych mtitle przechowuje nazwy z podłogami
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i].replace(/_/g, " ");
txt += c;
}
return txt;
};
});
/////////
app.controller('VideoCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/video.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
app.controller('PhotosCtrl', function($scope, $http){
$http.get("http://tolmax.type.pl/assets/php/photos.php")
.then(function (response) {$scope.names = response.data.records;});
$scope.myCategory = {
"Id rosnąco" : {wartosc : "id"},
"Id malejąco" : {wartosc : "-id"},
"Tytuł rosnąco" : {wartosc : "title"},
"Tytuł malejąco" : {wartosc : "-title"}
}
});
|
//VARIABLES
var currentCountries = [];
var lastbenchrmak = null;
var test = "test";
var measures;
var calculatedBenchmark = null;
var routeJson = null;
// UTILITY FUNCTIONS
// SELECTION
function selectedBenchmarkMenu(menu) {
if (menu == "cbenchmark")
return $('#cbenchmark').val();
if (menu == 'disabledbenchmark')
return $('#disabledbenchmark').val();
if (menu == 'tempbenchmark')
return $('#tempbenchmark').val();
}
function selectedBenchmark() {
if ($.isEmptyObject(selectedBenchmarkMenu("cbenchmark")))
return selectedBenchmarkMenu("disabledbenchmark");
else
return selectedBenchmarkMenu("cbenchmark");
}
function loading() {
$('#loading_button').button('loading')
disableInput();
}
function loaded() {
$('#loading_button').button('reset')
enableInput();
}
function customer() {
return $('#customers').val();
}
function country() {
return $('#country').val();
}
function day() {
return $('#day').val();
}
// INPUT
function disableInput() {
$("#day").multiselect('disable')
$("#country").multiselect('disable')
$("#customers").multiselect('disable')
$("#benchmarks").multiselect('disable')
$('.todisable').prop('disabled', true);
}
function enableInput() {
$("#day").multiselect('enable')
$("#country").multiselect('enable')
$("#customers").multiselect('enable')
$("#benchmarks").multiselect('enable')
$('.todisable').prop('disabled', false);
}
function initBenchmarkMenus() {
$("#benchmarks").multiselect('dataprovider', []);
}
// GRAPHS
function noPlot() {
$('#graph').highcharts({
title : {
text : 'No data in line chart'
},
series : [ {
type : 'line',
name : 'Random data',
data : []
} ],
lang : {},
/* Custom options */
noData : {
position : {},
attr : {},
style : {}
}
});
}
function plot(jdata, country, customer, graph, day, id, suffix) {
var suffix = "";
if (graph == 'ACDA' || graph == 'ACDV') {
suffix = " Seconds";
} else if (graph == 'Buy' || graph == 'Sell') {
suffix = " EUR Cent";
} else if (graph == 'ARSV' || graph == 'GpPercent') {
suffix = "%;"
} else {
suffix = " Minutes";
}
var yserie = [];
$.each(jdata, function(day, graphs) {
var numbers = [];
for ( var g in graphs) {
$.each(graphs[g], function(route, measures) {
numbers = [];
for ( var m in measures) {
var me = measures[m];
numbers.push({
x : me["Hour"],
y : me[graph]
});
}
console.log(route);
yserie.push({
name : customer + " " + country + " day " + day,
data : numbers
});
});
}
yserie.sort(function(a, b) {
return a.x - b.x
});
});
$('#' + id).highcharts({
chart : {
borderColor : '#2f7ed8',
borderWidth : 3,
type : 'line'
},
title : {
text : 'Daily ' + id,
x : -20
},
subtitle : {
text : 'Source: Golem srl',
x : -20
},
xAxis : {
categories : [ '0', '1', '2' ]
},
yAxis : {
title : {
text : id
},
plotLines : [ {
value : 0,
width : 1,
color : '#808080'
} ]
},
plotOptions : {
line : {
dataLabels : {
enabled : false,
style : {
textShadow : '0 0 3px white, 0 0 3px white'
}
},
enableMouseTracking : true
}
},
tooltip : {
valueDecimals : 5,
valueSuffix : suffix
},
series : yserie,
noData : {
// Custom positioning/aligning options
position : {},
attr : {},
style : {}
}
});
};
function multiplot(jdata, country, customer, graph, day) {
plot(jdata, country, customer, graph, day, 'graph');
plot(jdata, country, customer, 'Minutes', day, 'minutes');
plot(jdata, country, customer, 'Revenue', day, 'revenue');
plot(jdata, country, customer, 'ACDV', day, 'acdv');
plot(jdata, country, customer, 'ARSV', day, 'arsv');
}
function benchmarkPlot(benchmark, graph, html) {
console.log(benchmark)
if (graph != "Multiplot") {
var chart = $('#' + html).highcharts();
var serie = [];
for ( var m in benchmark) {
var me = benchmark[m];
serie.push({
x : me["Hour"],
y : me[graph]
});
}
serie.sort(function(a, b) {
return a.x - b.x
});
chart.addSeries({
name : "benchmark",
data : serie
});
} else {
benchmarkPlot(benchmark, 'Minutes', 'minutes')
benchmarkPlot(benchmark, 'Revenue', 'revenue')
benchmarkPlot(benchmark, 'ACDV', 'acdv')
benchmarkPlot(benchmark, 'ARSV', 'arsv')
}
}
// CALLS
function bcall(country, customer) {
var servlet = "/benchmark";
var call = "?list=true&country=" + country + "&customer=" + customer;
var options_active = [];
var options_disabled = [];
initBenchmarkMenus();
console.log(call);
$.getJSON(servlet + call, function(json) {
setTimeout(function() {
$.each(json["active_opt"], function(index, name) {
options_active.push({
label : name,
value : name
});
});
$.each(json["disabled_opt"], function(index, name) {
options_disabled.push({
label : name,
value : name
});
});
console.log(options_active)
console.log(options_disabled)
$.each(json["toplot"], function(index, benchmark) {
benchmarkPlot(benchmark['measures'], $('#sampleTabs>.active')
.text(), 'graph');
});
$("#benchmarks").multiselect('dataprovider', options_active);
$("#benchmakr_scope").multiselect('dataprovider', options_active);
$("#benchmakr_scope").multiselect('dataprovider', options_disabled);
$("#benchmarks").multiselect('dataprovider', options_disabled);
}, 2000);
});
}
function gcall(country, customer, graph, day) {
var servlet = 'graph';
var call = '?day=' + day + '&country=' + country + '&customer=' + customer;
console.log(call);
if (measures != null) {
multiplot(measures, country, customer, graph, day);
} else {
$.getJSON(servlet + call, function(jdata) {
console.log(jdata);
if (jQuery.isEmptyObject(jdata) || jdata["message"] != null) {
console.log(jdata["message"]);
noPlot();
} else {
measures = jdata;
multiplot(jdata, country, customer, graph, day);
}
});
}
};
// BUTTONS
function changeButtonText(id, val) {
$('#' + id).html(val)
};
// ALERTING-CALLS
function markAsRead(id, button) {
$.ajax({
url : "/alert?id=" + id,
type : 'GET',
success : function() {
$(button).parent().parent().parent().remove();
}
});
};
// USERS-CALLS
function makeAdmin(id, button) {
$.ajax({
url : "/user?admin=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
};
function makeUser(id, button) {
$.ajax({
url : "/user?admin=false&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
};
function upgrade(id, button) {
$.ajax({
url : "/user?up=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
}
function downgrade(id, button) {
$.ajax({
url : "/user?down=true&id=" + id,
type : 'POST',
success : function() {
$(button).parent().parent().parent().remove();
setTimeout(function() {
location.reload();
}, 0001);
}
});
}
// ACTIONS
$(function() {
$('#savebutton').click(function() {
$.ajax({
url : "/sliding?customer=" + customer() + "&country=" + country(),
type : 'POST',
success : function() {
setTimeout(function() {
bcall(country(), customer());
}, 1000);
}
});
calculatedBenchmark = null;
});
$('#calcbutton').click(
function() {
var servlet = "/sliding"
var graph = $("ul#sampleTabs li.active").text();
var call = "?day=" + day() + "&customer=" + customer()
+ "&country=" + country();
console.log(call)
if (day() != null && customer() != null && country() != null) {
$.getJSON(servlet + call, function(json) {
if (!$.isEmptyObject(json)) {
calculatedBenchmark = json;
benchmarkPlot(calculatedBenchmark, $(
'#sampleTabs>.active').text(), 'graph');
} else {
console.log("No local benchmark");
alert("No local benchmark, press calculate");
}
});
}
});
});
// SELECT_MENU
$(function() {
$('#day').change(function() {
var days = [];
days.push($(this).val());
if (days == "0,1")
days = [ "0", "1" ];
if ($.isEmptyObject(day()))
return;
var call = '/routes?days=' + days
console.log(call)
loading();
$.getJSON(call, function(j) {
routeJson = j;
var options = [ {
label : "None Selected",
value : "none"
} ];
var optionsCheck = [];
$.each(days, function(index, d) {
for (var i = 0; i < j.length; i++) {
if (j[i].day == d) {
if ($.inArray(j[i].customer, optionsCheck) == -1) {
optionsCheck.push(j[i].customer);
options.push({
label : j[i].customer,
value : j[i].customer
})
}
}
}
});
setTimeout(function() {
$("#customers").multiselect('dataprovider', options)
loaded();
}, 005);
}
);
});
$('#customers')
.change(
function() {
loading();
if ($.isEmptyObject(customer()))
return;
if (routeJson == null) {
$.getJSON('/routes?days=' + $('#day').val(),
function(j) {
routeJson = j;
var options = '';
j.sort(function(ja, jb) {
return ja.order - jb.order
});
for (var i = 0; i < j.length; i++) {
options.push({
label : routeJson[i].country,
value : routeJson[i].country
})
}
});
} else {
var options = [];
var optionsUnique = [];
options.push({
label : "None Selected",
value : "none"
})
var days = [];
days.push($('#day').val());
if (days == "0,1")
days = [ "0", "1" ];
routeJson.sort(function(ja, jb) {
return ja.order - jb.order
});
for (var i = 0; i < routeJson.length; i++) {
$
.each(
days,
function(index, d) {
if (routeJson[i].day == d
&& routeJson[i].customer == customer()
&& (optionsUnique
.indexOf(routeJson[i].country) == -1)) {
currentCountries
.push(routeJson[i].country);
optionsUnique
.push(routeJson[i].country);
options
.push({
label : routeJson[i].country,
value : routeJson[i].country
})
}
});
}
}
setTimeout(function() {
$("#country").multiselect('dataprovider', options);
loaded();
}, 001);
});
$('#country').change(
function() {
loading();
measures = null;
if (country() != null && customer() != null && day() != null) {
setTimeout(function() {
gcall(country(), customer(), $('#sampleTabs>.active')
.text(), day());
bcall(country(), customer());
loaded();
}, 001);
}
});
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function(e) {
var action = $('#sampleTabs>.active').text();
if (action == "Benchmark") {
} else if (country() != null && customer() != null && day() != null) {
gcall(country(), customer(), action, day());
bcall(country(), customer());
}
});
$('#benchmarks').change(
function() {
measures = null;
var servlet = "/benchmark";
var benchmark = $(this).val();
var call = "?benchmark=" + benchmark + "&list=false";
console.log(call)
if (!$.isEmptyObject(benchmark)) {
$.getJSON(servlet + call, function(jsonB) {
console.log(jsonB)
buttonChange(jsonB, $(this).attr('ref'));
benchmarkPlot(jsonB["measures"], $(
'#sampleTabs>.active').text(), 'graph');
});
}
});
});
function buttonChange(jb, ref) {
if (jb["Alwaysplot"])
changeButtonText("alwaysbutton_" + ref, "Always");
else
changeButtonText("alwaysbutton", "OnDemand");
}
function editBenchmark() {
var active = $('#benchmark_active:checked').val();
var alwaysPlot = $('#always_plot:checked').val();
var id = $("#benchmakr_scope").val()
$.ajax({
url : "/benchmark/update?id=" + id + "&activation=" + active
+ "&alwaysplot=" + alwaysPlot,
type : 'POST',
success : function() {
bcall();
}
});
}
function deleteBenchmark() {
var id = $("#benchmakr_scope").val()
console.log(id);
$.ajax({
url : "/benchmark/delete?id=" + id,
type : 'POST',
success : function() {
console.log("deleted "+id)
}
});
}
|
'use strict';
/* istanbul ignore next */
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('hashes', {
h1: {
allowNull: false,
primaryKey: true,
type: Sequelize.STRING(128),
},
s2: {
allowNull: false,
type: Sequelize.STRING(64),
}
});
},
down: (queryInterface, Sequelize) => {
return queryInterface.dropTable('hashes');
},
};
|
import React from 'react';
import { assert } from 'chai';
import {
createMount,
createShallow,
describeConformance,
getClasses,
} from '@material-ui/core/test-utils';
import DialogTitle from './DialogTitle';
describe('<DialogTitle />', () => {
let mount;
let shallow;
let classes;
before(() => {
mount = createMount({ strict: true });
shallow = createShallow({ dive: true });
classes = getClasses(<DialogTitle>foo</DialogTitle>);
});
after(() => {
mount.cleanUp();
});
describeConformance(<DialogTitle>foo</DialogTitle>, () => ({
classes,
inheritComponent: 'div',
mount,
refInstanceof: window.HTMLDivElement,
skip: ['componentProp'],
}));
it('should render JSX children', () => {
const children = <p className="test">Hello</p>;
const wrapper = shallow(<DialogTitle disableTypography>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).equals(children), true);
});
it('should render string children as given string', () => {
const children = 'Hello';
const wrapper = shallow(<DialogTitle>{children}</DialogTitle>);
assert.strictEqual(wrapper.childAt(0).props().children, children);
});
});
|
var a = require('./a');
exports.value = 3;
|
export function threePointSecondDerivative(previous, current, next, uniformDistance) {
return (next - 2 * current + previous) / (uniformDistance * uniformDistance);
}
|
function encode (value) {
if (Object.prototype.toString.call(value) === '[object Date]') {
return '__q_date|' + value.toUTCString()
}
if (Object.prototype.toString.call(value) === '[object RegExp]') {
return '__q_expr|' + value.source
}
if (typeof value === 'number') {
return '__q_numb|' + value
}
if (typeof value === 'boolean') {
return '__q_bool|' + (value ? '1' : '0')
}
if (typeof value === 'string') {
return '__q_strn|' + value
}
if (typeof value === 'function') {
return '__q_strn|' + value.toString()
}
if (value === Object(value)) {
return '__q_objt|' + JSON.stringify(value)
}
// hmm, we don't know what to do with it,
// so just return it as is
return value
}
function decode (value) {
let type, length, source
length = value.length
if (length < 10) {
// then it wasn't encoded by us
return value
}
type = value.substr(0, 8)
source = value.substring(9)
switch (type) {
case '__q_date':
return new Date(source)
case '__q_expr':
return new RegExp(source)
case '__q_numb':
return Number(source)
case '__q_bool':
return Boolean(source === '1')
case '__q_strn':
return '' + source
case '__q_objt':
return JSON.parse(source)
default:
// hmm, we reached here, we don't know the type,
// then it means it wasn't encoded by us, so just
// return whatever value it is
return value
}
}
function generateFunctions (fn) {
return {
local: fn('local'),
session: fn('session')
}
}
let
hasStorageItem = generateFunctions(
(type) => (key) => window[type + 'Storage'].getItem(key) !== null
),
getStorageLength = generateFunctions(
(type) => () => window[type + 'Storage'].length
),
getStorageItem = generateFunctions((type) => {
let
hasFn = hasStorageItem[type],
storage = window[type + 'Storage']
return (key) => {
if (hasFn(key)) {
return decode(storage.getItem(key))
}
return null
}
}),
getStorageAtIndex = generateFunctions((type) => {
let
lengthFn = getStorageLength[type],
getItemFn = getStorageItem[type],
storage = window[type + 'Storage']
return (index) => {
if (index < lengthFn()) {
return getItemFn(storage.key(index))
}
}
}),
getAllStorageItems = generateFunctions((type) => {
let
lengthFn = getStorageLength[type],
storage = window[type + 'Storage'],
getItemFn = getStorageItem[type]
return () => {
let
result = {},
key,
length = lengthFn()
for (let i = 0; i < length; i++) {
key = storage.key(i)
result[key] = getItemFn(key)
}
return result
}
}),
setStorageItem = generateFunctions((type) => {
let storage = window[type + 'Storage']
return (key, value) => { storage.setItem(key, encode(value)) }
}),
removeStorageItem = generateFunctions((type) => {
let storage = window[type + 'Storage']
return (key) => { storage.removeItem(key) }
}),
clearStorage = generateFunctions((type) => {
let storage = window[type + 'Storage']
return () => { storage.clear() }
}),
storageIsEmpty = generateFunctions((type) => {
let getLengthFn = getStorageLength[type]
return () => getLengthFn() === 0
})
export var LocalStorage = {
has: hasStorageItem.local,
get: {
length: getStorageLength.local,
item: getStorageItem.local,
index: getStorageAtIndex.local,
all: getAllStorageItems.local
},
set: setStorageItem.local,
remove: removeStorageItem.local,
clear: clearStorage.local,
isEmpty: storageIsEmpty.local
}
export var SessionStorage = { // eslint-disable-line one-var
has: hasStorageItem.session,
get: {
length: getStorageLength.session,
item: getStorageItem.session,
index: getStorageAtIndex.session,
all: getAllStorageItems.session
},
set: setStorageItem.session,
remove: removeStorageItem.session,
clear: clearStorage.session,
isEmpty: storageIsEmpty.session
}
|
import { map } from './dsl';
var specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
function isArray(test) {
return Object.prototype.toString.call(test) === "[object Array]";
}
// A Segment represents a segment in the original route description.
// Each Segment type provides an `eachChar` and `regex` method.
//
// The `eachChar` method invokes the callback with one or more character
// specifications. A character specification consumes one or more input
// characters.
//
// The `regex` method returns a regex fragment for the segment. If the
// segment is a dynamic of star segment, the regex fragment also includes
// a capture.
//
// A character specification contains:
//
// * `validChars`: a String with a list of all valid characters, or
// * `invalidChars`: a String with a list of all invalid characters
// * `repeat`: true if the character specification can repeat
function StaticSegment(string) { this.string = string; }
StaticSegment.prototype = {
eachChar: function (callback) {
var string = this.string, ch;
for (var i = 0, l = string.length; i < l; i++) {
ch = string.charAt(i);
callback({ validChars: ch });
}
},
regex: function () {
return this.string.replace(escapeRegex, '\\$1');
},
generate: function () {
return this.string;
}
};
function DynamicSegment(name) { this.name = name; }
DynamicSegment.prototype = {
eachChar: function (callback) {
callback({ invalidChars: "/", repeat: true });
},
regex: function () {
return "([^/]+)";
},
generate: function (params) {
return params[this.name];
}
};
function StarSegment(name) { this.name = name; }
StarSegment.prototype = {
eachChar: function (callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function () {
return "(.+)";
},
generate: function (params) {
return params[this.name];
}
};
function EpsilonSegment() { }
EpsilonSegment.prototype = {
eachChar: function () { },
regex: function () { return ""; },
generate: function () { return ""; }
};
function parse(route, names, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.charAt(0) === "/") {
route = route.substr(1);
}
var segments = route.split("/"), results = [];
for (var i = 0, l = segments.length; i < l; i++) {
var segment = segments[i], match;
if (match = segment.match(/^:([^\/]+)$/)) {
results.push(new DynamicSegment(match[1]));
names.push(match[1]);
types.dynamics++;
}
else if (match = segment.match(/^\*([^\/]+)$/)) {
results.push(new StarSegment(match[1]));
names.push(match[1]);
types.stars++;
}
else if (segment === "") {
results.push(new EpsilonSegment());
}
else {
results.push(new StaticSegment(segment));
types.statics++;
}
}
return results;
}
// A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
function State(charSpec) {
this.charSpec = charSpec;
this.nextStates = [];
}
State.prototype = {
get: function (charSpec) {
var nextStates = this.nextStates;
for (var i = 0, l = nextStates.length; i < l; i++) {
var child = nextStates[i];
var isEqual = child.charSpec.validChars === charSpec.validChars;
isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars;
if (isEqual) {
return child;
}
}
},
put: function (charSpec) {
var state;
// If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(charSpec)) {
return state;
}
// Make a new state for the character spec
state = new State(charSpec);
// Insert the new state as a child of the current state
this.nextStates.push(state);
// If this character specification repeats, insert the new state as a child
// of itself. Note that this will not trigger an infinite loop because each
// transition during recognition consumes a character.
if (charSpec.repeat) {
state.nextStates.push(state);
}
// Return the new state
return state;
},
// Find a list of child states matching the next character
match: function (ch) {
// DEBUG "Processing `" + ch + "`:"
var nextStates = this.nextStates, child, charSpec, chars;
// DEBUG " " + debugState(this)
var returned = [];
for (var i = 0, l = nextStates.length; i < l; i++) {
child = nextStates[i];
charSpec = child.charSpec;
if (typeof (chars = charSpec.validChars) !== 'undefined') {
if (chars.indexOf(ch) !== -1) {
returned.push(child);
}
}
else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
if (chars.indexOf(ch) === -1) {
returned.push(child);
}
}
}
return returned;
}
};
/** IF DEBUG
function debug(log) {
console.log(log);
}
function debugState(state) {
return state.nextStates.map(function(n) {
if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; }
return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )";
}).join(", ")
}
END IF **/
// This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
// * prefers fewer stars to more, then
// * prefers using stars for less of the match to more, then
// * prefers fewer dynamic segments to more, then
// * prefers more static segments to more
function sortSolutions(states) {
return states.sort(function (a, b) {
if (a.types.stars !== b.types.stars) {
return a.types.stars - b.types.stars;
}
if (a.types.stars) {
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
if (a.types.dynamics !== b.types.dynamics) {
return b.types.dynamics - a.types.dynamics;
}
}
if (a.types.dynamics !== b.types.dynamics) {
return a.types.dynamics - b.types.dynamics;
}
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var oCreate = Object.create || function (proto) {
function F() { }
F.prototype = proto;
return new F();
};
function RecognizeResults(queryParams) {
this.queryParams = queryParams || {};
}
RecognizeResults.prototype = oCreate({
splice: Array.prototype.splice,
slice: Array.prototype.slice,
push: Array.prototype.push,
length: 0,
queryParams: null
});
function findHandler(state, path, queryParams) {
var handlers = state.handlers, regex = state.regex;
var captures = path.match(regex), currentCapture = 1;
var result = new RecognizeResults(queryParams);
for (var i = 0, l = handlers.length; i < l; i++) {
var handler = handlers[i], names = handler.names, params = {};
for (var j = 0, m = names.length; j < m; j++) {
params[names[j]] = captures[currentCapture++];
}
result.push({ handler: handler.handler, params: params, isDynamic: !!names.length });
}
return result;
}
function addSegment(currentState, segment) {
segment.eachChar(function (ch) {
var state;
currentState = currentState.put(ch);
});
return currentState;
}
// The main interface
export var RouteRecognizer = function () {
this.rootState = new State();
this.names = {};
};
RouteRecognizer.prototype = {
add: function (routes, options) {
var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name;
var isEmpty = true;
for (var i = 0, l = routes.length; i < l; i++) {
var route = routes[i], names = [];
var segments = parse(route.path, names, types);
allSegments = allSegments.concat(segments);
for (var j = 0, m = segments.length; j < m; j++) {
var segment = segments[j];
if (segment instanceof EpsilonSegment) {
continue;
}
isEmpty = false;
// Add a "/" for the new segment
currentState = currentState.put({ validChars: "/" });
regex += "/";
// Add a representation of the segment to the NFA and regex
currentState = addSegment(currentState, segment);
regex += segment.regex();
}
var handler = { handler: route.handler, names: names };
handlers.push(handler);
}
if (isEmpty) {
currentState = currentState.put({ validChars: "/" });
regex += "/";
}
currentState.handlers = handlers;
currentState.regex = new RegExp(regex + "$");
currentState.types = types;
if (name = options && options.as) {
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
},
handlersFor: function (name) {
var route = this.names[name], result = [];
if (!route) {
throw new Error("There is no route named " + name);
}
for (var i = 0, l = route.handlers.length; i < l; i++) {
result.push(route.handlers[i]);
}
return result;
},
hasRoute: function (name) {
return !!this.names[name];
},
generate: function (name, params) {
var route = this.names[name], output = "";
if (!route) {
throw new Error("There is no route named " + name);
}
var segments = route.segments;
for (var i = 0, l = segments.length; i < l; i++) {
var segment = segments[i];
if (segment instanceof EpsilonSegment) {
continue;
}
output += "/";
output += segment.generate(params);
}
if (output.charAt(0) !== '/') {
output = '/' + output;
}
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams, route.handlers);
}
return output;
},
generateQueryString: function (params, handlers) {
var pairs = [];
var keys = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.sort();
for (var i = 0, len = keys.length; i < len; i++) {
key = keys[i];
var value = params[key];
if (value === null) {
continue;
}
var pair = encodeURIComponent(key);
if (isArray(value)) {
for (var j = 0, l = value.length; j < l; j++) {
var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
}
else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) {
return '';
}
return "?" + pairs.join("&");
},
parseQueryString: function (queryString) {
var pairs = queryString.split("&"), queryParams = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('='), key = decodeURIComponent(pair[0]), keyLength = key.length, isArray = false, value;
if (pair.length === 1) {
value = 'true';
}
else {
//Handle arrays
if (keyLength > 2 && key.slice(keyLength - 2) === '[]') {
isArray = true;
key = key.slice(0, keyLength - 2);
if (!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? decodeURIComponent(pair[1]) : '';
}
if (isArray) {
queryParams[key].push(value);
}
else {
queryParams[key] = value;
}
}
return queryParams;
},
recognize: function (path) {
var states = [this.rootState], pathLen, i, l, queryStart, queryParams = {}, isSlashDropped = false;
queryStart = path.indexOf('?');
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
path = decodeURI(path);
// DEBUG GROUP path
if (path.charAt(0) !== "/") {
path = "/" + path;
}
pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
isSlashDropped = true;
}
for (i = 0, l = path.length; i < l; i++) {
states = recognizeChar(states, path.charAt(i));
if (!states.length) {
break;
}
}
// END DEBUG GROUP
var solutions = [];
for (i = 0, l = states.length; i < l; i++) {
if (states[i].handlers) {
solutions.push(states[i]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") {
path = path + "/";
}
return findHandler(state, path, queryParams);
}
}
};
RouteRecognizer.prototype.map = map;
|
import { themr } from 'react-css-themr';
import { PAGER } from '../identifiers.js';
import { pagerFactory } from './pager.js';
import Page from './page.js';
import theme from './theme.scss';
const Pager = pagerFactory(Page);
const ThemedPager = themr(PAGER, theme)(Pager);
export default ThemedPager;
export { ThemedPager as Pager };
|
import {LEAGUE_BY_SUMMONER_FULL, LEAGUE_BY_SUMMONER, LEAGUE_BY_TEAM_FULL, LEAGUE_BY_TEAM, CHALLENGER_LEAGUE} from '../Constants';
export const League = {
getBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER_FULL
});
},
getEntriesBySummonerId(summonerId, options) {
return Object.assign({}, options, {
id: summonerId,
uri: LEAGUE_BY_SUMMONER
});
},
getByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM_FULL
});
},
getEntriesByTeamId(teamId, options) {
return Object.assign({}, options, {
id: teamId,
uri: LEAGUE_BY_TEAM
});
},
getChallenger(type, options) {
return Object.assign({}, options, {
uri: CHALLENGER_LEAGUE,
query: {
type: type || 'RANKED_SOLO_5x5'
}
});
}
};
|
import { combineReducers } from 'redux';
import todos from './todos';
import filter from './filter';
import editing from './editing';
const rootReducer = combineReducers({
todos,
filter,
editing,
});
export default rootReducer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.