code stringlengths 2 1.05M |
|---|
var hello = require('./lib/sayHello')
hello()
|
var UrlBuilder = (function() {
'use strict';
var createSimpleUrl = function() {
var url = 'http://www.simple.com/';
return url;
}
var UrlBuilder = {
createSimpleUrl: createSimpleUrl
};
return UrlBuilder;
})();
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const uint64be = require("uint64be");
class SocketStream {
constructor(socket, buffer) {
this.bytesRead = 0;
this.hasInsufficientDataForReading = false;
this.buffer = buffer;
this.socket = socket;
}
WriteInt32(num) {
this.WriteInt64(num);
}
WriteInt64(num) {
let buffer = uint64be.encode(num);
this.socket.write(buffer);
}
WriteString(value) {
let stringBuffer = new Buffer(value, "utf-8");
this.WriteInt32(stringBuffer.length);
if (stringBuffer.length > 0) {
this.socket.write(stringBuffer);
}
}
Write(buffer) {
this.socket.write(buffer);
}
get Buffer() {
return this.buffer;
}
BeginTransaction() {
this.isInTransaction = true;
this.bytesRead = 0;
this.ClearErrors();
}
EndTransaction() {
this.isInTransaction = false;
this.buffer = this.buffer.slice(this.bytesRead);
this.bytesRead = 0;
this.ClearErrors();
}
RollBackTransaction() {
this.isInTransaction = false;
this.bytesRead = 0;
this.ClearErrors();
}
ClearErrors() {
this.hasInsufficientDataForReading = false;
}
get HasInsufficientDataForReading() {
return this.hasInsufficientDataForReading;
}
toString() {
return this.buffer.toString();
}
get Length() {
return this.buffer.length;
}
Append(additionalData) {
if (this.buffer.length === 0) {
this.buffer = additionalData;
return;
}
let newBuffer = new Buffer(this.buffer.length + additionalData.length);
this.buffer.copy(newBuffer);
additionalData.copy(newBuffer, this.buffer.length);
this.buffer = newBuffer;
}
isSufficientDataAvailable(length) {
if (this.buffer.length < (this.bytesRead + length)) {
this.hasInsufficientDataForReading = true;
}
return !this.hasInsufficientDataForReading;
}
ReadByte() {
if (!this.isSufficientDataAvailable(1)) {
return null;
}
let value = this.buffer.slice(this.bytesRead, this.bytesRead + 1)[0];
if (this.isInTransaction) {
this.bytesRead++;
}
else {
this.buffer = this.buffer.slice(1);
}
return value;
}
ReadString() {
let byteRead = this.ReadByte();
if (this.HasInsufficientDataForReading) {
return null;
}
if (byteRead < 0) {
throw new Error("IOException() - Socket.ReadString failed to read string type;");
}
let type = new Buffer([byteRead]).toString();
let isUnicode = false;
switch (type) {
case "N": // null string
return null;
case "U":
isUnicode = true;
break;
case "A": {
isUnicode = false;
break;
}
default: {
throw new Error("IOException(); Socket.ReadString failed to parse unknown string type " + type);
}
}
let len = this.ReadInt32();
if (this.HasInsufficientDataForReading) {
return null;
}
if (!this.isSufficientDataAvailable(len)) {
return null;
}
let stringBuffer = this.buffer.slice(this.bytesRead, this.bytesRead + len);
if (this.isInTransaction) {
this.bytesRead = this.bytesRead + len;
}
else {
this.buffer = this.buffer.slice(len);
}
let resp = isUnicode ? stringBuffer.toString("utf-8") : stringBuffer.toString();
return resp;
}
ReadInt32() {
return this.ReadInt64();
}
ReadInt64() {
if (!this.isSufficientDataAvailable(8)) {
return null;
}
let buf = this.buffer.slice(this.bytesRead, this.bytesRead + 8);
if (this.isInTransaction) {
this.bytesRead = this.bytesRead + 8;
}
else {
this.buffer = this.buffer.slice(8);
}
let returnValue = uint64be.decode(buf);
return returnValue;
}
ReadAsciiString(length) {
if (!this.isSufficientDataAvailable(length)) {
return null;
}
let stringBuffer = this.buffer.slice(this.bytesRead, this.bytesRead + length);
if (this.isInTransaction) {
this.bytesRead = this.bytesRead + length;
}
else {
this.buffer = this.buffer.slice(length);
}
return stringBuffer.toString("ascii");
}
readValueInTransaction(dataType) {
let startedTransaction = false;
if (!this.isInTransaction) {
this.BeginTransaction();
startedTransaction = true;
}
let data;
switch (dataType) {
case DataType.string: {
data = this.ReadString();
break;
}
case DataType.int32: {
data = this.ReadInt32();
break;
}
case DataType.int64: {
data = this.ReadInt64();
break;
}
}
if (this.HasInsufficientDataForReading) {
if (startedTransaction) {
this.RollBackTransaction();
}
return undefined;
}
if (startedTransaction) {
this.EndTransaction();
}
return data;
}
readStringInTransaction() {
return this.readValueInTransaction(DataType.string);
}
readInt32InTransaction() {
return this.readValueInTransaction(DataType.int32);
}
readInt64InTransaction() {
return this.readValueInTransaction(DataType.int64);
}
}
exports.SocketStream = SocketStream;
var DataType;
(function (DataType) {
DataType[DataType["string"] = 0] = "string";
DataType[DataType["int32"] = 1] = "int32";
DataType[DataType["int64"] = 2] = "int64";
})(DataType || (DataType = {}));
//# sourceMappingURL=SocketStream.js.map |
/**
* A selection model for {@link Ext.grid.Panel grids} which allows you to select data in
* a spreadsheet-like manner.
*
* Supported features:
*
* - Single / Range / Multiple individual row selection.
* - Single / Range cell selection.
* - Column selection by click selecting column headers.
* - Select / deselect all by clicking in the top-left, header.
* - Adds row number column to enable row selection.
* - Optionally you can enable row selection using checkboxes
*
* # Example usage
*
* @example
* var store = Ext.create('Ext.data.Store', {
* fields: ['name', 'email', 'phone'],
* data: [
* { name: 'Lisa', email: 'lisa@simpsons.com', phone: '555-111-1224' },
* { name: 'Bart', email: 'bart@simpsons.com', phone: '555-222-1234' },
* { name: 'Homer', email: 'homer@simpsons.com', phone: '555-222-1244' },
* { name: 'Marge', email: 'marge@simpsons.com', phone: '555-222-1254' }
* ]
* });
*
* Ext.create('Ext.grid.Panel', {
* title: 'Simpsons',
* store: store,
* width: 400,
* renderTo: Ext.getBody(),
* columns: [
* { text: 'Name', dataIndex: 'name' },
* { text: 'Email', dataIndex: 'email', flex: 1 },
* { text: 'Phone', dataIndex: 'phone' }
* ],
* selModel: {
* type: 'spreadsheet'
* }
* });
*
* @since 5.1.0
*/
Ext.define('Ext.grid.selection.SpreadsheetModel', {
extend: 'Ext.selection.Model',
requires: [
'Ext.grid.selection.Selection',
'Ext.grid.selection.Cells',
'Ext.grid.selection.Rows',
'Ext.grid.selection.Columns',
'Ext.grid.selection.SelectionExtender' // TODO: cmd-auto-dependency
],
alias: 'selection.spreadsheet',
isSpreadsheetModel: true,
config: {
/**
* @cfg {Boolean} [columnSelect=false]
* Set to `true` to enable selection of columns.
*
* **NOTE**: This will remove sorting on header click and instead provide column
* selection and deselection. Sorting is still available via column header menu.
*/
columnSelect: {
$value: false,
lazy: true
},
/**
* @cfg {Boolean} [cellSelect=true]
* Set to `true` to enable selection of individual cells or a single rectangular
* range of cells. This will provide cell range selection using click, and
* potentially drag to select a rectangular range. You can also use "SHIFT + arrow"
* key navigation to select a range of cells.
*/
cellSelect: {
$value: true,
lazy: true
},
/**
* @cfg {Boolean} [rowSelect=true]
* Set to `true` to enable selection of rows by clicking on a row number column.
*
* *Note*: This feature will add the row number as the first column.
*/
rowSelect: {
$value: true,
lazy: true
},
/**
* @cfg {Boolean} [dragSelect=true]
* Set to `true` to enables cell range selection by cell dragging.
*/
dragSelect: {
$value: true,
lazy: true
},
/**
* @cfg {Ext.grid.selection.Selection} [selected]
* Pass an instance of one of the subclasses of {@link Ext.grid.selection.Selection}.
*/
selected: null,
/**
* @cfg {String} extensible
* This configures whether this selection model is to implement a mouse based dragging gesture to extend a *contiguou*s selection.
*
* Note that if there are multiple, discontiguous selected rows or columns, selection extension is not available.
*
* If set, then the bottom right corner of the contiguous selection will display a drag handle. By dragging this, an extension area
* may be defined into which the selection is extended.
*
* Upon the end of the drag, the {@link Ext.panel.Table#event-beforeselectionextend beforeselectionextend} event will be fired though the
* encapsulating grid. Event handlers may manipulate the store data in any way.
*
* Possible values for this configuration are
*
* - `"x"` Only allow extending the block to the left or right.
* - `"y"` Only allow extending the block above or below.
* - `"xy"` Allow extebnding the block in both dimensions.
* - `"both"` Allow extebnding the block in both dimensions.
* - `true` Allow extebnding the block in both dimensions.
*/
extensible: {
$value: true,
lazy: true
}
},
/**
* @event selectionchange
* Fired *by the grid* after the selection changes. Return `false` to veto the selection extension.
* @param {Ext.grid.Panel} grid The grid whose selection has changed.
* @param {Ext.grid.selection.Selection} selection A subclass of
* {@link Ext.grid.selection.Selection} describing the new selection.
*/
/**
* @cfg {Boolean} checkboxSelect [checkboxSelect=false]
* Enables selection of the row via clicking on checkbox. Note: this feature will add
* new column at position specified by {@link #checkboxColumnIndex}.
*/
checkboxSelect: false,
/**
* @cfg {Number/String} [checkboxColumnIndex=0]
* The index at which to insert the checkbox column.
* Supported values are a numeric index, and the strings 'first' and 'last'. Only valid when set
* *before* render.
*/
checkboxColumnIndex: 0,
/**
* @cfg {Boolean} [showHeaderCheckbox=true]
* Configure as `false` to not display the header checkbox at the top of the checkbox column
* when {@link #checkboxSelect} is set.
*/
showHeaderCheckbox: true,
/**
* @cfg {Number/String} [checkboxHeaderWidth=24]
* Width of checkbox column.
*/
checkboxHeaderWidth: 24,
/**
* @cfg {Number/String} [rowNumbererHeaderWidth=46]
* Width of row numbering column.
*/
rowNumbererHeaderWidth: 46,
columnSelectCls: Ext.baseCSSPrefix + 'ssm-column-select',
rowNumbererHeaderCls: Ext.baseCSSPrefix + 'ssm-row-numberer-hd',
/**
* @private
*/
checkerOnCls: Ext.baseCSSPrefix + 'grid-hd-checker-on',
tdCls: Ext.baseCSSPrefix + 'grid-cell-special ' + Ext.baseCSSPrefix + 'grid-cell-row-checker',
/**
* @method getCount
* This method is not supported by SpreadsheetModel.
*
* To interrogate the selection use {@link #method-getSelected} which will return an instance of one
* of the three selection types, or `null` if no selection.
*
* The three selection types are:
*
* * {@link Ext.grid.selection.Rows}
* * {@link Ext.grid.selection.Columns}
* * {@link Ext.grid.selection.Cells}
*/
/**
* @method getSelectionMode
* This method is not supported by SpreadsheetModel.
*/
/**
* @method setSelectionMode
* This method is not supported by SpreadsheetModel.
*/
/**
* @method setLocked
* This method is not currently supported by SpreadsheetModel.
*/
/**
* @method isLocked
* This method is not currently supported by SpreadsheetModel.
*/
/**
* @method isRangeSelected
* This method is not supported by SpreadsheetModel.
*
* To interrogate the selection use {@link #getSelected} which will return an instance of one
* of the three selection types, or `null` if no selection.
*
* The three selection types are:
*
* * {@link Ext.grid.selection.Rows}
* * {@link Ext.grid.selection.Columns}
* * {@link Ext.grid.selection.Cells}
*/
/**
* @member Ext.panel.Table
* @event beforeselectionextend
*
* An event fired when an extension block is extended using a drag gesture. Only fired when the
* SpreadsheetSelectionModel is used and configured with the
* {@link Ext.grid.selection.SpreadsheetModel#extensible extensible} config.
*
* @param {Ext.panel.Table} grid The owning grid.
* @param {Ext.grid.selection.Selection} An object which encapsulates a contiguous selection block.
* @param {Object} extension An object describing the type and size of extension.
* @param {String} extension.type `"rows"` or `"columns"`
* @param {Ext.grid.CellContext} extension.start The start (top left) cell of the extension area.
* @param {Ext.grid.CellContext} extension.end The end (bottom right) cell of the extension area.
* @param {number} [extension.columns] The number of columns extended (-ve means on the left side).
* @param {number} [extension.rows] The number of rows extended (-ve means on the top side).
*/
/**
* @member Ext.panel.Table
* @event selectionextenderdrag
*
* An event fired when an extension block is dragged to encompass a new range. Only fired when the
* SpreadsheetSelectionModel is used and configured with the
* {@link Ext.grid.selection.SpreadsheetModel#extensible extensible} config.
*
* @param {Ext.panel.Table} grid The owning grid.
* @param {Ext.grid.selection.Selection} An object which encapsulates a contiguous selection block.
* @param {Object} extension An object describing the type and size of extension.
* @param {String} extension.type `"rows"` or `"columns"`
* @param {HTMLElement} extension.overCell The grid cell over which the mouse is being dragged.
* @param {Ext.grid.CellContext} extension.start The start (top left) cell of the extension area.
* @param {Ext.grid.CellContext} extension.end The end (bottom right) cell of the extension area.
* @param {number} [extension.columns] The number of columns extended (-ve means on the left side).
* @param {number} [extension.rows] The number of rows extended (-ve means on the top side).
*/
/**
* @private
*/
bindComponent: function(view) {
var me = this,
viewListeners,
lockedGrid;
if (me.view !== view) {
if (me.view) {
me.navigationModel = null;
Ext.destroy(me.viewListeners, me.navigationListeners);
}
me.view = view;
if (view) {
// We need to realize our lazy configs now that we have the view...
me.getCellSelect();
lockedGrid = view.ownerGrid.lockedGrid;
// If there is a locked grid, process it now
if (lockedGrid) {
me.hasLockedHeader = true;
me.onViewCreated(lockedGrid, lockedGrid.getView());
}
// Otherwise, get back to us when the view is fully created so that we can tweak its headerCt
else {
view.grid.on({
viewcreated: me.onViewCreated,
scope: me,
single: true
});
}
me.gridListeners = view.ownerGrid.on({
columnschanged: me.onColumnsChanged,
columnmove: me.onColumnMove,
scope: me,
destroyable: true
});
viewListeners = me.getViewListeners();
viewListeners.scope = me;
viewListeners.destroyable = true;
me.viewListeners = view.on(viewListeners);
me.navigationModel = view.getNavigationModel();
me.navigationListeners = me.navigationModel.on({
navigate: me.onNavigate,
scope: me,
destroyable: true
});
// Add class to add special cursor pointer to column headers
if (me.getColumnSelect()) {
view.ownerGrid.addCls(me.columnSelectCls);
}
me.updateHeaderState();
}
}
},
/**
* Retrieve a configuration to be used in a HeaderContainer.
* This should be used when checkboxSelect is set to false.
* @protected
*/
getCheckboxHeaderConfig: function() {
var me = this,
showCheck = me.showHeaderCheckbox !== false;
return {
ignoreExport: true,
isCheckerHd: showCheck,
text : ' ',
clickTargetName: 'el',
width: me.checkboxHeaderWidth,
sortable: false,
draggable: false,
resizable: false,
hideable: false,
menuDisabled: true,
dataIndex: '',
tdCls: me.tdCls,
cls: showCheck ? Ext.baseCSSPrefix + 'column-header-checkbox ' : '',
defaultRenderer: me.checkboxRenderer.bind(me),
editRenderer: ' ',
locked: me.hasLockedHeader
};
},
/**
* Generates the HTML to be rendered in the injected checkbox column for each row.
* Creates the standard checkbox markup by default; can be overridden to provide custom rendering.
* See {@link Ext.grid.column.Column#renderer} for description of allowed parameters.
* @private
*/
checkboxRenderer: function () {
return '<div class="' + Ext.baseCSSPrefix + 'grid-row-checker" role="presentation"> </div>';
},
/**
* @private
*/
onHeaderClick: function(headerCt, header, e) {
// Template method. See base class
var me = this,
sel = me.selected,
cm,
range,
i;
if (header === me.numbererColumn || header === me.checkColumn) {
e.stopEvent();
// Not all selected, select all
if (!sel || !sel.isAllSelected()) {
me.selectAll();
} else {
me.deselectAll();
}
me.updateHeaderState();
me.lastColumnSelected = null;
} else if (me.columnSelect) {
if (e.shiftKey && sel && sel.lastColumnSelected) {
sel.clear();
cm = this.view.ownerGrid.getVisibleColumnManager();
range = Ext.Array.sort([cm.indexOf(sel.lastColumnSelected), cm.indexOf(header)], Ext.Array.numericSortFn);
for (i = range[0]; i <= range[1]; i++) {
me.selectColumn(cm.getHeaderAtIndex(i), true);
}
} else {
if (me.isColumnSelected(header)) {
me.deselectColumn(header);
me.selected.lastColumnSelected = null;
} else {
me.selectColumn(header, e.ctrlKey);
me.selected.lastColumnSelected = header;
}
}
}
},
/**
* @private
*/
updateHeaderState: function() {
// check to see if all records are selected
var me = this,
store = me.view.dataSource,
views = me.views,
sel = me.selected,
checkHd = me.checkColumn,
cls = me.checkerOnCls,
isChecked = false,
storeCount;
if (store) {
storeCount = store.getCount();
isChecked = sel && sel.isRows && !store.isBufferedStore && storeCount > 0 && (storeCount === sel.getCount());
}
if (views && views.length) {
if (checkHd) {
if (isChecked) {
checkHd.addCls(cls);
} else {
checkHd.removeCls(cls);
}
}
}
},
onBindStore: function(store, oldStore, initial) {
if (!initial) {
this.onStoreRefresh();
}
},
/**
* Handles the grid's beforereconfigure event. Adds the checkbox header if the columns have been reconfigured.
* Also adds the row numberer.
* @param {Ext.panel.Table} grid
* @param {Ext.data.Store} store
* @param {Object[]} columns
* @private
*/
onBeforeReconfigure: function(grid, store, columns) {
var me = this,
checkboxColumnIndex = me.checkboxColumnIndex;
if (columns) {
Ext.suspendLayouts();
if (me.numbererColumn) {
me.numbererColumn.ownerCt.remove(me.numbererColumn, false);
columns.unshift(me.numbererColumn);
}
if (me.checkColumn) {
if (checkboxColumnIndex === 'first') {
checkboxColumnIndex = 0;
} else if (checkboxColumnIndex === 'last') {
checkboxColumnIndex = columns.length;
}
me.checkColumn.ownerCt.remove(me.checkColumn, false);
Ext.Array.insert(columns, checkboxColumnIndex, [me.checkColumn]);
}
Ext.resumeLayouts();
}
},
/**
* This is a helper method to create a cell context which encapsulates one cell in a grid view.
*
* It will contain the following properties:
* colIdx - column index
* rowIdx - row index
* column - {@link Ext.grid.column.Column Column} under which the cell is located.
* record - {@link Ext.data.Model} Record from which the cell derives its data.
* view - The view. If this selection model is for a locking grid, this will be the
* outermost view, the {@link Ext.grid.locking.View} which encapsulates the sub
* grids. Column indices are relative to the outermost view's visible column set.
*
* @param {Number} record Record for which to select the cell, or row index.
* @param {Number} column Grid column header, or column index.
* @return {Ext.grid.CellContext} A context object describing the cell. Note that the `rowidx` and `colIdx` properties are only valid
* at the time the context object is created. Column movement, sorting or filtering might changed where the cell is.
* @private
*/
getCellContext: function(record, column) {
return new Ext.grid.CellContext(this.view.ownerGrid.getView()).setPosition(record, column);
},
select: function(records, keepExisting, suppressEvent) {
// API docs are inherited
var me = this,
sel = me.selected,
view = me.view,
store = view.dataSource,
len,
i,
record,
changed = false;
// Ensure selection object is of the correct type
if (!sel || !sel.isRows || sel.view !== view) {
me.resetSelection(true);
sel = me.selected = new Ext.grid.selection.Rows(view);
} else if (!keepExisting) {
sel.clear();
}
if (!Ext.isArray(records)) {
records = [records];
}
len = records.length;
for (i = 0; i < len; i++) {
record = records[i];
if (typeof record === 'number') {
record = store.getAt(record);
}
if (!sel.contains(record)) {
sel.add(record);
changed = true;
}
}
if (changed) {
me.updateHeaderState();
if (!suppressEvent) {
me.fireSelectionChange();
}
}
},
deselect: function(records, suppressEvent) {
// API docs are inherited
var me = this,
sel = me.selected,
store = me.view.dataSource,
len,
i,
record,
changed = false;
if (sel && sel.isRows) {
if (!Ext.isArray(records)) {
records = [records];
}
len = records.length;
for (i = 0; i < len; i++) {
record = records[i];
if (typeof record === 'number') {
record = store.getAt(record);
}
changed = changed || sel.remove(record);
}
}
if (changed) {
me.updateHeaderState();
if (!suppressEvent) {
me.fireSelectionChange();
}
}
},
/**
* This method allows programmatic selection of the cell range.
*
* @example
* var store = Ext.create('Ext.data.Store', {
* fields : ['name', 'email', 'phone'],
* data : {
* items : [
* { name : 'Lisa', email : 'lisa@simpsons.com', phone : '555-111-1224' },
* { name : 'Bart', email : 'bart@simpsons.com', phone : '555-222-1234' },
* { name : 'Homer', email : 'homer@simpsons.com', phone : '555-222-1244' },
* { name : 'Marge', email : 'marge@simpsons.com', phone : '555-222-1254' }
* ]
* },
* proxy : {
* type : 'memory',
* reader : {
* type : 'json',
* root : 'items'
* }
* }
* });
*
* var grid = Ext.create('Ext.grid.Panel', {
* title : 'Simpsons',
* store : store,
* width : 400,
* renderTo : Ext.getBody(),
* columns : [
* columns: [
* { text: 'Name', dataIndex: 'name' },
* { text: 'Email', dataIndex: 'email', flex: 1 },
* { text: 'Phone', dataIndex: 'phone', width:120 },
* {
* text:'Combined', dataIndex: 'name', width : 300,
* renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
* console.log(arguments);
* return value + ' has email: ' + record.get('email');
* }
* }
* ],
* ],
* selType: 'spreadsheet'
* });
*
* var model = grid.getSelectionModel(); // get selection model
*
* // We will create range of 4 cells.
*
* // Now set the range and prevent rangeselect event from being fired.
* // We can use a simple array when we have no locked columns.
* model.selectCells([0, 0], [1, 1], true);
*
* @param rangeStart {Ext.grid.CellContext/Number[]} Range starting position. Can be either Cell context or a `[rowIndex, columnIndex]` numeric array.
*
* Note that when a numeric array is used in a locking grid, the column indices are relative to the outermost grid, encompassing locked *and* normal sides.
* @param rangeEnd {Ext.grid.CellContext/Number[]} Range end position. Can be either Cell context or a `[rowIndex, columnIndex]` numeric array.
*
* Note that when a numeric array is used in a locking grid, the column indices are relative to the outermost grid, encompassing locked *and* normal sides.
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
selectCells: function(rangeStart, rangeEnd, suppressEvent) {
var me = this,
view = me.view.ownerGrid.view,
sel;
rangeStart = rangeStart.isCellContext ? rangeStart.clone() : new Ext.grid.CellContext(view).setPosition(rangeStart);
rangeEnd = rangeEnd.isCellContext ? rangeEnd.clone() : new Ext.grid.CellContext(view).setPosition(rangeEnd);
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Cells(rangeStart.view);
sel.setRangeStart(rangeStart);
sel.setRangeEnd(rangeEnd);
if (!suppressEvent) {
me.fireSelectionChange();
}
},
/**
* Select all the data if possible.
*
* If {@link #rowSelect} is `true`, then all *records* will be selected.
*
* If {@link #cellSelect} is `true`, then all *rendered cells* will be selected.
*
* If {@link #columnSelect} is `true`, then all *columns* will be selected.
*
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
selectAll: function (suppressEvent) {
var me = this,
sel = me.selected,
doSelect,
view = me.view;
if (me.rowSelect) {
if (!sel || !sel.isRows) {
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Rows(view);
}
doSelect = true;
}
else if (me.cellSelect) {
if (!sel || !sel.isCells) {
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Cells(view);
}
doSelect = true;
}
else if (me.columnSelect) {
if (!sel || !sel.isColumns) {
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Columns(view);
}
doSelect = true;
}
if (doSelect) {
sel.selectAll();
me.updateHeaderState();
if (!suppressEvent) {
me.fireSelectionChange();
}
}
},
/**
* Clears the selection.
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
deselectAll: function (suppressEvent) {
var sel = this.selected;
if (sel && sel.getCount()) {
sel.clear();
if (!suppressEvent) {
this.fireSelectionChange();
}
}
},
/**
* Select one or more rows.
* @param rows {Ext.data.Model[]} Records to select.
* @param {Boolean} [keepSelection=false] Pass `true` to keep previous selection.
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
selectRows: function(rows, keepSelection, suppressEvent) {
var me = this,
sel = me.selected,
isSelectingRows = sel && sel.isRows,
len = rows.length,
i;
if (!keepSelection || !isSelectingRows) {
me.resetSelection(true);
}
if (!isSelectingRows) {
me.selected = sel = new Ext.grid.selection.Rows(me.view);
}
if (rows.isEntity) {
sel.add(rows);
} else for (i = 0; i < len; i++) {
sel.add(rows[i]);
}
if (!suppressEvent) {
me.fireSelectionChange();
}
},
isSelected: function(record) {
// API docs are inherited.
return this.isRowSelected(record);
},
/**
* Selects a column.
* @param {Ext.grid.column.Column} column Column to select.
* @param {Boolean} [keepSelection=false] Pass `true` to keep previous selection.
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
selectColumn: function(column, keepSelection, suppressEvent) {
var me = this,
selData = me.selected,
view = column.getView();
// Clear other selection types
if (!selData || !selData.isColumns || selData.view !== view.ownerGrid.view) {
me.resetSelection(true);
me.selected = selData = new Ext.grid.selection.Columns(view);
}
if (!selData.contains(column)) {
if (!keepSelection) {
selData.clear();
}
selData.add(column);
me.updateHeaderState();
if (!suppressEvent) {
me.fireSelectionChange();
}
}
},
/**
* Deselects a column.
* @param {Ext.grid.column.Column} column Column to deselect.
* @param {Boolean} [suppressEvent] Pass `true` to prevent firing the
* `{@link #selectionchange}` event.
*/
deselectColumn: function(column, suppressEvent) {
var me = this,
selData = me.getSelected();
if (selData && selData.isColumns && selData.contains(column)) {
selData.remove(column);
me.updateHeaderState();
if (!suppressEvent) {
me.fireSelectionChange();
}
}
},
getSelection: function() {
// API docs are inherited.
// Superclass returns array of selected records
var selData = this.selected;
if (selData && selData.isRows) {
return selData.getRecords();
}
return [];
},
destroy: function() {
var me = this,
scrollEls = me.scrollEls;
Ext.destroy(me.gridListeners, me.viewListeners, me.selected, me.navigationListeners, me.extensible);
if (scrollEls) {
Ext.dd.ScrollManager.unregister(scrollEls);
}
me.selected = me.gridListeners = me.viewListeners = me.selectionData = me.navigationListeners = me.scrollEls = null;
me.callParent();
},
//-------------------------------------------------------------------------
privates: {
/**
* @property {Object} axesConfigs
* Use when converting the extensible config into a SelectionExtender to create its `axes` config to specify which axes it may extend.
* @private
*/
axesConfigs: {
x: 1,
y: 2,
xy: 3,
both: 3,
"true": 3 // reserved word MUST be quoted when used an a property name
},
/**
* @return {Object}
* @private
*/
getViewListeners: function() {
return {
beforerefresh: this.onBeforeViewRefresh,
refresh: this.onViewRefresh,
keyup: {
element: 'el',
fn: this.onViewKeyUp,
scope: this
}
};
},
/**
* @private
*/
onViewKeyUp: function(e) {
var sel = this.selected;
// Released the shift key, terminate a keyboard based range selection
if (e.keyCode === e.SHIFT && sel && sel.isRows && sel.getRangeSize()) {
// Copy the drag range into the selected records collection
sel.addRange();
}
},
/**
* @private
*/
onColumnsChanged: function() {
var selData = this.selected,
rowRange,
colCount,
colIdx,
rowIdx,
view,
context,
selectionChanged;
// When columns have changed, we have to deselect *every* cell in the row range because we do not know where the
// columns have gone to.
if (selData) {
view = selData.view;
if (selData.isCells) {
context = new Ext.grid.CellContext(view);
rowRange = selData.getRowRange();
colCount = view.getVisibleColumnManager().getColumns().length;
for (rowIdx = rowRange[0]; rowIdx <= rowRange[1]; rowIdx++) {
context.setRow(rowIdx);
for (colIdx = 0; colIdx < colCount; colIdx++) {
context.setColumn(colIdx);
view.onCellDeselect(context);
}
}
}
// We have to deselect columns which have been hidden/removed
else if (selData.isColumns) {
selectionChanged = false;
selData.eachColumn(function(column, columnIdx) {
if (!column.isVisible() || !view.ownerGrid.isAncestor(column)) {
this.remove(column);
selectionChanged = true;
}
});
}
}
// This event is fired directly from the HeaderContainer before the view updates.
// So we have to wait until idle to update the selection UI.
// NB: fireSelectionChange calls updateSelectionExtender after firing its event.
Ext.on('idle', selectionChanged ? this.fireSelectionChange : this.updateSelectionExtender, this, {
single: true
});
},
// The selection may have acquired or lost contiguity, so the replicator may need enabling or disabling
onColumnMove: function() {
this.updateSelectionExtender();
},
/**
* @private
*/
onBeforeViewRefresh: function(view) {
var selData = this.selected;
// Allow cell preselection to survive, but not cell selection from a prior refresh
if (view.refreshCounter) {
if (selData && selData.isCells) {
this.resetSelection();
}
}
},
/**
* @private
*/
onViewRefresh: function(view) {
var me = this,
sel = this.selected,
store = me.view.store,
changed = false;
// Deselect filtered out records
if (sel && sel.isRows && store.isFiltered()) {
sel.eachRow(function(rec) {
if (!store.contains(rec)) {
this.remove(rec); // Maintainer: this is the Rows selection object, *NOT* me.
changed = true;
}
});
}
// The selection may have acquired or lost contiguity, so the replicator may need enabling or disabling
// NB: fireSelectionChange calls updateSelectionExtender after firing its event.
this[changed ? 'fireSelectionChange' : 'updateSelectionExtender']();
},
/**
* @private
*/
resetSelection: function(suppressEvent) {
var sel = this.selected;
if (sel) {
sel.clear();
if (!suppressEvent) {
this.fireSelectionChange();
}
}
},
onViewCreated: function(grid, view) {
var me = this,
ownerGrid = view.ownerGrid,
headerCt = view.headerCt;
// Only add columns to the locked view, or only view if there is no twin
if (!ownerGrid.lockable || view.isLockedView) {
// if there is no row number column and we ask for it, then it should be added here
if (me.getRowSelect()) {
// Ensure we have a rownumber column
me.getNumbererColumn();
}
if (me.checkboxSelect) {
me.addCheckbox(view, true);
}
me.mon(view.ownerGrid, 'beforereconfigure', me.onBeforeReconfigure, me);
}
// Disable sortOnClick if we're columnSelecting
headerCt.sortOnClick = !me.getColumnSelect();
if (me.getDragSelect()) {
view.on('render', me.onViewRender, me, {
single: true
});
}
},
/**
* Initialize drag selection support
* @private
*/
onViewRender: function(view) {
var me = this,
el = view.getEl(),
views = me.views,
len = views.length,
i;
// If we receive the render event after the columnSelect config has been set,
// ensure that the view's headerCts know not to sort on click if we're selecting columns.
for (i = 0; i < len; i++) {
views[i].headerCt.sortOnClick = !me.columnSelect;
}
el.ddScrollConfig = {
vthresh: 50,
hthresh: 50,
frequency: 300,
increment: 100
};
Ext.dd.ScrollManager.register(el);
// Possible two child views to register as scrollable on drag
(me.scrollEls || (me.scrollEls = [])).push(el);
view.on('cellmousedown', me.handleMouseDown, me);
// In a locking situation, we need a mousedown listener on both sides.
if (view.lockingPartner) {
view.lockingPartner.on('cellmousedown', me.handleMouseDown, me);
}
},
/**
* Plumbing for drag selection of cell range
* @private
*/
handleMouseDown: function(view, td, cellIndex, record, tr, rowIdx, e) {
var me = this,
sel = me.selected,
header = e.position.column,
isCheckClick,
startDragSelect;
// Ignore right click, shift and alt modifiers.
// Also ignore touchstart because e cannot drag select using touches and
// ignore when actionableMode is true so we can select the text inside an editor
if (e.button || e.shiftKey || e.altKey || e.pointerType ==='touch' || view.actionableMode) {
return;
}
if (header) {
me.mousedownPosition = e.position.clone();
isCheckClick = header === me.checkColumn;
// Differentiate between row and cell selections.
if (header === me.numbererColumn || isCheckClick || !me.cellSelect) {
// Enforce rowSelect setting
if (me.rowSelect) {
if (sel && sel.isRows) {
if (!e.ctrlKey && !isCheckClick) {
sel.clear();
}
} else {
if (sel) {
sel.clear();
}
sel = me.selected = new Ext.grid.selection.Rows(view);
}
startDragSelect = true;
} else if (me.columnSelect) {
if (sel && sel.isColumns) {
if (!e.ctrlKey && !isCheckClick) {
sel.clear();
}
} else {
if (sel) {
sel.clear();
}
sel = me.selected = new Ext.grid.selection.Columns(view);
}
startDragSelect = true;
} else {
return false;
}
} else {
if (sel) {
sel.clear();
}
if (!sel || !sel.isCells) {
sel = me.selected = new Ext.grid.selection.Cells(view);
}
startDragSelect = true;
}
me.lastOverRecord = me.lastOverColumn = null;
// Add the listener after the view has potentially been corrected
Ext.getBody().on('mouseup', me.onMouseUp, me, { single: true, view: sel.view });
// Only begin the drag process if configured to select what they asked for
if (startDragSelect) {
sel.view.el.on('mousemove', me.onMouseMove, me, {view: sel.view});
}
}
},
/**
* Selects range based on mouse movements
* @param e
* @param target
* @param opts
* @private
*/
onMouseMove: function(e, target, opts) {
var me = this,
view = opts.view,
record,
rowIdx,
cell = e.getTarget(view.cellSelector),
header = opts.view.getHeaderByCell(cell),
selData = me.selected,
pos,
recChange,
colChange;
// Clicking and dragging inside a checkbox shouldn't be handled here, see: EXTJS-20241
if (e.getTarget(null, null, true).hasCls(Ext.baseCSSPrefix + 'grid-row-checker')) {
return;
}
// Disable until a valid new selection is announced in fireSelectionChange
if (me.extensible) {
me.extensible.disable();
}
if (header) {
record = view.getRecord(cell.parentNode);
rowIdx = me.store.indexOf(record);
recChange = record !== me.lastOverRecord;
colChange = header !== me.lastOverColumn;
if (recChange || colChange) {
pos = me.getCellContext(record, header);
}
// Initial mousedown was in rownumberer or checkbox column
if (selData.isRows) {
// Only react if we've changed row
if (recChange) {
if (me.lastOverRecord) {
selData.setRangeEnd(rowIdx);
} else {
selData.setRangeStart(rowIdx);
}
}
}
// Selecting cells
else if (selData.isCells) {
// Only react if we've changed row or column
if (recChange || colChange) {
if (me.lastOverRecord) {
selData.setRangeEnd(pos);
} else {
selData.setRangeStart(pos);
}
}
}
// Selecting columns
else if (selData.isColumns) {
// Only react if we've changed column
if (colChange) {
if (me.lastOverColumn) {
selData.setRangeEnd(pos.column);
} else {
selData.setRangeStart(pos.column);
}
}
}
// Focus MUST follow the mouse.
// Otherwise the focus may scroll out of the rendered range and revert to document
if (recChange || colChange) {
// We MUST pass local view into NavigationModel, not the potentially outermost locking view.
// TODO: When that's fixed, use setPosition(pos).
view.getNavigationModel().setPosition(new Ext.grid.CellContext(header.getView()).setPosition(record, header));
}
me.lastOverColumn = header;
me.lastOverRecord = record;
}
},
/**
* Clean up mousemove event
* @param e
* @param target
* @param opts
* @private
*/
onMouseUp: function(e, target, opts) {
var me = this,
view = opts.view,
cell, record;
if (view && !view.destroyed) {
// If we catch the event before the View sees it and stamps a position in, we need to know where they mouseupped.
if (!e.position) {
cell = e.getTarget(view.cellSelector);
if (cell) {
record = view.getRecord(cell);
if (record) {
e.position = new Ext.grid.CellContext(view).setPosition(record, view.getHeaderByCell(cell));
}
}
}
// Disable until a valid new selection is announced in fireSelectionChange
if (me.extensible) {
me.extensible.disable();
}
view.el.un('mousemove', me.onMouseMove, me);
// Copy the records encompassed by the drag range into the record collection
if (me.selected.isRows) {
me.selected.addRange();
}
// Fire selection change only if we have dragged - if the mouseup position is different from the mousedown position.
// If there has been no drag, the click handler will select the single row
if (!e.position|| !e.position.isEqual(me.mousedownPosition)) {
me.fireSelectionChange();
}
}
},
/**
* Add the header checkbox to the header row
* @param view
* @param {Boolean} initial True if we're binding for the first time.
* @private
*/
addCheckbox: function(view, initial) {
var me = this,
checkbox = me.checkboxColumnIndex,
headerCt = view.headerCt;
// Preserve behaviour of false, but not clear why that would ever be done.
if (checkbox !== false) {
if (checkbox === 'first') {
checkbox = 0;
} else if (checkbox === 'last') {
checkbox = headerCt.getColumnCount();
}
me.checkColumn = headerCt.add(checkbox, me.getCheckboxHeaderConfig());
}
if (initial !== true) {
view.refresh();
}
},
/**
* Called when the grid's Navigation model detects navigation events (`mousedown`, `click` and certain `keydown` events).
* @param {Ext.event.Event} navigateEvent The event which caused navigation.
* @private
*/
onNavigate: function(navigateEvent) {
var me = this,
// Use outermost view. May be lockable
view = navigateEvent.view.ownerGrid.view,
record = navigateEvent.record,
sel = me.selected,
// Create a new Context based upon the outermost View.
// NavigationModel works on local views. TODO: remove this step when NavModel is fixed to use outermost view in locked grid.
// At that point, we can use navigateEvent.position
pos = new Ext.grid.CellContext(view).setPosition(record, navigateEvent.column),
keyEvent = navigateEvent.keyEvent,
ctrlKey = keyEvent.ctrlKey,
shiftKey = keyEvent.shiftKey,
keyCode = keyEvent.getKey(),
selectionChanged;
// A Column's processEvent method may set this flag if configured to do so.
if (keyEvent.stopSelection) {
return;
}
// CTRL/Arrow just navigates, does not select
if (ctrlKey && (keyCode === keyEvent.UP || keyCode === keyEvent.LEFT || keyCode === keyEvent.RIGHT || keyCode === keyEvent.DOWN)) {
return;
}
// Click is the mouseup at the end of a multi-cell/multi-column select swipe; reject.
if (sel && (sel.isCells || (sel.isColumns && !(ctrlKey || shiftKey))) && sel.getCount() > 1 && keyEvent.type === 'click') {
return;
}
// If all selection types are disabled, or it's not a selecting event, return
if (!(me.cellSelect || me.columnSelect || me.rowSelect) || !navigateEvent.record || keyEvent.type === 'mousedown') {
return;
}
// Ctrl/A key - Deselect current selection, or select all if no selection
if (ctrlKey && keyEvent.keyCode === keyEvent.A ) {
// No selection, or only one, select all
if (!sel || sel.getCount() < 2) {
me.selectAll();
} else {
me.deselectAll();
}
me.updateHeaderState();
return;
}
if (shiftKey) {
// If the event is in one of the row selecting cells, or cell selecting is turned off
if (pos.column === me.numbererColumn || pos.column === me.checkColumn || !(me.cellSelect || me.columnSelect) || (sel && sel.isRows)) {
if (me.rowSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isRows || sel.view !== view) {
me.resetSelection(true);
sel = me.selected = new Ext.grid.selection.Rows(view);
}
// First shift
if (!sel.getRangeSize()) {
sel.setRangeStart(navigateEvent.previousRecordIndex || 0);
}
sel.setRangeEnd(navigateEvent.recordIndex);
sel.addRange();
selectionChanged = true;
}
}
// Navigate event in a normal cell
else {
if (me.cellSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isCells || sel.view !== view) {
me.resetSelection(true);
sel = me.selected = new Ext.grid.selection.Cells(view);
}
// First shift
if (!sel.getRangeSize()) {
sel.setRangeStart(navigateEvent.previousPosition || me.getCellContext(0, 0));
}
sel.setRangeEnd(pos);
selectionChanged = true;
} else if (me.columnSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isColumns || sel.view !== view) {
me.resetSelection(true);
sel = me.selected = new Ext.grid.selection.Columns(view);
}
if (!sel.getCount()) {
sel.setRangeStart(pos.column);
}
sel.setRangeEnd(navigateEvent.position.column);
selectionChanged = true;
}
}
} else {
// If the event is in one of the row selecting cells, or cell selecting is turned off
if (pos.column === me.numbererColumn || pos.column === me.checkColumn || !(me.cellSelect || me.columnSelect)) {
if (me.rowSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isRows || sel.view !== view) {
me.resetSelection(true);
sel = me.selected = new Ext.grid.selection.Rows(view);
}
if (ctrlKey || pos.column === me.checkColumn) {
if (sel.contains(record)) {
sel.remove(record);
} else {
sel.add(record);
}
} else {
sel.clear();
sel.add(record);
}
selectionChanged = true;
}
}
// Navigate event in a normal cell
else {
if (me.cellSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isCells || sel.view !== view) {
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Cells(view);
} else {
sel.clear();
}
sel.setRangeStart(pos);
selectionChanged = true;
}
else if (me.columnSelect) {
// Ensure selection object is of the correct type
if (!sel || !sel.isColumns || sel.view !== view) {
me.resetSelection(true);
me.selected = sel = new Ext.grid.selection.Columns(view);
}
if (ctrlKey) {
if (sel.contains(pos.column)) {
sel.remove(pos.column);
} else {
sel.add(pos.column);
}
} else {
sel.setRangeStart(pos.column);
}
selectionChanged = true;
}
}
}
// If our configuration allowed selection changes, update check header and fire event
if (selectionChanged) {
if (sel.isRows) {
me.updateHeaderState();
}
me.fireSelectionChange();
}
},
/**
* Check if given record is currently selected.
*
* Used in {@link Ext.view.Table view} rendering to decide upon cell UI treatment.
* @param {Ext.data.Model} record
* @return {Boolean}
* @private
*/
isRowSelected: function(record) {
var me = this,
sel = me.selected;
if (sel && sel.isRows) {
record = Ext.isNumber(record) ? me.store.getAt(record) : record;
return sel.contains(record);
} else {
return false;
}
},
/**
* Check if given column is currently selected.
*
* @param {Ext.grid.column.Column} column
* @return {Boolean}
* @private
*/
isColumnSelected: function(column) {
var me = this,
sel = me.selected;
if (sel && sel.isColumns) {
return sel.contains(column);
} else {
return false;
}
},
/**
* Returns true if specified cell within specified view is selected
*
* Used in {@link Ext.view.Table view} rendering to decide upon row UI treatment.
* @param {Ext.grid.View} view - impactful when locked columns are used
* @param {Number} row - row index
* @param {Number} column - column index, within the current view
*
* @return {Boolean}
* @private
*/
isCellSelected: function(view, row, column) {
var me = this,
testPos,
sel = me.selected;
// view MUST be outermost (possible locking) view
view = view.ownerGrid.view;
if (sel) {
if (sel.isColumns) {
if (typeof column === 'number') {
column = view.getVisibleColumnManager().getColumns()[column];
}
return sel.contains(column);
}
if (sel.isCells) {
testPos = new Ext.grid.CellContext(view).setPosition({
row: row,
// IMPORTANT: The historic API for columns has been to include hidden columns
// in the index. So we must index into the "all" ColumnManager.
column: column
});
return sel.contains(testPos);
}
}
return false;
},
/**
* @private
*/
applySelected: function(selected) {
// Must override base class's applier which creates a Collection
//<debug>
if (selected && !(selected.isRows || selected.isCells || selected.isColumns)) {
Ext.raise('SpreadsheelModel#setSelected must be passed an instance of Ext.grid.selection.Selection');
}
//</debug>
return selected;
},
/**
* @private
*/
updateSelected: function(selected, oldSelected) {
var view,
columns,
len,
i,
cell;
// Clear old selection.
if (oldSelected) {
oldSelected.clear();
}
// Update the UI to match the new selection
if (selected && selected.getCount()) {
view = selected.view;
// Rows; update each selected row
if (selected.isRows) {
selected.eachRow(view.onRowSelect, view);
}
// Columns; update the selected columns for all rows
else if (selected.isColumns) {
columns = selected.getColumns();
len = columns.length;
if (len) {
cell = new Ext.grid.CelContext(view);
view.store.each(function(rec) {
cell.setRow(rec);
for (i = 0; i < len; i++) {
cell.setColumn(columns[i]);
view.onCellSelect(cell);
}
});
}
}
// Cells; update each selected cell
else if (selected.isCells) {
selected.eachCell(view.onCellSelect, view);
}
}
},
getNumbererColumn: function(col) {
var me = this,
result = me.numbererColumn,
view = me.view;
if (!result) {
// Always put row selection columns in the locked side if there is one.
if (view.isNormalView) {
view = view.ownerGrid.lockedGrid;
}
result = me.numbererColumn = view.headerCt.down('rownumberer') || view.headerCt.add(0, me.getNumbererColumnConfig());
}
return result;
},
getNumbererColumnConfig: function() {
var me = this;
return {
xtype: 'rownumberer',
width: me.rowNumbererHeaderWidth,
editRenderer: ' ',
tdCls: me.rowNumbererTdCls,
cls: me.rowNumbererHeaderCls,
locked: me.hasLockedHeader
};
},
/**
* Show/hide the extra column headers depending upon rowSelection.
* @private
*/
updateRowSelect: function(rowSelect) {
var me = this,
sel = me.selected,
view = me.view;
if (view && view.rendered) {
// Always put row selection columns in the locked side if there is one.
if (view.isNormalView) {
view = view.lockingPartner;
}
if (rowSelect) {
if (me.checkColumn) {
me.checkColumn.show();
}
me.getNumbererColumn().show();
} else {
if (me.checkColumn) {
me.checkColumn.hide();
}
if (me.numbererColumn) {
me.numbererColumn.hide();
}
}
if (!rowSelect && sel && sel.isRows) {
sel.clear();
me.fireSelectionChange();
}
}
},
/**
* Enable/disable the HeaderContainer's sortOnClick in line with column select on
* column click.
* @private
*/
updateColumnSelect: function(columnSelect) {
var me = this,
sel = me.selected,
views = me.views,
len = views ? views.length : 0,
i;
for (i = 0; i < len; i++) {
views[i].headerCt.sortOnClick = !columnSelect;
}
if (!columnSelect && sel && sel.isColumns) {
sel.clear();
me.fireSelectionChange();
}
if (columnSelect) {
me.view.ownerGrid.addCls(me.columnSelectCls);
} else {
me.view.ownerGrid.removeCls(me.columnSelectCls);
}
},
/**
* @private
*/
updateCellSelect: function(cellSelect) {
var me = this,
sel = me.selected;
if (!cellSelect && sel && sel.isCells) {
sel.clear();
me.fireSelectionChange();
}
},
/**
* @private
*/
fireSelectionChange: function () {
var me = this,
grid = me.view.ownerGrid,
sel = me.selected;
// Inform selection object that we're done
me.updateSelectionExtender();
// We must still fire a selectionchange event through the SelectionModel because Ext.panel.Table listens for this event
// to update its bound selection.
if (sel.isRows) {
me.fireEvent('selectionchange', me, sel.getRecords());
} else if (sel.isCells) {
me.fireEvent('selectionchange', me, me.store.getRange.apply(sel.view.dataSource, sel.getRowRange()));
}
grid.fireEvent('selectionchange', grid, sel);
},
/**
* @private
* Called by {@link Ext.panel.Table#updateBindSelection} when publishing the `selection` property.
* It should yield the last record selected.
* @return {Ext.data.Model} The last record selected. This is only available if the current selection type is cells or rows.
* In the case of multiple selection, the *last* record added to the selection is returned.
*/
getLastSelected: function() {
var sel = this.selected;
if (sel.getLastSelected) {
return sel.getLastSelected();
}
},
updateSelectionExtender: function() {
var sel = this.selected;
if (sel) {
sel.onSelectionFinish();
}
},
/**
* Called when a selection has been made. The selection object's onSelectionFinish calls back into this.
* @param {Ext.grid.selection.Selection} sel The selection object specific to
* the selection performed.
* @param {Ext.grid.CellContext} [firstCell] The left/top most selected cell.
* Will be undefined if the selection is clear.
* @param {Ext.grid.CellContext} [lastCell] The bottom/right most selected cell.
* Will be undefined if the selection is clear.
* @private
*/
onSelectionFinish: function(sel, firstCell, lastCell) {
var extensible = this.getExtensible();
if (extensible) {
extensible.setHandle(firstCell, lastCell);
}
},
applyExtensible: function(extensible) {
var me = this;
if (extensible === true || typeof extensible === 'string') {
extensible = {
axes: me.axesConfigs[extensible]
};
} else {
extensible = Ext.Object.chain(extensible); // don't mutate the user's config
}
extensible.view = me.selected.view;
return new Ext.grid.selection.SelectionExtender(extensible);
},
/**
* Called when the SelectionExtender has the mouse released.
* @param {Object} extension An object describing the type and size of extension.
* @param {String} extension.type `"rows"` or `"columns"`
* @param {Ext.grid.CellContext} extension.start The start (top left) cell of the extension area.
* @param {Ext.grid.CellContext} extension.end The end (bottom right) cell of the extension area.
* @param {number} [extension.columns] The number of columns extended (-ve means on the left side).
* @param {number} [extension.rows] The number of rows extended (-ve means on the top side).
* @private
*/
extendSelection: function(extension) {
var me = this,
sel = me.selected;
// Announce that the selection is to be extended, and if no objections, extend it
if (me.view.ownerGrid.fireEvent('beforeselectionextend', me.view.ownerGrid, sel, extension) !== false) {
sel.extendRange(extension);
me.fireSelectionChange();
}
},
/**
* @private
*/
onIdChanged: function(store, rec, oldId, newId) {
var sel = this.selected;
if (sel && sel.isRows && sel.selectedRecords) {
sel.selectedRecords.updateKey(rec, oldId);
}
},
/**
* Called when a page is added to BufferedStore.
* @private
*/
onPageAdd: function(pageMap, pageNumber, records) {
var sel = this.selected,
len = records.length,
i,
record,
selected = sel && sel.selectedRecords;
// Check for return of already selected records.
// Maintainer: To only use one conditional expression, the value of assignment of
// (selected = sel.selectedRecords) is part of the single conditional expression.
if (selected && sel.isRows) {
for (i = 0; i < len; i++) {
record = records[i];
if (selected.get(record.id)) {
selected.replace(record);
}
}
}
},
/**
* @private
*/
refresh: function() {
var sel = this.getSelected();
// Refreshing the selected record Collection based upon a possible
// store mutation is only valid if we are selecting records.
if (sel && sel.isRows) {
this.callParent();
}
},
/**
* @private
*/
onStoreAdd: function() {
var sel = this.getSelected();
// Updating on store mutation is only valid if we are selecting records.
if (sel && sel.isRows) {
this.callParent(arguments);
this.updateHeaderState();
}
},
/**
* @private
*/
onStoreClear: function() {
this.resetSelection();
},
/**
* @private
*/
onStoreLoad: function() {
var sel = this.getSelected();
// Updating on store mutation is only valid if we are selecting records.
if (sel && sel.isRows) {
this.callParent(arguments);
this.updateHeaderState();
}
},
/**
* @private
*/
onStoreRefresh: function() {
var sel = this.selected;
// Ensure that records which are no longer in the new store are pruned if configured to do so.
// Ensure that selected records in the collection are the correct instance.
if (sel && sel.isRows && sel.selectedRecords) {
this.updateSelectedInstances(sel.selectedRecords);
}
if (this.view) {
this.updateHeaderState();
}
},
/**
* @private
*/
onStoreRemove: function() {
var sel = this.getSelected();
// Updating on store mutation is only valid if we are selecting records.
if (sel && sel.isRows) {
this.callParent(arguments);
}
}
}
}, function (SpreadsheetModel) {
var RowNumberer = Ext.ClassManager.get('Ext.grid.column.RowNumberer');
if (RowNumberer) {
SpreadsheetModel.prototype.rowNumbererTdCls =
Ext.grid.column.RowNumberer.prototype.tdCls + ' ' + Ext.baseCSSPrefix + 'ssm-row-numberer-cell';
}
});
|
var greeks = require("../greeks.js"),
assert = require("assert");
/*
* Calculations verified using CBOE's option pricing calculator:
* http://www.cboe.com/framed/IVolframed.aspx?content=http%3a%2f%2fcboe.ivolatility.com%2fcalc%2findex.j%3fcontract%3d3AF7E2E8-2B92-4866-8D4A-92FDCD5DF873§ionName=SEC_TRADING_TOOLS&title=CBOE%20-%20IVolatility%20Services
*/
describe("Greeks", function()
{
describe("Delta", function()
{
it("should return ~50", function()
{
assert.equal(greeks.getDelta(100, 100, .086, .1, .0015, "call"), 0.5076040742445566);
assert.equal(greeks.getDelta(100, 100, .086, .1, .0015, "put"), -0.49239592575544344);
});
it("should return 0", function()
{
assert.equal(greeks.getDelta(100, 100, 0, .1, .0015, "call"), 0);
assert.equal(greeks.getDelta(99.99, 100, 0, .1, .0015, "call"), 0);
assert.equal(greeks.getDelta(100, 100, 0, .1, .0015, "put"), 0);
assert.equal(greeks.getDelta(100.01, 100, 0, .1, .0015, "put"), 0);
assert.equal(greeks.getDelta(100, 100, .1, 0, .0015, "call"), 0);
assert.equal(greeks.getDelta(99.99, 100, .1, 0, .0015, "call"), 0);
assert.equal(greeks.getDelta(100, 100, .1, 0, .0015, "put"), 0);
assert.equal(greeks.getDelta(100.01, 100, .1, 0, .0015, "put"), 0);
assert.equal(greeks.getDelta(100, 100, 0, 0, .0015, "call"), 0);
assert.equal(greeks.getDelta(99.99, 100, 0, 0, .0015, "call"), 0);
assert.equal(greeks.getDelta(100, 100, 0, 0, .0015, "put"), 0);
assert.equal(greeks.getDelta(100.01, 100, 0, 0, .0015, "put"), 0);
});
it("should return 1 for calls, -1 for puts", function()
{
assert.equal(greeks.getDelta(100.01, 100, 0, .1, .0015, "call"), 1);
assert.equal(greeks.getDelta(99.99, 100, 0, .1, .0015, "put"), -1);
assert.equal(greeks.getDelta(100.01, 100, .1, 0, .0015, "call"), 1);
assert.equal(greeks.getDelta(99.99, 100, .1, 0, .0015, "put"), -1);
assert.equal(greeks.getDelta(100.01, 100, 0, 0, .0015, "call"), 1);
assert.equal(greeks.getDelta(99.99, 100, 0, 0, .0015, "put"), -1);
});
}); // end delta
describe("Vega", function()
{
it("should return ~.24", function()
{
assert.equal(greeks.getVega(206.35, 206, .086, .1, .0015), 0.24070106056306836);
});
it("should return 0", function()
{
assert.equal(greeks.getVega(100, 100, 0, .1, .0015), 0);
assert.equal(greeks.getVega(100, 100, 0, 0, .0015), 0);
assert.equal(greeks.getVega(100, 100, .1, 0, .0015), 0);
});
}); // end vega
describe("Gamma", function()
{
it("should return ~.065", function()
{
assert.equal(greeks.getGamma(206.35, 206, .086, .1, .0015), 0.06573105549942765);
});
it("should return 0", function()
{
assert.equal(greeks.getGamma(100, 100, 0, .1, .0015), 0);
assert.equal(greeks.getGamma(100, 100, .1, 0, .0015), 0);
assert.equal(greeks.getGamma(100, 100, 0, 0, .0015), 0);
});
}); // end gamma
describe("Theta", function()
{
it("should return non-zero theta", function()
{
assert.equal(greeks.getTheta(206.35, 206, .086, .1, .0015, "call"), -0.03877971361524501);
assert.equal(greeks.getTheta(206.35, 206, .086, .1, .0015, "put"), -0.0379332474739548);
assert.equal(greeks.getTheta(206.35, 206, .086, .1, .0015, "call", 252), -0.05616902964112869);
assert.equal(greeks.getTheta(206.35, 206, .086, .1, .0015, "put", 252), -0.054942997333307556);
});
it("should return 0", function()
{
assert.equal(greeks.getTheta(100, 100, 0, .1, .0015, "call"), 0);
assert.equal(greeks.getTheta(100, 100, 0, .1, .0015, "put"), 0);
assert.equal(greeks.getTheta(100, 100, 0, .1, .0015, "call", 252), 0);
assert.equal(greeks.getTheta(100, 100, 0, .1, .0015, "put", 252), 0);
assert.equal(greeks.getTheta(100, 100, .1, 0, .0015, "call"), 0);
assert.equal(greeks.getTheta(100, 100, .1, 0, .0015, "put"), 0);
assert.equal(greeks.getTheta(100, 100, .1, 0, .0015, "call", 252), 0);
assert.equal(greeks.getTheta(100, 100, .1, 0, .0015, "put", 252), 0);
assert.equal(greeks.getTheta(100, 100, 0, 0, .0015, "call"), 0);
assert.equal(greeks.getTheta(100, 100, 0, 0, .0015, "put"), 0);
assert.equal(greeks.getTheta(100, 100, 0, 0, .0015, "call", 252), 0);
assert.equal(greeks.getTheta(100, 100, 0, 0, .0015, "put", 252), 0);
});
}); // end theta
describe("Rho", function()
{
it("should return non-zero rho", function()
{
assert.equal(greeks.getRho(206.35, 206, .086, .1, .0015, "call"), 0.09193271711465777);
assert.equal(greeks.getRho(206.35, 206, .086, .1, .0015, "put"), -0.08520443071933861);
assert.equal(greeks.getRho(206.35, 206, .086, .1, .0015, "call", 10000), 0.0009193271711465777);
assert.equal(greeks.getRho(206.35, 206, .086, .1, .0015, "put", 10000), -0.0008520443071933862);
// only the call has a non-zero rho when: v=0, t>0, s>k
assert.equal(greeks.getRho(206.35, 206, .086, 0, .0015, "call"), 0.17713714783399637);
// only the put has a non-zero rho when: v=0, t>0, s<k
assert.equal(greeks.getRho(205.35, 206, .086, 0, .0015, "put"), -0.17713714783399637);
});
it("should return 0", function()
{
assert.equal(greeks.getRho(100, 100, 0, .1, .0015, "call"), 0);
assert.equal(greeks.getRho(100, 100, 0, .1, .0015, "put"), 0);
assert.equal(greeks.getRho(100, 100, 0, 0, .0015, "call"), 0);
assert.equal(greeks.getRho(100, 100, 0, 0, .0015, "put"), 0);
// only the put has a rho of zero when: v=0, t>0, s>k
assert.equal(greeks.getRho(206.35, 206, .086, 0, .0015, "put"), 0);
// only the call has a rho of zero when: v=0, t>0, s<k
assert.equal(greeks.getRho(205.35, 206, .086, 0, .0015, "call"), 0);
});
}); // end rho
});
|
"use strict";
exports.__esModule = true;
exports._ForOfStatementArray = _ForOfStatementArray;
// istanbul ignore next
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}newObj["default"] = obj;return newObj;
}
}
var _messages = require("../../../messages");
var messages = _interopRequireWildcard(_messages);
var _util = require("../../../util");
var util = _interopRequireWildcard(_util);
var _types = require("../../../types");
var t = _interopRequireWildcard(_types);
/**
* [Please add a description.]
*/
var visitor = {
/**
* [Please add a description.]
*/
ForOfStatement: function ForOfStatement(node, parent, scope, file) {
if (this.get("right").isArrayExpression()) {
return _ForOfStatementArray.call(this, node, scope, file);
}
var callback = spec;
if (file.isLoose("es6.forOf")) callback = loose;
var build = callback(node, parent, scope, file);
var declar = build.declar;
var loop = build.loop;
var block = loop.body;
// ensure that it's a block so we can take all its statements
this.ensureBlock();
// add the value declaration to the new loop body
if (declar) {
block.body.push(declar);
}
// push the rest of the original loop body onto our new body
block.body = block.body.concat(node.body.body);
t.inherits(loop, node);
t.inherits(loop.body, node.body);
if (build.replaceParent) {
this.parentPath.replaceWithMultiple(build.node);
this.dangerouslyRemove();
} else {
return build.node;
}
}
};
exports.visitor = visitor;
/**
* [Please add a description.]
*/
function _ForOfStatementArray(node, scope) {
var nodes = [];
var right = node.right;
if (!t.isIdentifier(right) || !scope.hasBinding(right.name)) {
var uid = scope.generateUidIdentifier("arr");
nodes.push(t.variableDeclaration("var", [t.variableDeclarator(uid, right)]));
right = uid;
}
var iterationKey = scope.generateUidIdentifier("i");
var loop = util.template("for-of-array", {
BODY: node.body,
KEY: iterationKey,
ARR: right
});
t.inherits(loop, node);
t.ensureBlock(loop);
var iterationValue = t.memberExpression(right, iterationKey, true);
var left = node.left;
if (t.isVariableDeclaration(left)) {
left.declarations[0].init = iterationValue;
loop.body.body.unshift(left);
} else {
loop.body.body.unshift(t.expressionStatement(t.assignmentExpression("=", left, iterationValue)));
}
if (this.parentPath.isLabeledStatement()) {
loop = t.labeledStatement(this.parentPath.node.label, loop);
}
nodes.push(loop);
return nodes;
}
/**
* [Please add a description.]
*/
var loose = function loose(node, parent, scope, file) {
var left = node.left;
var declar, id;
if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) {
// for (i of test), for ({ i } of test)
id = left;
} else if (t.isVariableDeclaration(left)) {
// for (var i of test)
id = scope.generateUidIdentifier("ref");
declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, id)]);
} else {
throw file.errorWithNode(left, messages.get("unknownForHead", left.type));
}
var iteratorKey = scope.generateUidIdentifier("iterator");
var isArrayKey = scope.generateUidIdentifier("isArray");
var loop = util.template("for-of-loose", {
LOOP_OBJECT: iteratorKey,
IS_ARRAY: isArrayKey,
OBJECT: node.right,
INDEX: scope.generateUidIdentifier("i"),
ID: id
});
if (!declar) {
// no declaration so we need to remove the variable declaration at the top of
// the for-of-loose template
loop.body.body.shift();
}
//
return {
declar: declar,
node: loop,
loop: loop
};
};
/**
* [Please add a description.]
*/
var spec = function spec(node, parent, scope, file) {
var left = node.left;
var declar;
var stepKey = scope.generateUidIdentifier("step");
var stepValue = t.memberExpression(stepKey, t.identifier("value"));
if (t.isIdentifier(left) || t.isPattern(left) || t.isMemberExpression(left)) {
// for (i of test), for ({ i } of test)
declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue));
} else if (t.isVariableDeclaration(left)) {
// for (var i of test)
declar = t.variableDeclaration(left.kind, [t.variableDeclarator(left.declarations[0].id, stepValue)]);
} else {
throw file.errorWithNode(left, messages.get("unknownForHead", left.type));
}
//
var iteratorKey = scope.generateUidIdentifier("iterator");
var template = util.template("for-of", {
ITERATOR_HAD_ERROR_KEY: scope.generateUidIdentifier("didIteratorError"),
ITERATOR_COMPLETION: scope.generateUidIdentifier("iteratorNormalCompletion"),
ITERATOR_ERROR_KEY: scope.generateUidIdentifier("iteratorError"),
ITERATOR_KEY: iteratorKey,
STEP_KEY: stepKey,
OBJECT: node.right,
BODY: null
});
var isLabeledParent = t.isLabeledStatement(parent);
var tryBody = template[3].block.body;
var loop = tryBody[0];
if (isLabeledParent) {
tryBody[0] = t.labeledStatement(parent.label, loop);
}
//
return {
replaceParent: isLabeledParent,
declar: declar,
loop: loop,
node: template
};
};
//# sourceMappingURL=for-of-compiled.js.map |
'use strict';
var unsupported, isaosp;
if (window && window.navigator) {
var rxaosp = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
isaosp = (rxaosp && rxaosp[1] < 537);
if (!window.cordova && isaosp)
unsupported = true;
if (unsupported) {
window.location = '#/unsupported';
}
}
//Setting up route
angular
.module('copayApp')
.config(function(historicLogProvider, $provide, $logProvider, $stateProvider, $urlRouterProvider, $compileProvider) {
$urlRouterProvider.otherwise('/');
$logProvider.debugEnabled(true);
$provide.decorator('$log', ['$delegate', 'isDevel',
function($delegate, isDevel) {
var historicLog = historicLogProvider.$get();
['debug', 'info', 'warn', 'error', 'log'].forEach(function(level) {
if (isDevel && level == 'error') return;
var orig = $delegate[level];
$delegate[level] = function() {
if (level == 'error')
console.log(arguments);
var args = [].slice.call(arguments);
if (!Array.isArray(args)) args = [args];
args = args.map(function(v) {
try {
if (typeof v == 'undefined') v = 'undefined';
if (!v) v = 'null';
if (typeof v == 'object') {
if (v.message)
v = v.message;
else
v = JSON.stringify(v);
}
// Trim output in mobile
if (window.cordova) {
v = v.toString();
if (v.length > 300) {
v = v.substr(0, 297) + '...';
}
}
} catch (e) {
console.log('Error at log decorator:', e);
v = 'undefined';
}
return v;
});
try {
if (window.cordova)
console.log(args.join(' '));
historicLog.add(level, args.join(' '));
orig.apply(null, args);
} catch (e) {
console.log('ERROR (at log decorator):', e, args[0]);
}
};
});
return $delegate;
}
]);
// whitelist 'chrome-extension:' for chromeApp to work with image URLs processed by Angular
// link: http://stackoverflow.com/questions/15606751/angular-changes-urls-to-unsafe-in-extension-page?lq=1
$compileProvider.imgSrcSanitizationWhitelist(/^\s*((https?|ftp|file|blob|chrome-extension):|data:image\/)/);
$stateProvider
.state('translators', {
url: '/translators',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/translators.html'
}
}
})
.state('disclaimer', {
url: '/disclaimer',
needProfile: false,
views: {
'main': {
templateUrl: 'views/disclaimer.html',
}
}
})
.state('walletHome', {
url: '/',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/walletHome.html',
},
}
})
.state('unsupported', {
url: '/unsupported',
needProfile: false,
views: {
'main': {
templateUrl: 'views/unsupported.html'
}
}
})
.state('payment', {
url: '/uri-payment/:data',
templateUrl: 'views/paymentUri.html',
views: {
'main': {
templateUrl: 'views/paymentUri.html',
},
},
needProfile: true
})
.state('selectWalletForPayment', {
url: '/selectWalletForPayment',
controller: 'walletForPaymentController',
needProfile: true
})
.state('join', {
url: '/join',
needProfile: true,
views: {
'main': {
templateUrl: 'views/join.html'
},
}
})
.state('import', {
url: '/import',
needProfile: true,
views: {
'main': {
templateUrl: 'views/import.html'
},
}
})
.state('importProfile', {
url: '/importProfile',
templateUrl: 'views/importProfile.html',
needProfile: false
})
.state('importLegacy', {
url: '/importLegacy',
needProfile: true,
views: {
'main': {
templateUrl: 'views/importLegacy.html',
},
}
})
.state('create', {
url: '/create',
templateUrl: 'views/create.html',
needProfile: true,
views: {
'main': {
templateUrl: 'views/create.html'
},
}
})
.state('copayers', {
url: '/copayers',
needProfile: true,
views: {
'main': {
templateUrl: 'views/copayers.html'
},
}
})
.state('preferences', {
url: '/preferences',
templateUrl: 'views/preferences.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferences.html',
},
}
})
.state('preferencesLanguage', {
url: '/preferencesLanguage',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesLanguage.html'
},
}
})
.state('preferencesUnit', {
url: '/preferencesUnit',
templateUrl: 'views/preferencesUnit.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesUnit.html'
},
}
})
.state('preferencesFee', {
url: '/preferencesFee',
templateUrl: 'views/preferencesFee.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesFee.html'
},
}
})
.state('uriglidera', {
url: '/uri-glidera?code',
needProfile: true,
views: {
'main': {
templateUrl: 'views/glideraUri.html'
},
}
})
.state('glidera', {
url: '/glidera',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/glidera.html'
},
}
})
.state('buyGlidera', {
url: '/buy',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/buyGlidera.html'
},
}
})
.state('sellGlidera', {
url: '/sell',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/sellGlidera.html'
},
}
})
.state('preferencesGlidera', {
url: '/preferencesGlidera',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesGlidera.html'
},
}
})
.state('preferencesAdvanced', {
url: '/preferencesAdvanced',
templateUrl: 'views/preferencesAdvanced.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesAdvanced.html'
},
}
})
.state('preferencesTheme', {
url: '/preferencesTheme',
templateUrl: 'views/preferencesTheme.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesTheme.html'
},
}
})
.state('preferencesColor', {
url: '/preferencesColor',
templateUrl: 'views/preferencesColor.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesColor.html'
},
}
})
.state('preferencesAltCurrency', {
url: '/preferencesAltCurrency',
templateUrl: 'views/preferencesAltCurrency.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesAltCurrency.html'
},
}
})
.state('preferencesAlias', {
url: '/preferencesAlias',
templateUrl: 'views/preferencesAlias.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesAlias.html'
},
}
})
.state('preferencesEmail', {
url: '/preferencesEmail',
templateUrl: 'views/preferencesEmail.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesEmail.html'
},
}
})
.state('preferencesBwsUrl', {
url: '/preferencesBwsUrl',
templateUrl: 'views/preferencesBwsUrl.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesBwsUrl.html'
},
}
})
.state('preferencesHistory', {
url: '/preferencesHistory',
templateUrl: 'views/preferencesHistory.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesHistory.html'
},
}
})
.state('deleteWords', {
url: '/deleteWords',
templateUrl: 'views/preferencesDeleteWords.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesDeleteWords.html'
},
}
})
.state('delete', {
url: '/delete',
templateUrl: 'views/preferencesDeleteWallet.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesDeleteWallet.html'
},
}
})
.state('information', {
url: '/information',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesInformation.html'
},
}
})
.state('signMessage', {
url: '/signmessage',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/signMessage.html'
},
}
})
.state('about', {
url: '/about',
templateUrl: 'views/preferencesAbout.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesAbout.html'
},
}
})
.state('logs', {
url: '/logs',
templateUrl: 'views/preferencesLogs.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesLogs.html'
},
}
})
.state('export', {
url: '/export',
templateUrl: 'views/export.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/export.html'
},
}
})
.state('paperWallet', {
url: '/paperWallet',
templateUrl: 'views/paperWallet.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/paperWallet.html'
},
}
})
.state('backup', {
url: '/backup',
templateUrl: 'views/backup.html',
walletShouldBeComplete: true,
needProfile: true,
views: {
'main': {
templateUrl: 'views/backup.html'
},
}
})
.state('preferencesGlobal', {
url: '/preferencesGlobal',
needProfile: true,
views: {
'main': {
templateUrl: 'views/preferencesGlobal.html',
},
}
})
.state('termOfUse', {
url: '/termOfUse',
needProfile: true,
views: {
'main': {
templateUrl: 'views/termOfUse.html',
},
}
})
.state('warning', {
url: '/warning',
controller: 'warningController',
templateUrl: 'views/warning.html',
needProfile: false
})
.state('add', {
url: '/add',
needProfile: true,
views: {
'main': {
templateUrl: 'views/add.html'
},
}
})
.state('cordova', {
url: '/cordova/:status/:fromHome/:fromDisclaimer/:secondBackButtonPress',
views: {
'main': {
controller: function($rootScope, $state, $stateParams, $timeout, go, isCordova, gettextCatalog) {
switch ($stateParams.status) {
case 'resume':
$rootScope.$emit('Local/Resume');
break;
case 'backbutton':
if ($stateParams.fromDisclaimer == 'true')
navigator.app.exitApp();
if (isCordova && $stateParams.fromHome == 'true' && !$rootScope.modalOpened) {
if ($stateParams.secondBackButtonPress == 'true') {
navigator.app.exitApp();
} else {
window.plugins.toast.showShortBottom(gettextCatalog.getString('Press again to exit'));
}
} else {
$rootScope.$emit('closeModal');
}
break;
};
$timeout(function() {
$rootScope.$emit('Local/SetTab', 'walletHome', true);
}, 100);
go.walletHome();
}
}
},
needProfile: false
});
})
.run(function($rootScope, $state, $log, uriHandler, isCordova, profileService, $timeout, nodeWebkit, uxLanguage, animationService) {
FastClick.attach(document.body);
uxLanguage.init();
// Register URI handler, not for mobileApp
if (!isCordova) {
uriHandler.register();
}
if (nodeWebkit.isDefined()) {
var gui = require('nw.gui');
var win = gui.Window.get();
var nativeMenuBar = new gui.Menu({
type: "menubar"
});
try {
nativeMenuBar.createMacBuiltin("DigiByte Gaming");
} catch (e) {
$log.debug('This is not OSX');
}
win.menu = nativeMenuBar;
}
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
if (!profileService.profile && toState.needProfile) {
// Give us time to open / create the profile
event.preventDefault();
// Try to open local profile
profileService.loadAndBindProfile(function(err) {
if (err) {
if (err.message && err.message.match('NOPROFILE')) {
$log.debug('No profile... redirecting');
$state.transitionTo('disclaimer');
} else if (err.message && err.message.match('NONAGREEDDISCLAIMER')) {
$log.debug('Display disclaimer... redirecting');
$state.transitionTo('disclaimer');
} else {
throw new Error(err); // TODO
}
} else {
$log.debug('Profile loaded ... Starting UX.');
$state.transitionTo(toState.name || toState, toParams);
}
});
}
if (profileService.focusedClient && !profileService.focusedClient.isComplete() && toState.walletShouldBeComplete) {
$state.transitionTo('copayers');
event.preventDefault();
}
if (!animationService.transitionAnimated(fromState, toState)) {
event.preventDefault();
// Time for the backpane to render
setTimeout(function() {
$state.transitionTo(toState);
}, 50);
}
});
});
|
'use strict';
import VueRouter from "vue-router";
import features from "features";
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: features
});
export default router; |
"use strict";
/*
TODO standardize edit names (e.g. remove, addExisting)
*/
var _ = require('underscorem')
var editFp = require('./../tcp_shared').editFp
var editCodes = editFp.codes
var editNames = editFp.names
var typeSuffix = {
int: 'Int',
long: 'Long',
string: 'String',
boolean: 'Boolean',
real: 'Real',
timestamp: 'Long'
}
exports.setOp = function(t){
if(t.type === 'primitive'){
var ts = typeSuffix[t.primitive]
if(ts === undefined) _.errout('TODO: ' + t.primitive)
return editCodes['set'+ts]
}else{
return editCodes.setObject
}
}
exports.putOp = function(t){
if(t.value.type === 'primitive'){
var ts = typeSuffix[t.value.primitive]
if(ts === undefined) _.errout('TODO: ' + t.value.primitive)
return editCodes['put'+ts]
}else{
if(t.value.type === 'view'){
return editCodes.putViewObject
}else{
return editCodes.putExisting
}
}
}
exports.putAddOp = function(t){
_.assertDefined(t.value.members.primitive)
var ts = typeSuffix[t.value.members.primitive]
return editCodes['putAdd'+ts]
}
exports.putRemoveOp = function(t){
_.assertDefined(t.value.members.primitive)
var ts = typeSuffix[t.value.members.primitive]
return editCodes['putRemove'+ts]
}
exports.selectKeyOp = function(t){
var ts
if(t.key.primitive) ts = typeSuffix[t.key.primitive]
else if(t.key.type === 'object') ts = 'Object'
else ts = 'ViewObject'
var res = editCodes['select'+ts+'Key']
if(res === undefined) _.errout('cannot compute key select op for type: ' + JSON.stringify(t))
return res
}
exports.addOp = function(t){
if(t.members.type === 'primitive'){
var ts = typeSuffix[t.members.primitive]
if(ts === undefined) _.errout('TODO: ' + t.members.primitive)
return editCodes['add'+ts]
}else{
return editCodes.addExisting
}
}
exports.removeOp = function(t){
if(t.members.type === 'primitive'){
var ts = typeSuffix[t.members.primitive]
if(ts === undefined) _.errout('TODO: ' + t.members.primitive)
return editCodes['remove'+ts]
}else{
return editCodes.remove
}
}
exports.computeSharedObjectType = function(schema, objectNames){
_.assert(objectNames.length > 0)
if(objectNames.length === 1){
return objectNames[0]
}else{
var currentBase = objectNames[0]
var curSchema = schema[currentBase]
if(curSchema === undefined) _.errout('cannot find object type named: ' + currentBase)
_.assertDefined(curSchema)
objectNames.slice(1).forEach(function(n){
if(!curSchema) return
var s = schema[n]
_.assertDefined(s)
if(currentBase === n) return
if(s.superTypes && s.superTypes[currentBase]) return
if(curSchema.superTypes && curSchema.superTypes[n]){
currentBase = n
curSchema = s
if(!curSchema) _.errout('unknown: ' + n)
return
}
if(curSchema.superTypes && s.superTypes){
var found = false
Object.keys(curSchema.superTypes).forEach(function(st){
if(st === 'uuided') return
if(s.superTypes[st]){
currentBase = st
curSchema = schema[currentBase]
if(!curSchema) _.errout('unknown base: ' + currentBase)
found = true
}
})
//TODO descend to more specific subtype if possible
if(found) return
}
currentBase = 'object'
curSchema = undefined
//console.log(JSON.stringify(curSchema))
//console.log(JSON.stringify(s))
//_.errout('cannot find shared supertype for: ' + currentBase + ' and ' + n)
})
return currentBase
}
}
|
var fs = require('fs');
var rework = require('rework');
var extend = require('rework-inherit')();
var validator = require('..');
var expect = require('chai').expect;
function fixture (name) {
return fs.readFileSync('test/fixtures/' + name + '.css', 'utf-8').trim();
}
function compareFixtures (name) {
return expect(
rework(fixture(name))
.use(validator)
.use(extend)
.toString().trim()
).to.equal(fixture(name + '.out'));
}
function output (name) {
return rework(fixture(name))
.use(validator)
.use(extend)
.toString();
}
describe('rework-extend-validator', function () {
it('test-1', function () {
var result = function () {
return rework(fixture('test-1'))
.use(validator)
.use(extend)
.toString();
};
expect(result).to.Throw(Error, 'rework-extend-validator: extended rules have same properties');
});
it('test-2', function () {
compareFixtures('test-2');
});
it('test-3', function () {
var result = function () {
return rework(fixture('test-3'))
.use(validator)
.use(extend)
.toString();
};
expect(result).to.Throw(Error, 'rework-extend-validator: extended rules have same properties');
});
it('test-4', function () {
compareFixtures('test-4');
});
});
|
import types from 'config/types';
import getPartialDescriptor from 'virtualdom/items/Partial/getPartialDescriptor';
import applyIndent from 'virtualdom/items/Partial/applyIndent';
import circular from 'circular';
var Partial, Fragment;
circular.push( function () {
Fragment = circular.Fragment;
});
Partial = function ( options ) {
var parentFragment = this.parentFragment = options.parentFragment, template;
this.type = types.PARTIAL;
this.name = options.template.r;
this.index = options.index;
this.root = parentFragment.root;
if ( !options.template.r ) {
// TODO support dynamic partial switching
throw new Error( 'Partials must have a static reference (no expressions). This may change in a future version of Ractive.' );
}
template = getPartialDescriptor( parentFragment.root, options.template.r );
this.fragment = new Fragment({
template: template,
root: parentFragment.root,
owner: this,
pElement: parentFragment.pElement
});
};
Partial.prototype = {
bubble: function () {
this.parentFragment.bubble();
},
firstNode: function () {
return this.fragment.firstNode();
},
findNextNode: function () {
return this.parentFragment.findNextNode( this );
},
detach: function () {
return this.fragment.detach();
},
render: function () {
return this.fragment.render();
},
unrender: function ( shouldDestroy ) {
this.fragment.unrender( shouldDestroy );
},
rebind: function ( indexRef, newIndex, oldKeypath, newKeypath ) {
return this.fragment.rebind( indexRef, newIndex, oldKeypath, newKeypath );
},
unbind: function () {
this.fragment.unbind();
},
toString: function ( toString ) {
var string, previousItem, lastLine, match;
string = this.fragment.toString( toString );
previousItem = this.parentFragment.items[ this.index - 1 ];
if ( !previousItem || ( previousItem.type !== types.TEXT ) ) {
return string;
}
lastLine = previousItem.template.split( '\n' ).pop();
if ( match = /^\s+$/.exec( lastLine ) ) {
return applyIndent( string, match[0] );
}
return string;
},
find: function ( selector ) {
return this.fragment.find( selector );
},
findAll: function ( selector, query ) {
return this.fragment.findAll( selector, query );
},
findComponent: function ( selector ) {
return this.fragment.findComponent( selector );
},
findAllComponents: function ( selector, query ) {
return this.fragment.findAllComponents( selector, query );
},
getValue: function () {
return this.fragment.getValue();
}
};
export default Partial;
|
angular.module('beerCreator.directives').controller('MashInstructionsCtrl', function($scope){
$scope.calculateStrikeTemp = function(step, beer) {
var maltWeight = 0;
for (var i in beer.ingredients.malts) {
var malt = beer.ingredients.malts[i];
if (malt.recommendMash) {
maltWeight += malt.amount;
}
}
// Convert grams to pounds for formula
maltWeight = maltWeight * 0.00220462;
var grainSpecific = maltWeight * 0.05;
// Convert liters to gallons for formula
var waterSpecific = 0;
if (step.waterToAdd) {
waterSpecific = step.waterToAdd * 0.264172;
} else {
waterSpecific = $scope.waterToAdd(beer) * 0.264172;
}
var mashSpecific = grainSpecific + waterSpecific;
var grain = grainSpecific * beer.mash.temperatures.grain;
var mash = mashSpecific * step.temperature;
return (mash - grain)/waterSpecific;
};
$scope.waterToAdd = function(beer) {
if (!beer.mash || !beer.mash.properties) {
return undefined;
}
var maltWeight = 0;
for (var index in beer.ingredients.malts) {
var malt = beer.ingredients.malts[index];
if ((malt.type === 'malt' || malt.type === 'husk') && malt.recommendMash) {
maltWeight += malt.amount;
}
}
return (maltWeight / beer.mash.properties.waterGrainRation)
};
$scope.getDecoctionVolume = function(step, beer) {
var decoctionStep = 0;
var addedVolume = 0;
for (var j in beer.mash.steps) {
if (beer.mash.steps[j].type === 'temperature' || beer.mash.steps[j].type === 'infusion' ) {
addedVolume += beer.mash.steps[j].waterToAdd;
}
}
for (var i in beer.mash.steps) {
if (beer.mash.steps[i].type === 'decoction') {
if (beer.mash.steps[i] === step) {
return (1 / (3 + i)) * addedVolume;
}
i++;
}
}
};
if ($scope.beer.mash.steps && $scope.beer.mash.steps.length > 0) {
$scope.stepOne = $scope.beer.mash.steps[0];
}
});
angular.module('beerCreator.directives').directive('mashInstructions', function() {
return {
restrict: 'E',
replace: true,
controller: 'MashInstructionsCtrl',
scope: {
beer: '='
},
templateUrl: 'directives/mashInstructions/mashInstructions.html',
link: function(scope, element, attrs, fn) {
}
};
}); |
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = mongoose.Schema.Types.ObjectId;
var CardSchema = new Schema({
username: { type: String, unique: true},
author: String,
title: String,
body: String
});
var Card = mongoose.model('Card',CardSchema); //creating database collection(table)
var cardMethods = {};
cardMethods.add = function(body, callback) {
var newCard = new Card(body);
newCard.save(callback);
};
cardMethods.get = function(body, callback) {
Card.find(body, callback);
};
cardMethods.update = function(old, updated, callback) {
Card.findOneAndUpdate(old, updated, callback);
};
cardMethods.remove = function(body, callback) {
Card.remove(body, callback);
// Card.findOneAndRemove(body, callback);
};
module.exports = cardMethods;
|
/// <module name=elquire.BadNamespace.module>
|
var searchData=
[
['sir_5fdefault_5fstyles',['sir_default_styles',['../da/df8/group__custom.html#gaab713b2ff4a81272aad35de4b59a0af0',1,'sirdefaults.h']]],
['sir_5ffile_5fdef_5flvls',['sir_file_def_lvls',['../da/df8/group__custom.html#ga1337de627cb0dd234f34b07b4d77a931',1,'sirdefaults.h']]],
['sir_5ffile_5fdef_5fopts',['sir_file_def_opts',['../da/df8/group__custom.html#ga7b82b6fc3f0701c4db31d05a0b7a17ba',1,'sirdefaults.h']]],
['sir_5foverride_5fstyles',['sir_override_styles',['../d0/dfe/group__intern.html#ga53ad3bc02bfc1e709c51f57be7cada23',1,'sirtextstyle.h']]],
['sir_5fpriv_5fmap',['sir_priv_map',['../d0/dfe/group__intern.html#gae3e5b45bf488fbf366f61a1c903a74b1',1,'sirtextstyle.h']]],
['sir_5fstderr_5fdef_5flvls',['sir_stderr_def_lvls',['../da/df8/group__custom.html#ga0c89af75ec9acb60d1160fa6cabb82dc',1,'sirdefaults.h']]],
['sir_5fstderr_5fdef_5fopts',['sir_stderr_def_opts',['../da/df8/group__custom.html#ga6175606145e324da9dfb3011c2a02b74',1,'sirdefaults.h']]],
['sir_5fstdout_5fdef_5flvls',['sir_stdout_def_lvls',['../da/df8/group__custom.html#ga47b9f4b74ed2b3d81d34c0d0237b100f',1,'sirdefaults.h']]],
['sir_5fstdout_5fdef_5fopts',['sir_stdout_def_opts',['../da/df8/group__custom.html#ga570e5f904a2aacfaf3284276784d4ddb',1,'sirdefaults.h']]],
['sir_5fsyslog_5fdef_5flvls',['sir_syslog_def_lvls',['../da/df8/group__custom.html#ga7a0b53f25f5140db6a320d815097e268',1,'sirdefaults.h']]],
['sir_5fte',['sir_te',['../d6/d87/group__errors.html#ga9b90b7b0b86e5db5c56e00e180ad2209',1,'sirerrors.c']]],
['style',['style',['../df/d50/structsir__style__map.html#ab541a2f9197fbddaf60f9578ad4aa551',1,'sir_style_map']]]
];
|
/* jslint node: true */
'use strict';
var _ = require('lodash');
var TraversalTracker = require('./traversalTracker');
var DocMeasure = require('./docMeasure');
var DocumentContext = require('./documentContext');
var PageElementWriter = require('./pageElementWriter');
var ColumnCalculator = require('./columnCalculator');
var TableProcessor = require('./tableProcessor');
var Line = require('./line');
var pack = require('./helpers').pack;
var offsetVector = require('./helpers').offsetVector;
var fontStringify = require('./helpers').fontStringify;
var isFunction = require('./helpers').isFunction;
var TextTools = require('./textTools');
var StyleContextStack = require('./styleContextStack');
function addAll(target, otherArray) {
_.each(otherArray, function (item) {
target.push(item);
});
}
/**
* Creates an instance of LayoutBuilder - layout engine which turns document-definition-object
* into a set of pages, lines, inlines and vectors ready to be rendered into a PDF
*
* @param {Object} pageSize - an object defining page width and height
* @param {Object} pageMargins - an object defining top, left, right and bottom margins
*/
function LayoutBuilder(pageSize, pageMargins, imageMeasure) {
this.pageSize = pageSize;
this.pageMargins = pageMargins;
this.tracker = new TraversalTracker();
this.imageMeasure = imageMeasure;
this.tableLayouts = {};
}
LayoutBuilder.prototype.registerTableLayouts = function (tableLayouts) {
this.tableLayouts = pack(this.tableLayouts, tableLayouts);
};
/**
* Executes layout engine on document-definition-object and creates an array of pages
* containing positioned Blocks, Lines and inlines
*
* @param {Object} docStructure document-definition-object
* @param {Object} fontProvider font provider
* @param {Object} styleDictionary dictionary with style definitions
* @param {Object} defaultStyle default style definition
* @return {Array} an array of pages
*/
LayoutBuilder.prototype.layoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
function addPageBreaksIfNecessary(linearNodeList, pages) {
if (!isFunction(pageBreakBeforeFct)) {
return false;
}
linearNodeList = _.reject(linearNodeList, function (node) {
return _.isEmpty(node.positions);
});
_.each(linearNodeList, function (node) {
var nodeInfo = _.pick(node, [
'id', 'text', 'ul', 'ol', 'table', 'image', 'qr', 'canvas', 'columns',
'headlineLevel', 'style', 'pageBreak', 'pageOrientation',
'width', 'height'
]);
nodeInfo.startPosition = _.first(node.positions);
nodeInfo.pageNumbers = _.chain(node.positions).map('pageNumber').uniq().value();
nodeInfo.pages = pages.length;
nodeInfo.stack = _.isArray(node.stack);
node.nodeInfo = nodeInfo;
});
return _.some(linearNodeList, function (node, index, followingNodeList) {
if (node.pageBreak !== 'before' && !node.pageBreakCalculated) {
node.pageBreakCalculated = true;
var pageNumber = _.first(node.nodeInfo.pageNumbers);
var followingNodesOnPage = _.chain(followingNodeList).drop(index + 1).filter(function (node0) {
return _.includes(node0.nodeInfo.pageNumbers, pageNumber);
}).value();
var nodesOnNextPage = _.chain(followingNodeList).drop(index + 1).filter(function (node0) {
return _.includes(node0.nodeInfo.pageNumbers, pageNumber + 1);
}).value();
var previousNodesOnPage = _.chain(followingNodeList).take(index).filter(function (node0) {
return _.includes(node0.nodeInfo.pageNumbers, pageNumber);
}).value();
if (pageBreakBeforeFct(node.nodeInfo,
_.map(followingNodesOnPage, 'nodeInfo'),
_.map(nodesOnNextPage, 'nodeInfo'),
_.map(previousNodesOnPage, 'nodeInfo'))) {
node.pageBreak = 'before';
return true;
}
}
});
}
this.docMeasure = new DocMeasure(fontProvider, styleDictionary, defaultStyle, this.imageMeasure, this.tableLayouts, images);
function resetXYs(result) {
_.each(result.linearNodeList, function (node) {
node.resetXY();
});
}
var result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
while (addPageBreaksIfNecessary(result.linearNodeList, result.pages)) {
resetXYs(result);
result = this.tryLayoutDocument(docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark);
}
return result.pages;
};
LayoutBuilder.prototype.tryLayoutDocument = function (docStructure, fontProvider, styleDictionary, defaultStyle, background, header, footer, images, watermark, pageBreakBeforeFct) {
this.linearNodeList = [];
docStructure = this.docMeasure.measureDocument(docStructure);
this.writer = new PageElementWriter(
new DocumentContext(this.pageSize, this.pageMargins), this.tracker);
var _this = this;
this.writer.context().tracker.startTracking('pageAdded', function () {
_this.addBackground(background);
});
this.addBackground(background);
this.processNode(docStructure);
this.addHeadersAndFooters(header, footer);
/* jshint eqnull:true */
if (watermark != null) {
this.addWatermark(watermark, fontProvider, defaultStyle);
}
return {pages: this.writer.context().pages, linearNodeList: this.linearNodeList};
};
LayoutBuilder.prototype.addBackground = function (background) {
var backgroundGetter = isFunction(background) ? background : function () {
return background;
};
var pageBackground = backgroundGetter(this.writer.context().page + 1);
if (pageBackground) {
var pageSize = this.writer.context().getCurrentPage().pageSize;
this.writer.beginUnbreakableBlock(pageSize.width, pageSize.height);
this.processNode(this.docMeasure.measureDocument(pageBackground));
this.writer.commitUnbreakableBlock(0, 0);
}
};
LayoutBuilder.prototype.addStaticRepeatable = function (headerOrFooter, sizeFunction) {
this.addDynamicRepeatable(function () {
return headerOrFooter;
}, sizeFunction);
};
LayoutBuilder.prototype.addDynamicRepeatable = function (nodeGetter, sizeFunction) {
var pages = this.writer.context().pages;
for (var pageIndex = 0, l = pages.length; pageIndex < l; pageIndex++) {
this.writer.context().page = pageIndex;
var node = nodeGetter(pageIndex + 1, l, this.writer.context().pages[pageIndex].pageSize);
if (node) {
var sizes = sizeFunction(this.writer.context().getCurrentPage().pageSize, this.pageMargins);
this.writer.beginUnbreakableBlock(sizes.width, sizes.height);
this.processNode(this.docMeasure.measureDocument(node));
this.writer.commitUnbreakableBlock(sizes.x, sizes.y);
}
}
};
LayoutBuilder.prototype.addHeadersAndFooters = function (header, footer) {
var headerSizeFct = function (pageSize, pageMargins) {
return {
x: 0,
y: 0,
width: pageSize.width,
height: pageMargins.top
};
};
var footerSizeFct = function (pageSize, pageMargins) {
return {
x: 0,
y: pageSize.height - pageMargins.bottom,
width: pageSize.width,
height: pageMargins.bottom
};
};
if (isFunction(header)) {
this.addDynamicRepeatable(header, headerSizeFct);
} else if (header) {
this.addStaticRepeatable(header, headerSizeFct);
}
if (isFunction(footer)) {
this.addDynamicRepeatable(footer, footerSizeFct);
} else if (footer) {
this.addStaticRepeatable(footer, footerSizeFct);
}
};
LayoutBuilder.prototype.addWatermark = function (watermark, fontProvider, defaultStyle) {
if (typeof watermark === 'string') {
watermark = {'text': watermark};
}
if (!watermark.text) { // empty watermark text
return;
}
watermark.font = watermark.font || defaultStyle.font || 'Roboto';
watermark.color = watermark.color || 'black';
watermark.opacity = watermark.opacity || 0.6;
watermark.bold = watermark.bold || false;
watermark.italics = watermark.italics || false;
var watermarkObject = {
text: watermark.text,
font: fontProvider.provideFont(watermark.font, watermark.bold, watermark.italics),
size: getSize(this.pageSize, watermark, fontProvider),
color: watermark.color,
opacity: watermark.opacity
};
var pages = this.writer.context().pages;
for (var i = 0, l = pages.length; i < l; i++) {
pages[i].watermark = watermarkObject;
}
function getSize(pageSize, watermark, fontProvider) {
var width = pageSize.width;
var height = pageSize.height;
var targetWidth = Math.sqrt(width * width + height * height) * 0.8; /* page diagonal * sample factor */
var textTools = new TextTools(fontProvider);
var styleContextStack = new StyleContextStack(null, {font: watermark.font, bold: watermark.bold, italics: watermark.italics});
var size;
/**
* Binary search the best font size.
* Initial bounds [0, 1000]
* Break when range < 1
*/
var a = 0;
var b = 1000;
var c = (a + b) / 2;
while (Math.abs(a - b) > 1) {
styleContextStack.push({
fontSize: c
});
size = textTools.sizeOfString(watermark.text, styleContextStack);
if (size.width > targetWidth) {
b = c;
c = (a + b) / 2;
} else if (size.width < targetWidth) {
a = c;
c = (a + b) / 2;
}
styleContextStack.pop();
}
/*
End binary search
*/
return {size: size, fontSize: c};
}
};
function decorateNode(node) {
var x = node.x, y = node.y;
node.positions = [];
_.each(node.canvas, function (vector) {
var x = vector.x, y = vector.y, x1 = vector.x1, y1 = vector.y1, x2 = vector.x2, y2 = vector.y2;
vector.resetXY = function () {
vector.x = x;
vector.y = y;
vector.x1 = x1;
vector.y1 = y1;
vector.x2 = x2;
vector.y2 = y2;
};
});
node.resetXY = function () {
node.x = x;
node.y = y;
_.each(node.canvas, function (vector) {
vector.resetXY();
});
};
}
LayoutBuilder.prototype.processNode = function (node) {
var self = this;
this.linearNodeList.push(node);
decorateNode(node);
applyMargins(function () {
var absPosition = node.absolutePosition;
if (absPosition) {
self.writer.context().beginDetachedBlock();
self.writer.context().moveTo(absPosition.x || 0, absPosition.y || 0);
}
var relPosition = node.relativePosition;
if (relPosition) {
self.writer.context().beginDetachedBlock();
self.writer.context().moveTo((relPosition.x || 0) + self.writer.context().x, (relPosition.y || 0) + self.writer.context().y);
}
if (node.stack) {
self.processVerticalContainer(node);
} else if (node.columns) {
self.processColumns(node);
} else if (node.ul) {
self.processList(false, node);
} else if (node.ol) {
self.processList(true, node);
} else if (node.table) {
self.processTable(node);
} else if (node.text !== undefined) {
self.processLeaf(node);
} else if (node.image) {
self.processImage(node);
} else if (node.canvas) {
self.processCanvas(node);
} else if (node.qr) {
self.processQr(node);
} else if (!node._span) {
throw 'Unrecognized document structure: ' + JSON.stringify(node, fontStringify);
}
if (absPosition || relPosition) {
self.writer.context().endDetachedBlock();
}
});
function applyMargins(callback) {
var margin = node._margin;
if (node.pageBreak === 'before') {
self.writer.moveToNextPage(node.pageOrientation);
}
if (margin) {
self.writer.context().moveDown(margin[1]);
self.writer.context().addMargin(margin[0], margin[2]);
}
callback();
if (margin) {
self.writer.context().addMargin(-margin[0], -margin[2]);
self.writer.context().moveDown(margin[3]);
}
if (node.pageBreak === 'after') {
self.writer.moveToNextPage(node.pageOrientation);
}
}
};
// vertical container
LayoutBuilder.prototype.processVerticalContainer = function (node) {
var self = this;
node.stack.forEach(function (item) {
self.processNode(item);
addAll(node.positions, item.positions);
//TODO: paragraph gap
});
};
// columns
LayoutBuilder.prototype.processColumns = function (columnNode) {
var columns = columnNode.columns;
var availableWidth = this.writer.context().availableWidth;
var gaps = gapArray(columnNode._gap);
if (gaps) {
availableWidth -= (gaps.length - 1) * columnNode._gap;
}
ColumnCalculator.buildColumnWidths(columns, availableWidth);
var result = this.processRow(columns, columns, gaps);
addAll(columnNode.positions, result.positions);
function gapArray(gap) {
if (!gap) {
return null;
}
var gaps = [];
gaps.push(0);
for (var i = columns.length - 1; i > 0; i--) {
gaps.push(gap);
}
return gaps;
}
};
LayoutBuilder.prototype.processRow = function (columns, widths, gaps, tableBody, tableRow) {
var self = this;
var pageBreaks = [], positions = [];
this.tracker.auto('pageChanged', storePageBreakData, function () {
widths = widths || columns;
self.writer.context().beginColumnGroup();
for (var i = 0, l = columns.length; i < l; i++) {
var column = columns[i];
var width = widths[i]._calcWidth;
var leftOffset = colLeftOffset(i);
if (column.colSpan && column.colSpan > 1) {
for (var j = 1; j < column.colSpan; j++) {
width += widths[++i]._calcWidth + gaps[i];
}
}
self.writer.context().beginColumn(width, leftOffset, getEndingCell(column, i));
if (!column._span) {
self.processNode(column);
addAll(positions, column.positions);
} else if (column._columnEndingContext) {
// row-span ending
self.writer.context().markEnding(column);
}
}
self.writer.context().completeColumnGroup();
});
return {pageBreaks: pageBreaks, positions: positions};
function storePageBreakData(data) {
var pageDesc;
for (var i = 0, l = pageBreaks.length; i < l; i++) {
var desc = pageBreaks[i];
if (desc.prevPage === data.prevPage) {
pageDesc = desc;
break;
}
}
if (!pageDesc) {
pageDesc = data;
pageBreaks.push(pageDesc);
}
pageDesc.prevY = Math.max(pageDesc.prevY, data.prevY);
pageDesc.y = Math.min(pageDesc.y, data.y);
}
function colLeftOffset(i) {
if (gaps && gaps.length > i) {
return gaps[i];
}
return 0;
}
function getEndingCell(column, columnIndex) {
if (column.rowSpan && column.rowSpan > 1) {
var endingRow = tableRow + column.rowSpan - 1;
if (endingRow >= tableBody.length) {
throw 'Row span for column ' + columnIndex + ' (with indexes starting from 0) exceeded row count';
}
return tableBody[endingRow][columnIndex];
}
return null;
}
};
// lists
LayoutBuilder.prototype.processList = function (orderedList, node) {
var self = this,
items = orderedList ? node.ol : node.ul,
gapSize = node._gapSize;
this.writer.context().addMargin(gapSize.width);
var nextMarker;
this.tracker.auto('lineAdded', addMarkerToFirstLeaf, function () {
items.forEach(function (item) {
nextMarker = item.listMarker;
self.processNode(item);
addAll(node.positions, item.positions);
});
});
this.writer.context().addMargin(-gapSize.width);
function addMarkerToFirstLeaf(line) {
// I'm not very happy with the way list processing is implemented
// (both code and algorithm should be rethinked)
if (nextMarker) {
var marker = nextMarker;
nextMarker = null;
if (marker.canvas) {
var vector = marker.canvas[0];
offsetVector(vector, -marker._minWidth, 0);
self.writer.addVector(vector);
} else {
var markerLine = new Line(self.pageSize.width);
markerLine.addInline(marker._inlines[0]);
markerLine.x = -marker._minWidth;
markerLine.y = line.getAscenderHeight() - markerLine.getAscenderHeight();
self.writer.addLine(markerLine, true);
}
}
}
};
// tables
LayoutBuilder.prototype.processTable = function (tableNode) {
var processor = new TableProcessor(tableNode);
processor.beginTable(this.writer);
for (var i = 0, l = tableNode.table.body.length; i < l; i++) {
processor.beginRow(i, this.writer);
var result = this.processRow(tableNode.table.body[i], tableNode.table.widths, tableNode._offsets.offsets, tableNode.table.body, i);
addAll(tableNode.positions, result.positions);
processor.endRow(i, this.writer, result.pageBreaks);
}
processor.endTable(this.writer);
};
// leafs (texts)
LayoutBuilder.prototype.processLeaf = function (node) {
var line = this.buildNextLine(node);
var currentHeight = (line) ? line.getHeight() : 0;
var maxHeight = node.maxHeight || -1;
while (line && (maxHeight === -1 || currentHeight < maxHeight)) {
var positions = this.writer.addLine(line);
node.positions.push(positions);
line = this.buildNextLine(node);
if (line) {
currentHeight += line.getHeight();
}
}
};
LayoutBuilder.prototype.buildNextLine = function (textNode) {
if (!textNode._inlines || textNode._inlines.length === 0) {
return null;
}
var line = new Line(this.writer.context().availableWidth);
while (textNode._inlines && textNode._inlines.length > 0 && line.hasEnoughSpaceForInline(textNode._inlines[0])) {
line.addInline(textNode._inlines.shift());
}
line.lastLineInParagraph = textNode._inlines.length === 0;
return line;
};
// images
LayoutBuilder.prototype.processImage = function (node) {
var position = this.writer.addImage(node);
node.positions.push(position);
};
LayoutBuilder.prototype.processCanvas = function (node) {
var height = node._minHeight;
if (this.writer.context().availableHeight < height) {
// TODO: support for canvas larger than a page
// TODO: support for other overflow methods
this.writer.moveToNextPage();
}
node.canvas.forEach(function (vector) {
var position = this.writer.addVector(vector);
node.positions.push(position);
}, this);
this.writer.context().moveDown(height);
};
LayoutBuilder.prototype.processQr = function (node) {
var position = this.writer.addQr(node);
node.positions.push(position);
};
module.exports = LayoutBuilder;
|
import { connect } from 'react-redux';
import actions from 'src/actions';
import { Header } from './header';
const { setDefaultSettings } = actions;
const mapStateToProps = (state) => {
return {
user: state.user
};
};
const mapDispatchToProps = (dispatch) => {
return {
onSettingsClick: () => {
dispatch(setDefaultSettings());
}
};
};
const HeaderContainer = connect(
mapStateToProps,
mapDispatchToProps
)(Header);
export default HeaderContainer;
|
const runSift = require(`../run-sift`)
const {
GraphQLObjectType,
GraphQLNonNull,
GraphQLID,
GraphQLString,
GraphQLList,
} = require(`graphql`)
jest.mock(`../../db/node-tracking`, () => {
return {
trackInlineObjectsInRootNode: () => jest.fn(),
}
})
const mockNodes = [
{
id: `id_1`,
string: `foo`,
internal: {
type: `notTest`,
},
},
{
id: `id_2`,
string: `bar`,
internal: {
type: `test`,
},
},
{
id: `id_3`,
string: `baz`,
internal: {
type: `test`,
},
},
{
id: `id_4`,
string: `qux`,
internal: {
type: `test`,
},
first: {
willBeResolved: `willBeResolved`,
second: [
{
willBeResolved: `willBeResolved`,
third: {
foo: `foo`,
},
},
],
},
},
]
jest.mock(`../../db/nodes`, () => {
return {
getNode: id => mockNodes.find(node => node.id === id),
getNodesByType: type =>
mockNodes.filter(node => node.internal.type === type),
}
})
describe(`run-sift`, () => {
const typeName = `test`
const gqlType = new GraphQLObjectType({
name: typeName,
fields: () => {
return {
id: { type: new GraphQLNonNull(GraphQLID) },
string: { type: GraphQLString },
first: {
type: new GraphQLObjectType({
name: `First`,
fields: {
willBeResolved: {
type: GraphQLString,
resolve: () => `resolvedValue`,
},
second: {
type: new GraphQLList(
new GraphQLObjectType({
name: `Second`,
fields: {
willBeResolved: {
type: GraphQLString,
resolve: () => `resolvedValue`,
},
third: new GraphQLObjectType({
name: `Third`,
fields: {
foo: GraphQLString,
},
}),
},
})
),
},
},
}),
},
}
},
})
const nodes = mockNodes
describe(`filters by just id correctly`, () => {
it(`eq operator`, async () => {
const queryArgs = {
filter: {
id: { eq: `id_2` },
},
}
const resultSingular = await runSift({
gqlType,
queryArgs,
firstOnly: true,
})
const resultMany = await runSift({
gqlType,
queryArgs,
firstOnly: false,
})
expect(resultSingular).toEqual([nodes[1]])
expect(resultMany).toEqual([nodes[1]])
})
it(`eq operator honors type`, async () => {
const queryArgs = {
filter: {
id: { eq: `id_1` },
},
}
const resultSingular = await runSift({
gqlType,
queryArgs,
firstOnly: true,
})
const resultMany = await runSift({
gqlType,
queryArgs,
firstOnly: false,
})
// `id-1` node is not of queried type, so results should be empty
expect(resultSingular).toEqual([])
expect(resultMany).toEqual(null)
})
it(`non-eq operator`, async () => {
const queryArgs = {
filter: {
id: { ne: `id_2` },
},
}
const resultSingular = await runSift({
gqlType,
queryArgs,
firstOnly: true,
})
const resultMany = await runSift({
gqlType,
queryArgs,
firstOnly: false,
})
expect(resultSingular).toEqual([nodes[2]])
expect(resultMany).toEqual([nodes[2], nodes[3]])
})
})
it(`resolves fields before querying`, async () => {
const queryArgs = {
filter: {
first: {
willBeResolved: { eq: `resolvedValue` },
second: {
elemMatch: {
willBeResolved: { eq: `resolvedValue` },
third: {
foo: { eq: `foo` },
},
},
},
},
},
}
const results = await runSift({
gqlType,
queryArgs,
firstOnly: true,
})
expect(results[0].id).toBe(`id_4`)
})
})
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
var cc = cc || {};
/**
* A simple Audio Engine engine API.
* @class
* @extends cc.Class
*/
cc.AudioEngine = cc.Class.extend(/** @lends cc.AudioEngine# */{
_audioID:0,
_audioIDList:null,
ctor:function(){
this._audioIDList = {};
},
/**
* Check each type to see if it can be played by current browser
* @param {Object} capabilities The results are filled into this dict
* @protected
*/
_checkCanPlay: function(capabilities) {
var au = document.createElement('audio');
if (au.canPlayType) {
// <audio> tag is supported, go on
var _check = function(typeStr) {
var result = au.canPlayType(typeStr);
return result != "no" && result != "";
};
capabilities.mp3 = _check("audio/mpeg");
capabilities.mp4 = _check("audio/mp4");
capabilities.m4a = _check("audio/x-m4a") || _check("audio/aac");
capabilities.ogg = _check('audio/ogg; codecs="vorbis"');
capabilities.wav = _check('audio/wav; codecs="1"');
} else {
// <audio> tag is not supported, nothing is supported
var formats = ['mp3', 'mp4', 'm4a', 'ogg', 'wav'];
for (var idx in formats) {
capabilities[formats[idx]] = false;
}
}
},
/**
* Helper function for cutting out the extension from the path
* @param {String} fullpath
* @protected
*/
_getPathWithoutExt: function (fullpath) {
if (typeof(fullpath) != "string") {
return;
}
var endPos = fullpath.lastIndexOf(".");
if (endPos != -1) {
return fullpath.substring(0, endPos);
}
return fullpath;
},
/**
* Helper function for extracting the extension from the path
* @param {String} fullpath
* @protected
*/
_getExtFromFullPath: function (fullpath) {
var startPos = fullpath.lastIndexOf(".");
if (startPos != -1) {
return fullpath.substring(startPos + 1, fullpath.length);
}
return -1;
}
});
/**
* the entity stored in soundList and effectList, containing the audio element and the extension name.
* used in cc.SimpleAudioEngine
*/
cc.SimpleSFX = function (audio, ext) {
this.audio = audio;
this.ext = ext || ".ogg";
};
/**
* The Audio Engine implementation via <audio> tag in HTML5.
* @class
* @extends cc.AudioEngine
*/
cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */{
_supportedFormat:[],
_soundEnable:false,
_effectList:{},
_soundList:{},
_playingMusic:null,
_effectsVolume:1,
_maxAudioInstance:10,
_canPlay:true,
_capabilities:{
mp3:false,
ogg:false,
wav:false,
mp4:false,
m4a:false
},
/**
* Constructor
*/
ctor:function () {
cc.AudioEngine.prototype.ctor.call(this);
this._supportedFormat = [];
this._checkCanPlay(this._capabilities);
// enable sound if any of the audio format is supported
this._soundEnable = this._capabilities.mp3 || this._capabilities.mp4
|| this._capabilities.m4a || this._capabilities.ogg
|| this._capabilities.wav;
var ua = navigator.userAgent;
if(/Mobile/.test(ua) && (/iPhone OS/.test(ua)||/iPad/.test(ua)||/Firefox/.test(ua)) || /MSIE/.test(ua)){
this._canPlay = false;
}
},
/**
* Initialize sound type
* @return {Boolean}
*/
init:function () {
// detect the prefered audio format
this._getSupportedAudioFormat();
return this._soundEnable;
},
/**
* Preload music resource.<br />
* This method is called when cc.Loader preload resources.
* @param {String} path The path of the music file with filename extension.
*/
preloadSound:function (path) {
if (this._soundEnable) {
var extName = this._getExtFromFullPath(path);
var keyname = this._getPathWithoutExt(path);
if (this.isFormatSupported(extName) && !this._soundList.hasOwnProperty(keyname)) {
if(this._canPlay){
var sfxCache = new cc.SimpleSFX();
sfxCache.ext = extName;
sfxCache.audio = new Audio(path);
sfxCache.audio.preload = 'auto';
sfxCache.audio.addEventListener('canplaythrough', function (e) {
cc.Loader.getInstance().onResLoaded();
this.removeEventListener('canplaythrough', arguments.callee, false);
}, false);
sfxCache.audio.addEventListener("error", function (e) {
cc.Loader.getInstance().onResLoadingErr(e.srcElement.src);
this.removeEventListener('error', arguments.callee, false);
}, false);
this._soundList[keyname] = sfxCache;
sfxCache.audio.load();
}
else{
cc.Loader.getInstance().onResLoaded();
}
}
else {
cc.Loader.getInstance().onResLoaded();
}
}
//cc.Loader.getInstance().onResLoaded();
},
/**
* Play music.
* @param {String} path The path of the music file without filename extension.
* @param {Boolean} loop Whether the music loop or not.
* @example
* //example
* cc.AudioEngine.getInstance().playMusic(path, false);
*/
playMusic:function (path, loop) {
var keyname = this._getPathWithoutExt(path);
var extName = this._getExtFromFullPath(path);
var au;
if (this._soundList.hasOwnProperty(this._playingMusic)) {
this._soundList[this._playingMusic].audio.pause();
}
this._playingMusic = keyname;
if (this._soundList.hasOwnProperty(this._playingMusic)) {
au = this._soundList[this._playingMusic].audio;
}
else {
var sfxCache = new cc.SimpleSFX();
sfxCache.ext = extName;
au = sfxCache.audio = new Audio(path);
sfxCache.audio.preload = 'auto';
this._soundList[keyname] = sfxCache;
sfxCache.audio.load();
}
au.addEventListener("pause", this._musicListener , false);
au.loop = loop || false;
au.play();
cc.AudioEngine.isMusicPlaying = true;
},
_musicListener:function(e){
cc.AudioEngine.isMusicPlaying = false;
this.removeEventListener('pause', arguments.callee, false);
},
/**
* Stop playing music.
* @param {Boolean} releaseData If release the music data or not.As default value is false.
* @example
* //example
* cc.AudioEngine.getInstance().stopMusic();
*/
stopMusic:function (releaseData) {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
var au = this._soundList[this._playingMusic].audio;
au.pause();
au.currentTime = au.duration;
if (releaseData) {
delete this._soundList[this._playingMusic];
}
cc.AudioEngine.isMusicPlaying = false;
}
},
/**
* Pause playing music.
* @example
* //example
* cc.AudioEngine.getInstance().pauseMusic();
*/
pauseMusic:function () {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
var au = this._soundList[this._playingMusic].audio;
au.pause();
cc.AudioEngine.isMusicPlaying = false;
}
},
/**
* Resume playing music.
* @example
* //example
* cc.AudioEngine.getInstance().resumeMusic();
*/
resumeMusic:function () {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
var au = this._soundList[this._playingMusic].audio;
au.play();
au.addEventListener("pause", this._musicListener , false);
cc.AudioEngine.isMusicPlaying = true;
}
},
/**
* Rewind playing music.
* @example
* //example
* cc.AudioEngine.getInstance().rewindMusic();
*/
rewindMusic:function () {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
var au = this._soundList[this._playingMusic].audio;
au.currentTime = 0;
au.play();
au.addEventListener("pause", this._musicListener , false);
cc.AudioEngine.isMusicPlaying = true;
}
},
willPlayMusic:function () {
return false;
},
/**
* The volume of the music max value is 1.0,the min value is 0.0 .
* @return {Number}
* @example
* //example
* var volume = cc.AudioEngine.getInstance().getMusicVolume();
*/
getMusicVolume:function () {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
return this._soundList[this._playingMusic].audio.volume;
}
return 0;
},
/**
* Set the volume of music.
* @param {Number} volume Volume must be in 0.0~1.0 .
* @example
* //example
* cc.AudioEngine.getInstance().setMusicVolume(0.5);
*/
setMusicVolume:function (volume) {
if (this._soundList.hasOwnProperty(this._playingMusic)) {
var music = this._soundList[this._playingMusic].audio;
if (volume > 1) {
music.volume = 1;
}
else if (volume < 0) {
music.volume = 0;
}
else {
music.volume = volume;
}
}
},
/**
* Whether the music is playing.
* @return {Boolean} If is playing return true,or return false.
* @example
* //example
* if (cc.AudioEngine.getInstance().isMusicPlaying()) {
* cc.log("music is playing");
* }
* else {
* cc.log("music is not playing");
* }
*/
isMusicPlaying: function () {
return cc.AudioEngine.isMusicPlaying;
},
/**
* Play sound effect.
* @param {String} path The path of the sound effect with filename extension.
* @param {Boolean} loop Whether to loop the effect playing, default value is false
* @example
* //example
* var soundId = cc.AudioEngine.getInstance().playEffect(path);
*/
playEffect:function (path, loop) {
var keyname = this._getPathWithoutExt(path), actExt;
if (this._soundList.hasOwnProperty(keyname)) {
actExt = this._soundList[keyname].ext;
}
else {
actExt = this._getExtFromFullPath(path);
}
var reclaim = this._getEffectList(keyname), au;
if (reclaim.length > 0) {
for (var i = 0; i < reclaim.length; i++) {
//if one of the effect ended, play it
if (reclaim[i].ended) {
au = reclaim[i];
au.currentTime = 0;
break;
}
}
}
if (!au) {
if (reclaim.length >= this._maxAudioInstance) {
cc.log("Error: " + path + " greater than " + this._maxAudioInstance);
return path;
}
au = new Audio(keyname + "." + actExt);
au.volume = this._effectsVolume;
reclaim.push(au);
}
if (loop) {
au.loop = loop;
}
au.play();
var audioID = this._audioID++;
this._audioIDList[audioID] = au;
return audioID;
},
/**
*The volume of the effects max value is 1.0,the min value is 0.0 .
* @return {Number}
* @example
* //example
* var effectVolume = cc.AudioEngine.getInstance().getEffectsVolume();
*/
getEffectsVolume:function () {
return this._effectsVolume;
},
/**
* Set the volume of sound effecs.
* @param {Number} volume Volume must be in 0.0~1.0 .
* @example
* //example
* cc.AudioEngine.getInstance().setEffectsVolume(0.5);
*/
setEffectsVolume:function (volume) {
if (volume > 1) {
this._effectsVolume = 1;
}
else if (volume < 0) {
this._effectsVolume = 0;
}
else {
this._effectsVolume = volume;
}
var tmpArr, au;
for (var i in this._effectList) {
tmpArr = this._effectList[i];
if (tmpArr.length > 0) {
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
au.volume = this._effectsVolume;
}
}
}
},
/**
* Pause playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @example
* //example
* cc.AudioEngine.getInstance().pauseEffect(audioID);
*/
pauseEffect:function (audioID) {
if (audioID == null) return;
if (this._audioIDList.hasOwnProperty(audioID)) {
var au = this._audioIDList[audioID];
if (!au.ended) {
au.pause();
}
}
},
/**
* Pause all playing sound effect.
* @example
* //example
* cc.AudioEngine.getInstance().pauseAllEffects();
*/
pauseAllEffects:function () {
var tmpArr, au;
for (var i in this._effectList) {
tmpArr = this._effectList[i];
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
if (!au.ended) {
au.pause();
}
}
}
},
/**
* Resume playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @audioID
* //example
* cc.AudioEngine.getInstance().resumeEffect(audioID);
*/
resumeEffect:function (audioID) {
if (audioID == null) return;
if (this._audioIDList.hasOwnProperty(audioID)) {
var au = this._audioIDList[audioID];
if (!au.ended) {
au.play();
}
}
},
/**
* Resume all playing sound effect
* @example
* //example
* cc.AudioEngine.getInstance().resumeAllEffects();
*/
resumeAllEffects:function () {
var tmpArr, au;
for (var i in this._effectList) {
tmpArr = this._effectList[i];
if (tmpArr.length > 0) {
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
if (!au.ended) {
au.play();
}
}
}
}
},
/**
* Stop playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @example
* //example
* cc.AudioEngine.getInstance().stopEffect(audioID);
*/
stopEffect:function (audioID) {
if (audioID == null) return;
if (this._audioIDList.hasOwnProperty(audioID)) {
var au = this._audioIDList[audioID];
if (!au.ended) {
au.loop = false;
au.currentTime = au.duration;
}
}
},
/**
* Stop all playing sound effects.
* @example
* //example
* cc.AudioEngine.getInstance().stopAllEffects();
*/
stopAllEffects:function () {
var tmpArr, au;
for (var i in this._effectList) {
tmpArr = this._effectList[i];
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
if (!au.ended) {
au.loop = false;
au.currentTime = au.duration;
}
}
}
},
/**
* Unload the preloaded effect from internal buffer
* @param {String} path
* @example
* //example
* cc.AudioEngine.getInstance().unloadEffect(EFFECT_FILE);
*/
unloadEffect:function (path) {
if (!path) return;
var keyname = this._getPathWithoutExt(path);
if (this._effectList.hasOwnProperty(keyname)) {
this.stopEffect(path);
delete this._effectList[keyname];
}
var au,pathName;
for (var k in this._audioIDList) {
au = this._audioIDList[k];
pathName = this._getPathWithoutExt(au.src);
if(pathName == keyname){
delete this._audioIDList[k];
}
}
},
_getEffectList:function (elt) {
if (this._effectList.hasOwnProperty(elt)) {
return this._effectList[elt];
}
else {
this._effectList[elt] = [];
return this._effectList[elt];
}
},
/**
* search in this._supportedFormat if @param ext is there
* @param {String} ext
* @returns {Boolean}
*/
isFormatSupported:function (ext) {
var tmpExt;
for (var i = 0; i < this._supportedFormat.length; i++) {
tmpExt = this._supportedFormat[i];
if (tmpExt == ext) {
return true;
}
}
return false;
},
_getSupportedAudioFormat:function () {
// check for sound support by the browser
if (!this._soundEnable) {
return;
}
var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a'];
for (var idx in formats) {
var name = formats[idx];
if (this._capabilities[name]) {
this._supportedFormat.push(name);
}
}
}
});
/**
* The entity stored in cc.WebAudioEngine, representing a sound object
*/
cc.WebAudioSFX = function(key, sourceNode, volumeNode, startTime, pauseTime) {
// the name of the relevant audio resource
this.key = key;
// the node used in Web Audio API in charge of the source data
this.sourceNode = sourceNode;
// the node used in Web Audio API in charge of volume
this.volumeNode = volumeNode;
/*
* when playing started from beginning, startTime is set to the current time of AudioContext.currentTime
* when paused, pauseTime is set to the current time of AudioContext.currentTime
* so how long the music has been played can be calculated
* these won't be used in other cases
*/
this.startTime = startTime || 0;
this.pauseTime = pauseTime || 0;
// by only sourceNode's playbackState, it cannot distinguish finished state from paused state
this.isPaused = false;
};
/**
* The Audio Engine implementation via Web Audio API.
* @class
* @extends cc.AudioEngine
*/
cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
// the Web Audio Context
_ctx: null,
// may be: mp3, ogg, wav, mp4, m4a
_supportedFormat: [],
// if sound is not enabled, this engine's init() will return false
_soundEnable: false,
// containing all binary buffers of loaded audio resources
_audioData: {},
/*
* Issue: When loading two resources with different suffixes asynchronously, the second one might start loading
* when the first one is already loading!
* To avoid this duplication, loading synchronously somehow doesn't work. _ctx.decodeAudioData() would throw an
* exception "DOM exception 12", it should be a bug of the browser.
* So just add something to mark some audios as LOADING so as to avoid duplication.
*/
_audiosLoading: {},
// the music being played, cc.WebAudioSFX, when null, no music is being played; when not null, it may be playing or paused
_music: null,
// the volume applied to the music
_musicVolume: 1,
// the effects being played: { key => [cc.WebAudioSFX] }, many effects of the same resource may be played simultaneously
_effects: {},
// the volume applied to all effects
_effectsVolume: 1,
/*
* _canPlay is a property in cc.SimpleAudioEngine, but not used in cc.WebAudioEngine.
* Only those which support Web Audio API will be using this cc.WebAudioEngine, so no need to add an extra check.
*/
// _canPlay: true,
/*
* _maxAudioInstance is also a property in cc.SimpleAudioEngine, but not used here
*/
// _maxAudioInstance: 10,
/**
* Constructor
*/
ctor: function() {
cc.AudioEngine.prototype.ctor.call(this);
},
/**
* Initialization
* @return {Boolean}
*/
init: function() {
/*
* browser has proved to support Web Audio API in miniFramework.js
* only in that case will cc.WebAudioEngine be chosen to run, thus the following is guaranteed to work
*/
this._ctx = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
// gather capabilities information, enable sound if any of the audio format is supported
var capabilities = {};
this._checkCanPlay(capabilities);
var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a'];
for (var idx in formats) {
var name = formats[idx];
if (capabilities[name]) {
this._supportedFormat.push(name);
}
}
this._soundEnable = this._supportedFormat.length > 0;
return this._soundEnable;
},
/**
* search in this._supportedFormat if @param ext is there
* @param {String} ext
* @returns {Boolean}
*/
isFormatSupported: function(ext) {
for (var idx in this._supportedFormat) {
if (ext === this._supportedFormat[idx]) {
return true;
}
}
return false;
},
/**
* Using XMLHttpRequest to retrieve the resource data from server.
* Not using cc.FileUtils.getByteArrayFromFile() because it is synchronous,
* so doing the retrieving here is more handful.
* @param {String} url The url to retrieve data
* @param {Object} onSuccess The callback to run when retrieving succeeds, the binary data array is passed into it
* @param {Object} onError The callback to run when retrieving fails
* @private
*/
_fetchData: function(url, onSuccess, onError) {
// currently, only the webkit browsers support Web Audio API, so it should be fine just writing like this.
var req = new window.XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
var engine = this;
req.onload = function() {
// when context decodes the array buffer successfully, call onSuccess
engine._ctx.decodeAudioData(req.response, onSuccess, onError);
};
req.onerror = onError;
req.send();
},
/**
* Preload music resource.<br />
* This method is called when cc.Loader preload resources.
* @param {String} path The path of the music file with filename extension.
*/
preloadSound: function(path) {
if (!this._soundEnable) {
return;
}
var extName = this._getExtFromFullPath(path);
var keyName = this._getPathWithoutExt(path);
// not supported, already loaded, already loading
if (!this.isFormatSupported(extName) || keyName in this._audioData || keyName in this._audiosLoading) {
cc.Loader.getInstance().onResLoaded();
return;
}
this._audiosLoading[keyName] = true;
var engine = this;
this._fetchData(path, function(buffer) {
// resource fetched, in @param buffer
engine._audioData[keyName] = buffer;
delete engine._audiosLoading[keyName];
cc.Loader.getInstance().onResLoaded();
}, function() {
// resource fetching failed
delete engine._audiosLoading[keyName];
cc.Loader.getInstance().onResLoadingErr(path);
});
},
/**
* Init a new WebAudioSFX and play it, return this WebAudioSFX object
* assuming that @param key exists in this._audioData
* @param {String} key
* @param {Boolean} loop Default value is false
* @param {Number} volume 0.0 - 1.0, default value is 1.0
* @param {Number} offset Where to start playing (in seconds)
* @private
*/
_beginSound: function(key, loop, volume, offset) {
var sfxCache = new cc.WebAudioSFX();
loop = loop || false;
volume = volume || 1;
offset = offset || 0;
sfxCache.key = key;
sfxCache.sourceNode = this._ctx.createBufferSource();
sfxCache.sourceNode.buffer = this._audioData[key];
sfxCache.sourceNode.loop = loop;
sfxCache.volumeNode = this._ctx.createGainNode();
sfxCache.volumeNode.gain.value = volume;
sfxCache.sourceNode.connect(sfxCache.volumeNode);
sfxCache.volumeNode.connect(this._ctx.destination);
/*
* Safari on iOS 6 only supports noteOn(), noteGrainOn(), and noteOff() now.(iOS 6.1.3)
* The latest version of chrome has supported start() and stop()
* start() & stop() are specified in the latest specification (written on 04/26/2013)
* Reference: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
* noteOn(), noteGrainOn(), and noteOff() are specified in Draft 13 version (03/13/2012)
* Reference: http://www.w3.org/2011/audio/drafts/2WD/Overview.html
*/
if (sfxCache.sourceNode.start) {
// starting from offset means resuming from where it paused last time
sfxCache.sourceNode.start(0, offset);
} else if (sfxCache.sourceNode.noteGrainOn) {
var duration = sfxCache.sourceNode.buffer.duration;
if (loop) {
/*
* On Safari on iOS 6, if loop == true, the passed in @param duration will be the duration from now on.
* In other words, the sound will keep playing the rest of the music all the time.
* On latest chrome desktop version, the passed in duration will only be the duration in this cycle.
* Now that latest chrome would have start() method, it is prepared for iOS here.
*/
sfxCache.sourceNode.noteGrainOn(0, offset, duration);
} else {
sfxCache.sourceNode.noteGrainOn(0, offset, duration - offset);
}
} else {
// if only noteOn() is supported, resuming sound will NOT work
sfxCache.sourceNode.noteOn(0);
}
// currentTime - offset is necessary for pausing multiple times!
sfxCache.startTime = this._ctx.currentTime - offset;
sfxCache.pauseTime = sfxCache.startTime;
sfxCache.isPaused = false;
return sfxCache;
},
/**
* According to the spec: dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html
* const unsigned short UNSCHEDULED_STATE = 0;
* const unsigned short SCHEDULED_STATE = 1;
* const unsigned short PLAYING_STATE = 2; // this means it is playing
* const unsigned short FINISHED_STATE = 3;
* However, the older specification doesn't include this property, such as this one: http://www.w3.org/2011/audio/drafts/2WD/Overview.html
* @param {Object} sfxCache Assuming not null
* @returns {Boolean} Whether @param sfxCache is playing or not
* @private
*/
_isSoundPlaying: function(sfxCache) {
return sfxCache.sourceNode.playbackState == 2;
},
/**
* To distinguish 3 kinds of status for each sound (PLAYING, PAUSED, FINISHED), _isSoundPlaying() is not enough
* @param {Object} sfxCache Assuming not null
* @returns {Boolean}
* @private
*/
_isSoundPaused: function(sfxCache) {
// checking _isSoundPlaying() won't hurt
return this._isSoundPlaying(sfxCache) ? false : sfxCache.isPaused;
},
/**
* Whether it is playing any music
* @return {Boolean} If is playing return true,or return false.
* @example
* //example
* if (cc.AudioEngine.getInstance().isMusicPlaying()) {
* cc.log("music is playing");
* }
* else {
* cc.log("music is not playing");
* }
*/
isMusicPlaying: function () {
/*
* cc.AudioEngine.isMusicPlaying property is not going to be used here in cc.WebAudioEngine
* that is only used in cc.SimpleAudioEngine
* WebAudioEngine uses Web Audio API which contains a playbackState property in AudioBufferSourceNode
* So there is also no need to be any method like setMusicPlaying(), it is done automatically
*/
return this._music ? this._isSoundPlaying(this._music) : false;
},
/**
* Play music.
* @param {String} path The path of the music file without filename extension.
* @param {Boolean} loop Whether the music loop or not.
* @example
* //example
* cc.AudioEngine.getInstance().playMusic(path, false);
*/
playMusic: function (path, loop) {
var keyName = this._getPathWithoutExt(path);
var extName = this._getExtFromFullPath(path);
loop = loop || false;
if (this._music) {
// there is a music being played currently, stop it (may be paused)
this.stopMusic();
}
if (keyName in this._audioData) {
// already loaded, just play it
this._music = this._beginSound(keyName, loop, this.getMusicVolume());
} else if (this.isFormatSupported(extName) && !(keyName in this._audiosLoading)) {
// load now only if the type is supported and it is not being loaded currently
this._audiosLoading[keyName] = true;
var engine = this;
this._fetchData(path, function(buffer) {
// resource fetched, save it and call playMusic() again, this time it should be alright
engine._audioData[keyName] = buffer;
delete engine._audiosLoading[keyName];
engine.playMusic(path, loop);
}, function() {
// resource fetching failed, doing nothing here
delete engine._audiosLoading[keyName];
/*
* Potential Bug: if fetching data fails every time, loading will be tried again and again.
* Preloading would prevent this issue: if it fails to fetch, preloading procedure will not achieve 100%.
*/
});
}
},
/**
* Ends a sound, call stop() or noteOff() accordingly
* @param {Object} sfxCache Assuming not null
* @private
*/
_endSound: function(sfxCache) {
if (sfxCache.sourceNode.stop) {
sfxCache.sourceNode.stop(0);
} else {
sfxCache.sourceNode.noteOff(0);
}
// Do not call disconnect()! Otherwise the sourceNode's playbackState may not be updated correctly
// sfxCache.sourceNode.disconnect();
// sfxCache.volumeNode.disconnect();
},
/**
* Stop playing music.
* @param {Boolean} releaseData If release the music data or not.As default value is false.
* @example
* //example
* cc.AudioEngine.getInstance().stopMusic();
*/
stopMusic: function(releaseData) {
// can stop when it's playing/paused
if (!this._music) {
return;
}
var key = this._music.key;
this._endSound(this._music);
this._music = null;
if (releaseData) {
delete this._audioData[key];
}
},
/**
* Used in pauseMusic() & pauseEffect() & pauseAllEffects()
* @param {Object} sfxCache Assuming not null
* @private
*/
_pauseSound: function(sfxCache) {
sfxCache.pauseTime = this._ctx.currentTime;
sfxCache.isPaused = true;
this._endSound(sfxCache);
},
/**
* Pause playing music.
* @example
* //example
* cc.AudioEngine.getInstance().pauseMusic();
*/
pauseMusic: function() {
// can pause only when it's playing
if (!this.isMusicPlaying()) {
return;
}
this._pauseSound(this._music);
},
/**
* Used in resumeMusic() & resumeEffect() & resumeAllEffects()
* @param {Object} paused The paused WebAudioSFX, assuming not null
* @param {Number} volume Can be getMusicVolume() or getEffectsVolume()
* @returns {Object} A new WebAudioSFX object representing the resumed sound
* @private
*/
_resumeSound: function(paused, volume) {
var key = paused.key;
var loop = paused.sourceNode.loop;
// the paused sound may have been playing several loops, (pauseTime - startTime) may be too large
var offset = (paused.pauseTime - paused.startTime) % paused.sourceNode.buffer.duration;
return this._beginSound(key, loop, volume, offset);
},
/**
* Resume playing music.
* @example
* //example
* cc.AudioEngine.getInstance().resumeMusic();
*/
resumeMusic: function() {
// can resume only when it's paused
if (!this._music || !this._isSoundPaused(this._music)) {
return;
}
this._music = this._resumeSound(this._music, this.getMusicVolume());
},
/**
* Rewind playing music.
* @example
* //example
* cc.AudioEngine.getInstance().rewindMusic();
*/
rewindMusic: function() {
// can rewind when it's playing or paused
if (!this._music) {
return;
}
var key = this._music.key;
var loop = this._music.sourceNode.loop;
var volume = this.getMusicVolume();
this._endSound(this._music);
this._music = this._beginSound(key, loop, volume);
},
willPlayMusic: function() {
// TODO what is the purpose of this method? This is just a copy from cc.SimpleAudioEngine
return false;
},
/**
* The volume of the music max value is 1.0,the min value is 0.0 .
* @return {Number}
* @example
* //example
* var volume = cc.AudioEngine.getInstance().getMusicVolume();
*/
getMusicVolume: function() {
return this._musicVolume;
},
/**
* update volume, used in setMusicVolume() or setEffectsVolume()
* @param {Object} sfxCache Assuming not null
* @param {Number} volume
* @private
*/
_setSoundVolume: function(sfxCache, volume) {
sfxCache.volumeNode.gain.value = volume;
},
/**
* Set the volume of music.
* @param {Number} volume Volume must be in 0.0~1.0 .
* @example
* //example
* cc.AudioEngine.getInstance().setMusicVolume(0.5);
*/
setMusicVolume: function(volume) {
if (volume > 1) {
volume = 1;
} else if (volume < 0) {
volume = 0;
}
if (this.getMusicVolume() == volume) {
// it is the same, no need to update
return;
}
this._musicVolume = volume;
if (this._music) {
this._setSoundVolume(this._music, volume);
}
},
/**
* Play sound effect.
* @param {String} path The path of the sound effect with filename extension.
* @param {Boolean} loop Whether to loop the effect playing, default value is false
* @example
* //example
* cc.AudioEngine.getInstance().playEffect(path);
*/
playEffect: function(path, loop) {
var keyName = this._getPathWithoutExt(path);
var extName = this._getExtFromFullPath(path);
loop = loop || false;
if (keyName in this._audioData) {
// the resource has been loaded, just play it
if (!(keyName in this._effects)) {
this._effects[keyName] = [];
}
// a list of sound objects from the same resource
var effectList = this._effects[keyName];
for (var idx in effectList) {
var sfxCache = effectList[idx];
if (!this._isSoundPlaying(sfxCache) && !this._isSoundPaused(sfxCache)) {
// not playing && not paused => it is finished, this position can be reused
effectList[idx] = this._beginSound(keyName, loop, this.getEffectsVolume());
return path;
}
}
// no new sound was created to replace an old one in the list, then just append one
effectList.push(this._beginSound(keyName, loop, this.getEffectsVolume()));
} else if (this.isFormatSupported(extName) && !(keyName in this._audiosLoading)) {
// load now only if the type is supported and it is not being loaded currently
this._audiosLoading[keyName] = true;
var engine = this;
this._fetchData(path, function(buffer) {
// resource fetched, save it and call playEffect() again, this time it should be alright
engine._audioData[keyName] = buffer;
delete engine._audiosLoading[keyName];
engine.playEffect(path, loop);
}, function() {
// resource fetching failed, doing nothing here
delete engine._audiosLoading[keyName];
/*
* Potential Bug: if fetching data fails every time, loading will be tried again and again.
* Preloading would prevent this issue: if it fails to fetch, preloading procedure will not achieve 100%.
*/
});
}
// cc.SimpleAudioEngine returns path, just do the same for backward compatibility. DO NOT rely on this, though!
var audioID = this._audioID++;
this._audioIDList[audioID] = this._effects[keyName];
return audioID;
},
/**
* The volume of the effects max value is 1.0,the min value is 0.0 .
* @return {Number}
* @example
* //example
* var effectVolume = cc.AudioEngine.getInstance().getEffectsVolume();
*/
getEffectsVolume: function() {
return this._effectsVolume;
},
/**
* Set the volume of sound effects.
* @param {Number} volume Volume must be in 0.0~1.0 .
* @example
* //example
* cc.AudioEngine.getInstance().setEffectsVolume(0.5);
*/
setEffectsVolume: function(volume) {
if (volume > 1) {
volume = 1;
} else if (volume < 0) {
volume = 0;
}
if (this.getEffectsVolume() == volume) {
// it is the same, no need to update
return;
}
this._effectsVolume = volume;
for (var key in this._effects) {
var effectList = this._effects[key];
for (var idx in effectList) {
this._setSoundVolume(effectList[idx], volume);
}
}
},
/**
* Used in pauseEffect() and pauseAllEffects()
* @param {Object} effectList A list of sounds, each sound may be playing/paused/finished
* @private
*/
_pauseSoundList: function(effectList) {
for (var idx in effectList) {
var sfxCache = effectList[idx];
if (this._isSoundPlaying(sfxCache)) {
this._pauseSound(sfxCache);
}
}
},
/**
* Pause playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @example
* //example
* cc.AudioEngine.getInstance().pauseEffect(audioID);
*/
pauseEffect: function(audioID) {
if (audioID == null) {
return;
}
if (this._audioIDList.hasOwnProperty(audioID)) {
this._pauseSoundList(this._audioIDList[audioID]);
}
},
/**
* Pause all playing sound effect.
* @example
* //example
* cc.AudioEngine.getInstance().pauseAllEffects();
*/
pauseAllEffects: function() {
for (var key in this._effects) {
this._pauseSoundList(this._effects[key]);
}
},
/**
* Used in resumeEffect() and resumeAllEffects()
* @param {Object} effectList A list of sounds, each sound may be playing/paused/finished
* @private
*/
_resumeSoundList: function(effectList, volume) {
for (var idx in effectList) {
var sfxCache = effectList[idx];
if (this._isSoundPaused(sfxCache)) {
effectList[idx] = this._resumeSound(sfxCache, volume);
}
}
},
/**
* Resume playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @example
* //example
* cc.AudioEngine.getInstance().resumeEffect(audioID);
*/
resumeEffect: function(audioID) {
if (audioID == null) {
return;
}
if (this._audioIDList.hasOwnProperty(audioID)) {
this._resumeSoundList(this._audioIDList[audioID], this.getEffectsVolume());
}
},
/**
* Resume all playing sound effect
* @example
* //example
* cc.AudioEngine.getInstance().resumeAllEffects();
*/
resumeAllEffects: function() {
for (var key in this._effects) {
this._resumeSoundList(this._effects[key], this.getEffectsVolume());
}
},
/**
* Stop playing sound effect.
* @param {Number} audioID The return value of function playEffect.
* @example
* //example
* cc.AudioEngine.getInstance().stopEffect(audioID);
*/
stopEffect: function(audioID) {
if (audioID == null) {
return;
}
if (this._audioIDList.hasOwnProperty(audioID)) {
this._endSound(this._audioIDList[audioID]);
}
},
/**
* Stop all playing sound effects.
* @example
* //example
* cc.AudioEngine.getInstance().stopAllEffects();
*/
stopAllEffects: function() {
for (var key in this._effects) {
var effectList = this._effects[key];
for (var idx in effectList) {
this._endSound(effectList[idx]);
}
/*
* Another way is to set this._effects = {} outside this for loop.
* However, the cc.Class.extend() put all properties in the prototype.
* If I reassign a new {} to it, that will be appear in the instance.
* In other words, the dict in prototype won't release its children.
*/
delete this._effects[key];
}
},
/**
* Unload the preloaded effect from internal buffer
* @param {String} path
* @example
* //example
* cc.AudioEngine.getInstance().unloadEffect(EFFECT_FILE);
*/
unloadEffect: function(path) {
if (!path) {
return;
}
var keyName = this._getPathWithoutExt(path);
if (keyName in this._effects) {
this.stopEffect(path);
}
if (keyName in this._audioData) {
delete this._audioData[keyName];
}
}
});
cc.AudioEngine._instance = null;
cc.AudioEngine.isMusicPlaying = false;
/**
* Get the shared Engine object, it will new one when first time be called.
* @return {cc.AudioEngine}
*/
cc.AudioEngine.getInstance = function () {
if (!this._instance) {
var ua = navigator.userAgent;
if (cc.Browser.supportWebAudio && (/iPhone OS/.test(ua)||/iPad/.test(ua))) {
this._instance = new cc.WebAudioEngine();
} else {
this._instance = new cc.SimpleAudioEngine();
}
this._instance.init();
}
return this._instance;
};
/**
* Stop all music and sound effects
* @example
* //example
* cc.AudioEngine.end();
*/
cc.AudioEngine.end = function () {
if (this._instance) {
this._instance.stopMusic();
this._instance.stopAllEffects();
}
this._instance = null;
};
|
_T.createModuleTest('myModule')
.injectModule('someOtherModule')
.injectService({ name: '$state', value: true })
.describe(function () {
var myModuleTest = this;
it('mySpecialObject should have id of 123', function () {
var result = myModuleTest.$injector.get('mySpecialObject');
result.id.should.equal(123);
});
it('myConstant should have value of 456', function () {
var result = myModuleTest.$injector.get('myConstant');
result.should.equal(456);
});
}); |
{
"totalPages": 7,
"totalRows": 140,
"rowsPerPage": 20,
"pageIndex": 3,
"pageRows": 20,
"rows": [
{
"RowID": {
"value": 60
},
"TeamID": {
"value": "ti-60"
},
"TeamName": {
"value": "tn-60"
},
"Yield": {
"value": 61
},
"Cost": {
"value": 62
},
"Margin": {
"value": 63
}
},
{
"RowID": {
"value": 61
},
"TeamID": {
"value": "ti-61"
},
"TeamName": {
"value": "tn-61"
},
"Yield": {
"value": 62
},
"Cost": {
"value": 63
},
"Margin": {
"value": 64
}
},
{
"RowID": {
"value": 62
},
"TeamID": {
"value": "ti-62"
},
"TeamName": {
"value": "tn-62"
},
"Yield": {
"value": 63
},
"Cost": {
"value": 64
},
"Margin": {
"value": 65
}
},
{
"RowID": {
"value": 63
},
"TeamID": {
"value": "ti-63"
},
"TeamName": {
"value": "tn-63"
},
"Yield": {
"value": 64
},
"Cost": {
"value": 65
},
"Margin": {
"value": 66
}
},
{
"RowID": {
"value": 64
},
"TeamID": {
"value": "ti-64"
},
"TeamName": {
"value": "tn-64"
},
"Yield": {
"value": 65
},
"Cost": {
"value": 66
},
"Margin": {
"value": 67
}
},
{
"RowID": {
"value": 65
},
"TeamID": {
"value": "ti-65"
},
"TeamName": {
"value": "tn-65"
},
"Yield": {
"value": 66
},
"Cost": {
"value": 67
},
"Margin": {
"value": 68
}
},
{
"RowID": {
"value": 66
},
"TeamID": {
"value": "ti-66"
},
"TeamName": {
"value": "tn-66"
},
"Yield": {
"value": 67
},
"Cost": {
"value": 68
},
"Margin": {
"value": 69
}
},
{
"RowID": {
"value": 67
},
"TeamID": {
"value": "ti-67"
},
"TeamName": {
"value": "tn-67"
},
"Yield": {
"value": 68
},
"Cost": {
"value": 69
},
"Margin": {
"value": 70
}
},
{
"RowID": {
"value": 68
},
"TeamID": {
"value": "ti-68"
},
"TeamName": {
"value": "tn-68"
},
"Yield": {
"value": 69
},
"Cost": {
"value": 70
},
"Margin": {
"value": 71
}
},
{
"RowID": {
"value": 69
},
"TeamID": {
"value": "ti-69"
},
"TeamName": {
"value": "tn-69"
},
"Yield": {
"value": 70
},
"Cost": {
"value": 71
},
"Margin": {
"value": 72
}
},
{
"RowID": {
"value": 70
},
"TeamID": {
"value": "ti-70"
},
"TeamName": {
"value": "tn-70"
},
"Yield": {
"value": 71
},
"Cost": {
"value": 72
},
"Margin": {
"value": 73
}
},
{
"RowID": {
"value": 71
},
"TeamID": {
"value": "ti-71"
},
"TeamName": {
"value": "tn-71"
},
"Yield": {
"value": 72
},
"Cost": {
"value": 73
},
"Margin": {
"value": 74
}
},
{
"RowID": {
"value": 72
},
"TeamID": {
"value": "ti-72"
},
"TeamName": {
"value": "tn-72"
},
"Yield": {
"value": 73
},
"Cost": {
"value": 74
},
"Margin": {
"value": 75
}
},
{
"RowID": {
"value": 73
},
"TeamID": {
"value": "ti-73"
},
"TeamName": {
"value": "tn-73"
},
"Yield": {
"value": 74
},
"Cost": {
"value": 75
},
"Margin": {
"value": 76
}
},
{
"RowID": {
"value": 74
},
"TeamID": {
"value": "ti-74"
},
"TeamName": {
"value": "tn-74"
},
"Yield": {
"value": 75
},
"Cost": {
"value": 76
},
"Margin": {
"value": 77
}
},
{
"RowID": {
"value": 75
},
"TeamID": {
"value": "ti-75"
},
"TeamName": {
"value": "tn-75"
},
"Yield": {
"value": 76
},
"Cost": {
"value": 77
},
"Margin": {
"value": 78
}
},
{
"RowID": {
"value": 76
},
"TeamID": {
"value": "ti-76"
},
"TeamName": {
"value": "tn-76"
},
"Yield": {
"value": 77
},
"Cost": {
"value": 78
},
"Margin": {
"value": 79
}
},
{
"RowID": {
"value": 77
},
"TeamID": {
"value": "ti-77"
},
"TeamName": {
"value": "tn-77"
},
"Yield": {
"value": 78
},
"Cost": {
"value": 79
},
"Margin": {
"value": 80
}
},
{
"RowID": {
"value": 78
},
"TeamID": {
"value": "ti-78"
},
"TeamName": {
"value": "tn-78"
},
"Yield": {
"value": 79
},
"Cost": {
"value": 80
},
"Margin": {
"value": 81
}
},
{
"RowID": {
"value": 79
},
"TeamID": {
"value": "ti-79"
},
"TeamName": {
"value": "tn-79"
},
"Yield": {
"value": 80
},
"Cost": {
"value": 81
},
"Margin": {
"value": 82
}
}
]
} |
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 3L4 9v12h16V9l-8-6zm4 13.06L14 15v1c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h4c.55 0 1 .45 1 1v1l2-1.06v4.12z" />
, 'CameraIndoor');
|
import test from 'tape'
import {createAction} from 'redux-actions'
import boot, {BOOT} from '../src/bootstrap'
test('Use redux-actions handlers instead of pure Redux reducers', assert => {
const AFTER_BOOT = 'redux-boot/test/AFTER_BOOT'
const afterBootAction = value => {
return {
type: AFTER_BOOT,
payload: {
foo: value
}
}
}
const initialState = {
foo: 'bar'
}
// React to an action with less boilerplaing.
const handlers = {
[AFTER_BOOT]: (state, action) => {
assert.pass('Reducer called')
return {
...state,
foo: action.payload.foo
}
}
}
const testModule = {
// Less boilerplating.
reducer: handlers,
middleware({getState, dispatch}) {
return next => action => {
if (action.type === BOOT) {
assert.pass('Middleware called')
dispatch(afterBootAction('baz'))
}
return next(action)
}
}
}
const modules = [
testModule
]
const app = boot(initialState, modules)
app.then(({action, store}) => {
assert.equal(
store.getState().foo,
'baz',
"Module reducer was handled by redux-actions"
)
assert.end()
})
})
test('Use redux-actions action helper instead of a pure function', assert => {
const AFTER_BOOT = 'redux-boot/test/AFTER_BOOT'
const afterBootAction = createAction(AFTER_BOOT, value => {
return {
foo: value
}
})
const initialState = {
foo: 'bar'
}
// React to an action with less boilerplaing.
const handlers = {
[AFTER_BOOT]: (state, action) => {
assert.pass('Reducer called')
return {
...state,
foo: action.payload.foo
}
}
}
const testModule = {
// Less boilerplating.
reducer: handlers,
middleware({getState, dispatch}) {
return next => action => {
if (action.type === BOOT) {
assert.pass('Middleware called')
dispatch(afterBootAction('baz'))
}
return next(action)
}
}
}
const modules = [
testModule
]
const app = boot(initialState, modules)
app.then(({action, store}) => {
assert.equal(
store.getState().foo,
'baz',
"Module action was handled by redux-actions"
)
assert.end()
})
})
|
/*
* The MIT License (MIT)
* Copyright (c) 2015 Oguz Bastemur
*/
var commons = require('./commons');
var scope_string = {};
for(var o in commons.scopeTypes) {
scope_string[commons.scopeTypes[o]] = o;
}
var bit_names = {};
for(var o in commons.BIT_NAME) {
bit_names[commons.BIT_NAME[o]] = o;
}
var colors = ['green', 'yellow'];
var printBlocks = function (bl, depth) {
if (!depth) {
depth = "";
}
var type_ = bit_names[bl.name];
var scopeType = scope_string[bl.scopeType];
bl = bl.subs;
console.log(depth + "--->", type_, "(" + scopeType + ")");
for (var i = 0; i < bl.length; i++) {
var clr = colors[i % 2];
type_ = bit_names[bl[i].name];
var ext = bl[i].isWordish() ? bl[i].delimiter : type_ == commons.BIT_TYPE.NUMBER ? bl[i].delimiter : "";
jxcore.utils.console.log(depth + type_, bl[i].rowIndex + ":" + bl[i].columnIndex, ext, clr);
if (bl[i].subs && bl[i].subs.length) {
printBlocks(bl[i], depth + " ");
console.log(depth + "<---", type_);
}
}
};
exports.printBlocks = printBlocks;
var arr = [];
function write(filename, block) {
if (block.name == commons.BIT_NAME.ROOT)
return write(filename, block.subs);
var close_scope = {
"{" : "}",
"[" : "]",
"(" : ")"
};
for (var i = 0, ln = block.length; i < ln; i++) {
if (block[i].subs.length || block[i].scope) {
arr.push(block[i].delimiter);
if (block[i].subs.length)
write(filename, block[i].subs);
arr.push(close_scope[block[i].delimiter]);
} else {
arr.push(block[i].getData());
}
}
}
exports.blockToCode = function (block, filename) {
arr = [];
if (block.name == commons.BIT_NAME.ROOT)
write(filename, block.subs);
else
write(filename, block);
return arr.join('');
}; |
define(['srv/core/Handler', 'path', 'flow', 'fs', 'xmldom', 'underscore'], function (Handler, Path, flow, Fs, xmldom, _) {
return Handler.inherit('srv.handler.NodeRenderingHandler', {
defaults: {
// used for making ajax relative ajax requests - null indicates that it is hosted on this server
applicationUrl: null,
// the document root will be used by default
applicationDirectory: null,
options: null,
application: 'app/App.xml',
indexFile: 'index.html',
config: 'config.json',
usePackageVersion: false,
defaultStartParameter: {}
},
start: function (server, callback) {
var self = this;
this.$.applicationDirectory = this.$.applicationDirectory ||
this.$stage.$applicationContext.$config.documentRoot;
this.$.applicationDirectory = Path.resolve(this.$.applicationDirectory);
if (!this.$.applicationUrl) {
for (var i = 0; i < server.$endPoints.$endPoints.length; i++) {
var endPoint = server.$endPoints.$endPoints[i];
if (endPoint.uri instanceof Function) {
this.$.applicationUrl = endPoint.uri();
break;
}
}
}
flow()
.seq("config", function (cb) {
if (_.isString(self.$.config)) {
Fs.readFile(Path.join(self.$.applicationDirectory, self.$.config), function (err, data) {
if (!err) {
data = JSON.parse(data);
data.nodeRequire = require;
data.baseUrl = self.$.applicationDirectory;
data.applicationUrl = self.$.applicationUrl;
}
cb(err, data);
});
} else {
cb(null, self.$.config);
}
})
.seq("applicationContext", function (cb) {
// create an application context
// TODO: create in own requirejs context -> we need a context name
var require = self.$stage.$applicationContext.$nodeRequire;
var rAppid = require(Path.join(self.$.applicationDirectory, 'js', 'lib', 'rAppid')).rAppid;
rAppid.createApplicationContext(self.$.application, cb.vars['config'], cb);
})
.seq("html", function () {
var indexContent = Fs.readFileSync(Path.join(self.$.applicationDirectory, self.$.indexFile)).toString();
if (self.$.usePackageVersion) {
var packageContent = JSON.parse(Fs.readFileSync(Path.join(self.$.applicationDirectory, "..", "package.json")));
var version = packageContent.version;
if (version) {
indexContent = indexContent.replace(/(href|src)=(["'])(?!(http|\/\/))([^'"]+)/g, '$1=$2' + version + '/$4');
indexContent = indexContent.replace(/\$\{VERSION\}/g, version);
}
}
indexContent = indexContent.replace(/<meta\sname=["']fragment["']\scontent=["']!["']>/, "");
// TODO: clean up html
var doc = (new xmldom.DOMParser()).parseFromString(indexContent).documentElement;
doc.constructor.prototype.style = {};
if (!doc.innerHTML) {
Object.defineProperty(doc.constructor.prototype, 'innerHTML', {
get: function () {
var ret = "";
for (var i = 0; i < this.childNodes.length; i++) {
ret += this.childNodes[i].toString() || "";
}
return ret;
},
set: function (data) {
data = "<root>" + data + "</root>";
var doc = (new xmldom.DOMParser()).parseFromString(data);
if (!doc.documentElement) {
this.data = data;
} else {
while (this.firstChild) {
this.removeChild(this.firstChild);
}
while (doc.documentElement.firstChild) {
var child = doc.documentElement.firstChild;
doc.documentElement.removeChild(child);
this.appendChild(child);
}
}
}
});
}
var scripts = doc.getElementsByTagName('script');
for (var i = scripts.length - 1; i >= 0; i--) {
var usage = scripts[i].getAttribute("data-usage");
if (usage == "bootstrap" || usage == "lib") {
scripts[i].parentNode.removeChild(scripts[i]);
}
}
return (new xmldom.XMLSerializer()).serializeToString(doc);
})
.exec(function (err, results) {
if (!err) {
self.$applicationContext = results["applicationContext"];
self.$html = results["html"];
self.log('Starting NodeRenderingHandler with applicationDirectory: ' + self.$.applicationDirectory);
}
callback(err);
});
},
isResponsibleForRequest: function (context) {
// see https://developers.google.com/webmasters/ajax-crawling/docs/getting-started
return context.request.urlInfo.parameter.hasOwnProperty('_escaped_fragment_') &&
context.request.urlInfo.pathname === this.$.path;
},
handleRequest: function (context, callback) {
var self = this;
flow()
.seq("window", function () {
// generate document
var document = (new xmldom.DOMParser()).parseFromString(self.$html);
document.head = document.head || document.getElementsByTagName("head")[0];
document.body = document.body || document.getElementsByTagName("body")[0];
return {
document: document
};
})
.seq("app", function (cb) {
self.$applicationContext.createApplicationInstance(cb.vars.window, function (err, s, application) {
cb(err, application);
});
})
.seq(function (cb) {
// start application
var startParameter = _.extend({}, self.$.defaultStartParameter);
var initialHash = context.request.urlInfo.parameter["_escaped_fragment_"] || "";
if (initialHash instanceof Array) {
// _escaped_fragment_ parameter was given more the once
initialHash = initialHash[0];
}
startParameter.initialHash = initialHash;
cb.vars["app"].start(startParameter, cb);
})
.seq("html", function () {
this.vars["app"].$stage.render(this.vars.window.document.getElementsByTagName("body")[0]);
return '<!DOCTYPE html>\n' + (new xmldom.XMLSerializer()).serializeToString(this.vars.window.document.documentElement);
})
.exec(function (err, results) {
if (!err) {
context.response.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
context.response.write(results.html);
context.response.end();
}
results.app.$stage.destroy();
results = null;
self = null;
callback(err);
});
}
});
}); |
var CleanCSS = require('clean-css');
var log = require('../log');
module.exports = function (code, args) {
log.trace('Call CleanCSS with %j', args);
return new CleanCSS(args).minify(code).styles;
};
|
'use strict';
// Projects controller
angular.module('events').controller('EventsController',
['$scope', '$state', '$stateParams', '$location', 'HackathonEvent', 'EventCategory',
function ($scope, $state, $stateParams, $location, HackathonEvent, EventCategory) {
EventCategory.query(function(eventCategories) {
$scope.eventCategories = eventCategories;
$scope.eventCategoriesMap = {};
for (var i = 0; i < $scope.eventCategories.length; i++) {
$scope.eventCategoriesMap[i] = $scope.eventCategories[i];
}
$scope.resetSelectedCategories();
});
$scope.resetSelectedCategories = function() {
$scope.selectedCategories = {};
for (var i = 0; i < $scope.eventCategories.length; i++) {
$scope.selectedCategories[i] = false;
}
};
$scope.create = function() {
var categories = [];
for (var key in $scope.selectedCategories) {
if (!$scope.selectedCategories.hasOwnProperty(key)) continue;
if ($scope.selectedCategories[key] === false) continue;
categories.push($scope.eventCategoriesMap[key]._id);
}
var event = new HackathonEvent({
title: this.title,
description: this.description,
locations: this.locations,
categories: categories,
start: this.start,
end: this.end
});
// Redirect after save
event.$save(function (response) {
$location.path('admin/events');
// Clear form fields
$scope.title = '';
$scope.description = '';
$scope.locations = '';
$scope.categories = [];
$scope.resetSelectedCategories();
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.update = function () {
var event = $scope.event;
var categories = [];
for (var key in $scope.selectedCategories) {
if (!$scope.selectedCategories.hasOwnProperty(key)) continue;
if ($scope.selectedCategories[key] === false) continue;
categories.push($scope.eventCategoriesMap[key]._id);
}
event.categories = categories;
$scope.resetSelectedCategories();
event.$update(function () {
$location.path('admin/events');
}, function (errorResponse) {
$scope.error = errorResponse.data.message;
});
};
$scope.find = function() {
$scope.events = HackathonEvent.query({
});
};
$scope.findOne = function () {
HackathonEvent.get({
eventId: $stateParams.eventId
}, function(event) {
$scope.event = event;
for (var i = 0; i < $scope.eventCategories.length; i++) {
$scope.selectedCategories[i] = false;
for (var j = 0; j < $scope.event.categories.length; j++) {
if ($scope.eventCategories[i]._id === $scope.event.categories[j]._id) {
$scope.selectedCategories[i] = true;
}
}
}
});
};
$scope.remove = function (event) {
if (event) {
event.$remove();
$location.path('admin/events');
} else {
$scope.event.$remove(function () {
$location.path('admin/events');
});
}
};
}]);
|
// Compiled by ClojureScript 0.0-2322
goog.provide('clojure.browser.net');
goog.require('cljs.core');
goog.require('goog.Uri');
goog.require('goog.net.xpc.CrossPageChannel');
goog.require('goog.net.xpc.CfgFields');
goog.require('goog.net.EventType');
goog.require('goog.net.XhrIo');
goog.require('goog.json');
goog.require('goog.json');
goog.require('clojure.browser.event');
goog.require('clojure.browser.event');
clojure.browser.net._STAR_timeout_STAR_ = (10000);
clojure.browser.net.event_types = cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p__17616){var vec__17617 = p__17616;var k = cljs.core.nth.call(null,vec__17617,(0),null);var v = cljs.core.nth.call(null,vec__17617,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
}),cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.net.EventType))));
clojure.browser.net.IConnection = (function (){var obj17619 = {};return obj17619;
})();
clojure.browser.net.connect = (function() {
var connect = null;
var connect__1 = (function (this$){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$1;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$1(this$);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$);
}
});
var connect__2 = (function (this$,opt1){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$2;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$2(this$,opt1);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1);
}
});
var connect__3 = (function (this$,opt1,opt2){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$3;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$3(this$,opt1,opt2);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1,opt2);
}
});
var connect__4 = (function (this$,opt1,opt2,opt3){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$connect$arity$4;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$connect$arity$4(this$,opt1,opt2,opt3);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.connect[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.connect["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.connect",this$);
}
}
})().call(null,this$,opt1,opt2,opt3);
}
});
connect = function(this$,opt1,opt2,opt3){
switch(arguments.length){
case 1:
return connect__1.call(this,this$);
case 2:
return connect__2.call(this,this$,opt1);
case 3:
return connect__3.call(this,this$,opt1,opt2);
case 4:
return connect__4.call(this,this$,opt1,opt2,opt3);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
connect.cljs$core$IFn$_invoke$arity$1 = connect__1;
connect.cljs$core$IFn$_invoke$arity$2 = connect__2;
connect.cljs$core$IFn$_invoke$arity$3 = connect__3;
connect.cljs$core$IFn$_invoke$arity$4 = connect__4;
return connect;
})()
;
clojure.browser.net.transmit = (function() {
var transmit = null;
var transmit__2 = (function (this$,opt){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$2;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$2(this$,opt);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt);
}
});
var transmit__3 = (function (this$,opt,opt2){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$3;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$3(this$,opt,opt2);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2);
}
});
var transmit__4 = (function (this$,opt,opt2,opt3){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$4;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$4(this$,opt,opt2,opt3);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3);
}
});
var transmit__5 = (function (this$,opt,opt2,opt3,opt4){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$5;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$5(this$,opt,opt2,opt3,opt4);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3,opt4);
}
});
var transmit__6 = (function (this$,opt,opt2,opt3,opt4,opt5){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$transmit$arity$6;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$transmit$arity$6(this$,opt,opt2,opt3,opt4,opt5);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.transmit[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.transmit["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.transmit",this$);
}
}
})().call(null,this$,opt,opt2,opt3,opt4,opt5);
}
});
transmit = function(this$,opt,opt2,opt3,opt4,opt5){
switch(arguments.length){
case 2:
return transmit__2.call(this,this$,opt);
case 3:
return transmit__3.call(this,this$,opt,opt2);
case 4:
return transmit__4.call(this,this$,opt,opt2,opt3);
case 5:
return transmit__5.call(this,this$,opt,opt2,opt3,opt4);
case 6:
return transmit__6.call(this,this$,opt,opt2,opt3,opt4,opt5);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
transmit.cljs$core$IFn$_invoke$arity$2 = transmit__2;
transmit.cljs$core$IFn$_invoke$arity$3 = transmit__3;
transmit.cljs$core$IFn$_invoke$arity$4 = transmit__4;
transmit.cljs$core$IFn$_invoke$arity$5 = transmit__5;
transmit.cljs$core$IFn$_invoke$arity$6 = transmit__6;
return transmit;
})()
;
clojure.browser.net.close = (function close(this$){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$IConnection$close$arity$1;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$IConnection$close$arity$1(this$);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.close[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.close["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"IConnection.close",this$);
}
}
})().call(null,this$);
}
});
goog.net.XhrIo.prototype.clojure$browser$event$IEventType$ = true;
goog.net.XhrIo.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){var this$__$1 = this;return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){
return (function (p__17620){var vec__17621 = p__17620;var k = cljs.core.nth.call(null,vec__17621,(0),null);var v = cljs.core.nth.call(null,vec__17621,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
});})(this$__$1))
,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.net.EventType))));
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$ = true;
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$2 = (function (this$,uri){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,"GET",null,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$3 = (function (this$,uri,method){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,null,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$4 = (function (this$,uri,method,content){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,content,null,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$5 = (function (this$,uri,method,content,headers){var this$__$1 = this;return clojure.browser.net.transmit.call(null,this$__$1,uri,method,content,headers,clojure.browser.net._STAR_timeout_STAR_);
});
goog.net.XhrIo.prototype.clojure$browser$net$IConnection$transmit$arity$6 = (function (this$,uri,method,content,headers,timeout){var this$__$1 = this;this$__$1.setTimeoutInterval(timeout);
return this$__$1.send(uri,method,content,headers);
});
clojure.browser.net.xpc_config_fields = cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,(function (p__17622){var vec__17623 = p__17622;var k = cljs.core.nth.call(null,vec__17623,(0),null);var v = cljs.core.nth.call(null,vec__17623,(1),null);return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
}),cljs.core.js__GT_clj.call(null,goog.net.xpc.CfgFields)));
/**
* Returns an XhrIo connection
*/
clojure.browser.net.xhr_connection = (function xhr_connection(){return (new goog.net.XhrIo());
});
clojure.browser.net.ICrossPageChannel = (function (){var obj17625 = {};return obj17625;
})();
clojure.browser.net.register_service = (function() {
var register_service = null;
var register_service__3 = (function (this$,service_name,fn){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$3;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$3(this$,service_name,fn);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.register_service[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.register_service["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"ICrossPageChannel.register-service",this$);
}
}
})().call(null,this$,service_name,fn);
}
});
var register_service__4 = (function (this$,service_name,fn,encode_json_QMARK_){if((function (){var and__5741__auto__ = this$;if(and__5741__auto__)
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$4;
} else
{return and__5741__auto__;
}
})())
{return this$.clojure$browser$net$ICrossPageChannel$register_service$arity$4(this$,service_name,fn,encode_json_QMARK_);
} else
{var x__6711__auto__ = (((this$ == null))?null:this$);return (function (){var or__5757__auto__ = (clojure.browser.net.register_service[goog.typeOf(x__6711__auto__)]);if(or__5757__auto__)
{return or__5757__auto__;
} else
{var or__5757__auto____$1 = (clojure.browser.net.register_service["_"]);if(or__5757__auto____$1)
{return or__5757__auto____$1;
} else
{throw cljs.core.missing_protocol.call(null,"ICrossPageChannel.register-service",this$);
}
}
})().call(null,this$,service_name,fn,encode_json_QMARK_);
}
});
register_service = function(this$,service_name,fn,encode_json_QMARK_){
switch(arguments.length){
case 3:
return register_service__3.call(this,this$,service_name,fn);
case 4:
return register_service__4.call(this,this$,service_name,fn,encode_json_QMARK_);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
register_service.cljs$core$IFn$_invoke$arity$3 = register_service__3;
register_service.cljs$core$IFn$_invoke$arity$4 = register_service__4;
return register_service;
})()
;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$ = true;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$1 = (function (this$){var this$__$1 = this;return clojure.browser.net.connect.call(null,this$__$1,null);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$2 = (function (this$,on_connect_fn){var this$__$1 = this;return this$__$1.connect(on_connect_fn);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$3 = (function (this$,on_connect_fn,config_iframe_fn){var this$__$1 = this;return clojure.browser.net.connect.call(null,this$__$1,on_connect_fn,config_iframe_fn,document.body);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$connect$arity$4 = (function (this$,on_connect_fn,config_iframe_fn,iframe_parent){var this$__$1 = this;this$__$1.createPeerIframe(iframe_parent,config_iframe_fn);
return this$__$1.connect(on_connect_fn);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$transmit$arity$3 = (function (this$,service_name,payload){var this$__$1 = this;return this$__$1.send(cljs.core.name.call(null,service_name),payload);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$IConnection$close$arity$1 = (function (this$){var this$__$1 = this;return this$__$1.close();
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$ = true;
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$register_service$arity$3 = (function (this$,service_name,fn){var this$__$1 = this;return clojure.browser.net.register_service.call(null,this$__$1,service_name,fn,false);
});
goog.net.xpc.CrossPageChannel.prototype.clojure$browser$net$ICrossPageChannel$register_service$arity$4 = (function (this$,service_name,fn,encode_json_QMARK_){var this$__$1 = this;return this$__$1.registerService(cljs.core.name.call(null,service_name),fn,encode_json_QMARK_);
});
/**
* When passed with a config hash-map, returns a parent
* CrossPageChannel object. Keys in the config hash map are downcased
* versions of the goog.net.xpc.CfgFields enum keys,
* e.g. goog.net.xpc.CfgFields.PEER_URI becomes :peer_uri in the config
* hash.
*
* When passed with no args, creates a child CrossPageChannel object,
* and the config is automatically taken from the URL param 'xpc', as
* per the CrossPageChannel API.
*/
clojure.browser.net.xpc_connection = (function() {
var xpc_connection = null;
var xpc_connection__0 = (function (){var temp__4126__auto__ = (new goog.Uri(window.location.href)).getParameterValue("xpc");if(cljs.core.truth_(temp__4126__auto__))
{var config = temp__4126__auto__;return (new goog.net.xpc.CrossPageChannel(goog.json.parse(config)));
} else
{return null;
}
});
var xpc_connection__1 = (function (config){return (new goog.net.xpc.CrossPageChannel(cljs.core.reduce.call(null,(function (sum,p__17631){var vec__17632 = p__17631;var k = cljs.core.nth.call(null,vec__17632,(0),null);var v = cljs.core.nth.call(null,vec__17632,(1),null);var temp__4124__auto__ = cljs.core.get.call(null,clojure.browser.net.xpc_config_fields,k);if(cljs.core.truth_(temp__4124__auto__))
{var field = temp__4124__auto__;var G__17633 = sum;(G__17633[field] = v);
return G__17633;
} else
{return sum;
}
}),(function (){var obj17635 = {};return obj17635;
})(),config)));
});
xpc_connection = function(config){
switch(arguments.length){
case 0:
return xpc_connection__0.call(this);
case 1:
return xpc_connection__1.call(this,config);
}
throw(new Error('Invalid arity: ' + arguments.length));
};
xpc_connection.cljs$core$IFn$_invoke$arity$0 = xpc_connection__0;
xpc_connection.cljs$core$IFn$_invoke$arity$1 = xpc_connection__1;
return xpc_connection;
})()
;
|
module.exports = function (info, brain, viewArea) {
this.brain = brain
this.energy = info.energy,
this.fitness = 0
this.position = {
x: info.position.x,
y: info.position.y
}
this.behaved = false
this.viewArea = viewArea
this.viewport = []
this.behave = function (world) {
this.findViewport(world)
for (var x = 0; x < this.viewArea; x += 1) {
for (var y = 0; y < this.viewArea; y += 1) {
if (this.brain.viewArea[x][y].length > 0) {
for (var link = 0; link < this.brain.viewArea[x][y].length; link += 1) {
if (this.viewport[x][y] == this.brain.viewArea[x][y][link].test) {
if (!this.behaved) {
this.brain.viewArea[x][y][link].run(this, world)
this.behaved = true
}
}
}
}
}
}
this.behaved = false
}
this.findViewport = function (world) {
this.viewport = []
for (var x = 0; x < this.viewArea; x += 1) {
this.viewport[x] = []
for (var y = 0; y < this.viewArea; y += 1) {
if (this.position.x + x - Math.floor(this.viewArea / 2) < 0 || this.position.x + x - Math.floor(this.viewArea / 2) > world.size - 1 || this.position.y + y - Math.floor(this.viewArea / 2) < 0 || this.position.y + y - Math.floor(this.viewArea / 2) > world.size - 1) {
this.viewport[x][y] = ''
}
else {
this.viewport[x][y] = world.world[this.position.x + x - Math.floor(this.viewArea / 2)][this.position.y + y - Math.floor(this.viewArea / 2)]
}
}
}
}
}
|
<ToastContainer>
<Toast>
<Toast.Header>
<img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
<strong className="me-auto">Bootstrap</strong>
<small className="text-muted">just now</small>
</Toast.Header>
<Toast.Body>See? Just like this.</Toast.Body>
</Toast>
<Toast>
<Toast.Header>
<img src="holder.js/20x20?text=%20" className="rounded me-2" alt="" />
<strong className="me-auto">Bootstrap</strong>
<small className="text-muted">2 seconds ago</small>
</Toast.Header>
<Toast.Body>Heads up, toasts will stack automatically</Toast.Body>
</Toast>
</ToastContainer>;
|
app.factory("MatchesService", function ($http, $q) {
//var token = sessionStorage.getItem('accessToken');
var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtYXJjbyIsImVtYWlsIjoibWFyY28iLCJ2ZXIiOiIzIiwiaXNzIjoiaHR0cHM6Ly9hcGktZ2hvc3RzLmF6dXJld2Vic2l0ZXMubmV0LyIsImF1ZCI6Imh0dHBzOi8vYXBpLWdob3N0cy5henVyZXdlYnNpdGVzLm5ldC8iLCJleHAiOjE0Nzk1NDYxOTgsIm5iZiI6MTQ3OTQ1OTc5OH0.t7OEn6TV1KOCmZZlUY9PnjNu0z-KaN4RS1VSJ3OmytM";
//var _sediEnergia = [];
//var _sediEnergiaLoaded = false;
var _getMatches = function () {
var deferred = $q.defer();
$http({
url: config.apiurl + "odata/Matches",
method: "GET"
//,headers: {
// "X-ZUMO-AUTH": token
//}
}).then(function (result) {
deferred.resolve({ "Data": result.data.value });
}, function () { // failure
deferred.reject("Errore durante la richiesta di elaborazione stagioni.");
});
return deferred.promise;
};
return {
GetMatches: _getMatches
};
}); |
var NodeGit = require("../");
var normalizeOid = require("./util/normalize_oid");
var Blob = require("./blob");
var Tree = require("./tree");
var Tag = require("./tag");
var Reference = require("./reference");
var Revwalk = require("./revwalk");
var Commit = require("./commit");
var Remote = require("./remote");
var Promise = require("nodegit-promise");
var TreeBuilder = NodeGit.Treebuilder;
var Repository = NodeGit.Repository;
Object.defineProperty(Repository.prototype, "openIndex", {
enumerable: false,
value: Repository.prototype.index
});
/**
* Creates a branch with the passed in name pointing to the commit
*
* @param {String} name Branch name, e.g. "master"
* @param {Commit|String|Oid} commit The commit the branch will point to
* @param {bool} force Overwrite branch if it exists
* @param {Signature} signature Identity to use to populate reflog
* @param {String} logMessage One line message to be appended to the reflog
* @return {Ref}
*/
Repository.prototype.createBranch =
function(name, commit, force, signature, logMessage) {
var repo = this;
if (commit instanceof Commit) {
return NodeGit.Branch.create(
repo,
name,
commit,
force ? 1 : 0,
signature,
logMessage);
}
else {
return repo.getCommit(commit).then(function(commit) {
return NodeGit.Branch.create(
repo,
name,
commit,
force ? 1 : 0,
signature,
logMessage);
});
}
};
/**
* Look up a branch
*
* @param {String} name Branch name, e.g. "master"
* @param {Function} callback
* @return {Ref}
*/
Repository.prototype.getBranch = function(name, callback) {
name = ~name.indexOf("refs/heads/") ? name : "refs/heads/" + name;
return this.getReference(name).then(function(reference) {
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}, callback);
};
/**
* Look up a branch's most recent commit.
*
* @param {String} name Branch name, e.g. "master"
* @param {Function} callback
* @return {Commit}
*/
Repository.prototype.getBranchCommit = function(name, callback) {
var repository = this;
return this.getBranch(name).then(function(reference) {
return repository.getCommit(reference.target()).then(function(commit) {
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
});
}, callback);
};
/**
* Lists out the remotes in the given repository.
*
* @param {Function} Optional callback
* @return {Object} Promise object.
*/
Repository.prototype.getRemotes = function(callback) {
return Remote.list(this).then(function(remotes) {
if (typeof callback === "function") {
callback(null, remotes);
}
return remotes;
}, callback);
};
/**
* Lookup the reference with the given name.
*
* @param {String} name
* @param {Function} callback
* @return {Reference}
*/
Repository.prototype.getReference = function(name, callback) {
var repository = this;
return Reference.lookup(this, name).then(function(reference) {
if (reference.isSymbolic()) {
return reference.resolve(function (error, reference) {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
});
} else {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}
}, callback);
};
Repository.getReferences = function(repo, type, refNamesOnly, callback) {
return Reference.list(repo).then(function(refList) {
var refFilterPromises = [];
var filteredRefs = [];
refList.forEach(function(refName) {
refFilterPromises.push(Reference.lookup(repo, refName)
.then(function(ref) {
if (type == Reference.TYPE.ALL || ref.type() == type) {
if (refNamesOnly) {
filteredRefs.push(refName);
return;
}
if (ref.isSymbolic()) {
return ref.resolve().then(function(resolvedRef) {
resolvedRef.repo = repo;
filteredRefs.push(resolvedRef);
});
}
else {
filteredRefs.push(ref);
}
}
})
);
});
return Promise.all(refFilterPromises).then(function() {
if (typeof callback === "function") {
callback(null, filteredRefs);
}
return filteredRefs;
}, callback);
});
};
Repository.prototype.getReferences = function(type, callback) {
return Repository.getReferences(this, type, false, callback);
};
Repository.prototype.getReferenceNames = function(type, callback) {
return Repository.getReferences(this, type, true, callback);
};
/**
* Retrieve the commit identified by oid.
*
* @param {String|Oid} String sha or Oid
* @param {Function} callback
* @return {Commit}
*/
Repository.prototype.getCommit = function(oid, callback) {
oid = normalizeOid(oid);
var repository = this;
return Commit.lookup(repository, oid).then(function(commit) {
commit.repo = repository;
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
}, callback);
};
/**
* Retrieve the blob represented by the oid.
*
* @param {String|Oid} String sha or Oid
* @param {Function} callback
* @return {Blob}
*/
Repository.prototype.getBlob = function(oid, callback) {
oid = normalizeOid(oid);
var repository = this;
return Blob.lookup(repository, oid).then(function(blob) {
blob.repo = repository;
if (typeof callback === "function") {
callback(null, blob);
}
return blob;
}, callback);
};
/**
* Retrieve the tree represented by the oid.
*
* @param {String|Oid} String sha or Oid
* @param {Function} callback
* @return {Tree}
*/
Repository.prototype.getTree = function(oid, callback) {
oid = normalizeOid(oid);
var repository = this;
return Tree.lookup(repository, oid).then(function(tree) {
tree.repo = repository;
if (typeof callback === "function") {
callback(null, tree);
}
return tree;
}, callback);
};
/**
* Retrieve the tag represented by the oid.
*
* @param {String|Oid} String sha or Oid
* @param {Function} callback
* @return {Tag}
*/
Repository.prototype.getTag = function(oid, callback) {
oid = normalizeOid(oid);
var repository = this;
return Tag.lookup(repository, oid).then(function(reference) {
reference.repo = repository;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
}, callback);
};
/**
* Retrieve the tag represented by the tag name.
*
* @param {String} Short or full tag name
* @param {Function} callback
* @return {Tag}
*/
Repository.prototype.getTagByName = function(name, callback) {
var repo = this;
name = ~name.indexOf("refs/tags/") ? name : "refs/tags/" + name;
return Reference.nameToId(repo, name).then(function(oid) {
return Tag.lookup(repo, oid).then(function(reference) {
reference.repo = repo;
if (typeof callback === "function") {
callback(null, reference);
}
return reference;
});
}, callback);
};
/**
* Instantiate a new revision walker for browsing the Repository"s history.
* See also `Commit.prototype.history()`
*
* @param {String|Oid} String sha or Oid
* @param {Function} callback
* @return {RevWalk}
*/
Repository.prototype.createRevWalk = function() {
var revWalk = Revwalk.create(this);
revWalk.repo = this;
return revWalk;
};
/**
* Retrieve the master branch commit.
*
* @param {Function} callback
* @return {Commit}
*/
Repository.prototype.getMasterCommit = function(callback) {
return this.getBranchCommit("master", callback);
};
/**
* Create a commit
*
* @param {String} updateRef
* @param {Signature} author
* @param {Signature} committer
* @param {String} message
* @param {Tree|Oid|String} Tree
* @param {Array} parents
* @param {Function} callback
* @return {Oid} The oid of the commit
*/
Repository.prototype.createCommit = function(
updateRef, author, committer, message, tree, parents, callback) {
var createCommit = null;
var repo = this;
if (tree instanceof Tree) {
createCommit = Promise.all([
Commit.create(
repo,
updateRef,
author,
committer,
null /* use default message encoding */,
message,
tree,
parents.length,
parents
)
]);
} else {
createCommit = this.getTree(tree).then(function(tree) {
return Commit.create(
repo,
updateRef,
author,
committer,
null /* use default message encoding */,
message,
tree,
parents.length,
parents
);
});
}
return createCommit.then(function(commit) {
if (typeof callback === "function") {
callback(null, commit);
}
return commit;
}, callback);
};
/**
* Create a blob from a buffer
*
* @param {Buffer} buffer
* @param {Function} callback
* @return {Blob}
*/
Repository.prototype.createBlobFromBuffer = function(buffer, callback) {
return Blob.createFrombuffer.call(this, buffer, buffer.length, callback);
};
/**
* Create a new tree builder.
*
* @param {Tree} tree
*/
Repository.prototype.treeBuilder = function() {
var builder = TreeBuilder.create(null);
builder.root = builder;
builder.repo = this;
return builder;
};
module.exports = Repository;
|
export default {
today: 'आज',
now: 'अभी',
backToToday: 'आज तक',
ok: 'ठीक',
clear: 'स्पष्ट',
month: 'महीना',
year: 'साल',
timeSelect: 'समय का चयन करें',
dateSelect: 'तारीख़ चुनें',
weekSelect: 'एक सप्ताह चुनें',
monthSelect: 'एक महीना चुनें',
yearSelect: 'एक वर्ष चुनें',
decadeSelect: 'एक दशक चुनें',
yearFormat: 'YYYY',
dateFormat: 'M/D/YYYY',
dayFormat: 'D',
dateTimeFormat: 'M/D/YYYY HH:mm:ss',
monthBeforeYear: true,
previousMonth: 'पिछला महीना (पेजअप)',
nextMonth: 'अगले महीने (पेजडाउन)',
previousYear: 'पिछले साल (Ctrl + बाएं)',
nextYear: 'अगले साल (Ctrl + दाहिना)',
previousDecade: 'पिछला दशक',
nextDecade: 'अगले दशक',
previousCentury: 'पीछ्ली शताब्दी',
nextCentury: 'अगली सदी',
};
|
export default function getElementOverride (element, overrides) {
const parentNode = getTopMostElementParent(element)
for (const override in overrides) {
if (overrides.hasOwnProperty(override)) {
try {
const matches = parentNode.querySelectorAll(override)
if (Array.prototype.indexOf.call(matches, element) > -1) {
return overrides[override]
}
} catch (e) {
// At least we tried.
}
}
}
}
function getTopMostElementParent (element) {
let parentNode = element.parentNode
// Traverse up the DOM tree until the last parent is found.
while (parentNode.parentNode) {
parentNode = parentNode.parentNode
}
return parentNode
}
|
/**
* The description of some function c.
* @param {void}
* @return {function} a function return type
*/ |
window.djangocms_tonicdev_render = function(source, opts, callback) {
try {
var notebook = Tonic.createNotebook({
element: document.getElementById(opts.variable_name + "_element"),
source: source,
readOnly: opts.readonly,
nodeVersion: opts.node_version,
onURLChanged: function(notebook) {
console.log("Tonic Notebook {{ instance.ident }} URL:", notebook.URL);
}
});
callback(undefined, notebook);
} catch(err) {
console.log(err);
callback(err);
}
} |
// Karma configuration
// Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-jquery', 'jquery-1.8.3', 'sinon-chai'],
plugins: [
'karma-mocha',
'karma-chai',
'karma-sinon-chai',
'karma-chrome-launcher',
'karma-phantomjs-launcher',
'karma-jquery',
'karma-chai-jquery'
],
// list of files / patterns to load in the browser
files: [
'bower/angular/angular.js',
'bower/angular-sanitize/angular-sanitize.js',
'bower/angular-mocks/angular-mocks.js',
'dist/ng-timeline.js',
'test/unit/**/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// 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: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
var mongoose = require('mongoose');
// mongoose.connect('mongodb://localhost:27017/linda');
var userSchema = require('../models/user')
var Faker = require('faker')
function getUsers(db, callback) {
console.log('Im alive')
var userModel = mongoose.model('User', userSchema)
userModel.find(function (err, res) {
if (err) console.log('shit error', err)
console.log('finished reading database')
callback(err, res)
})
}
function saveUser(db, userForDB, callback) {
console.log('started save process')
var userModel = mongoose.model('User', userSchema)
userForDB = new userModel(userForDB)
userForDB.save(function (err, res) {
if (err) return console.log('shit error', err)
console.log('save finished')
callback(err, res)
})
}
module.exports = {
"getUsers": getUsers,
"saveUser": saveUser
}
// fakeUserOptions (n) => [{}, {}]
// function fakerUsers(userNumber) {
// var userOptions = []
// for (var i = 0; i < userNumber; i++) {
// var user = {
// email: Faker.Internet.email(),
// firstName: Faker.Name.firstName(),
// lastName: Faker.Name.lastName(),
// age: 32,
// description: "Pretend description!!",
// location: Faker.Address.city(),
// img: Faker.Image.imageUrl()
// }
// userOptions.push(user)
// }
// return userOptions
// }
|
//Bindings
//Debug Mode Switch Detector
keyboard.bindKey(keyboard.getKeyID("F4"),"debugswitch.js")
//Fireball (Debug stuff!)
keyboard.bindKey(45,"fireball.js")
//Global Timers
//Ship Reset (~~ SPOILER ALERT ~~)
shipResetTimer = shipResetTimer + 1
//Heal over Time
//NOTE: EXTERNAL :P
if(keyboard.isKeyDown(keyboard.getKeyID("F10"))) {chat.print(debug)}
//Defining
//Position
pos = player.getPosition()
//Inventory
inv = player.getInventory()
//Speed
playerspeed = player.moveSpeed
//Function "SwingRHand()"[Swings the Right Hand] and "SwingLHand()"[Swings the left hand]
function swingRHand(){player.swingMainHand()}
function swingLHand(){player.swingOffHand()}
//Entities around the player[20 Blocks]
pentities = player.getEntitiesWithinRange(20);
for(var i=0; i<pentities.length; i++)
{
pent = pentities[i];
}
//Jump Velocity
jumpVelocity = player.jumpVelocity
//Width and Height of screen
width = ui.getWidth()
height = ui.getHeight()
//Check if near... function
isNear = function isNear(scriptPos,shouldpos)
{
aboutPos = Vec3(Math.round(scriptPos.x),Math.round(scriptPos.y),Math.round(scriptPos.z))
if(aboutPos == shouldpos) {return true} else {return false}
}
//LookVec
lookVec = player.lookVec
//NULL
printxyz = function printxyz(argVec) {
chat.print(argVec.x)
chat.print(argVec.y)
chat.print(argVec.z)
}
//Scripts
//Sprint
//Check if Sprint-Key is Pressed
if(keyboard.isKeyDown(29) == true) //Here LControl
{
//Set into Sprint Speed
player.moveSpeed = 1.7
//Set into Sprint Jump Velocity
player.jumpVelocity = 0.42 * 1.2
}
else
{ //If its not already....
if (player.moveSpeed >= 1.1)
{ //Set to normal Speed
player.moveSpeed = 1
}
//Also ...
if(player.jumpVelocity >= 0.43)
{ //Set into normal Jumpvelocity
player.jumpVelocity = 0.42
}
}
//Item Manager
//IronSword always in first Slot
PosofSword = inv.getSlotContainingItem(267)
if(PosofSword != -1)
{
if(PosofSword != 0)
{
try
{
inv.emptySlot(PosofSword)
pitem = inv.getItemInSlot(0)
inv.setSlot(0, Item(267))
inv.setCursorItem(Item(pitem.getItemID(),pitem.getQuantity(),pitem.getDamage()));
}
catch(e) {}
}
}
//Shield always in Second Slot
PosofShield = inv.getSlotContainingItem(461)
if(PosofShield != -1)
{
if(PosofShield != 1)
{
try
{
inv.emptySlot(PosofShield)
pitem = inv.getItemInSlot(1)
inv.setSlot(1, Item(461))
inv.setCursorItem(Item(pitem.getItemID(),pitem.getQuantity()));
}
catch(e) {}
}
}
//Feather Vanish
inv.consumeItem(288)
//Resets Sugar Canes after Death[Needed Due to AdventureCraft bug (Version: r1095)]
if(player.isAlive() == 0)
{
world.triggerBlock(-98,64,-97)
}
//Sleep (seprate)
script.runScript("sleeping.js")
//Bugfix Sleep <-- Gonna be used soon again, found the "source of all evil"!
if(sleepEffect.alpha > 1)
{
sleepEffect.alpha = 1
}
if(sleepEffect.alpha < 0)
{
sleepEffect.alpha = 0
}
//Rolloverhealth(seprate)
if(rollhealth) {
script.runScript("rolloverhealth.js")
}
//Stacks above 64 update(seprate)
script.runScript("U_Stack.js")
//Fly up(debug only)
if(keyboard.isKeyDown(keyboard.getKeyID("I")))
{
player.setVelocity(player.getVelocity().x,0.3,player.getVelocity().z)
}
//Heal over time (seprate)
script.runScript("healovertime.js")
//Money GUI (seprate)
script.runScript("Displaymoney.js")
//Reseting Ship (~~ SPOILER ALERT ~~)
if(shipResetTimer >= 60) {
world.triggerBlock(-76,62,103)
world.triggerBlock(-86,62,133)
shipResetTimer = 0
}
//Health Pack (seprate)
//script.runScript("healPack.js")
//fireBoom Script (aka the "Player on Fire + Bomb in Hand = Boom" Script)
script.runScript("fireBoom.js") |
///////////////////////////////////////////////////////////////////////////
// Copyright © Esri. All Rights Reserved.
//
// Licensed under the Apache License Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
define({
"_widgetLabel": "Аналіз вартості",
"unableToFetchInfoErrMessage": "Неможливо виконати вибірку детальної інформації сервісу геометрії/налаштованого шару",
"invalidCostingGeometryLayer": "Неможливо отримати параметр «esriFieldTypeGlobalID» при оцінці вартості шару геометрії.",
"projectLayerNotFound": "Неможливо знайти налаштований проектний шар на карті.",
"costingGeometryLayerNotFound": "Неможливо знайти налаштований шар оцінки вартості геометрії на карті.",
"projectMultiplierTableNotFound": "Неможливо знайти налаштовану таблицю проектної додаткової вартості з множником на карті.",
"projectAssetTableNotFound": "Неможливо знайти налаштовану таблицю проектних активів на карті.",
"createLoadProject": {
"createProjectPaneTitle": "Створити проект",
"loadProjectPaneTitle": "Завантажити проект",
"projectNamePlaceHolder": "Назва проекту",
"projectDescPlaceHolder": "Опис проекту",
"selectProject": "Вибрати проект",
"viewInMapLabel": "Переглянути на карті",
"loadLabel": "Завантажити",
"createLabel": "Створити",
"deleteProjectConfirmationMsg": "Бажаєте видалити проект?",
"noAssetsToViewOnMap": "Вибраний проект не має активів для перегляду на карті.",
"projectDeletedMsg": "Проект успішно видалено.",
"errorInCreatingProject": "Помилка при створенні проекту.",
"errorProjectNotFound": "Проект не знайдено.",
"errorInLoadingProject": "Перевірте, чи вибрано дійсний проект.",
"errorProjectNotSelected": "Вибрати таблицю з розкривного списку",
"errorDuplicateProjectName": "Назва проекту вже існує.",
"errorFetchingPointLabel": "Помилка під час вибірки точки напису. Спробуйте знову",
"errorAddingPointLabel": "Помилка під час додавання точки напису. Спробуйте знову"
},
"statisticsSettings": {
"tabTitle": "Налаштування статистики",
"addStatisticsLabel": "Додати статистику",
"addNewStatisticsText": "Додати нову статистику",
"deleteStatisticsText": "Видалити статистику",
"moveStatisticsUpText": "Перемістити статистику вгору",
"moveStatisticsDownText": "Перемістити статистику вниз",
"layerNameTitle": "Шар",
"statisticsTypeTitle": "Тип",
"fieldNameTitle": "Поле",
"statisticsTitle": "Напис",
"actionLabelTitle": "Дії",
"selectDeselectAllTitle": "Вибрати всі"
},
"statisticsType": {
"countLabel": "Лічильник",
"averageLabel": "Середнє",
"maxLabel": "Максимум",
"minLabel": "Мінімум",
"summationLabel": "Підсумовування",
"areaLabel": "Площа",
"lengthLabel": "Довжина"
},
"costingInfo": {
"noEditableLayersAvailable": "Шар(-и) необхідно відмітити як редагований у вкладці налаштувань шару"
},
"workBench": {
"refresh": "Оновити",
"noAssetAddedMsg": "Активи не додано",
"units": "одиниця(-і)",
"assetDetailsTitle": "Детальна інформація про елемент активу",
"costEquationTitle": "Рівняння вартості",
"newCostEquationTitle": "Нове рівняння",
"defaultCostEquationTitle": "Рівняння за замовчуванням",
"geographyTitle": "Географія",
"scenarioTitle": "Сценарій",
"costingInfoHintText": "<div>Підказка: Використовуйте наступні ключові слова</div><ul><li><b>{TOTALCOUNT}</b>: Використовує загальну кількість одного типу активу в географії</li> <li><b>{MEASURE}</b>: Використовує довжину для лінійного активу та площу для полігонального активу</li><li><b>{TOTALMEASURE}</b>: Використовує загальну довжину для лінійного активу та загальну площу для полігонального активу одного типу в географії</li></ul> Можна використовувати такі функції як:<ul><li>Math.abs(-100)</li><li>Math.floor({TOTALMEASURE})</li></ul>Відредагуйте рівняння вартості відповідно до потреб проекту.",
"zoomToAsset": "Масштабувати до активу",
"deleteAsset": "Видалити актив",
"closeDialog": "Закрити діалог",
"objectIdColTitle": "Ідентифікатор об'єкту",
"costColTitle": "Вартість",
"errorInvalidCostEquation": "Недійсне рівняння вартості.",
"errorInSavingAssetDetails": "Неможливо зберегти детальну інформацію про актив.",
"featureModeText": "Режим об'єкту",
"sketchToolTitle": "Скетч",
"selectToolTitle": "Вибрати"
},
"assetDetails": {
"inGeography": " в ${geography} ",
"withScenario": " з ${scenario}",
"totalCostTitle": "Загальна вартість",
"additionalCostLabel": "Опис",
"additionalCostValue": "Значення",
"additionalCostNetValue": "Чисте значення"
},
"projectOverview": {
"assetItemsTitle": "Елементи активів",
"assetStatisticsTitle": "Статистика активів",
"projectSummaryTitle": "Коротка інформація про проект",
"projectName": "Назва проекту: ${name}",
"totalCostLabel": "Загальна вартість проекту (*):",
"grossCostLabel": "Валова вартість проекту (*):",
"roundingLabel": "* Округлення до '${selectedRoundingOption}'",
"unableToSaveProjectBoundary": "Неможливо зберегти проектний кордон у проектному шарі.",
"unableToSaveProjectCost": "Неможливо зберегти вартість у проектному шарі.",
"roundCostValues": {
"twoDecimalPoint": "Дві десяткові коми",
"nearestWholeNumber": "Найближче ціле значення",
"nearestTen": "Найближчий десяток",
"nearestHundred": "Найближча сотня",
"nearestThousand": "Найближча тисяча",
"nearestTenThousands": "Найближчі десять тисяч"
}
},
"projectAttribute": {
"projectAttributeText": "Атрибут проекту",
"projectAttributeTitle": "Редагувати атрибути проекту"
},
"costEscalation": {
"costEscalationLabel": "Додати додаткову вартість",
"valueHeader": "Значення",
"addCostEscalationText": "Додати додаткову вартість",
"deleteCostEscalationText": "Видалити вибрану додаткову вартість",
"moveCostEscalationUpText": "Перемістити вибрану додаткову вартість вгору",
"moveCostEscalationDownText": "Перемістити вибрану додаткову вартість вниз",
"invalidEntry": "Один або більше записів недійсний.",
"errorInSavingCostEscalation": "Неможливо зберегти детальну інформацію про додаткову вартість."
},
"scenarioSelection": {
"popupTitle": "Вибрати сценарій для активу",
"regionLabel": "Географія",
"scenarioLabel": "Сценарій",
"noneText": "Немає",
"copyFeatureMsg": "Бажаєте копіювати вибрані об’єкти?"
},
"detailStatistics": {
"detailStatisticsLabel": "Детальна статистика",
"noDetailStatisticAvailable": "Статистику активів не додано"
},
"copyFeatures": {
"title": "Копіювати об'єкти",
"createFeatures": "Створити об'єкти",
"createSingleFeature": "Створити 1 мультигеометричний об'єкт",
"noFeaturesSelectedMessage": "Об'єкти не вибрано",
"selectFeatureToCopyMessage": "Виберіть об'єкти для копіювання."
},
"updateCostEquationPanel": {
"updateProjectCostTabLabel": "Оновити рівняння проекту",
"updateProjectCostSelectProjectTitle": "Вибрати всі проекти",
"updateButtonTextForm": "Оновлення",
"updateProjectCostSuccess": "Рівняння вартості вибраних проектів оновлено",
"updateProjectCostError": "Не вдалося оновити рівняння вартості вибраних проектів",
"updateProjectNoProject": "Проектів не знайдено"
}
}); |
/**
* Description: Hull model object for Vega Conflict
* Author: Alexander Abramov
* Date: 2014-08-11
*/
angular.module('vcApp').factory("Hull", ["Resources",
function(Resources) {
var Hull = function() {};
Object.defineProperty(Hull.prototype, "friendlyType", {
get: function() {
if (this.friendlyName != null) {
return this.friendlyName.substring(this.friendlyName.lastIndexOf(' ') + 1);
}
return "";
}
});
Object.defineProperty(Hull.prototype, "faction", {
get: function() {
if (this.descriptor != null) {
var firstSlashIndex = this.descriptor.indexOf('/');
var secondSlashIndex = this.descriptor.indexOf('/', firstSlashIndex + 1);
if (firstSlashIndex > 0 && secondSlashIndex > 0) {
return this.descriptor.substring(firstSlashIndex + 1, secondSlashIndex);
}
}
return "";
}
});
Object.defineProperty(Hull.prototype, "isBuildable", {
get: function() {
return (this.race == "Rebel" && this.filter == "Hull");
}
});
Object.defineProperty(Hull.prototype, "buildTime", {
get: function() {
if (this.cost != null && this.cost.item != null) {
var timeCandidates = this.cost.item.filter(Resources.isTimeCost);
if (timeCandidates.length > 0) {
return timeCandidates[0]["@amount"];
}
}
return 0;
}
});
Object.defineProperty(Hull.prototype, "repairTime", {
get: function() {
if (this.repair != null && this.repair.item != null) {
var timeCandidates = this.repair.item.filter(Resources.isTimeCost);
if (timeCandidates.length > 0) {
return timeCandidates[0]["@amount"];
}
}
return 0;
}
});
return Hull;
}
]);
angular.module('vcApp').factory("hulls", ["$http", "$q", "$filter", "modelTransformer", "Hull",
function($http, $q, $filter, modelTransformer, Hull) {
var result = $q.defer();
var hullsPromise = $http.get('data/vc/hulls.json');
var hullpropsPromise = $http.get('data/vc/hullprops.json');
$q.all([hullsPromise, hullpropsPromise]).then(function(data) {
var hullprops = data[1].data.root.objects;
var hulls = $filter('filter')(modelTransformer.transform(data[0].data.root.objects, Hull), {
isBuildable: true
});
angular.forEach(hulls, function(hull) {
var type = hull.type;
var hull2 = hullprops.find(function(el) {
return el.type == type;
});
for (var key in hull2) {
if (hull2.hasOwnProperty(key)) {
hull[key] = hull2[key];
}
}
});
console.log('Hulls factory: ', hulls);
result.resolve(hulls);
});
return result.promise;
}
]); |
/*
* @name app.home
*
* @description tbd
*/
angular.module('components.footer', []);
|
import Deck from './deck';
import Slide from './slide';
export { Deck, Slide };
|
var SilentError = require('../../node_modules/ember-cli/lib/errors/silent');
var fs = require('../../node_modules/ember-cli/node_modules/fs-extra');
var inflection = require('../../node_modules/ember-cli/node_modules/inflection');
var path = require('path');
var EOL = require('os').EOL;
module.exports = {
description: 'Generates a route and registers it with the router.',
availableOptions: [
{ name: 'type', values: ['route', 'resource'], default: 'route' }
],
fileMapTokens: function() {
return {
__templatepath__: function(options) {
if (options.pod) {
return path.join(options.podPath, options.dasherizedModuleName);
}
return 'templates';
},
__templatename__: function(options) {
if (options.pod) {
return 'template';
}
return options.dasherizedModuleName;
}
};
},
beforeInstall: function(options) {
var type = options.type;
if (type && !/^(resource|route)$/.test(type)) {
throw new SilentError('Unknown route type "' + type + '". Should be "route" or "resource".');
}
},
shouldTouchRouter: function(name) {
var isIndex = /index$/.test(name);
var isBasic = name === 'basic';
var isApplication = name === 'application';
return !isBasic && !isIndex && !isApplication;
},
afterInstall: function(options) {
var entity = options.entity;
if (this.shouldTouchRouter(entity.name) && !options.dryRun) {
addRouteToRouter(entity.name, {
type: options.type
});
}
},
beforeUninstall: function(options) {
var type = options.type;
if (type && !/^(resource|route)$/.test(type)) {
throw new SilentError('Unknown route type "' + type + '". Should be "route" or "resource".');
}
},
afterUninstall: function(options) {
var entity = options.entity;
if (this.shouldTouchRouter(entity.name) && !options.dryRun) {
removeRouteFromRouter(entity.name, {
type: options.type
});
}
}
};
function removeRouteFromRouter(name, options) {
var type = options.type || 'route';
var routerPath = path.join(process.cwd(), 'app', 'router.js');
var oldContent = fs.readFileSync(routerPath, 'utf-8');
var existence = new RegExp("(?:route|resource)\\s*\\(\\s*(['\"])" + name + "\\1");
var newContent;
var plural;
if (!existence.test(oldContent)) {
return;
}
switch (type) {
case 'route':
var re = new RegExp('\\s*this.route\\((["\'])'+ name +'(["\'])\\);');
newContent = oldContent.replace(re, '');
break;
case 'resource':
plural = inflection.pluralize(name);
if (plural === name) {
var re = new RegExp('\\s*this.resource\\((["\'])'+ name +'(["\'])\\);');
newContent = oldContent.replace(re, '');
} else {
var re = new RegExp('\\s*this.resource\\((["\'])'+ name +'(["\']),.*\\);');
newContent = oldContent.replace(re, '');
}
break;
}
fs.writeFileSync(routerPath, newContent);
}
function addRouteToRouter(name, options) {
var type = options.type || 'route';
var routerPath = path.join(process.cwd(), 'app', 'router.js');
var oldContent = fs.readFileSync(routerPath, 'utf-8');
var existence = new RegExp("(?:route|resource)\\s*\\(\\s*(['\"])" + name + "\\1");
var newContent;
var plural;
if (existence.test(oldContent)) {
return;
}
switch (type) {
case 'route':
newContent = oldContent.replace(
/(map\(function\(\) {[\s\S]+)}\)/,
"$1 this.route('" + name + "');" + EOL + "})"
);
break;
case 'resource':
plural = inflection.pluralize(name);
if (plural === name) {
newContent = oldContent.replace(
/(map\(function\(\) {[\s\S]+)}\)/,
"$1 this.resource('" + name + "', function() { });" + EOL + "})"
);
} else {
newContent = oldContent.replace(
/(map\(function\(\) {[\s\S]+)}\)/,
"$1 this.resource('" + name + "', { path: '" + plural + "/:" + name + "_id' }, function() { });" + EOL + "})"
);
}
break;
}
fs.writeFileSync(routerPath, newContent);
}
|
/* rekord 1.5.11 - A javascript REST ORM that is offline and real-time capable http://rekord.github.io/rekord/ by Philip Diffenderfer */
// UMD (Universal Module Definition)
(function (root, factory)
{
if (typeof define === 'function' && define.amd) // jshint ignore:line
{
// AMD. Register as an anonymous module.
define('rekord', [], function() { // jshint ignore:line
return factory(root);
});
}
else if (typeof module === 'object' && module.exports) // jshint ignore:line
{
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(global); // jshint ignore:line
}
else
{
// Browser globals (root is window)
root.Rekord = factory(root);
}
}(this, function(global, undefined)
{
var win = typeof window !== 'undefined' ? window : global; // jshint ignore:line
var AP = Array.prototype;
/**
* Converts the given variable to an array of strings. If the variable is a
* string it is split based on the delimiter given. If the variable is an
* array then it is returned. If the variable is any other type it may result
* in an error.
*
* ```javascript
* Rekord.toArray([1, 2, 3]); // [1, 2, 3]
* Rekord.toArray('1,2,3', ','); // ['1', '2', '3']
* Rekord.toArray(1); // [1]
* Rekord.toArray(null); // []
* ```
*
* @memberof Rekord
* @param {String|String[]} x
* The variable to convert to an Array.
* @param {String} [delimiter]
* The delimiter to split if the given variable is a string.
* @return {String[]} -
* The array of strings created.
*/
function toArray(x, delimiter)
{
if ( x instanceof Array )
{
return x;
}
if ( isString( x ) )
{
return x.split( delimiter );
}
if ( isValue( x ) )
{
return [ x ];
}
return [];
}
/**
* Finds the index of a variable in an array optionally using a custom
* comparison function. If the variable is not found in the array then `false`
* is returned.
*
* ```javascript
* Rekord.indexOf([1, 2, 3], 1); // 0
* Rekord.indexOf([1, 2, 3], 4); // false
* Rekord.indexOf([1, 2, 2], 2); // 1
* ```
*
*
* @memberof Rekord
* @param {Array} arr
* The array to search through.
* @param {Any} x
* The variable to search for.
* @param {Function} [comparator]
* The function to use which compares two values and returns a truthy
* value if they are considered equivalent. If a comparator is not given
* then strict comparison is used to determine equivalence.
* @return {Number|Boolean} -
* The index in the array the variable exists at, otherwise false if
* the variable wasn't found in the array.
*/
function indexOf(arr, x, comparator)
{
var cmp = comparator || equalsStrict;
for (var i = 0, n = arr.length; i < n; i++)
{
if ( cmp( arr[i], x ) )
{
return i;
}
}
return false;
}
/**
* Returns an instance of {@link Rekord.Collection} with the initial values
* passed as arguments to this function.
*
* ```javascript
* Rekord.collect(1, 2, 3, 4);
* Rekord.collect([1, 2, 3, 4]); // same as above
* Rekord.collect();
* Rekord.collect([]); // same as above
* ```
*
* @memberof Rekord
* @param {Any[]|...Any} a
* The initial values in the collection. You can pass an array of values
* or any number of arguments.
* @return {Rekord.Collection} -
* A newly created instance containing the given values.
*/
function collect(a)
{
var values = arguments.length > 1 || !isArray(a) ? Array.prototype.slice.call( arguments ) : a;
return Collection.create( values );
}
/**
* Returns an instance of {@link Rekord.Collection} with the initial values
* passed as arguments to this function.
*
* ```javascript
* Rekord.collectArray(1, 2, 3, 4);
* Rekord.collectArray([1, 2, 3, 4]); // same as above
* Rekord.collectArray();
* Rekord.collectArray([]); // same as above
* ```
*
* @memberof Rekord
* @param {Any[]|...Any} a
* The initial values in the collection. You can pass an array of values
* or any number of arguments.
* @return {Rekord.Collection} -
* A newly created instance containing the given values.
*/
function collectArray(a)
{
var values = arguments.length > 1 || !isArray(a) ? Array.prototype.slice.call( arguments ) : a;
return Collection.native( values );
}
function swap(a, i, k)
{
var t = a[ i ];
a[ i ] = a[ k ];
a[ k ] = t;
}
function reverse(arr)
{
var n = arr.length;
var half = Math.floor( n / 2 );
for (var i = 0; i < half; i++)
{
swap( arr, n - i - 1, i );
}
return arr;
}
function isSorted(comparator, array)
{
if ( !comparator )
{
return true;
}
for (var i = 0, n = array.length - 1; i < n; i++)
{
if ( comparator( array[ i ], array[ i + 1 ] ) > 0 )
{
return false;
}
}
return true;
}
function isPrimitiveArray(array)
{
for (var i = 0; i < array.length; i++)
{
var item = array[i];
if ( isValue( item ) )
{
return !isObject( item );
}
}
return true;
}
// Class.create( construct, methods )
// Class.extend( parent, construct, override )
// Class.prop( target, name, value )
// Class.props( target, properties )
// Class.method( construct, methodName, method )
// Class.method( construct, methods )
// Class.replace( construct, methodName, methodFactory(super) )
// constructor.create( ... )
// constructor.native( ... ) // for arrays
// constructor.$constuctor
// constructor.prototype.$super
// constructor.$methods
// constructor.$prop( name, value ) // add to prototype
// constructor.$method( methodName, method ) // add to prototype
// constructor.$replace( methodName, methodFactory(super) )
var Class =
{
create: function( construct, methods )
{
Class.prop( construct, 'create', Class.factory( construct ) );
Class.build( construct, methods, noop );
},
extend: function( parent, construct, override )
{
var methods = collapse( override, parent.$methods );
var parentCopy = Class.copyConstructor( parent );
construct.prototype = new parentCopy();
var instanceFactory = Class.factory( construct );
if ( Class.isArray( parent ) )
{
var nativeArray = function()
{
var arr = [];
Class.props( arr, methods );
construct.apply( arr, arguments );
return arr;
};
Class.prop( construct, 'native', nativeArray );
Class.prop( construct, 'create', Settings.nativeArray ? nativeArray : instanceFactory );
}
else
{
Class.prop( construct, 'create', instanceFactory );
}
Class.build( construct, methods, parent );
},
dynamic: function(parent, parentInstance, className, code)
{
var DynamicClass = new Function('return function ' + className + code)(); // jshint ignore:line
DynamicClass.prototype = parentInstance;
Class.build( DynamicClass, {}, parent );
return DynamicClass;
},
build: function(construct, methods, parent)
{
Class.prop( construct, '$methods', methods );
Class.prop( construct, '$prop', Class.propThis );
Class.prop( construct, '$method', Class.methodThis );
Class.prop( construct, '$replace', Class.replaceThis );
Class.prop( construct.prototype, '$super', parent );
Class.prop( construct.prototype, 'constructor', construct );
Class.props( construct.prototype, methods );
},
isArray: function( construct )
{
return Array === construct || construct.prototype instanceof Array;
},
method: function( construct, methodName, method )
{
if (construct.$methods)
{
construct.$methods[ methodName ] = method;
}
Class.prop( construct.prototype, methodName, method );
},
methodThis: function( methodName, method )
{
Class.method( this, methodName, method );
},
methods: function( construct, methods )
{
for (var methodName in methods)
{
Class.method( construct, methodName, methods[ methodName ] );
}
},
prop: (function()
{
if (Object.defineProperty)
{
return function( target, property, value )
{
Object.defineProperty( target, property, {
configurable: true,
enumerable: false,
writable: true,
value: value
});
};
}
else
{
return function( target, property, value )
{
target[ property ] = value;
};
}
})(),
propThis: function( property, value )
{
Class.prop( this.prototype, property, value );
},
props: function( target, properties )
{
for (var propertyName in properties)
{
Class.prop( target, propertyName, properties[ propertyName ] );
}
},
replace: function( target, methodName, methodFactory )
{
var existingMethod = target.prototype[ methodName ] || target[ methodName ] || noop;
Class.method( target, methodName, methodFactory( existingMethod ) );
},
replaceThis: function( methodName, methodFactory )
{
Class.replace( this, methodName, methodFactory );
},
copyConstructor: function(construct)
{
function F()
{
}
F.prototype = construct.prototype;
return F;
},
factory: function(construct)
{
function F(args)
{
construct.apply( this, args );
}
F.prototype = construct.prototype;
return function()
{
return new F( arguments );
};
}
};
/**
* Determines whether the given variable is defined.
*
* ```javascript
* Rekord.isDefined(); // false
* Rekord.isDefined(0); // true
* Rekord.isDefined(true); // true
* Rekord.isDefined(void 0); // false
* Rekord.isDefined(undefined); // false
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is defined, otherwise false.
*/
function isDefined(x)
{
return x !== undefined;
}
/**
* Determines whether the given variable is a function.
*
* ```javascript
* Rekord.isFunction(); // false
* Rekord.isFunction(parseInt); // true
* Rekord.isFunction(2); // false
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a function, otherwise false.
*/
function isFunction(x)
{
return !!(x && x.constructor && x.call && x.apply);
}
/**
* Determines whether the given variable is a Rekord object. A Rekord object is a
* constructor for a model and also has a Database variable. A Rekord object is
* strictly created by the Rekord function.
*
* ```javascript
* var Task = Rekord({
* name: 'task',
* fields: ['name', 'done', 'finished_at', 'created_at', 'assigned_to']
* });
* Rekord.isRekord( Task ); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a Rekord object, otherwise false.
*/
function isRekord(x)
{
return !!(x && x.Database && isFunction( x ) && x.prototype instanceof Model);
}
/**
* Determines whether the given variable is a string.
*
* ```javascript
* Rekord.isString(); // false
* Rekord.isString('x'): // true
* Rekord.isString(1); // false
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a string, otherwise false.
*/
function isString(x)
{
return typeof x === 'string';
}
/**
* Determines whether the given variable is a valid number. NaN and Infinity are
* not valid numbers.
*
* ```javascript
* Rekord.isNumber(); // false
* Rekord.isNumber('x'): // false
* Rekord.isNumber(1); // true
* Rekord.isNumber(NaN); // false
* Rekord.isNumber(Infinity); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a valid number, otherwise false.
*/
function isNumber(x)
{
return typeof x === 'number' && !isNaN(x);
}
/**
* Determines whether the given variable is a boolean value.
*
* ```javascript
* Rekord.isBoolean(); // false
* Rekord.isBoolean('x'): // false
* Rekord.isBoolean(1); // false
* Rekord.isBoolean(true); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a boolean value, otherwise false.
*/
function isBoolean(x)
{
return typeof x === 'boolean';
}
/**
* Determines whether the given variable is an instance of Date.
*
* ```javascript
* Rekord.isDate(); // false
* Rekord.isDate('x'): // false
* Rekord.isDate(1); // false
* Rekord.isDate(true); // false
* Rekord.isDate(new Date()); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is an instance of Date, otherwise false.
*/
function isDate(x)
{
return x instanceof Date;
}
/**
* Determines whether the given variable is an instance of RegExp.
*
* ```javascript
* Rekord.isRegExp(); // false
* Rekord.isRegExp('x'): // false
* Rekord.isRegExp(1); // false
* Rekord.isRegExp(true); // false
* Rekord.isRegExp(/[xyz]/); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is an instance of RegExp, otherwise false.
*/
function isRegExp(x)
{
return x instanceof RegExp;
}
/**
* Determines whether the given variable is an instance of Array.
*
* ```javascript
* Rekord.isArray(); // false
* Rekord.isArray('x'): // false
* Rekord.isArray(1); // false
* Rekord.isArray([]); // true
* Rekord.isArray(Rekord.collect(1, 2, 3)); // true
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is an instance of Array, otherwise false.
*/
function isArray(x)
{
return x instanceof Array;
}
/**
* Determines whether the given variable is a non-null object. As a note,
* Arrays are considered objects.
*
* ```javascript
* Rekord.isObject(); // false
* Rekord.isObject('x'): // false
* Rekord.isObject(1); // false
* Rekord.isObject([]); // true
* Rekord.isObject({}); // true
* Rekord.isObject(null); // false
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is a non-null object, otherwise false.
*/
function isObject(x)
{
return x !== null && typeof x === 'object';
}
/**
* Determines whether the given variable is not null and is not undefined.
*
* ```javascript
* Rekord.isValue(); // false
* Rekord.isValue('x'): // true
* Rekord.isValue(1); // true
* Rekord.isValue([]); // true
* Rekord.isValue({}); // true
* Rekord.isValue(null); // false
* Rekord.isValue(void 0); // false
* Rekord.isValue(undefined); // false
* ```
*
* @memberof Rekord
* @param {Any} x
* The variable to test.
* @return {Boolean} -
* True if the variable is non-null and not undefined.
*/
function isValue(x)
{
return !!(x !== undefined && x !== null);
}
/**
* A function that doesn't perform any operations.
*
* @memberof Rekord
*/
function noop()
{
}
/**
* Returns the given function with the given context (`this`). This also has the
* benefits of returning a "copy" of the function which makes it ideal for use
* in listening on/once events and off events.
*
* ```javascript
* var context = {};
* var func = Rekord.bind( context, function(x) {
* this.y = x * 2;
* });
* func( 4 );
* context.y; // 8
* ```
*
* @memberof Rekord
* @param {Object} context
* The value of `this` for the given function.
* @param {Function}
* The function to invoke with the given context.
* @return {Function} -
* A new function which is a copy of the given function with a new context.
*/
function bind(context, func)
{
return function bindedFunction()
{
return func.apply( context, arguments );
};
}
/**
* Generates a UUID using the random number method.
*
* @memberof Rekord
* @return {String} -
* The generated UUID.
*/
function uuid()
{
return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}
function S4()
{
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
var now = Date.now || function()
{
return new Date().getTime();
};
function sizeof(x)
{
if ( isArray(x) || isString(x) )
{
return x.length;
}
else if ( isObject(x) )
{
var properties = 0;
for (var prop in x) // jshint ignore:line
{
properties++;
}
return properties;
}
else if ( isNumber( x ) )
{
return x;
}
return 0;
}
function isEmpty(x)
{
if (x === null || x === undefined || x === 0)
{
return true;
}
if (isArray(x) || isString(x))
{
return x.length === 0;
}
if (isDate(x))
{
return x.getTime() === 0 || isNaN( x.getTime() );
}
if (isObject(x))
{
for (var prop in x) // jshint ignore:line
{
return false;
}
return true;
}
return false;
}
function evaluate(x, avoidCopy, context)
{
if ( !isValue( x ) )
{
return x;
}
if ( isRekord( x ) )
{
return new x();
}
if ( isFunction( x ) )
{
return context ? x.apply( context ) : x();
}
return avoidCopy ? x : copy( x );
}
function addPlugin( callback, beforeCreation )
{
if ( beforeCreation )
{
return Rekord.on( Rekord.Events.Options, callback ); // (options)
}
else
{
return Rekord.on( Rekord.Events.Plugins, callback ); // (model, db, options)
}
}
/**
* A string, a function, or an array of mixed values.
*
* ```javascript
* 'age' // age property of an object
* '-age' // age property of an object, ordering reversed
* function(a, b) {} // a function which compares two values
* ['age', 'done'] // age property of an object, and when equal, the done value
* 'creator.name' // name sub-property of creator property
* '{creator.name}, {age}' // formatted string
* ```
*
* @typedef {String|comparisonCallback|Array} comparatorInput
*/
var Comparators = {};
function saveComparator(name, comparatorInput, nullsFirst)
{
var comparator = createComparator( comparatorInput, nullsFirst );
Comparators[ name ] = comparator;
return comparator;
}
function addComparator(second, comparatorInput, nullsFirst)
{
var first = createComparator( comparatorInput, nullsFirst );
if ( !isFunction( second ) )
{
return first;
}
return function compareCascading(a, b)
{
var d = first( a, b );
return d !== 0 ? d : second( a, b );
};
}
/**
* Creates a function which compares two values.
*
* @memberof Rekord
* @param {comparatorInput} comparator
* The input which creates a comparison function.
* @param {Boolean} [nullsFirst=false] -
* True if null values should be sorted first.
* @return {comparisonCallback}
*/
function createComparator(comparator, nullsFirst)
{
if ( isFunction( comparator ) )
{
return comparator;
}
else if ( isString( comparator ) )
{
if ( comparator in Comparators )
{
return Comparators[ comparator ];
}
if ( comparator.charAt(0) === '-' )
{
var parsed = createComparator( comparator.substring( 1 ), !nullsFirst );
return function compareObjectsReversed(a, b)
{
return -parsed( a, b );
};
}
else if ( isFormatInput( comparator ) )
{
var formatter = createFormatter( comparator );
return function compareFormatted(a, b)
{
var af = formatter( a );
var bf = formatter( b );
return af.localeCompare( bf );
};
}
else if ( isParseInput( comparator ) )
{
var parser = createParser( comparator );
return function compareExpression(a, b)
{
var ap = parser( a );
var bp = parser( b );
return compare( ap, bp, nullsFirst );
};
}
else
{
return function compareObjects(a, b)
{
var av = isValue( a ) ? a[ comparator ] : a;
var bv = isValue( b ) ? b[ comparator ] : b;
return compare( av, bv, nullsFirst );
};
}
}
else if ( isArray( comparator ) )
{
var parsedChain = [];
for (var i = 0; i < comparator.length; i++)
{
parsedChain[ i ] = createComparator( comparator[ i ], nullsFirst );
}
return function compareObjectsCascade(a, b)
{
var d = 0;
for (var i = 0; i < parsedChain.length && d === 0; i++)
{
d = parsedChain[ i ]( a, b );
}
return d;
};
}
return null;
}
/**
* A function for comparing two values and determine whether they're considered
* equal.
*
* @callback equalityCallback
* @param {Any} a -
* The first value to test.
* @param {Any} b -
* The second value to test.
* @return {Boolean} -
* Whether or not the two values are considered equivalent.
* @see Rekord.equals
* @see Rekord.equalsStrict
* @see Rekord.equalsCompare
*/
/**
* A function for comparing two values to determine if one is greater or lesser
* than the other or if they're equal.
*
* ```javascript
* comparisonCallback( a, b ) < 0 // a < b
* comparisonCallback( a, b ) > 0 // a > b
* comparisonCallback( a, b ) == 0 // a == b
* ```
*
* @callback comparisonCallback
* @param {Any} a -
* The first value to test.
* @param {Any} b -
* The second value to test.
* @return {Number} -
* 0 if the two values are considered equal, a negative value if `a` is
* considered less than `b`, and a positive value if `a` is considered
* greater than `b`.
* @see Rekord.compare
* @see Rekord.compareNumbers
*/
function equalsStrict(a, b)
{
return a === b;
}
function equalsWeak(a, b)
{
return a == b; // jshint ignore:line
}
function equalsCompare(a, b)
{
return compare( a, b ) === 0;
}
function equals(a, b)
{
if (a === b)
{
return true;
}
if (a === null || b === null)
{
return false;
}
if (a !== a && b !== b)
{
return true; // NaN === NaN
}
var at = typeof a;
var bt = typeof b;
var ar = isRegExp(a);
var br = isRegExp(b);
if (at === 'string' && br)
{
return b.test(a);
}
if (bt === 'string' && ar)
{
return a.test(b);
}
if (at !== bt)
{
return false;
}
var aa = isArray(a);
var ba = isArray(b);
if (aa !== ba)
{
return false;
}
if (aa)
{
if (a.length !== b.length)
{
return false;
}
for (var i = 0; i < a.length; i++)
{
if (!equals(a[i], b[i]))
{
return false;
}
}
return true;
}
if (isDate(a))
{
return isDate(b) && equals( a.getTime(), b.getTime() );
}
if (ar)
{
return br && a.toString() === b.toString();
}
if (at === 'object')
{
for (var ap in a)
{
if (ap.charAt(0) !== '$' && !isFunction(a[ap]))
{
if (!(ap in b) || !equals(a[ap], b[ap]))
{
return false;
}
}
}
for (var bp in b)
{
if (bp.charAt(0) !== '$' && !isFunction(b[bp]))
{
if (!(bp in a))
{
return false;
}
}
}
return true;
}
return false;
}
function compareNumbers(a, b)
{
return (a === b ? 0 : (a < b ? -1 : 1));
}
function compare(a, b, nullsFirst)
{
if (a == b) // jshint ignore:line
{
return 0;
}
var av = isValue( a );
var bv = isValue( b );
if (av !== bv)
{
return (av && !nullsFirst) || (bv && nullsFirst) ? -1 : 1;
}
if (isDate(a))
{
a = a.getTime();
}
if (isDate(b))
{
b = b.getTime();
}
if (isNumber(a) && isNumber(b))
{
return compareNumbers(a, b);
}
if (isArray(a) && isArray(b))
{
return compareNumbers(a.length, b.length);
}
if (isBoolean(a) && isBoolean(b))
{
return (a ? -1 : 1);
}
return (a + '').localeCompare(b + '');
}
function addEventFunction(target, functionName, events, secret)
{
var on = secret ? '$on' : 'on';
var off = secret ? '$off' : 'off';
var eventFunction = function(callback, context)
{
var subject = this;
var unlistened = false;
function listener()
{
var result = callback.apply( context || subject, arguments );
if ( result === false )
{
unlistener();
}
}
function unlistener()
{
if ( !unlistened )
{
subject[ off ]( events, listener );
unlistened = true;
}
}
subject[ on ]( events, listener );
return unlistener;
};
if (target.$methods)
{
Class.method( target, functionName, eventFunction );
}
else
{
Class.prop( target, functionName, eventFunction );
}
}
function EventNode(before, callback, context, type, group)
{
this.next = before ? before : this;
this.prev = before ? before.prev : this;
if ( before )
{
before.prev.next = this;
before.prev = this;
}
this.callback = callback;
this.context = context;
this.type = type;
this.group = group || 0;
}
EventNode.Types =
{
Persistent: 1,
Once: 2,
After: 4
};
Class.create( EventNode,
{
remove: function()
{
var next = this.next;
var prev = this.prev;
if ( next !== this )
{
prev.next = next;
next.prev = prev;
this.next = this.prev = this;
}
},
hasType: function(type)
{
return (this.type & type) !== 0;
},
trigger: function(group, args, after)
{
var type = this.type;
var isAfter = this.hasType( EventNode.Types.After );
if ( this.group !== group )
{
if ( (after && isAfter) || !isAfter )
{
this.group = group;
this.callback.apply( this.context, args );
}
if ( this.hasType( EventNode.Types.Once ) )
{
this.remove();
}
}
}
});
/**
* Adds functions to the given object (or prototype) so you can listen for any
* number of events on the given object, optionally once. Listeners can be
* removed later.
*
* The following methods will be added to the given target:
*
* ```
* target.on( events, callback, [context] )
* target.once( events, callback, [context] )
* target.after( events, callback, [context] )
* target.off( events, callback )
* target.trigger( events, [a, b, c...] )
* ```
*
* Where...
* - `events` is a string of space delimited events.
* - `callback` is a function to invoke when the event is triggered.
* - `context` is an object that should be the `this` when the callback is
* invoked. If no context is given the default value is the object which has
* the trigger function that was invoked.
*
* @memberof Rekord
* @param {Object} [target] -
* The object to add `on`, `once`, `off`, and `trigger` functions to.
* @param {Boolean} [secret=false] -
* If true - the functions will be prefixed with `$`.
*/
function addEventful(target, secret)
{
var triggerId = 0;
/**
* A mixin which adds `on`, `once`, `after`, and `trigger` functions to
* another object.
*
* @class Eventful
* @memberof Rekord
* @see Rekord.addEventful
*/
/**
* A mixin which adds `$on`, `$once`, `$after`, and `$trigger` functions to
* another object.
*
* @class Eventful$
* @memberof Rekord
* @see Rekord.addEventful
*/
// Adds a listener to $this
function onListeners($this, eventsInput, callback, context, type)
{
if ( !isFunction( callback ) )
{
return noop;
}
var callbackContext = context || $this;
var events = toArray( eventsInput, ' ' );
var listeners = $this.$$on;
if ( !listeners )
{
Class.prop( $this, '$$on', listeners = {} );
}
var nodes = [];
for (var i = 0; i < events.length; i++)
{
var eventName = events[ i ];
var eventListeners = listeners[ eventName ];
if ( !eventListeners )
{
eventListeners = listeners[ eventName ] = new EventNode();
}
nodes.push( new EventNode( eventListeners, callback, callbackContext, type, triggerId ) );
}
return function ignore()
{
for (var i = 0; i < nodes.length; i++)
{
nodes[ i ].remove();
}
nodes.length = 0;
};
}
/**
* Listens for every occurrence of the given events and invokes the callback
* each time any of them are triggered.
*
* @method on
* @memberof Rekord.Eventful#
* @param {String|Array} events -
* The event or events to listen to.
* @param {Function} callback -
* The function to invoke when any of the events are invoked.
* @param {Object} [context] -
* The value of `this` when the callback is invoked. If not specified, the
* reference of the object this function exists on will be `this`.
* @return {Function} -
* A function to invoke to stop listening to all of the events given.
*/
/**
* Listens for every occurrence of the given events and invokes the callback
* each time any of them are triggered.
*
* @method $on
* @memberof Rekord.Eventful$#
* @param {String|Array} events -
* The event or events to listen to.
* @param {Function} callback -
* The function to invoke when any of the events are invoked.
* @param {Object} [context] -
* The value of `this` when the callback is invoked. If not specified, the
* reference of the object this function exists on will be `this`.
* @return {Function} -
* A function to invoke to stop listening to all of the events given.
*/
function on(events, callback, context)
{
return onListeners( this, events, callback, context, EventNode.Types.Persistent );
}
/**
* Listens for the first of the given events to be triggered and invokes the
* callback once.
*
* @method once
* @memberof Rekord.Eventful#
* @param {String|Array} events -
* The event or events to listen to.
* @param {Function} callback -
* The function to invoke when any of the events are invoked.
* @param {Object} [context] -
* The value of `this` when the callback is invoked. If not specified, the
* reference of the object this function exists on will be `this`.
* @return {Function} -
* A function to invoke to stop listening to all of the events given.
*/
/**
* Listens for the first of the given events to be triggered and invokes the
* callback once.
*
* @method $once
* @memberof Rekord.Eventful$#
* @param {String|Array} events -
* The event or events to listen to.
* @param {Function} callback -
* The function to invoke when any of the events are invoked.
* @param {Object} [context] -
* The value of `this` when the callback is invoked. If not specified, the
* reference of the object this function exists on will be `this`.
* @return {Function} -
* A function to invoke to stop listening to all of the events given.
*/
function once(events, callback, context)
{
return onListeners( this, events, callback, context, EventNode.Types.Once );
}
function after(events, callback, context)
{
return onListeners( this, events, callback, context, EventNode.Types.After );
}
// Removes a listener from an array of listeners.
function offListeners(listeners, event, callback)
{
if (listeners && event in listeners)
{
var eventListeners = listeners[ event ];
var next, node = eventListeners.next;
while (node !== eventListeners)
{
next = node.next;
if (node.callback === callback)
{
node.remove();
}
node = next;
}
}
}
// Deletes a property from the given object if it exists
function deleteProperty(obj, prop)
{
if ( obj && prop in obj )
{
delete obj[ prop ];
}
}
/**
* Stops listening for a given callback for a given set of events.
*
* **Examples:**
*
* target.off(); // remove all listeners
* target.off('a b'); // remove all listeners on events a & b
* target.off(['a', 'b']); // remove all listeners on events a & b
* target.off('a', x); // remove listener x from event a
*
* @method off
* @for addEventful
* @param {String|Array|Object} [eventsInput]
* @param {Function} [callback]
* @chainable
*/
function off(eventsInput, callback)
{
// Remove ALL listeners
if ( !isDefined( eventsInput ) )
{
deleteProperty( this, '$$on' );
}
else
{
var events = toArray( eventsInput, ' ' );
// Remove listeners for given events
if ( !isFunction( callback ) )
{
for (var i = 0; i < events.length; i++)
{
deleteProperty( this.$$on, events[i] );
}
}
// Remove specific listener
else
{
for (var i = 0; i < events.length; i++)
{
offListeners( this.$$on, events[i], callback );
}
}
}
return this;
}
// Triggers listeneers for the given event
function triggerListeners(listeners, event, args)
{
if (listeners && event in listeners)
{
var eventListeners = listeners[ event ];
var triggerGroup = ++triggerId;
var next, node = eventListeners.next;
while (node !== eventListeners)
{
next = node.next;
node.trigger( triggerGroup, args, false );
node = next;
}
node = eventListeners.next;
while (node !== eventListeners)
{
next = node.next;
node.trigger( triggerGroup, args, true );
node = next;
}
}
}
/**
* Triggers a single event optionally passing an argument to any listeners.
*
* @method trigger
* @for addEventful
* @param {String} eventsInput
* @param {Array} args
* @chainable
*/
function trigger(eventsInput, args)
{
try
{
var events = toArray( eventsInput, ' ' );
for (var i = 0; i < events.length; i++)
{
triggerListeners( this.$$on, events[ i ], args );
}
}
catch (ex)
{
Rekord.trigger( Rekord.Events.Error, [ex] );
}
return this;
}
var methods = null;
if ( secret )
{
methods = {
$on: on,
$once: once,
$after: after,
$off: off,
$trigger: trigger
};
}
else
{
methods = {
on: on,
once: once,
after: after,
off: off,
trigger: trigger
};
}
if ( target.$methods )
{
Class.methods( target, methods );
}
else
{
Class.props( target, methods );
}
}
// Given two objects, merge src into dst.
// - If a property in src has a truthy value in ignoreMap then skip merging it.
// - If a property exists in src and not in dst, the property is added to dst.
// - If an array property exists in src and in dst, the src elements are added to dst.
// - If an array property exists in dst and a non array value exists in src, added the value to the dst array.
// - If a property in dst is an object, try to merge the property from src into it.
// - If a property exists in dst that is not an object or array, replace it with the value in src.
function merge(dst, src, ignoreMap)
{
if (isObject( dst ) && isObject( src ))
{
for (var prop in src)
{
if (!ignoreMap || !ignoreMap[ prop ])
{
var adding = src[ prop ];
if (prop in dst)
{
var existing = dst[ prop ];
if (isArray( existing ))
{
if (isArray( adding ))
{
existing.push.apply( existing, adding );
}
else
{
existing.push( adding );
}
}
else if (isObject( existing ))
{
merge( existing, adding, ignoreMap );
}
else
{
dst[ prop ] = copy( adding, true );
}
}
else
{
dst[ prop ] = copy( adding, true );
}
}
}
}
return dst;
}
function applyOptions( target, options, defaults, secret )
{
options = options || {};
for (var defaultProperty in defaults)
{
var defaultValue = defaults[ defaultProperty ];
var option = options[ defaultProperty ];
var valued = isValue( option );
if ( !valued && defaultValue === undefined )
{
throw defaultProperty + ' is a required option';
}
else if ( valued )
{
target[ defaultProperty ] = option;
}
else
{
target[ defaultProperty ] = copy( defaultValue );
}
}
for (var optionProperty in options)
{
if ( !(optionProperty in defaults) )
{
target[ optionProperty ] = options[ optionProperty ];
}
}
if ( secret )
{
target.$options = options;
}
else
{
target.options = options;
}
}
/**
* Determines whether the properties on one object equals the properties on
* another object.
*
* @memberof Rekord
* @param {Object} test -
* The object to test for matching.
* @param {String|String[]} testFields -
* The property name or array of properties to test for equality on `test`.
* @param {Object} expected -
* The object with the expected values.
* @param {String|String[]} expectedFields -
* The property name or array of properties to test for equality on `expected`.
* @param {equalityCallback} [equals] -
* The equality function which compares two values and returns whether they
* are considered equivalent.
* @return {Boolean} -
* True if the `testFields` properties on `test` are equivalent to the
* `expectedFields` on `expected` according to the `equals` function.
*/
function propsMatch(test, testFields, expected, expectedFields, equals)
{
var equality = equals || Rekord.equals;
if ( isString( testFields ) ) // && isString( expectedFields )
{
return equality( test[ testFields ], expected[ expectedFields ] );
}
else // if ( isArray( testFields ) && isArray( expectedFields ) )
{
for (var i = 0; i < testFields.length; i++)
{
var testProp = testFields[ i ];
var expectedProp = expectedFields[ i ];
if ( !equality( test[ testProp ], expected[ expectedProp ] ) )
{
return false;
}
}
return true;
}
return false;
}
// Determines whether the given model has the given fields
function hasFields(model, fields, exists)
{
if ( isArray( fields ) )
{
for (var i = 0; i < fields.length; i++)
{
if ( !exists( model[ fields[ i ] ] ) )
{
return false;
}
}
return true;
}
else // isString( fields )
{
return exists( model[ fields ] );
}
}
function clearFieldsReturnChanges(target, targetFields)
{
var changes = false;
if ( isArray( targetFields ) )
{
for (var i = 0; i < targetFields.length; i++)
{
var targetField = targetFields[ i ];
if ( target[ targetField ] )
{
target[ targetField ] = null;
changes = true;
}
}
}
else
{
if ( target[ targetFields ] )
{
target[ targetFields ] = null;
changes = true;
}
}
return changes;
}
function updateFieldsReturnChanges(target, targetFields, source, sourceFields)
{
var changes = false;
if ( isArray( targetFields ) ) // && isArray( sourceFields )
{
for (var i = 0; i < targetFields.length; i++)
{
var targetField = targetFields[ i ];
var targetValue = target[ targetField ];
var sourceField = sourceFields[ i ];
var sourceValue = source[ sourceField ];
if ( !equals( targetValue, sourceValue ) )
{
target[ targetField ] = copy( sourceValue );
changes = true;
}
}
}
else
{
var targetValue = target[ targetFields ];
var sourceValue = source[ sourceFields ];
if ( !equals( targetValue, sourceValue ) )
{
target[ targetFields ] = copy( sourceValue );
changes = true;
}
}
return changes;
}
function grab(obj, props, copyValues)
{
var grabbed = {};
for (var i = 0; i < props.length; i++)
{
var p = props[ i ];
if ( p in obj )
{
grabbed[ p ] = copyValues ? copy( obj[ p ] ) : obj[ p ];
}
}
return grabbed;
}
function pull(obj, props, copyValues)
{
if ( isString( props ) )
{
var pulledValue = obj[ props ];
return copyValues ? copy( pulledValue ) : pulledValue;
}
else // isArray( props )
{
var pulled = [];
for (var i = 0; i < props.length; i++)
{
var p = props[ i ];
var pulledValue = obj[ p ];
pulled.push( copyValues ? copy( pulledValue ) : pulledValue );
}
return pulled;
}
}
function transfer(from, to)
{
for (var prop in from)
{
to[ prop ] = from[ prop ];
}
return to;
}
function collapse()
{
var target = {};
for (var i = 0; i < arguments.length; i++)
{
var a = arguments[ i ];
if ( isObject( a ) )
{
for (var prop in a)
{
if ( !(prop in target) )
{
target[ prop ] = a[ prop ];
}
}
}
}
return target;
}
function clean(x)
{
for (var prop in x)
{
if ( prop.charAt(0) === '$' )
{
delete x[ prop ];
}
}
return x;
}
function cleanFunctions(x)
{
for (var prop in x)
{
if ( isFunction( x[prop] ) )
{
delete x[ prop ];
}
}
return x;
}
function copy(x, copyHidden)
{
if (x === null || x === undefined || typeof x !== 'object' || isFunction(x) || isRegExp(x))
{
return x;
}
if (isArray(x))
{
var c = [];
for (var i = 0; i < x.length; i++)
{
c.push( copy(x[i], copyHidden) );
}
return c;
}
if (isDate(x))
{
return new Date( x.getTime() );
}
var c = {};
for (var prop in x)
{
if (copyHidden || prop.charAt(0) !== '$')
{
c[ prop ] = copy( x[prop], copyHidden );
}
}
return c;
}
function diff(curr, old, props, comparator)
{
var d = {};
for (var i = 0; i < props.length; i++)
{
var p = props[ i ];
if (!comparator( curr[ p ], old[ p ] ) )
{
d[ p ] = copy( curr[ p ] );
}
}
return d;
}
function isParseInput(x)
{
return x.indexOf('.') !== -1 || x.indexOf('[') !== -1 || x.indexOf('(') !== -1;
}
function parse(expr, base)
{
return createParser( expr )( base );
}
parse.REGEX = /([\w$]+)/g;
function createParser(expr)
{
var regex = parse.REGEX;
var nodes = [];
var match = null;
while ((match = regex.exec( expr )) !== null)
{
nodes.push( match[ 1 ] );
}
return function(base)
{
for (var i = 0; i < nodes.length && base !== undefined; i++)
{
var n = nodes[ i ];
if ( isObject( base ) )
{
base = evaluate( base[ n ], true, base );
}
}
return base;
};
}
function isFormatInput(x)
{
return x.indexOf('{') !== -1;
}
function format(template, base)
{
return createFormatter( template )( base );
}
format.REGEX = /[\{\}]/;
function createFormatter(template)
{
// Every odd element in parts is a parse expression
var parts = template.split( format.REGEX );
for (var i = 1; i < parts.length; i += 2 )
{
parts[ i ] = createParser( parts[ i ] );
}
return function formatter(base)
{
var formatted = '';
for (var i = 0; i < parts.length; i++)
{
if ( (i & 1) === 0 )
{
formatted += parts[ i ];
}
else
{
var parsed = parts[ i ]( base );
formatted += isValue( parsed ) ? parsed : '';
}
}
return formatted;
};
}
function parseDate(x, utc)
{
if ( isString( x ) )
{
if ( Date.parse )
{
x = Date.parse( x );
}
if ( !isNumber( x ) )
{
x = new Date( x );
}
}
if ( isNumber( x ) )
{
x = new Date( x );
}
if ( isDate( x ) && isNumber( x.getTime() ) )
{
if ( utc )
{
x = new Date( x.getUTCFullYear(), x.getUTCMonth(), x.getUTCDate(), x.getUTCHours(), x.getUTCMinutes(), x.getUTCSeconds() );
}
return x;
}
return false;
}
/**
* A function for resolving a value from a given value. Typically used to
* transform an object into one of it's properties.
*
* @callback propertyResolverCallback
* @param {Any} model -
* The model to use to resolve a value.
* @return {Any} -
* The resolved value.
* @see Rekord.createPropertyResolver
*/
/**
* An expression which resolves a value from another value.
*
* ```javascript
* // {age: 6, name: 'x', user: {first: 'tom'}}
* 'age' // age property of an object
* 'user.first' // sub property
* '{age}, {user.first}' // a formatted string built from object values
* function(a) {} // a function which returns a value itself
* ['age', 'name'] // multiple properties resolves to an array of values
* {age:null, user:'first'} // multiple properties including a sub property returns an object of values
* ```
*
* @typedef {String|Function|Array|Object} propertyResolverInput
*/
var NumberResolvers = {};
function saveNumberResolver(name, numbers, invalidValue)
{
var resolver = createNumberResolver( numbers, invalidValue );
NumberResolvers[ name ] = resolver;
return resolver;
}
function createNumberResolver(numbers, invalidValue)
{
var resolver = createPropertyResolver( numbers );
if ( isString( numbers ) && numbers in NumberResolvers )
{
return NumberResolvers[ numbers ];
}
return function resolveNumber(model)
{
var parsed = parseFloat( resolver( model ) );
return isNaN( parsed ) ? invalidValue : parsed;
};
}
var PropertyResolvers = {};
function savePropertyResolver(name, properties)
{
var resolver = createPropertyResolver( properties );
PropertyResolvers[ name ] = resolver;
return resolver;
}
/**
* Creates a function which resolves a value from another value given an
* expression. This is often used to get a property value of an object.
*
* ```javascript
* // x = {age: 6, name: 'tom', user: {first: 'jack'}}
* createPropertyResolver()( x ) // x
* createPropertyResolver( 'age' )( x ) // 6
* createPropertyResolver( 'user.first' )( x ) // 'jack'
* createPropertyResolver( '{name} & {user.first}')( x ) // 'tom & jack'
* createPropertyResolver( ['name', 'age'] )( x ) // ['tom', 6]
* createPropertyResolver( {age:null, user:'first'})( x ) // {age: 6, user:'jack'}
* ```
*
* @memberof Rekord
* @param {propertyResolverInput} [properties] -
* The expression which converts one value into another.
* @return {propertyResolverCallback} -
* A function to take values and resolve new ones.
*/
function createPropertyResolver(properties)
{
if ( isFunction( properties ) )
{
return properties;
}
else if ( isString( properties ) )
{
if ( properties in PropertyResolvers )
{
return PropertyResolvers[ properties ];
}
if ( isFormatInput( properties ) )
{
return createFormatter( properties );
}
else if ( isParseInput( properties ) )
{
return createParser( properties );
}
else
{
return function resolveProperty(model)
{
return model ? model[ properties ] : undefined;
};
}
}
else if ( isArray( properties ) )
{
return function resolveProperties(model)
{
return pull( model, properties );
};
}
else if ( isObject( properties ) )
{
var propsArray = [];
var propsResolver = [];
for (var prop in properties)
{
propsArray.push( prop );
propsResolver.push( createPropertyResolver( properties[ prop ] ) );
}
return function resolvePropertyObject(model)
{
var resolved = {};
for (var i = 0; i < propsArray.length; i++)
{
var prop = propsArray[ i ];
resolved[ prop ] = propsResolver[ i ]( model[ prop ] );
}
return resolved;
};
}
else
{
return function resolveNone(model)
{
return model;
};
}
}
var Settings = global.RekordSettings || win.RekordSettings || {};
if ( win.document && win.document.currentScript )
{
var script = win.document.currentScript;
if (script.getAttribute('native-array') !== null)
{
Settings.nativeArray = true;
}
}
function camelCaseReplacer(match)
{
return match.length === 1 ? match.toUpperCase() : match.charAt(1).toUpperCase();
}
function toCamelCase(name)
{
return name.replace( toCamelCase.REGEX, camelCaseReplacer );
}
toCamelCase.REGEX = /(^.|_.)/g;
function split(x, delimiter, escape)
{
var regexDelimiter = isRegExp( delimiter ) ? delimiter : new RegExp( '(' + delimiter + ')' );
var splits = x.split( regexDelimiter );
var i = 0;
var n = splits.length - 2;
while (i < n)
{
var a = splits[ i ];
var ae = a.length - escape.length;
if ( a.substring( ae ) === escape )
{
var b = splits[ i + 1 ];
var c = splits[ i + 2 ];
var joined = a.substring( 0, ae ) + b + c;
splits.splice( i, 3, joined );
n -= 2;
}
else
{
i += 1;
splits.splice( i, 1 );
n -= 1;
}
}
return splits;
}
/**
* A function which takes a value (typically an object) and returns a true or
* false value.
*
* @callback whereCallback
* @param {Any} value -
* The value to test.
* @return {Boolean} -
* Whether or not the value passed the test.
* @see Rekord.createWhere
* @see Rekord.saveWhere
*/
/**
* An expression which can be used to generate a function for testing a value
* and returning a boolean result. The following types can be given and will
* result in the following tests:
*
* - `String`: If a string & value are given - the generated function will test
* if the object has a property with the given value. If a string is given
* and no value is given - the generated function will test if the object
* has the property and a non-null value.
* - `Object`: If an object is given - the generated function will test all
* properties of the given object and return true only if the object being
* tested has the same values.
* - `Array`: If an array is given - each element in the array is passed as
* arguments to generate a new function. The returned function will only
* return true if all generated functions return true - otherwise false.
* - `whereCallback`: A function can be given which is immediately returned as
* the test function.
*
* @typedef {String|Object|Array|whereCallback} whereInput
*/
/**
* A map of saved {@link whereCallback} functions.
*
* @type {Object}
*/
var Wheres = {};
/**
* Saves a function created with {@link Rekord.createWhere} to a cache of
* filter functions which can be created more quickly in subsequent calls. It's
* advised to make use of saved where's even in simpler scenarios for several
* reasons:
*
* - You can name a comparison which is self documenting
* - When refactoring, you only need to modify a single place in the code
* - It's slightly more efficient (time & memory) to cache filter functions
*
* ```javascript
* Rekord.saveWhere('whereName', 'field', true);
* Rekord.createWhere('whereName'); // returns the same function except quicker
* ```
*
* @memberof Rekord
* @param {String} name -
* The name of the filter function to save for later use.
* @param {String|Object|Array|whereCallback} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @see Rekord.createWhere
*/
function saveWhere(name, properties, values, equals)
{
var where = createWhere( properties, values, equals );
Wheres[ name ] = where;
return where;
}
/**
* Creates a function which returns a true or false value given a test value.
* This is also known as a filter function.
*
* ```javascript
* Rekord.createWhere('field', true); // when an object has property where field=true
* Rekord.createWhere('field'); // when an object has the property named field
* Rekord.createWhere(function(){}); // a function can be given which is immediately returned
* Rekord.createWhere(['field', function(){}, ['field', true]]); // when an object meets all of the above criteria
* Rekord.createWhere({foo: 1, bar: 2}); // when an object has foo=1 and bar=2
* Rekord.createWhere('field', true, myEquals); // A custom comparison function can be given.
* Rekord.createWhere(); // always returns true
* ```
*
* @memberof Rekord
* @param {whereInput} [properties] -
* The first expression used to generate a filter function.
* @param {Any} [value] -
* When the first argument is a string this argument will be treated as a
* value to compare to the value of the named property on the object passed
* through the filter function.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* An alternative function can be used to compare to values.
* @return {whereCallback} -
* A function which takes a value (typically an object) and returns a true
* or false value.
* @see Rekord.saveWhere
*/
function createWhere(properties, value, equals)
{
var equality = equals || equalsStrict;
if ( isFunction( properties ) )
{
return properties;
}
else if ( isArray( properties ) )
{
var parsed = [];
for (var i = 0; i < properties.length; i++)
{
var where = properties[ i ];
parsed.push( isArray( where ) ? createWhere.apply( this, where ) : createWhere( where ) );
}
return function whereMultiple(model)
{
for (var i = 0; i < parsed.length; i++)
{
if ( !parsed[ i ]( model ) )
{
return false;
}
}
return true;
};
}
else if ( isObject( properties ) )
{
var props = [];
for (var prop in properties)
{
props.push({
tester: exprEqualsTester( properties[ prop ], equality ),
resolver: createPropertyResolver( prop )
});
}
return function whereEqualsObject(model)
{
for (var i = 0; i < props.length; i++)
{
var prop = props[ i ];
if ( !prop.tester( prop.resolver( model ) ) )
{
return false;
}
}
return true;
};
}
else if ( isString( properties ) )
{
if ( properties in Wheres )
{
return Wheres[ properties ];
}
var resolver = createPropertyResolver( properties );
if ( isValue( value ) )
{
var tester = exprEqualsTester( value, equality );
return function whereEqualsValue(model)
{
return tester( resolver( model ) );
};
}
else
{
return function whereHasValue(model)
{
return isValue( resolver( model ) );
};
}
}
else
{
return function whereAll(model)
{
return true;
};
}
}
function expr(func)
{
func.expression = true;
return func;
}
function exprEquals(value, test, equals)
{
return isExpr( value ) ? value( test, equals ) : equals( value, test );
}
function exprEqualsTester(value, equals)
{
if ( isExpr( value ) )
{
return function tester(test)
{
return value( test, equals );
};
}
return function tester(test)
{
return equals( value, test );
};
}
function isExpr(x)
{
return isFunction( x ) && x.expression;
}
function not(x)
{
if ( isExpr( x ) )
{
return expr(function notExpr(value, equals)
{
return !x( value, equals );
});
}
if ( isFunction( x ) )
{
return function notWhere(value)
{
return !x( value );
};
}
return expr(function notValue(value, equals)
{
return !equals( value, x );
});
}
function oneOf(input)
{
var values = isArray( input ) ? input : AP.slice.call( arguments );
return expr(function oneOfValue(value, equals)
{
for (var i = 0; i < values.length; i++)
{
if (exprEquals( values[ i ], value, equals ) )
{
return true;
}
}
return false;
});
}
/**
* Creates a Rekord object given a set of options. A Rekord object is also the
* constructor for creating instances of the Rekord object defined.
*
* @namespace
* @param {Object} options
* The options of
*/
function Rekord(options)
{
var promise = Rekord.get( options.name );
if ( promise.isComplete() )
{
return promise.results[0];
}
Rekord.trigger( Rekord.Events.Options, [options] );
var database = new Database( options );
var model = Class.dynamic(
Model,
new Model( database ),
database.className,
'(props, remoteData) { this.$init( props, remoteData ) }'
);
database.Model = model;
model.Database = database;
Rekord.classes[ database.name ] = model;
Rekord.trigger( Rekord.Events.Plugins, [model, database, options] );
if ( Rekord.autoload )
{
database.loadBegin(function onLoadFinish(success)
{
if ( success )
{
database.loadFinish();
}
});
}
else
{
Rekord.unloaded.push( database );
}
Rekord.get( database.name ).resolve( model );
Rekord.get( database.className ).resolve( model );
Rekord.debug( Rekord.Debugs.CREATION, database, options );
return model;
}
Rekord.classes = {};
Rekord.autoload = false;
Rekord.unloaded = [];
Rekord.loadPromise = null;
Rekord.load = function(callback, context)
{
var promise = Rekord.loadPromise = Rekord.loadPromise || new Promise( null, false );
var loading = Rekord.unloaded.slice();
var loaded = [];
var loadedSuccess = [];
promise.success( callback, context || this );
Rekord.unloaded.length = 0;
function onLoadFinish(success, db)
{
loadedSuccess.push( success );
loaded.push( db );
if ( loaded.length === loading.length )
{
for (var k = 0; k < loaded.length; k++)
{
var db = loaded[ k ];
var success = loadedSuccess[ k ];
if ( success )
{
db.loadFinish();
}
}
promise.reset().resolve();
}
}
// Load by priority defined in Database
loading.sort(function(a, b)
{
return b.priority - a.priority;
});
// Begin the loading procedure for every unloaded Database
for (var i = 0; i < loading.length; i++)
{
loading[ i ].loadBegin( onLoadFinish );
}
return promise;
};
Rekord.promises = {};
Rekord.get = function(name)
{
var existing = Rekord.promises[ name ];
if ( !existing )
{
existing = Rekord.promises[ name ] = new Promise( null, false );
}
return existing;
};
Rekord.export = function()
{
var classes = Rekord.classes;
for (var className in classes)
{
win[ className ] = classes[ className ];
}
};
Rekord.clear = function(removeListeners)
{
var classes = Rekord.classes;
for (var className in classes)
{
classes[ className ].clear( removeListeners );
}
};
Rekord.reset = function(failOnPendingChanges, removeListeners)
{
var classes = Rekord.classes;
if ( failOnPendingChanges )
{
for (var className in classes)
{
var db = classes[ className ].Database;
if ( db.hasPending() )
{
return Promise.reject( db );
}
}
}
return Promise.singularity(this, function()
{
for (var className in classes)
{
var db = classes[ className ].Database;
db.reset( false, removeListeners );
}
});
};
Rekord.unload = function(names, reset, failOnPendingChanges, removeListeners)
{
var classes = Rekord.classes;
var promises = Rekord.promises;
if ( failOnPendingChanges )
{
for (var className in classes)
{
var db = classes[ className ].Database;
var check = ( !isArray( names ) || indexOf( names, className ) !== false );
if ( check && db.hasPending() )
{
return Promise.reject( db );
}
}
}
return Promise.singularity(this, function()
{
for (var className in classes)
{
var db = classes[ className ].Database;
var check = ( !isArray( names ) || indexOf( names, className ) !== false );
if ( check )
{
if ( reset )
{
db.reset( false, removeListeners );
}
delete classes[ className ];
delete promises[ db.name ];
delete promises[ db.className ];
}
}
});
};
/**
* A value which identifies a model instance. This can be the key of the model,
* an array of values (if the model has composite keys), an object which at
* least contains fields which identify the model, an instance of a model, the
* reference to a Rekord instance, or a function.
*
* If a plain object is given and it shares the same key as an existing model -
* the other fields on the object will be applied to the existing instance. If
* a plain object is given and it's key doesn't map to an existing model - a new
* one is created.
*
* If a reference to a Rekord instance is given - a new model instance is created
* with default values.
*
* If a function is given - it's invoked and the returning value is used as the
* value to identify the model instance.
*
* @typedef {String|Number|String[]|Number[]|Object|Rekord|Rekord.Model|Function} modelInput
*/
/**
* A key to a model instance.
*
* @typedef {String|Number} modelKey
*/
addEventful( Rekord );
Rekord.Events =
{
Initialized: 'initialized',
Plugins: 'plugins',
Options: 'options',
Online: 'online',
Offline: 'offline',
Error: 'error'
};
var Cache =
{
None: 'none',
Pending: 'pending',
All: 'all'
};
var Cascade =
{
None: 0,
Local: 1,
Rest: 2,
NoLive: 3,
Live: 4,
NoRest: 5,
Remote: 6,
All: 7
};
function canCascade(cascade, type)
{
return !isNumber( cascade ) || (cascade & type) === type;
}
var Load =
{
None: 0,
All: 1,
Lazy: 2,
Both: 3
};
var RestStatus =
{
Conflict: {409: true},
NotFound: {404: true, 410: true},
Offline: {0: true}
};
var Save =
{
None: 0,
Model: 4,
Key: 5,
Keys: 6
};
var Store =
{
None: 0,
Model: 1,
Key: 2,
Keys: 3
};
var batchDepth = 0;
var batches = [];
var batchHandlers = [];
var batchOverwrites = [];
function batch(namesInput, operationsInput, handler)
{
var names = toArray( namesInput, /\s*,\s/ );
var operations = toArray( operationsInput, /\s*,\s/ );
var batchID = batchHandlers.push( handler ) - 1;
var batch = batches[ batchID ] = new Collection();
for (var i = 0; i < names.length; i++)
{
var modelName = names[ i ];
var modelHandler = createModelHandler( operations, batch );
if ( isString( modelName ) )
{
if ( modelName in Rekord.classes )
{
modelHandler( Rekord.classes[ modelName ] );
}
else
{
earlyModelHandler( modelName, modelHandler );
}
}
else if ( isRekord( modelName ) )
{
modelHandler( modelName );
}
else if ( modelName === true )
{
for (var databaseName in Rekord.classes)
{
modelHandler( Rekord.classes[ databaseName ] );
}
Rekord.on( Rekord.Events.Plugins, modelHandler );
}
else
{
throw modelName + ' is not a valid input for batching';
}
}
}
function earlyModelHandler(name, modelHandler)
{
var off = Rekord.on( Rekord.Events.Plugins, function(model, database)
{
if ( database.name === name )
{
modelHandler( model );
off();
}
});
}
function createModelHandler(operations, batch)
{
return function(modelClass)
{
var db = modelClass.Database;
var rest = db.rest;
for (var i = 0; i < operations.length; i++)
{
var op = operations[ i ];
batchOverwrites.push( rest, op, rest[ op ] );
switch (op)
{
case 'all':
rest.all = function(options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'all',
options: options,
success: success,
failure: failure
});
};
break;
case 'get':
rest.get = function(model, options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'get',
options: options,
success: success,
failure: failure,
model: model
});
};
break;
case 'create':
rest.create = function(model, encoded, options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'create',
options: options,
success: success,
failure: failure,
model: model,
encoded: encoded
});
};
break;
case 'update':
rest.update = function(model, encoded, options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'update',
options: options,
success: success,
failure: failure,
model: model,
encoded: encoded
});
};
break;
case 'remove':
rest.remove = function(model, options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'remove',
options: options,
success: success,
failure: failure,
model: model
});
};
break;
case 'query':
rest.query = function(url, query, options, success, failure) // jshint ignore:line
{
batch.push({
database: db,
class: modelClass,
operation: 'query',
options: options,
success: success,
failure: failure,
url: url,
encoded: query
});
};
break;
default:
throw op + ' is not a valid operation you can batch';
}
}
};
}
function batchRun()
{
for (var i = 0; i < batches.length; i++)
{
var batch = batches[ i ];
var handler = batchHandlers[ i ];
if ( batch.length )
{
handler( batch );
batch.clear();
}
}
}
function batchStart()
{
batchDepth++;
}
function batchEnd()
{
batchDepth--;
if ( batchDepth === 0 )
{
batchRun();
}
}
function batchClear()
{
for (var i = 0; i < batchOverwrites.length; i += 3)
{
var rest = batchOverwrites[ i + 0 ];
var prop = batchOverwrites[ i + 1 ];
var func = batchOverwrites[ i + 2 ];
rest[ prop ] = func;
}
batches.length = 0;
batchHandlers.length = 0;
batchOverwrites.length = 0;
}
function batchExecute(func, context)
{
try
{
batchStart();
func.apply( context );
}
catch (ex)
{
Rekord.trigger( Rekord.Events.Error, [ex] );
throw ex;
}
finally
{
batchEnd();
}
}
Rekord.batch = batch;
Rekord.batchRun = batchRun;
Rekord.batchStart = batchStart;
Rekord.batchEnd = batchEnd;
Rekord.batchClear = batchClear;
Rekord.batchExecute = batchExecute;
Rekord.batchDepth = function() { return batchDepth; };
Rekord.debug = function(event, source) /*, data.. */
{
// up to the user
};
/**
* Sets the debug implementation provided the factory function. This function
* can only be called once - all subsequent calls will be ignored unless
* `overwrite` is given as a truthy value.
*
* @memberof Rekord
* @param {Function} factory -
* The factory which provides debug implementations.
* @param {Boolean} [overwrite=false] -
* True if existing implementations are to be ignored and the given factory
* should be the implementation.
*/
Rekord.setDebug = function(factory, overwrite)
{
if ( !Rekord.debugSet || overwrite )
{
Rekord.debug = factory;
Rekord.debugSet = true;
}
};
Rekord.Debugs = {
CREATION: 0, // options
REST: 1, // options
AUTO_REFRESH: 73, //
MISSING_KEY: 33, // encoded
REMOTE_UPDATE: 2, // encoded, Model
REMOTE_CREATE: 3, // encoded, Model
REMOTE_REMOVE: 4, // Model
REMOTE_LOAD: 5, // encoded[]
REMOTE_LOAD_OFFLINE: 6, //
REMOTE_LOAD_ERROR: 7, // status
REMOTE_LOAD_REMOVE: 8, // key
REMOTE_LOAD_RESUME: 22, //
LOCAL_LOAD: 9, // encoded[]
LOCAL_RESUME_DELETE: 10, // Model
LOCAL_RESUME_SAVE: 11, // Model
LOCAL_LOAD_SAVED: 12, // Model
REALTIME_SAVE: 13, // encoded, key
REALTIME_REMOVE: 14, // key
SAVE_VALUES: 15, // encoded, Model
SAVE_PUBLISH: 16, // encoded, Model
SAVE_CONFLICT: 17, // encoded, Model
SAVE_UPDATE_FAIL: 18, // Model
SAVE_ERROR: 19, // Model, status
SAVE_OFFLINE: 20, // Model
SAVE_RESUME: 21, // Model
SAVE_REMOTE: 25, // Model
SAVE_DELETED: 40, // Model
SAVE_OLD_REVISION: 48, // Model, encoded
SAVE_LOCAL: 23, // Model
SAVE_LOCAL_ERROR: 24, // Model, error
SAVE_LOCAL_DELETED: 38, // Model
SAVE_LOCAL_BLOCKED: 39, // Model
SAVE_REMOTE_DELETED: 41, // Model, [encoded]
SAVE_REMOTE_BLOCKED: 42, // Model
REMOVE_PUBLISH: 26, // key, Model
REMOVE_LOCAL: 27, // key, Model
REMOVE_MISSING: 28, // key, Model
REMOVE_ERROR: 29, // status, key, Model
REMOVE_OFFLINE: 30, // Model
REMOVE_RESUME: 31, // Model
REMOVE_REMOTE: 32, // Model
REMOVE_CANCEL_SAVE: 47, // Model
REMOVE_LOCAL_ERROR: 34, // Model, error
REMOVE_LOCAL_BLOCKED: 44, // Model
REMOVE_LOCAL_NONE: 45, // Model
REMOVE_LOCAL_UNSAVED: 46, // Model
REMOVE_REMOTE_BLOCKED: 43, // Model
GET_LOCAL_SKIPPED: 104, // Model
GET_LOCAL: 105, // Model, encoded
GET_LOCAL_ERROR: 106, // Model, e
GET_REMOTE: 107, // Model, data
GET_REMOTE_ERROR: 108, // Model, data, status
ONLINE: 35, //
OFFLINE: 36, //
PUBSUB_CREATED: 37, // PubSub
HASONE_INIT: 53, // HasOne
HASONE_NINJA_REMOVE: 49, // Model, relation
HASONE_INITIAL_PULLED: 51, // Model, initial
HASONE_INITIAL: 52, // Model, initial
HASONE_CLEAR_MODEL: 54, // relation
HASONE_SET_MODEL: 55, // relation
HASONE_PRESAVE: 56, // Model, relation
HASONE_POSTREMOVE: 57, // Model, relation
HASONE_CLEAR_KEY: 58, // Model, local
HASONE_UPDATE_KEY: 59, // Model, targetFields, Model, sourceFields
HASONE_LOADED: 60, // Model, relation, [Model]
HASONE_QUERY: 111, // Model, RemoteQuery, queryOption, query
HASONE_QUERY_RESULTS: 112, // Model, RemoteQuery
BELONGSTO_INIT: 61, // HasOne
BELONGSTO_NINJA_REMOVE: 62, // Model, relation
BELONGSTO_NINJA_SAVE: 63, // Model, relation
BELONGSTO_INITIAL_PULLED: 64,// Model, initial
BELONGSTO_INITIAL: 65, // Model, initial
BELONGSTO_CLEAR_MODEL: 66, // relation
BELONGSTO_SET_MODEL: 67, // relation
BELONGSTO_POSTREMOVE: 69, // Model, relation
BELONGSTO_CLEAR_KEY: 70, // Model, local
BELONGSTO_UPDATE_KEY: 71, // Model, targetFields, Model, sourceFields
BELONGSTO_LOADED: 72, // Model, relation, [Model]
BELONGSTO_QUERY: 113, // Model, RemoteQuery, queryOption, query
BELONGSTO_QUERY_RESULTS: 114,// Model, RemoteQuery
HASREFERENCE_INIT: 131, // HasOne
HASREFERENCE_NINJA_REMOVE: 132, // Model, relation
HASREFERENCE_INITIAL_PULLED: 133, // Model, initial
HASREFERENCE_INITIAL: 134, // Model, initial
HASREFERENCE_CLEAR_MODEL: 135, // relation
HASREFERENCE_SET_MODEL: 136, // relation
HASREFERENCE_CLEAR_KEY: 137, // Model, local
HASREFERENCE_UPDATE_KEY: 138, // Model, targetFields, Model, sourceFields
HASREFERENCE_LOADED: 139, // Model, relation, [Model]
HASREFERENCE_QUERY: 140, // Model, RemoteQuery, queryOption, query
HASREFERENCE_QUERY_RESULTS: 141, // Model, RemoteQuery
HASMANY_INIT: 74, // HasMany
HASMANY_NINJA_REMOVE: 75, // Model, Model, relation
HASMANY_NINJA_SAVE: 76, // Model, Model, relation
HASMANY_INITIAL: 77, // Model, relation, initial
HASMANY_INITIAL_PULLED: 78, // Model, relation
HASMANY_REMOVE: 79, // relation, Model
HASMANY_SORT: 80, // relation
HASMANY_ADD: 81, // relation, Model
HASMANY_LAZY_LOAD: 82, // relation, Model[]
HASMANY_INITIAL_GRABBED: 83, // relation, Model
HASMANY_NINJA_ADD: 84, // relation, Model
HASMANY_AUTO_SAVE: 85, // relation
HASMANY_PREREMOVE: 86, // Model, relation
HASMANY_POSTSAVE: 87, // Model, relation
HASMANY_QUERY: 115, // Model, RemoteQuery, queryOption, query
HASMANY_QUERY_RESULTS: 116, // Model, RemoteQuery
HASMANY_UPDATE_KEY: 129, // Model, targetFields, Model, sourceFields
HASMANYTHRU_INIT: 88, // HasMany
HASMANYTHRU_NINJA_REMOVE: 89, // Model, Model, relation
HASMANYTHRU_NINJA_SAVE: 90, // Model, Model, relation
HASMANYTHRU_NINJA_THRU_REMOVE: 91,// Model, Model, relation
HASMANYTHRU_INITIAL: 92, // Model, relation, initial
HASMANYTHRU_INITIAL_PULLED: 93, // Model, relation
HASMANYTHRU_REMOVE: 94, // relation, Model
HASMANYTHRU_SORT: 95, // relation
HASMANYTHRU_ADD: 96, // relation, Model
HASMANYTHRU_LAZY_LOAD: 97, // relation, Model[]
HASMANYTHRU_INITIAL_GRABBED: 98, // relation, Model
HASMANYTHRU_NINJA_ADD: 99, // relation, Model
HASMANYTHRU_AUTO_SAVE: 100, // relation
HASMANYTHRU_PREREMOVE: 101, // Model, relation
HASMANYTHRU_POSTSAVE: 102, // Model, relation
HASMANYTHRU_THRU_ADD: 103, // relation, Model
HASMANYTHRU_THRU_REMOVE: 68, // relation, Model, Model
HASMANYTHRU_QUERY: 117, // Model, RemoteQuery, queryOption, query
HASMANYTHRU_QUERY_RESULTS: 118, // Model, RemoteQuery
HASMANYTHRU_UPDATE_KEY: 130, // Model, targetFields, Model, sourceFields
HASREMOTE_INIT: 50, // HasRemote
HASREMOTE_SORT: 121, // relation
HASREMOTE_NINJA_REMOVE: 109, // Model, Model, relation
HASREMOTE_NINJA_SAVE: 110, // Model, Model, relation
HASREMOTE_QUERY: 119, // Model, RemoteQuery, queryOption, query
HASREMOTE_QUERY_RESULTS: 120, // Model, RemoteQuery
HASLIST_INIT: 122, // HasList
HASLIST_SORT: 123, // relation
HASLIST_NINJA_REMOVE: 124, // Model, Model, relation
HASLIST_NINJA_SAVE: 125, // Model, Model, relation
HASLIST_REMOVE: 126, // HasList, relation, Model
HASLIST_ADD: 127, // HasList, relation, Model
HASLIST_INITIAL: 128 // HasList, Model, relation, initial
};
var Lives = {};
/**
* The factory responsible for creating a service which publishes operations
* and receives operations that have occurred. The first argument is a reference
* to the Database and the second argument is a function to invoke when a
* live operation occurs. This function must return a function that can be passed
* an operation to be delegated to other clients.
*
* @param {Database} database
* The database this live function is for.
* @return {function} -
* The function which sends operations.
*/
Lives.Default =
Rekord.defaultLive =
Rekord.live = function(database)
{
return {
save: function(model, data)
{
// ignore save
},
remove: function(model)
{
// ignore remove
}
};
};
/**
* Sets the live implementation provided the factory function. This function
* can only be called once - all subsequent calls will be ignored unless
* `overwrite` is given as a truthy value.
*
* @memberof Rekord
* @param {Function} factory -
* The factory which provides live implementations.
* @param {Boolean} [overwrite=false] -
* True if existing implementations are to be ignored and the given factory
* should be the implementation.
*/
Rekord.setLive = function(factory, overwrite)
{
if ( !Rekord.liveSet || overwrite )
{
Rekord.live = factory;
Rekord.liveSet = true;
}
};
// Initial online
Rekord.isOnline = function()
{
return !win.navigator || win.navigator.onLine !== false;
};
Rekord.online = Rekord.isOnline();
Rekord.forceOffline = false;
// Set network status to online and notify all listeners
Rekord.setOnline = function()
{
Rekord.online = true;
Rekord.debug( Rekord.Debugs.ONLINE );
batchExecute(function()
{
Rekord.trigger( Rekord.Events.Online );
});
};
// Set network status to offline and notify all listeners
Rekord.setOffline = function()
{
Rekord.online = false;
Rekord.debug( Rekord.Debugs.OFFLINE );
Rekord.trigger( Rekord.Events.Offline );
};
// This must be called manually - this will try to use built in support for
// online/offline detection instead of solely using status codes of 0.
Rekord.listenToNetworkStatus = function()
{
if (win.addEventListener)
{
win.addEventListener( Rekord.Events.Online, Rekord.setOnline, false );
win.addEventListener( Rekord.Events.Offline, Rekord.setOffline, false );
}
else
{
win.document.body.ononline = Rekord.setOnline;
win.document.body.onoffline = Rekord.setOffline;
}
};
// Check to see if the network status has changed.
Rekord.checkNetworkStatus = function()
{
var online = Rekord.isOnline();
if ( Rekord.forceOffline )
{
online = false;
}
if (online === true && Rekord.online === false)
{
Rekord.setOnline();
}
else if (online === false && Rekord.online === true)
{
Rekord.setOffline();
}
};
var Rests = {};
// Rekord.rest = function(options, success(data), failure(data, status))
Rests.Default =
Rekord.defaultRest =
Rekord.rest = function(database)
{
return {
// success ( data[] )
// failure ( data[], status )
all: function( options, success, failure )
{
success( [] );
},
// success( data )
// failure( data, status )
get: function( model, options, success, failure )
{
failure( null, -1 );
},
// success ( data )
// failure ( data, status )
create: function( model, encoded, options, success, failure )
{
success( {} );
},
// success ( data )
// failure ( data, status )
update: function( model, encoded, options, success, failure )
{
success( {} );
},
// success ( data )
// failure ( data, status )
remove: function( model,options, success, failure )
{
success( {} );
},
// success ( data[] )
// failure ( data[], status )
query: function( url, query, options, success, failure )
{
success( [] );
}
};
};
/**
* Sets the rest implementation provided the factory function. This function
* can only be called once - all subsequent calls will be ignored unless
* `overwrite` is given as a truthy value.
*
* @memberof Rekord
* @param {Function} factory -
* The factory which provides rest implementations.
* @param {Boolean} [overwrite=false] -
* True if existing implementations are to be ignored and the given factory
* should be the implementation.
*/
Rekord.setRest = function(factory, overwrite)
{
if ( !Rekord.restSet || overwrite )
{
Rekord.rest = factory;
Rekord.restSet = true;
}
};
var Stores = {};
/**
* A factory function for returning an object capable of storing objects for
* retrieval later by the application.
*
* @param {Database} database
* The database this store is for.
* @return {Object} -
* An object with put, remove, and all functions.
*/
Stores.Default =
Rekord.defaultStore =
Rekord.store = function(database)
{
return {
/**
* Places a record in the store with the given key.
*
* @param {String|Number} key
* The key to store the record as.
* @param {Object} record
* The record to store.
* @param {function} success
* A function to invoke when the record is successfully stored with
* the key. The arguments of the function should be the key and
* record passed to this function.
* @param {function} failure
* A function to invoke when the record failed to be stored with the
* key. The arguments of the function should be the key, record, and
* an error that occurred if available.
*/
put: function(key, record, success, failure)
{
success( key, record );
},
// TODO
get: function(key, success, failure)
{
failure( key, undefined );
},
/**
* Removes a record from the store with the given key.
*
* @param {String|Number} key
* The key to remove from the store.
* @param {function} success
* A function to invoke when the record doesn't exist in the store.
* The arguments of the function are the removedValue (if any) and
* the key passed to this function.
* @param {function} failure
* A function to invoke when there was an issue removing the key
* from the store. The arguments of the function are the key given
* to this function and an error that occurred if available.
*/
remove: function(key, success, failure)
{
success( key );
},
/**
* Returns all records and their keys to the given success callback.
*
* @param {function} success
* The function to invoke with the array of records and an array
* of keys.
* @param {function} failure
* The function to invoke with the error that occurred if available.
*/
all: function(success, failure)
{
success( [], [] );
},
/**
* Resets the store so it contains ONLY the given keys & record pairs.
*
* @param {String[]} keys -
* The array of keys.
* @param {Object[]} records -
* The array of records to save.
* @param {function} success
* The function to invoke with the array of records and an array
* of keys.
* @param {function} failure
* The function to invoke with the error that occurred if available.
*/
reset: function(keys, records, success, failure)
{
success( keys, records );
}
};
};
/**
* Sets the store implementation provided the factory function. This function
* can only be called once - all subsequent calls will be ignored unless
* `overwrite` is given as a truthy value.
*
* @memberof Rekord
* @param {Function} factory -
* The factory which provides store implementations.
* @param {Boolean} [overwrite=false] -
* True if existing implementations are to be ignored and the given factory
* should be the implementation.
*/
Rekord.setStore = function(factory, overwrite)
{
if ( !Rekord.storeSet || overwrite )
{
Rekord.store = factory;
Rekord.storeSet = true;
}
};
function Gate(callback)
{
var opened = false;
var blocked = [];
var gate = function()
{
if ( opened )
{
callback.apply( this, arguments );
}
else
{
blocked.push( this, AP.slice.apply( arguments ) );
}
};
gate.open = function()
{
if ( !opened )
{
for (var i = 0; i < blocked.length; i += 2)
{
var context = blocked[ i ];
var args = blocked[ i + 1 ];
callback.apply( context, args );
}
blocked.length = 0;
opened = true;
}
};
return gate;
}
/**
*
* @constructor
* @memberof Rekord
* @augments Rekord.Eventful
*/
function Database(options)
{
// Apply the options to this database!
applyOptions( this, options, Defaults );
// Create the key handler based on the given key
this.keyHandler = isArray( this.key ) ?
new KeyComposite( this ) : new KeySimple( this );
// If key fields aren't in fields array, add them in
this.keyHandler.addToFields( this.fields );
// Properties
this.modelsCached = this.models = ModelCollection.create( this );
this.allCached = this.all = {};
this.loaded = {};
this.className = this.className || toCamelCase( this.name );
this.initialized = false;
this.pendingRefresh = false;
this.localLoaded = false;
this.remoteLoaded = false;
this.firstRefresh = false;
this.pendingOperations = 0;
this.afterOnline = false;
this.saveFields = copy( this.fields );
this.readyPromise = new Promise( null, false );
this.context = null;
this.contextIndex = -1;
// Prepare
this.prepare( this, options );
// Services
this.rest = this.createRest( this );
this.store = this.createStore( this );
this.live = this.createLive( this );
// Functions
this.setComparator( this.comparator, this.comparatorNullsFirst );
this.setRevision( this.revision );
this.setSummarize( this.summarize );
// Relations
this.relations = {};
this.relationNames = [];
for (var relationType in options)
{
if ( !(relationType in Rekord.Relations) )
{
continue;
}
var RelationClass = Rekord.Relations[ relationType ];
if ( !(RelationClass.prototype instanceof Relation ) )
{
continue;
}
var relationMap = options[ relationType ];
for ( var name in relationMap )
{
var relationOptions = relationMap[ name ];
var relation = new RelationClass();
if ( isString( relationOptions ) )
{
relationOptions = {
model: relationOptions
};
}
else if ( !isObject( relationOptions ) )
{
relationOptions = {};
}
if ( !relationOptions.model && !relationOptions.discriminator )
{
relationOptions.model = name;
}
relation.init( this, name, relationOptions );
if ( relation.save )
{
this.saveFields.push( name );
}
this.relations[ name ] = relation;
this.relationNames.push( name );
}
}
// Projections
for (var projectionName in this.projections)
{
this.projections[ projectionName ] = Projection.parse( this, projectionName );
}
}
function defaultEncode(model, data, forSaving)
{
var encodings = this.encodings;
for (var prop in data)
{
if ( prop in encodings )
{
data[ prop ] = encodings[ prop ]( data[ prop ], model, prop, forSaving );
}
}
return data;
}
function defaultDecode(rawData, data)
{
var decodings = this.decodings;
var target = data || rawData;
for (var prop in rawData)
{
if ( prop in decodings )
{
target[ prop ] = decodings[ prop ]( rawData[ prop ], rawData, prop );
}
else
{
target[ prop ] = rawData[ prop ];
}
}
return target;
}
function defaultSummarize(model)
{
return model.$key();
}
function defaultCreateRest(database)
{
return database.rest === false ? Rekord.defaultRest( database ) : Rekord.rest( database );
}
function defaultCreateStore(database)
{
return database.store === false ? Rekord.defaultStore( database ) : Rekord.store( database );
}
function defaultCreateLive( database )
{
return database.live === false ? Rekord.defaultLive( database ) : Rekord.live( database );
}
function defaultResolveModel( response )
{
return response;
}
function defaultResolveModels( response )
{
return response;
}
Database.Events =
{
NoLoad: 'no-load',
RemoteLoad: 'remote-load',
LocalLoad: 'local-load',
Updated: 'updated',
ModelAdded: 'model-added',
ModelUpdated: 'model-updated',
ModelRemoved: 'model-removed',
OperationsStarted: 'operations-started',
OperationsFinished: 'operations-finished',
Loads: 'no-load remote-load local-load',
Changes: 'updated'
};
var Defaults = Database.Defaults =
{
name: undefined, // required
className: null, // defaults to toCamelCase( name )
key: 'id',
keySeparator: '/',
fields: [],
ignoredFields: {},
defaults: {},
publishAlways: [],
saveAlways: [],
priority: 0,
comparator: null,
comparatorNullsFirst: null,
revision: null,
traits: [],
cascade: Cascade.All,
load: Load.None,
allComplete: false,
loadRelations: true,
autoRefresh: true,
cache: Cache.All,
fullSave: false,
fullPublish: false,
noReferences: false,
encodings: {},
decodings: {},
projections: {},
allOptions: null,
fetchOptions: null,
getOptions: null,
updateOptions: null,
createOptions: null,
saveOptions: null,
removeOptions: null,
queryOptions: null,
prune: {active: false, max: 0, keepAlive: 0, removeLocal: false},
prepare: noop,
encode: defaultEncode,
decode: defaultDecode,
resolveModel: defaultResolveModel,
resolveModels: defaultResolveModels,
summarize: defaultSummarize,
createRest: defaultCreateRest,
createStore: defaultCreateStore,
createLive: defaultCreateLive
};
Class.create( Database,
{
setStoreEnabled: function(enabled)
{
if ( enabled )
{
if ( this.storeDisabled )
{
this.store = this.storeDisabled;
this.storeDisabled = false;
}
}
else if ( !this.storeDisabled )
{
this.storeDisabled = this.store;
this.store = Rekord.defaultStore( this );
}
},
setRestEnabled: function(enabled)
{
if ( enabled )
{
if ( this.restDisabled )
{
this.rest = this.restDisabled;
this.restDisabled = false;
}
}
else if ( !this.restDisabled )
{
this.restDisabled = this.rest;
this.rest = Rekord.defaultRest( this );
}
},
setLiveEnabled: function(enabled)
{
if ( enabled )
{
if ( this.liveDisabled )
{
this.live = this.liveDisabled;
this.liveDisabled = false;
}
}
else if ( !this.liveDisabled )
{
this.liveDisabled = this.live;
this.live = Rekord.defaultLive( this );
}
},
// Notifies a callback when the database has loaded (either locally or remotely).
ready: function(callback, context, persistent)
{
return this.readyPromise.success( callback, context, persistent );
},
clearAll: function()
{
var db = this;
if (db.context)
{
db.context.clear( this );
}
else
{
db.allCached = db.all = {};
}
},
clear: function(removeListeners)
{
var db = this;
db.clearAll();
db.models.clear();
if ( removeListeners )
{
db.off();
}
return db;
},
hasPending: function()
{
return this.models.contains(function(model)
{
return model.$isPending();
});
},
reset: function(failOnPendingChanges, removeListeners)
{
var db = this;
var promise = new Promise();
if ( failOnPendingChanges && db.hasPending() )
{
promise.reject( db );
}
else
{
db.clear( removeListeners );
db.store.reset( [], [],
function()
{
promise.resolve( db );
},
function()
{
promise.reject( db );
}
);
}
return promise;
},
// Determines whether the given object has data to save
hasData: function(saving)
{
if ( !isObject( saving ) )
{
return false;
}
for (var prop in saving)
{
if ( !this.ignoredFields[ prop ] )
{
return true;
}
}
return false;
},
// Grab a model with the given input and notify the callback
grabModel: function(input, callback, context, remoteData)
{
var db = this;
var promise = new Promise();
promise.success( callback, context || db );
function checkModel()
{
var result = db.parseModel( input, remoteData );
if ( result !== false && !promise.isComplete() && db.initialized )
{
var remoteLoaded = db.remoteLoaded || !db.hasLoad( Load.All );
var missingModel = (result === null || !result.$isSaved());
var lazyLoad = db.hasLoad( Load.Lazy );
if ( lazyLoad && remoteLoaded && missingModel )
{
if ( !result )
{
result = db.keyHandler.buildObjectFromKey( db.keyHandler.buildKeyFromInput( input ) );
}
result.$once( Model.Events.RemoteGets, function()
{
if ( !promise.isComplete() )
{
if ( isObject( input ) )
{
result.$set( input );
}
promise.resolve( result.$isSaved() ? result : null );
}
});
result.$refresh( Cascade.All, db.fetchOptions );
}
else
{
promise.resolve( result );
}
}
return promise.isComplete() ? false : true;
}
if ( checkModel() )
{
db.ready( checkModel, db, true );
}
return promise;
},
// Parses the model from the given input
//
// Returns false if the input doesn't resolve to a model at the moment
// Returns null if the input doesn't resolve to a model and all models have been remotely loaded
//
// parseModel( Rekord )
// parseModel( Rekord.Model )
// parseModel( 'uuid' )
// parseModel( ['uuid'] )
// parseModel( modelInstance )
// parseModel( {name:'new model'} )
// parseModel( {id:4, name:'new or existing model'} )
//
parseModel: function(input, remoteData)
{
var db = this;
var keyHandler = db.keyHandler;
var hasRemote = db.remoteLoaded || !db.hasLoad( Load.All );
if ( !isValue( input ) )
{
return hasRemote ? null : false;
}
if ( isRekord( input ) )
{
input = new input();
}
if ( isFunction( input ) )
{
input = input();
}
var key = keyHandler.buildKeyFromInput( input );
if ( input instanceof db.Model )
{
return input;
}
else if ( key in db.all )
{
var model = db.all[ key ];
if ( isObject( input ) )
{
keyHandler.buildKeyFromRelations( input );
if ( remoteData )
{
db.putRemoteData( input, key, model );
}
else
{
model.$set( input );
}
}
return model;
}
else if ( isObject( input ) )
{
keyHandler.buildKeyFromRelations( input );
if ( remoteData )
{
return db.putRemoteData( input );
}
else
{
return db.instantiate( db.decode( input ) );
}
}
else if ( hasRemote )
{
return null;
}
return false;
},
// Sorts the models & notifies listeners that the database has been updated.
updated: function()
{
this.sort(); // TODO remove
this.trigger( Database.Events.Updated );
},
// Sets a revision comparision function for this database. It can be a field
// name or a function. This is used to avoid updating model data that is older
// than the model's current data.
setRevision: function(revision)
{
if ( isFunction( revision ) )
{
this.revisionFunction = revision;
}
else if ( isString( revision ) )
{
this.revisionFunction = function(a, b)
{
var ar = isObject( a ) && revision in a ? a[ revision ] : undefined;
var br = isObject( b ) && revision in b ? b[ revision ] : undefined;
return ar === undefined || br === undefined ? false : compare( ar, br ) > 0;
};
}
else
{
this.revisionFunction = function(a, b)
{
return false;
};
}
},
// Sets a comparator for this database. It can be a field name, a field name
// with a minus in the front to sort in reverse, or a comparator function.
setComparator: function(comparator, nullsFirst)
{
this.models.setComparator( comparator, nullsFirst );
},
addComparator: function(comparator, nullsFirst)
{
this.models.addComparator( comparator, nullsFirst );
},
setSummarize: function(summarize)
{
if ( isFunction( summarize ) )
{
this.summarize = summarize;
}
else if ( isString( summarize ) )
{
if ( indexOf( this.fields, summarize ) !== false )
{
this.summarize = function(model)
{
return isValue( model ) ? model[ summarize ] : model;
};
}
else
{
this.summarize = createFormatter( summarize );
}
}
else
{
this.summarize = function(model)
{
return model.$key();
};
}
},
// Sorts the database if it isn't sorted.
sort: function()
{
this.models.sort();
},
// Determines whether this database is sorted.
isSorted: function()
{
return this.models.isSorted();
},
clean: function()
{
var db = this;
var keys = db.models.keys;
var models = db.models;
db.clearAll();
for (var i = 0; i < keys.length; i++)
{
db.addReference( models[ i ], keys[ i ] );
}
},
// Handles when we receive data from the server - either from
// a publish, refresh, or values being returned on a save.
putRemoteData: function(encoded, key, model, overwrite)
{
if ( !isObject( encoded ) )
{
return model;
}
var db = this;
var key = key || db.keyHandler.getKey( encoded, true );
// The remote source might be crazy, if the key isn't there then log it and ignore it
if ( !isValue( key ) )
{
Rekord.debug( Rekord.Debugs.MISSING_KEY, db, encoded );
return;
}
var model = model || db.all[ key ];
var decoded = db.decode( copy( encoded ) );
// Reject the data if it's a lower revision
if ( model )
{
var revisionRejected = this.revisionFunction( model, encoded );
if ( revisionRejected )
{
Rekord.debug( Rekord.Debugs.SAVE_OLD_REVISION, db, model, encoded );
return model;
}
}
// If the model already exists, update it.
if ( model )
{
if ( db.keyHandler.hasKeyChange( model, decoded ) )
{
key = model.$setKey( db.keyHandler.getKey( decoded, true ) );
}
db.addReference( model, key );
if ( !model.$saved )
{
model.$saved = {};
}
var current = model; // model.$toJSON( true );
var conflicts = {};
var conflicted = false;
var updated = {};
var previous = {};
var saved = {};
var notReallySaved = isEmpty( model.$saved );
var relations = db.relations;
var compareTo = db.decode( model.$saved ); // model.$saved
for (var prop in encoded)
{
if ( prop.charAt(0) === '$' )
{
continue;
}
if ( prop in relations )
{
model.$set( prop, encoded[ prop ], true );
continue;
}
var currentValue = current[ prop ];
var savedValue = compareTo[ prop ];
previous[ prop ] = model[ prop ];
saved[ prop ] = savedValue;
if ( notReallySaved || overwrite || equals( currentValue, savedValue ) )
{
model[ prop ] = decoded[ prop ];
updated[ prop ] = encoded[ prop ];
if ( model.$local )
{
model.$local[ prop ] = encoded[ prop ];
}
}
else
{
conflicts[ prop ] = encoded[ prop ];
conflicted = true;
}
model.$saved[ prop ] = copy( encoded[ prop ] );
}
if ( conflicted )
{
model.$trigger( Model.Events.PartialUpdate, [encoded, updated, previous, saved, conflicts] );
}
else
{
model.$trigger( Model.Events.FullUpdate, [encoded, updated, previous, saved, conflicts] );
}
model.$trigger( Model.Events.RemoteUpdate, [encoded, updated, previous, saved, conflicts] );
model.$addOperation( SaveNow );
if ( !db.models.has( key ) )
{
db.saveReference( model, key );
db.trigger( Database.Events.ModelAdded, [model, true] );
}
}
// The model doesn't exist, create it.
else
{
model = db.createModel( decoded, true );
if ( model )
{
if ( db.cache === Cache.All )
{
model.$local = model.$toJSON( false );
model.$local.$status = model.$status;
model.$saved = model.$local.$saved = model.$toJSON( true );
model.$addOperation( SaveNow );
}
else
{
model.$saved = model.$toJSON( true );
}
}
}
return model;
},
createModel: function(decoded, remoteData)
{
var db = this;
var model = db.instantiate( decoded, remoteData );
if ( model.$invalid === true )
{
Rekord.debug( Rekord.Debugs.MISSING_KEY, db, decoded );
return;
}
var key = model.$key();
if ( !db.models.has( key ) )
{
db.saveReference( model, key );
db.trigger( Database.Events.ModelAdded, [model, remoteData] );
}
return model;
},
destroyModel: function(model, modelKey)
{
this.pruneModel( model, modelKey );
model.$trigger( Model.Events.RemoteAndRemove );
Rekord.debug( Rekord.Debugs.REMOTE_REMOVE, this, model );
},
pruneModel: function(model, modelKey)
{
var db = this;
var key = modelKey || model.$key();
db.removeReference( key );
db.models.remove( key );
db.trigger( Database.Events.ModelRemoved, [model] );
},
removeReference: function(key)
{
delete this.all[ key ];
},
hasPruning: function()
{
return this.prune.max || this.prune.keepAlive;
},
pruneModels: function()
{
var db = this;
var prune = db.prune;
var models = db.models;
if (prune.max || prune.keepAlive)
{
if (prune.active)
{
var youngestAllowed = now() - prune.keepAlive;
var pruneModel = function(model)
{
if (prune.removeLocal)
{
model.$remove( Cascade.Local );
}
else
{
db.pruneModel( model );
}
};
var isTooYoung = function(model)
{
return model.$touched <= youngestAllowed;
};
while ( prune.max && models.length > prune.max )
{
var youngest = models.minModel('$touched');
if (youngest)
{
pruneModel( youngest );
}
}
if ( prune.keepAlive )
{
models.eachWhere( pruneModel, isTooYoung );
}
}
}
},
destroyLocalUncachedModel: function(model, key)
{
var db = this;
if ( model )
{
if ( model.$hasChanges() )
{
delete model.$saved;
db.keyHandler.removeKey( model );
model.$trigger( Model.Events.Detach );
return false;
}
db.destroyModel( model, key );
return true;
}
return false;
},
destroyLocalCachedModel: function(model, key)
{
var db = this;
if ( model )
{
// If a model was removed remotely but the model has changes - don't remove it.
if ( model.$hasChanges() )
{
// Removed saved history and the current ID
delete model.$saved;
db.keyHandler.removeKey( model );
if ( model.$local )
{
delete model.$local.$saved;
db.keyHandler.removeKey( model.$local );
}
model.$trigger( Model.Events.Detach );
model.$addOperation( SaveNow );
return false;
}
model.$addOperation( RemoveNow );
db.destroyModel( model, key );
}
else
{
db.store.remove( key, function(removedValue)
{
if (removedValue)
{
Rekord.debug( Rekord.Debugs.REMOTE_REMOVE, db, removedValue );
}
});
// The model didn't exist
return false;
}
return true;
},
// Destroys a model locally because it doesn't exist remotely
destroyLocalModel: function(key)
{
var db = this;
var model = db.all[ key ];
if ( db.cache === Cache.All )
{
return db.destroyLocalCachedModel( model, key );
}
else
{
return db.destroyLocalUncachedModel( model, key );
}
},
loadFinish: function()
{
var db = this;
batchExecute(function()
{
for (var key in db.loaded)
{
var model = db.loaded[ key ];
if ( model.$status === Model.Status.RemovePending )
{
Rekord.debug( Rekord.Debugs.LOCAL_RESUME_DELETE, db, model );
model.$addOperation( RemoveRemote );
}
else
{
if ( model.$status === Model.Status.SavePending )
{
Rekord.debug( Rekord.Debugs.LOCAL_RESUME_SAVE, db, model );
model.$addOperation( SaveRemote );
}
else
{
Rekord.debug( Rekord.Debugs.LOCAL_LOAD_SAVED, db, model );
}
db.saveReference( model, key, true );
}
}
});
db.loaded = {};
db.updated();
if ( db.hasLoad( Load.All ) )
{
if ( db.pendingOperations === 0 )
{
db.refresh();
}
else
{
db.firstRefresh = true;
}
}
},
hasLoad: function(load)
{
return (this.load & load) !== 0;
},
loadBegin: function(onLoaded)
{
var db = this;
function onLocalLoad(records, keys)
{
Rekord.debug( Rekord.Debugs.LOCAL_LOAD, db, records );
for (var i = 0; i < records.length; i++)
{
var encoded = records[ i ];
var key = keys[ i ];
var decoded = db.decode( copy( encoded, true ) );
var existing = db.all[ key ];
var model = existing || db.instantiate( decoded, true );
if (existing)
{
model.$set( decoded, undefined, true );
}
if ( model.$invalid === true )
{
Rekord.debug( Rekord.Debugs.MISSING_KEY, db, encoded );
break;
}
model.$local = encoded;
model.$saved = encoded.$saved;
if ( model.$status !== Model.Status.Removed )
{
db.loaded[ key ] = model;
db.addReference( model, key );
}
}
db.localLoaded = true;
db.triggerLoad( Database.Events.LocalLoad );
onLoaded( true, db );
}
function onLocalError()
{
db.loadNone();
onLoaded( false, db );
}
if ( db.hasLoad( Load.All ) && db.autoRefresh )
{
Rekord.after( Rekord.Events.Online, db.onOnline, db );
}
if ( db.cache === Cache.None )
{
db.loadNone();
onLoaded( false, db );
}
else
{
db.store.all( onLocalLoad, onLocalError );
}
},
triggerLoad: function(loadEvent, additionalParameters)
{
var db = this;
db.initialized = true;
db.trigger( loadEvent, [ db ].concat( additionalParameters || [] ) );
db.readyPromise.reset().resolve( db );
},
loadNone: function()
{
var db = this;
if ( db.hasLoad( Load.All ) )
{
db.refresh();
}
else
{
db.triggerLoad( Database.Events.NoLoad );
}
},
onOnline: function()
{
var db = this;
db.afterOnline = true;
if ( db.pendingOperations === 0 )
{
db.onOperationRest();
}
},
onOperationRest: function()
{
var db = this;
if ( ( db.autoRefresh && db.remoteLoaded && db.afterOnline ) || db.firstRefresh )
{
db.afterOnline = false;
db.firstRefresh = false;
Rekord.debug( Rekord.Debugs.AUTO_REFRESH, db );
db.refresh();
}
},
handleRefreshSuccess: function(promise)
{
var db = this;
return function onRefreshSuccess(response)
{
var models = db.resolveModels( response );
var mapped = {};
for (var i = 0; i < models.length; i++)
{
var model = db.putRemoteData( models[ i ] );
if ( model )
{
var key = model.$key();
mapped[ key ] = model;
}
}
if ( db.allComplete )
{
var keys = db.models.keys().slice();
for (var i = 0; i < keys.length; i++)
{
var k = keys[ i ];
if ( !(k in mapped) )
{
var old = db.models.get( k );
if ( old.$saved )
{
Rekord.debug( Rekord.Debugs.REMOTE_LOAD_REMOVE, db, k );
db.destroyLocalModel( k );
}
}
}
}
db.remoteLoaded = true;
db.triggerLoad( Database.Events.RemoteLoad );
db.updated();
Rekord.debug( Rekord.Debugs.REMOTE_LOAD, db, models );
promise.resolve( db.models );
};
},
handleRefreshFailure: function(promise)
{
var db = this;
return function onRefreshFailure(response, status)
{
if ( status === 0 )
{
Rekord.checkNetworkStatus();
if ( !Rekord.online )
{
db.pendingRefresh = true;
Rekord.once( Rekord.Events.Online, db.onRefreshOnline, db );
}
Rekord.debug( Rekord.Debugs.REMOTE_LOAD_OFFLINE, db );
}
else
{
Rekord.debug( Rekord.Debugs.REMOTE_LOAD_ERROR, db, status );
db.triggerLoad( Database.Events.NoLoad, [response] );
}
promise.reject( db.models );
};
},
executeRefresh: function(success, failure)
{
this.rest.all( this.allOptions, success, failure );
},
// Loads all data remotely
refresh: function(callback, context)
{
var db = this;
var promise = new Promise();
var success = this.handleRefreshSuccess( promise );
var failure = this.handleRefreshFailure( promise );
promise.complete( callback, context || db );
batchExecute(function()
{
db.executeRefresh( success, failure );
});
return promise;
},
onRefreshOnline: function()
{
var db = this;
Rekord.debug( Rekord.Debugs.REMOTE_LOAD_RESUME, db );
if ( db.pendingRefresh )
{
db.pendingRefresh = false;
db.refresh();
}
},
// Returns a model
get: function(key)
{
return this.all[ this.keyHandler.buildKeyFromInput( key ) ];
},
filter: function(isValid)
{
var all = this.all;
var filtered = [];
for (var key in all)
{
var model = all[ key ];
if ( isValid( model ) )
{
filtered.push( model );
}
}
return filtered;
},
hasTrait: function(trait, comparator)
{
var cmp = comparator || equals;
return isArray( this.traits ) && indexOf( this.traits, trait, cmp ) !== false;
},
hasTraits: function(traits, comparator)
{
for (var i = 0; i < traits.length; i++)
{
if ( !this.hasTrait( traits[ i ], comparator ) )
{
return false;
}
}
return true;
},
liveSave: function(key, encoded)
{
this.putRemoteData( encoded, key );
this.updated();
Rekord.debug( Rekord.Debugs.REALTIME_SAVE, this, encoded, key );
},
liveRemove: function(key)
{
if ( this.destroyLocalModel( key ) )
{
this.updated();
}
Rekord.debug( Rekord.Debugs.REALTIME_REMOVE, this, key );
},
// Return an instance of the model with the data as initial values
instantiate: function(data, remoteData)
{
return new this.Model( data, remoteData );
},
addReference: function(model, key)
{
if (!this.noReferences)
{
this.all[ key || model.$key() ] = model;
}
},
saveReference: function(model, key, delaySort)
{
if ( !this.noReferences )
{
this.models.put( key || model.$key(), model, delaySort );
}
},
// Save the model
save: function(model, cascade, options)
{
var db = this;
if ( model.$isDeleted() )
{
Rekord.debug( Rekord.Debugs.SAVE_DELETED, db, model );
return;
}
var key = model.$key();
var existing = db.models.has( key );
if ( existing )
{
db.trigger( Database.Events.ModelUpdated, [model] );
model.$trigger( Model.Events.UpdateAndSave );
}
else
{
db.saveReference( model, key );
db.trigger( Database.Events.ModelAdded, [model] );
db.updated();
model.$trigger( Model.Events.CreateAndSave );
}
model.$addOperation( SaveLocal, cascade, options );
},
// Remove the model
remove: function(model, cascade, options)
{
var db = this;
// If we have it in the models, remove it!
this.removeFromModels( model );
// If we're offline and we have a pending save - cancel the pending save.
if ( model.$status === Model.Status.SavePending )
{
Rekord.debug( Rekord.Debugs.REMOVE_CANCEL_SAVE, db, model );
}
model.$status = Model.Status.RemovePending;
model.$addOperation( RemoveLocal, cascade, options );
},
removeFromModels: function(model)
{
var db = this;
var key = model.$key();
if ( db.models.has( key ) )
{
db.models.remove( key );
db.trigger( Database.Events.ModelRemoved, [model] );
db.updated();
model.$trigger( Model.Events.Removed );
}
}
});
addEventful( Database );
addEventFunction( Database, 'change', Database.Events.Changes );
/**
* An instance
*
* @constructor
* @memberof Rekord
* @augments Rekord.Eventful$
* @param {Rekord.Database} db
* The database instance used in model instances.
*/
function Model(db)
{
Class.prop( this, '$db', db );
/**
* @property {Database} $db
* The reference to the database this model is stored in.
*/
/**
* @property {Object} [$saved]
* An object of encoded data representing the values saved remotely.
* If this object does not exist - the model hasn't been created
* yet.
*/
/**
* @property {Object} [$local]
* The object of encoded data that is stored locally. It's $saved
* property is the same object as this $saved property.
*/
/**
* @property {Boolean} $status
* Whether there is a pending save for this model.
*/
}
Model.Events =
{
Created: 'created',
Saved: 'saved',
PreSave: 'pre-save',
PostSave: 'post-save',
PreRemove: 'pre-remove',
PostRemove: 'post-remove',
PartialUpdate: 'partial-update',
FullUpdate: 'full-update',
Updated: 'updated',
Detach: 'detach',
Change: 'change',
CreateAndSave: 'created saved',
UpdateAndSave: 'updated saved',
KeyUpdate: 'key-update',
RelationUpdate: 'relation-update',
Removed: 'removed',
RemoteUpdate: 'remote-update',
LocalSave: 'local-save',
LocalSaveFailure: 'local-save-failure',
LocalSaves: 'local-save local-save-failure',
RemoteSave: 'remote-save',
RemoteSaveFailure: 'remote-save-failure',
RemoteSaveOffline: 'remote-save-offline',
RemoteSaves: 'remote-save remote-save-failure remote-save-offline',
LocalRemove: 'local-remove',
LocalRemoveFailure: 'local-remove-failure',
LocalRemoves: 'local-remove local-remove-failure',
RemoteRemove: 'remote-remove',
RemoteRemoveFailure: 'remote-remove-failure',
RemoteRemoveOffline: 'remote-remove-offline',
RemoteRemoves: 'remote-remove remote-remove-failure remote-remove-offline',
LocalGet: 'local-get',
LocalGetFailure: 'local-get-failure',
LocalGets: 'local-get local-get-failure',
RemoteGet: 'remote-get',
RemoteGetFailure: 'remote-get-failure',
RemoteGetOffline: 'remote-get-offline',
RemoteGets: 'remote-get remote-get-failure remote-get-offline',
RemoteAndRemove: 'remote-remove removed',
SavedRemoteUpdate: 'saved remote-update',
OperationsStarted: 'operations-started',
OperationsFinished: 'operations-finished',
KeyChange: 'key-change',
Changes: 'saved remote-update key-update relation-update removed key-change change'
};
Model.Status =
{
Synced: 0,
SavePending: 1,
RemovePending: 2,
Removed: 3
};
Model.Blocked =
{
toString: true,
valueOf: true
};
Class.create( Model,
{
$init: function(props, remoteData)
{
this.$status = Model.Status.Synced;
Class.props(this, {
$operation: null,
$relations: {},
$dependents: new Dependents( this ),
$savedState: false,
$saved: false,
$local: false,
$touched: now()
});
if ( remoteData )
{
var key = this.$db.keyHandler.getKey( props, true );
if ( !isValue( key ) )
{
Class.prop( this, '$invalid', true );
return;
}
this.$db.addReference( this, key );
this.$set( props, undefined, remoteData );
}
else
{
this.$reset( props );
}
this.$initRelations( remoteData );
},
$initRelations: function(remoteData)
{
if ( this.$db.loadRelations )
{
var databaseRelations = this.$db.relations;
for (var name in databaseRelations)
{
var relation = databaseRelations[ name ];
if ( !relation.lazy )
{
this.$getRelation( name, undefined, remoteData );
}
}
}
},
$load: function(relations)
{
if ( isArray( relations ) )
{
for (var i = 0; i < relations.length; i++)
{
this.$getRelation( relations[ i ] );
}
}
else if ( isString( relations ) )
{
this.$getRelation( relations );
}
else
{
var databaseRelations = this.$db.relations;
for (var name in databaseRelations)
{
this.$getRelation( name );
}
}
},
$reset: function(props)
{
var def = this.$db.defaults;
var fields = this.$db.fields;
var relations = this.$db.relations;
var keyHandler = this.$db.keyHandler;
var keyFields = this.$db.key;
if ( !isEmpty( def ) )
{
for (var i = 0; i < fields.length; i++)
{
var prop = fields[ i ];
var defaultValue = def[ prop ];
var evaluatedValue = evaluate( defaultValue );
this[ prop ] = evaluatedValue;
}
}
else
{
for (var i = 0; i < fields.length; i++)
{
var prop = fields[ i ];
this[ prop ] = undefined;
}
}
var key = null;
// First try pulling key from properties (only if it hasn't been
// initialized through defaults)
if ( props )
{
key = keyHandler.getKey( props, true );
}
// If the key wasn't specified, try generating it on this model
if ( !isValue( key ) )
{
key = keyHandler.getKey( this );
}
// The key was specified in the properties, apply it to this model
else
{
updateFieldsReturnChanges( this, keyFields, props, keyFields );
}
// The key exists on this model - place the reference of this model
// in the all map and set the cached key.
if ( isValue( key ) )
{
this.$db.addReference( this, key );
this.$$key = key;
}
// Apply the default relation values now that this key is most likely populated
if ( !isEmpty( def ) )
{
for (var prop in relations)
{
if ( prop in def )
{
var defaultValue = def[ prop ];
var evaluatedValue = evaluate( defaultValue );
var hasRelation = !!this.$relations[ prop ];
var relation = this.$getRelation( prop, evaluatedValue );
if ( hasRelation )
{
relation.set( this, evaluatedValue );
}
}
}
}
// Set the remaing properties
this.$set( props );
},
$set: function(props, value, remoteData, avoidChange)
{
if ( isObject( props ) )
{
for (var prop in props)
{
this.$set( prop, props[ prop ], remoteData, true );
}
}
else if ( isString( props ) )
{
if ( Model.Blocked[ props ] )
{
return;
}
var exists = this.$hasRelation( props );
var relation = this.$getRelation( props, value, remoteData );
if ( relation )
{
if ( exists )
{
relation.set( this, value, remoteData );
}
}
else
{
this[ props ] = value;
}
}
if ( !avoidChange && isValue( props ) )
{
this.$trigger( Model.Events.Change, [props, value] );
}
},
$get: function(props, copyValues)
{
if ( isArray( props ) )
{
return grab( this, props, copyValues );
}
else if ( isObject( props ) )
{
for (var p in props)
{
props[ p ] = copyValues ? copy( this[ p ] ) : this[ p ];
}
return props;
}
else if ( isString( props ) )
{
if ( Model.Blocked[ props ] )
{
return;
}
var relation = this.$getRelation( props );
if ( relation )
{
var values = relation.get( this );
return copyValues ? copy( values ) : values;
}
else
{
return copyValues ? copy( this[ props ] ) : this[ props ];
}
}
},
$decode: function()
{
this.$db.decode( this );
},
$sync: function(prop, removeUnrelated)
{
var relation = this.$getRelation( prop );
if ( relation )
{
relation.sync( this, removeUnrelated );
}
},
$relate: function(prop, relate, remoteData)
{
var relation = this.$getRelation( prop );
if ( relation )
{
relation.relate( this, relate, remoteData );
}
},
$unrelate: function(prop, unrelated, remoteData)
{
var relation = this.$getRelation( prop );
if ( relation )
{
relation.unrelate( this, unrelated, remoteData );
}
},
$isRelated: function(prop, related)
{
var relation = this.$getRelation( prop );
return relation && relation.isRelated( this, related );
},
$hasRelation: function(prop)
{
return prop in this.$relations;
},
$getRelation: function(prop, initialValue, remoteData)
{
var databaseRelations = this.$db.relations;
var relation = databaseRelations[ prop ];
if ( relation )
{
if ( !(prop in this.$relations) )
{
relation.load( this, initialValue, remoteData );
}
return relation;
}
return false;
},
$save: function(setProperties, setValue, cascade, options)
{
if ( isObject( setProperties ) )
{
options = cascade;
cascade = setValue;
setValue = undefined;
}
else if ( isNumber( setProperties ) )
{
options = setValue;
cascade = setProperties;
setValue = undefined;
setProperties = undefined;
}
if ( !isNumber( cascade ) )
{
cascade = this.$db.cascade;
}
if ( this.$isDeleted() )
{
Rekord.debug( Rekord.Debugs.SAVE_DELETED, this.$db, this );
return Promise.resolve( this );
}
if ( !this.$hasKey() )
{
throw 'Key missing from model';
}
var promise = createModelPromise( this, cascade,
Model.Events.RemoteSave,
Model.Events.RemoteSaveFailure,
Model.Events.RemoteSaveOffline,
Model.Events.LocalSave,
Model.Events.LocalSaveFailure
);
return Promise.singularity( promise, this, function(singularity)
{
batchExecute(function()
{
this.$touch();
this.$db.addReference( this );
if ( setProperties !== undefined )
{
this.$set( setProperties, setValue );
}
this.$trigger( Model.Events.PreSave, [this] );
this.$db.save( this, cascade, options );
this.$db.pruneModels();
this.$trigger( Model.Events.PostSave, [this] );
}, this );
});
},
$remove: function(cascade, options)
{
var cascade = isNumber( cascade ) ? cascade : this.$db.cascade;
if ( !this.$exists() )
{
return Promise.resolve( this );
}
var promise = createModelPromise( this, cascade,
Model.Events.RemoteRemove,
Model.Events.RemoteRemoveFailure,
Model.Events.RemoteRemoveOffline,
Model.Events.LocalRemove,
Model.Events.LocalRemoveFailure
);
return Promise.singularity( promise, this, function(singularity)
{
batchExecute(function()
{
this.$trigger( Model.Events.PreRemove, [this] );
this.$db.remove( this, cascade, options );
this.$trigger( Model.Events.PostRemove, [this] );
}, this );
});
},
$refresh: function(cascade, options)
{
var promise = createModelPromise( this, cascade,
Model.Events.RemoteGet,
Model.Events.RemoteGetFailure,
Model.Events.RemoteGetOffline,
Model.Events.LocalGet,
Model.Events.LocalGetFailure
);
if ( canCascade( cascade, Cascade.Rest ) )
{
this.$addOperation( GetRemote, cascade, options );
}
else if ( canCascade( cascade, Cascade.Local ) )
{
this.$addOperation( GetLocal, cascade, options );
}
else
{
promise.resolve( this );
}
return promise;
},
$autoRefresh: function(cascade, options)
{
var callRefresh = function()
{
this.$refresh( cascade, options );
};
Rekord.on( Rekord.Events.Online, callRefresh, this );
return this;
},
$cancel: function(reset, options)
{
if ( this.$saved )
{
this.$save( this.$saved, this.$db.cascade, options );
}
else if ( reset )
{
this.$reset();
}
},
$clone: function(properties)
{
// If field is given, evaluate the value and use it instead of value on this object
// If relation is given, call clone on relation
var db = this.$db;
var key = db.key;
var fields = db.fields;
var relations = db.relations;
var values = {};
for (var i = 0; i < fields.length; i++)
{
var f = fields[ i ];
if ( properties && f in properties )
{
values[ f ] = evaluate( properties[ f ] );
}
else if ( f in this )
{
values[ f ] = copy( this[ f ] );
}
}
if ( isString( key ) )
{
delete values[ key ];
}
var cloneKey = db.keyHandler.getKey( values );
var modelKey = this.$key();
if ( cloneKey === modelKey )
{
throw 'A clone cannot have the same key as the original model.';
}
for (var relationName in relations)
{
if ( properties && relationName in properties )
{
relations[ relationName ].preClone( this, values, properties[ relationName ] );
}
}
var clone = db.instantiate( values );
var relationValues = {};
for (var relationName in relations)
{
if ( properties && relationName in properties )
{
relations[ relationName ].postClone( this, relationValues, properties[ relationName ] );
}
}
clone.$set( relationValues );
return clone;
},
$push: function(fields)
{
this.$savedState = this.$db.encode( this, grab( this, fields || this.$db.fields, true ), false );
},
$pop: function(dontDiscard)
{
if ( isObject( this.$savedState ) )
{
this.$set( this.$savedState );
if ( !dontDiscard )
{
this.$discard();
}
}
},
$discard: function()
{
this.$savedState = false;
},
$exists: function()
{
return !this.$isDeleted() && this.$db.models.has( this.$key() );
},
$addOperation: function(OperationType, cascade, options)
{
var operation = new OperationType( this, cascade, options );
if ( !this.$operation )
{
this.$operation = operation;
this.$operation.execute();
}
else
{
this.$operation.queue( operation );
}
},
$toJSON: function( forSaving )
{
var encoded = this.$db.encode( this, grab( this, this.$db.fields, true ), forSaving );
var databaseRelations = this.$db.relations;
var relations = this.$relations;
for (var name in relations)
{
databaseRelations[ name ].encode( this, encoded, forSaving );
}
return encoded;
},
$changed: function()
{
this.$trigger( Model.Events.Change );
},
$updated: function()
{
this.$changed();
this.$db.trigger( Database.Events.ModelUpdated, [this] );
},
$key: function(quietly)
{
if ( !this.$$key )
{
this.$$key = this.$db.keyHandler.getKey( this, quietly );
}
return this.$$key;
},
$keys: function()
{
return this.$db.keyHandler.getKeys( this );
},
$uid: function()
{
return this.$db.name + '$' + this.$key();
},
$hasKey: function()
{
return hasFields( this, this.$db.key, isValue );
},
$setKey: function(key, skipApplication)
{
var db = this.$db;
var newKey = db.keyHandler.buildKeyFromInput(key);
var oldKey = this.$$key;
if (newKey !== oldKey)
{
if (!db.keyChanges)
{
throw 'Key changes are not supported, see the documentation on how to enable key changes.';
}
db.removeReference( oldKey );
db.addReference( this, newKey );
this.$$key = newKey;
if ( !skipApplication )
{
db.keyHandler.applyKey( newKey, this );
}
this.$trigger( Model.Events.KeyChange, [this, oldKey, newKey] );
}
return newKey;
},
$remote: function(encoded, overwrite)
{
this.$db.putRemoteData( encoded, this.$key(), this, overwrite );
},
$isSynced: function()
{
return this.$status === Model.Status.Synced;
},
$isSaving: function()
{
return this.$status === Model.Status.SavePending;
},
$isPending: function()
{
return this.$status === Model.Status.SavePending || this.$status === Model.Status.RemovePending;
},
$isDeleted: function()
{
return this.$status >= Model.Status.RemovePending;
},
$isSaved: function()
{
return !!this.$saved;
},
$isSavedLocally: function()
{
return !!this.$local;
},
$isNew: function()
{
return !(this.$saved || this.$local);
},
$touch: function()
{
if ( this.$db.hasPruning() )
{
this.$touched = now();
}
},
$project: function(projectionInput)
{
var projection = Projection.parse( this.$db, projectionInput );
return projection.project( this );
},
$getChanges: function(alreadyDecoded)
{
var db = this.$db;
var saved = db.decode( this.$saved, {} );
var encoded = alreadyDecoded || this;
var fields = db.saveFields;
return saved ? diff( encoded, saved, fields, equals ) : encoded;
},
$hasChanges: function(local)
{
var compareTo = local ? this.$local : this.$saved;
if (!compareTo)
{
return true;
}
var db = this.$db;
var ignore = db.ignoredFields;
var saved = db.decode( compareTo, {} );
var fields = db.saveFields;
for (var i = 0; i < fields.length; i++)
{
var prop = fields[ i ];
var currentValue = this[ prop ];
var savedValue = saved[ prop ];
if ( ignore[ prop ] )
{
continue;
}
if ( !equals( currentValue, savedValue ) )
{
return true;
}
}
return false;
},
$hasChange: function(prop, local)
{
var compareTo = local ? this.$local : this.$saved;
if (!compareTo)
{
return true;
}
var db = this.$db;
var decoder = db.decodings[ prop ];
var currentValue = this[ prop ];
var savedValue = decoder ? decoder( compareTo[ prop ], compareTo, prop ) : compareTo[ prop ];
return !equals( currentValue, savedValue );
},
$listenForOnline: function(cascade, options)
{
if (!this.$offline)
{
this.$offline = true;
Rekord.once( Rekord.Events.Online, this.$resume, this );
}
Class.props(this,
{
$resumeCascade: cascade,
$resumeOptions: options
});
},
$resume: function()
{
if (this.$status === Model.Status.RemovePending)
{
Rekord.debug( Rekord.Debugs.REMOVE_RESUME, this );
this.$addOperation( RemoveRemote, this.$resumeCascade, this.$resumeOptions );
}
else if (this.$status === Model.Status.SavePending)
{
Rekord.debug( Rekord.Debugs.SAVE_RESUME, this );
this.$addOperation( SaveRemote, this.$resumeCascade, this.$resumeOptions );
}
this.$offline = false;
},
toString: function()
{
return this.$db.className + ' ' + JSON.stringify( this.$toJSON() );
}
});
addEventful( Model, true );
addEventFunction( Model, '$change', Model.Events.Changes, true );
function createModelPromise(model, cascade, restSuccess, restFailure, restOffline, localSuccess, localFailure)
{
var promise = new Promise( null, false );
if ( canCascade( cascade, Cascade.Rest ) )
{
var off1 = model.$once( restSuccess, function(data) {
off2();
off3();
promise.resolve( model, data );
});
var off2 = model.$once( restFailure, function(data, status) {
off1();
off3();
promise.reject( model, status, data );
});
var off3 = model.$once( restOffline, function() {
off1();
off2();
promise.noline( model );
});
}
else if ( canCascade( cascade, Cascade.Local ) )
{
var off1 = model.$once( localSuccess, function(data)
{
off2();
promise.resolve( model, data );
});
var off2 = model.$once( localFailure, function(data, status)
{
off1();
promise.reject( model, data );
});
}
else
{
promise.resolve( model );
}
return promise;
}
/**
* A Map has the key-to-value benefits of a map and iteration benefits of an
* array. This is especially beneficial when most of the time the contents of
* the structure need to be iterated and order doesn't matter (since removal
* performs a swap which breaks insertion order).
*
* @constructor
* @memberof Rekord
*/
function Map()
{
/**
* An array of the values in this map.
* @member {Array}
*/
this.values = [];
/**
* An array of the keys in this map.
* @type {Array}
*/
this.keys = [];
/**
* An object of key to index mappings.
* @type {Object}
*/
this.indices = {};
}
Class.create( Map,
{
/**
* Resets the map by initializing the values, keys, and indexes.
*
* @return {Rekord.Map} -
* The reference to this map.
*/
reset: function()
{
this.values.length = 0;
this.keys.length = 0;
this.indices = {};
return this;
},
/**
* Puts the value in the map by the given key.
*
* @param {String} key
* @param {V} value
* @return {Rekord.Map} -
* The reference to this map.
*/
put: function(key, value)
{
if ( key in this.indices )
{
this.values[ this.indices[ key ] ] = value;
}
else
{
this.indices[ key ] = this.values.length;
AP.push.call( this.values, value );
AP.push.call( this.keys, key );
}
return this;
},
/**
* Returns the value mapped by the given key.
*
* @param {String} key
* @return {V}
*/
get: function(key)
{
return this.values[ this.indices[ key ] ];
},
/**
* Removes the value by a given key
*
* @param {String} key
* @return {Rekord.Map} -
* The reference to this map.
*/
remove: function(key)
{
var index = this.indices[ key ];
if ( isNumber( index ) )
{
this.removeAt( index );
}
return this;
},
/**
* Removes the value & key at the given index.
*
* @param {Number} index
* @return {Rekord.Map} -
* The reference to this map.
*/
removeAt: function(index)
{
var key = this.keys[ index ];
var lastValue = AP.pop.apply( this.values );
var lastKey = AP.pop.apply( this.keys );
if ( index < this.values.length )
{
this.values[ index ] = lastValue;
this.keys[ index ] = lastKey;
this.indices[ lastKey ] = index;
}
delete this.indices[ key ];
return this;
},
/**
* Returns whether this map has a value for the given key.
*
* @param {String} key
* @return {Boolean}
*/
has: function(key)
{
return key in this.indices;
},
/**
* Returns the number of elements in the map.
*
* @return {Number}
*/
size: function()
{
return this.values.length;
},
subtract: function(map, dest)
{
var out = dest || new Map();
var n = this.size();
var values = this.values;
var keys = this.keys;
for (var i = 0; i < n; i++)
{
var v = values[ i ];
var k = keys[ i ];
if ( !map.has( k ) )
{
out.put( k, v );
}
}
return out;
},
/**
* Passes all values & keys in this map to a callback and if it returns a
* truthy value then the key and value are placed in the destination map.
*
* @param {Function} callback [description]
* @param {Rekord.Map} [dest] [description]
* @return {Rekord.Map} [description]
*/
filter: function(callback, dest)
{
var out = dest || new Map();
var n = this.size();
var values = this.values;
var keys = this.keys;
for (var i = 0; i < n; i++)
{
var v = values[ i ];
var k = keys[ i ];
if ( callback( v, k ) )
{
out.put( k, v );
}
}
return out;
},
/**
* Reverses the order of the underlying values & keys.
*
* @return {Rekord.Map} -
* The referense to this map.
*/
reverse: function()
{
reverse( this.values );
reverse( this.keys );
this.rebuildIndex();
return this;
},
/**
*
* @param {function} comparator [description]
* @return {Boolean} [description]
*/
isSorted: function(comparator)
{
return isSorted( comparator, this.values );
},
/**
* Sorts the underlying values & keys given a value compare function.
*
* @param {function} comparator
* A function which accepts two values and returns a number used for
* sorting. If the first argument is less than the second argument, a
* negative number should be returned. If the arguments are equivalent
* then 0 should be returned, otherwise a positive number should be
* returned.
* @return {Map} -
* The reference to this map.
*/
sort: function(comparator)
{
var map = this;
// Sort this partition!
function partition(left, right)
{
var pivot = map.values[ Math.floor((right + left) / 2) ];
var i = left;
var j = right;
while (i <= j)
{
while (comparator( map.values[i], pivot ) < 0)
{
i++;
}
while (comparator( map.values[j], pivot ) > 0)
{
j--;
}
if (i <= j)
{
swap( map.values, i, j );
swap( map.keys, i, j );
i++;
j--;
}
}
return i;
}
// Quicksort
function qsort(left, right)
{
var index = partition( left, right );
if (left < index - 1)
{
qsort( left, index - 1 );
}
if (index < right)
{
qsort( index, right );
}
}
var right = this.size() - 1;
// Are there elements to sort?
if ( right > 0 )
{
qsort( 0, right );
this.rebuildIndex();
}
return this;
},
/**
* Rebuilds the index based on the keys.
*
* @return {Rekord.Map} -
* The reference to this map.
*/
rebuildIndex: function()
{
this.indices = {};
for (var i = 0, l = this.keys.length; i < l; i++)
{
this.indices[ this.keys[ i ] ] = i;
}
return this;
},
/**
* Builds an object contain the keys and values in this map.
*
* @return {Object} -
* The built object.
*/
toObject: function(out)
{
var target = out || {};
var keys = this.keys;
var values = this.values;
for (var i = 0; i < keys.length; i++)
{
target[ keys[ i ] ] = values[ i ];
}
return target;
}
});
function Dependents(subject)
{
this.map = {};
this.listeners = {};
this.subject = subject;
}
Class.create( Dependents,
{
add: function(model, relator)
{
var key = model.$uid();
this.map[ key ] = model;
if ( model.$db.keyChanges && !this.listeners[ key ] )
{
var listener = this.handleKeyChange( relator );
this.listeners[ key ] = model.$on( Model.Events.KeyChange, listener, this );
}
},
remove: function(model)
{
var key = model.$uid();
evaluate( this.listeners[ key ] );
delete this.listeners[ key ];
delete this.map[ key ];
},
handleKeyChange: function(relator)
{
return function(model, oldKey, newKey)
{
var prefix = model.$db.name + '$';
oldKey = prefix + oldKey;
newKey = prefix + newKey;
this.listeners[ newKey ] = this.listeners[ oldKey ];
this.map[ newKey ] = this.map[ oldKey ];
delete this.listeners[ oldKey ];
delete this.map[ oldKey ];
relator.updateForeignKey( this.subject, model, true );
};
},
isSaved: function(callbackOnSaved, contextOnSaved)
{
var dependents = this.map;
var off = noop;
var onDependentSave = function()
{
callbackOnSaved.apply( contextOnSaved || this, arguments );
off();
};
for (var uid in dependents)
{
var dependent = dependents[ uid ];
if ( !dependent.$isSaved() )
{
off = dependent.$once( Model.Events.RemoteSaves, onDependentSave );
return false;
}
}
return true;
}
});
// field
// relation.field
// relations[pluckValue]
// relations?savedWhere[pluckValue]
// relations{pluckKey: pluckValue}
// relation(subprojection)
// relations(subprojection)
// relations?savedWhere(subprojection)
// expression|filter
// expression?savedWhere
// alias:expression
// expression#resolve
// relations@sum=field
function Projection(database, input)
{
this.database = database;
this.input = input;
this.projections = {};
for (var i = 0; i < input.length; i++)
{
this.addProjection( input[ i ] );
}
}
Class.create( Projection,
{
addProjection: function(input)
{
var projection = this;
var alias = input;
var aliasIndex = input.indexOf( Projection.ALIAS_DELIMITER );
if (aliasIndex > 0)
{
alias = input.substring( 0, aliasIndex );
input = input.substring( aliasIndex + 1 );
}
var word = '';
var words = [];
var tokens = ['property'];
var types = [this.database];
var i = 0;
var resolvers = [];
var processWord = function(word)
{
if (!word)
{
return;
}
var token = tokens[0];
var handler = Projection.TOKEN_HANDLER[ token ];
words.unshift( word );
if (handler && handler.post)
{
resolvers.push( handler.post( words, tokens, types, projection ) );
}
};
var processToken = function(token)
{
var handler = Projection.TOKEN_HANDLER[ token ];
tokens.unshift( token );
if (handler && handler.pre)
{
resolvers.push( handler.pre( words, tokens, types, projection ) );
}
};
for (var i = 0; i < input.length; i++)
{
var c = input.charAt( i );
var token = Projection.TOKENS[ c ];
if (token)
{
processWord( word );
processToken( token );
word = '';
}
else
{
word += c;
}
}
processWord( word );
var resolver = function(value) {
return value;
};
for (var i = resolvers.length - 1; i >= 0; i--) {
resolver = resolvers[ i ]( resolver );
}
this.projections[ alias ] = resolver;
},
project: function(model)
{
var out = {};
for (var alias in this.projections)
{
out[ alias ] = this.projections[ alias ]( model );
}
return out;
}
});
Projection.TOKENS =
{
'.': 'property',
'?': 'where',
'|': 'filter',
'#': 'resolve',
'(': 'subStart',
')': 'subEnd',
'[': 'pluckValueStart',
']': 'pluckValueEnd',
'{': 'pluckObjectStart',
':': 'pluckObjectDelimiter',
'}': 'pluckObjectEnd',
'@': 'aggregateStart',
'=': 'aggregateProperty'
};
Projection.TOKEN_HANDLER =
{
property:
{
post: function(words, tokens, types, projection)
{
var propertyName = words[0];
var sourceType = types[0];
if (!(sourceType instanceof Database))
{
throw ('The property ' + propertyName + ' can only be taken from a Model');
}
var relation = sourceType.relations[ propertyName ];
if (relation)
{
if (relation instanceof RelationSingle)
{
types.unshift( relation.model.Database );
}
else
{
types.unshift( relation );
}
}
var fieldIndex = indexOf( sourceType.fields, propertyName );
if (fieldIndex === false && !relation)
{
throw ('The property ' + propertyName + ' does not exist as a field or relation on the Model ' + sourceType.name );
}
return function(resolver)
{
return function(model)
{
if ( !isValue( model ) )
{
return null;
}
return resolver( model.$get( propertyName ) );
};
};
}
},
filter:
{
post: function(words, tokens, types, projection)
{
var filterName = words[0];
var filter = Rekord.Filters[ filterName ];
if (!filter)
{
throw (filterName + ' is not a valid filter function');
}
return function(resolver)
{
return function(value)
{
if ( !isValue( value ) )
{
return null;
}
return resolver( filter( value ) );
};
};
}
},
resolve:
{
post: function(words, tokens, types, projection)
{
var resolveName = words[0];
return function(resolver)
{
return function(source)
{
if ( !isValue( source ) )
{
return null;
}
var value = source[ resolveName ];
if ( isFunction( value ) )
{
value = value.apply( source );
}
return resolver( value );
};
};
}
},
where:
{
post: function(words, tokens, types, projection)
{
var whereName = words[0];
var whereFrom = types[0];
var where = Rekord.Wheres[ whereName ];
if (!where)
{
throw (whereName + ' is not a valid where expression');
}
if (!(whereFrom instanceof RelationMultiple))
{
throw (whereName + ' where expressions can only be used on relations');
}
return function(resolver)
{
return function(relation)
{
if ( !isValue( relation ) )
{
return null;
}
return resolver( relation.where( where ) );
};
};
}
},
aggregateProperty:
{
post: function(words, tokens, types, projection)
{
var property = words[0];
var aggregateFunction = words[1];
var aggregateFrom = types[0];
if (tokens[1] !== 'aggregateStart')
{
throw ('Aggregate function syntax error, a = must follow a @');
}
if (!(aggregateFrom instanceof Relation))
{
throw ('Aggregate functions like ' + aggregateFunction + ' from ' + aggregateFrom + ' can only be used on relations');
}
return function (resolver)
{
return function (relation)
{
if ( !isValue( relation ) )
{
return null;
}
return resolver( relation[ aggregateFunction ]( property ) );
};
};
}
},
subEnd:
{
pre: function(words, tokens, types, projection)
{
var projectionName = words[0];
var whereFrom = types[0];
if (tokens[1] !== 'subStart')
{
throw ('Sub projection syntax error, an ending ) requires a starting (');
}
if (!(whereFrom instanceof Relation))
{
throw ('Sub projections like ' + projectionName + ' from ' + words[1] + ' can only be used on relations');
}
if (!whereFrom.model.Database.projections[ projectionName ])
{
throw ('The projection ' + projectionName + ' does not exist on ' + whereFrom.model.Database.name);
}
if (whereFrom instanceof RelationSingle)
{
return function(resolver)
{
return function (relation)
{
if ( !isValue( relation ) )
{
return null;
}
return resolver( relation.$project( projectionName ) );
};
};
}
else
{
return function(resolver)
{
return function(relations)
{
if ( !isValue( relations ) )
{
return null;
}
return resolver( relations.project( projectionName ) );
};
};
}
}
},
pluckValueEnd:
{
pre: function(words, tokens, types, projection)
{
var properties = words[0];
var whereFrom = types[0];
if (tokens[1] !== 'pluckValueStart')
{
throw ('Pluck value syntax error, an ending ] requires a starting [');
}
if (!(whereFrom instanceof RelationMultiple))
{
throw ('Pluck values like ' + properties + ' from ' + words[1] + ' can only be used on relations');
}
return function (resolver)
{
return function (relations)
{
if ( !isValue( relations ) )
{
return null;
}
return resolver( relations.pluck( properties ) );
};
};
}
},
pluckObjectEnd:
{
pre: function(words, tokens, types, projection)
{
var properties = words[0];
var keys = words[1];
var whereFrom = types[0];
if (tokens[1] !== 'pluckObjectDelimiter' || tokens[2] !== 'pluckObjectStart')
{
throw ('Pluck object syntax error, must be {key: value}');
}
if (!(whereFrom instanceof RelationMultiple))
{
throw ('Pluck values like ' + properties + ' from ' + words[1] + ' can only be used on relations');
}
return function (resolver)
{
return function (relations)
{
if ( !isValue( relations ) )
{
return null;
}
return resolver( relations.pluck( properties, keys ) );
};
};
}
}
};
Projection.ALIAS_DELIMITER = ':';
Projection.parse = function(database, input)
{
var originalInput = input;
if ( isString( input ) )
{
input = database.projections[ input ];
}
if ( isArray( input ) )
{
input = new Projection( database, input );
}
if (!(input instanceof Projection))
{
throw (originalInput + ' is not a valid projection');
}
return input;
};
function Context(models)
{
this.databases = [];
this.alls = [];
this.models = [];
if ( isEmpty( models ) )
{
for (var name in Rekord.classes)
{
this.add( name );
}
}
else if ( isArray( models ) )
{
for (var i = 0; i < models.length; i++)
{
this.add( models[ i ] );
}
}
}
Context.start = function(models)
{
var context = new Context( models );
context.apply();
return context;
};
Class.create( Context,
{
add: function(type)
{
if ( isString( type ) )
{
type = Rekord.classes[ type ];
}
if ( isRekord( type ) )
{
type = type.Database;
}
if ( type instanceof Database )
{
this.databases.push( type );
this.alls.push( {} );
this.models.push( new ModelCollection( type ) );
}
},
getApplied: function()
{
var applied = 0;
this.each(function(db)
{
if (db.context === this)
{
applied++;
}
});
return applied / this.databases.length;
},
apply: function()
{
this.each( this.applyDatabase );
},
applyDatabase: function(db, all, models, i)
{
db.all = all;
db.models = models;
db.context = this;
db.contextIndex = i;
},
discard: function()
{
this.each( this.discardDatabase );
},
discardDatabase: function(db)
{
if (db.context === this)
{
db.all = db.allCached;
db.models = db.modelsCached;
db.context = null;
db.contextIndex = -1;
}
},
destroy: function()
{
this.each( this.destroyDatabase );
this.databases.length = 0;
this.alls.length = 0;
this.models.length = 0;
},
destroyDatabase: function(db, alls, models, i)
{
this.discardDatabase( db );
this.databases[ i ] = null;
this.alls[ i ] = null;
this.models[ i ].clear();
this.models[ i ] = null;
},
clear: function(db)
{
this.alls[ db.contextIndex ] = {};
},
each: function(iterator)
{
var dbs = this.databases;
var alls = this.alls;
var models = this.models;
for (var i = 0; i < dbs.length; i++)
{
iterator.call( this, dbs[ i ], alls[ i ], models[ i ], i );
}
}
});
function KeyHandler()
{
}
Class.create( KeyHandler,
{
init: function(database)
{
this.key = database.key;
this.keySeparator = database.keySeparator;
this.database = database;
},
getKey: function(model, quietly)
{
var field = this.key;
var modelKey = this.buildKey( model, field );
if ( hasFields( model, field, isValue ) )
{
return modelKey;
}
else if ( !quietly )
{
throw 'Composite key not supplied.';
}
return null;
},
buildKeyFromRelations: function(input)
{
if ( isObject( input ) )
{
var relations = this.database.relations;
for (var relationName in relations)
{
if ( relationName in input )
{
relations[ relationName ].buildKey( input );
}
}
}
},
buildKeyFromInput: function(input)
{
if ( input instanceof this.database.Model )
{
return input.$key();
}
else if ( isArray( input ) ) // && isArray( this.key )
{
return input.join( this.keySeparator );
}
else if ( isObject( input ) )
{
return this.buildKey( input );
}
return input;
}
});
function KeySimple(database)
{
this.init( database );
}
Class.extend( KeyHandler, KeySimple,
{
getKeys: function(model)
{
return this.buildKey( model );
},
removeKey: function(model)
{
var field = this.key;
delete model[ field ];
},
buildKey: function(input, otherFields)
{
this.buildKeyFromRelations( input );
var field = otherFields || this.key;
var key = input[ field ];
if ( !isValue( key ) )
{
key = input[ field ] = uuid();
}
return key;
},
buildObjectFromKey: function(key)
{
var field = this.key;
var props = {};
props[ field ] = key;
return this.database.instantiate( props );
},
hasKeyChange: function(a, b)
{
var field = this.key;
var akey = a[ field ];
var bkey = b[ field ];
return isValue( akey ) && isValue( bkey ) && akey !== bkey;
},
addToFields: function(out)
{
var field = this.key;
if ( indexOf( out, field ) === false )
{
out.unshift( field );
}
},
isValid: function(key)
{
return isValue( key );
},
copyFields: function(target, targetFields, source, sourceFields)
{
var targetValue = target[ targetFields ];
var sourceValue = source[ sourceFields ];
if ( !isValue( targetValue ) && isValue( sourceValue ) )
{
target[ targetFields ] = copy( sourceValue );
}
},
inKey: function(field)
{
if ( isArray( field ) )
{
for (var i = 0; i < field.length; i++)
{
if ( field[ i ] === this.key )
{
return true;
}
}
return false;
}
return field === this.key;
},
setKeyField: function(key, field, source, target)
{
if ( field === target )
{
key[ field ] = source[ this.key ];
}
},
applyKey: function(input, target)
{
target[ this.key ] = input;
}
});
function KeyComposite(database)
{
this.init( database );
}
Class.extend( KeyHandler, KeyComposite,
{
getKeys: function(input, otherFields)
{
this.buildKeyFromRelations( input );
return pull( input, otherFields || this.key );
},
removeKey: function(model)
{
var fields = this.key;
for (var i = 0; i < fields.length; i++)
{
delete model[ fields[ i ] ];
}
},
buildKey: function(input, otherFields)
{
return this.getKeys( input, otherFields ).join( this.keySeparator );
},
buildObjectFromKey: function(key)
{
var fields = this.key;
var props = {};
if ( isString( key ) )
{
key = key.split( this.keySeparator );
}
for (var i = 0; i < fields.length; i++)
{
props[ fields[ i ] ] = key[ i ];
}
return this.database.instantiate( props );
},
hasKeyChange: function(a, b)
{
var fields = this.key;
for (var i = 0; i < fields.length; i++)
{
var akey = a[ fields[ i ] ];
var bkey = b[ fields[ i ] ];
if ( isValue( akey ) && isValue( bkey ) && akey !== bkey )
{
return true;
}
}
return false;
},
addToFields: function(out)
{
var fields = this.key;
for (var i = fields.length - 1; i >= 0; i--)
{
if ( indexOf( out, fields[ i ] ) === false )
{
out.unshift( fields[ i ] );
}
}
},
isValid: function(key)
{
return isValue( key );
},
copyFields: function(target, targetFields, source, sourceFields)
{
for (var i = 0; i < targetFields.length; i++)
{
var targetValue = target[ targetFields[ i ] ];
var sourceValue = source[ sourceFields[ i ] ];
if ( !isValue( targetValue ) && isValue( sourceValue ) )
{
target[ targetFields[ i ] ] = copy( sourceValue );
}
}
},
inKey: function(field)
{
if ( isArray( field ) )
{
for (var i = 0; i < field.length; i++)
{
if ( indexOf( this.key, field[ i ] ) !== false )
{
return true;
}
}
return false;
}
return indexOf( this.key, field ) !== false;
},
setKeyField: function(key, field, source, target)
{
var index = indexOf( target );
if ( index !== false )
{
key[ field ] = source[ this.key[ index ] ];
}
},
applyKey: function(input, target)
{
var fields = this.key;
if ( isString( input ) )
{
input = input.split( this.keySeparator );
}
for (var i = 0; i < fields.length; i++)
{
target[ fields[ i ] ] = input[ i ];
}
}
});
/**
* An extension of the Array class adding many useful functions and events. This
* is the base collection class in Rekord.
*
* A collection of any type can be created via {@link Rekord.collect}.
*
* ```
* var nc = new Rekord.Collection([1, 2, 3, 4]);
* ```
*
* @constructor
* @memberof Rekord
* @augments Rekord.Eventful
* @extends Array
* @param {Array} [values] 0
* The initial set of values in this collection.
* @see Rekord.collect
*/
function Collection(values)
{
this.addAll( values, true );
}
/**
* A comparator to keep the collection sorted with.
*
* @memberof Rekord.Collection#
* @member {comparisonCallback} [comparator]
*/
/**
* The events a collection can emit.
*
* {@link Rekord.Collection#event:add Add}
* {@link Rekord.Collection#event:adds Adds}
* {@link Rekord.Collection#event:sort Sort}
* {@link Rekord.Collection#event:remove Remove}
* {@link Rekord.Collection#event:removes Removes}
* {@link Rekord.Collection#event:updates Updates}
* {@link Rekord.Collection#event:reset Reset}
* {@link Rekord.Collection#event:cleared Cleared}
* {@link Rekord.Collection#event:changes Changes}
*
* @static
*/
Collection.Events =
{
/**
* An event triggered when a single value is added to a collection.
*
* @event Rekord.Collection#add
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {T} value -
* The value added.
* @argument {number} index -
* The index where the value was added.
* @see Rekord.Collection#add
* @see Rekord.Collection#insertAt
* @see Rekord.ModelCollection#add
* @see Rekord.ModelCollection#push
*/
Add: 'add',
/**
* An event triggered when multiple values are added to a collection.
*
* @event Rekord.Collection#adds
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {T[]} value -
* The values added.
* @argument {number|number[]} indices -
* The index or indices where the values were added.
* @see Rekord.Collection#addAll
* @see Rekord.ModelCollection#addAll
*/
Adds: 'adds',
/**
* An event triggered when a collection is sorted. This may automatically
* be triggered by any method that modifies the collection.
*
* @event Rekord.Collection#sort
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @see Rekord.Collection#sort
* @see Rekord.ModelCollection#sort
*/
Sort: 'sort',
/**
* An event triggered when a collection has an element removed at a given index.
*
* @event Rekord.Collection#remove
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {Any} removing -
* The element that was removed.
* @argument {Number} index -
* The index where the element was removed at.
* @see Rekord.Collection#remove
* @see Rekord.Collection#removeAt
* @see Rekord.ModelCollection#remove
*/
Remove: 'remove',
/**
* An event triggered when a collection has multiple elements removed.
*
* @event Rekord.Collection#removes
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {Any[]} removed -
* The array of elements removed from the collection.
* @argument {number|number[]} indices -
* The index where the values were removed OR the array of indices.
* @argument {number} [removeCount] -
* The number of values removed at the given index (undefined if array specified).
* @see Rekord.Collection#removeAll
* @see Rekord.Collection#removeWhere
*/
Removes: 'removes',
/**
* An event triggered when a collection has elements modified.
*
* @event Rekord.Collection#updates
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {Array} updated -
* The array of elements modified.
* @see Rekord.ModelCollection#update
* @see Rekord.ModelCollection#updateWhere
*/
Updates: 'updates',
/**
* An event triggered when a collection's elements are entirely replaced by
* a new set of elements.
*
* @event Rekord.Collection#reset
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @argument {Array} updated -
* The array of elements modified.
* @see Rekord.FilteredCollection#sync
* @see Rekord.ModelCollection#reset
*/
Reset: 'reset',
/**
* An event triggered when a collection is cleared of all elements.
*
* @event Rekord.Collection#cleared
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
* @see Rekord.Collection#clear
*/
Cleared: 'cleared',
/**
* All events triggered by a collection when the contents of the collection changes.
*
* @event Rekord.Collection#changes
* @argument {Rekord.Collection} collection -
* The collection that triggered the event.
*/
Changes: 'add adds sort remove removes updates reset cleared'
};
Class.extend( Array, Collection,
{
/**
* Sets the comparator for this collection and performs a sort.
*
* @method
* @memberof Rekord.Collection#
* @param {ComparatorInput} comparator -
* The comparator input to convert to a comparison function.
* @param {Boolean} [nullsFirst=false] -
* When a comparison is done involving a null/undefined value this can
* determine which is ordered before the other.
* @emits Rekord.Collection#sort
* @see Rekord.createComparator
* @return {Rekord.Collection}
*/
setComparator: function(comparator, nullsFirst)
{
this.comparator = createComparator( comparator, nullsFirst );
this.sort();
return this;
},
/**
* Adds a comparator to the existing comparator. This added comparator is ran
* after the current comparator when it finds two elements equal. If no
* comparator exists on this collection then it's set to the given comparator.
*
* @method
* @memberof Rekord.Collection#
* @param {ComparatorInput} comparator -
* The comparator input to convert to a comparison function.
* @param {Boolean} [nullsFirst=false] -
* When a comparison is done involving a null/undefined value this can
* determine which is ordered before the other.
* @emits Rekord.Collection#sort
* @see Rekord.createComparator
* @return {Rekord.Collection}
*/
addComparator: function(comparator, nullsFirst)
{
this.comparator = addComparator( this.comparator, comparator, nullsFirst );
this.sort();
return this;
},
/**
* Determines if the collection is currently sorted based on the current
* comparator of the collection unless a comparator is given
*
* @method
* @memberof Rekord.Collection#
* @param {ComparatorInput} [comparator] -
* The comparator input to convert to a comparison function.
* @param {Boolean} [nullsFirst=false] -
* When a comparison is done involving a null/undefined value this can
* determine which is ordered before the other.
* @see Rekord.createComparator
* @return {Boolean}
*/
isSorted: function(comparator, nullsFirst)
{
var cmp = comparator ? createComparator( comparator, nullsFirst ) : this.comparator;
return isSorted( cmp, this );
},
/**
* Sorts the elements in this collection based on the current comparator
* unless a comparator is given. If a comparator is given it will not override
* the current comparator, subsequent operations to the collection may trigger
* a sort if the collection has a comparator.
*
* @method
* @memberof Rekord.Collection#
* @param {ComparatorInput} [comparator] -
* The comparator input to convert to a comparison function.
* @param {Boolean} [nullsFirst=false] -
* When a comparison is done involving a null/undefined value this can
* determine which is ordered before the other.
* @param {Boolean} [ignorePrimitive=false] -
* Sorting is automatically done for non-primitive collections if a
* comparator exists. This flag ensures primitive collections aren't sorted
* after every operation.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#sort
* @see Rekord.createComparator
*/
sort: function(comparator, nullsFirst, ignorePrimitive)
{
var cmp = comparator ? createComparator( comparator, nullsFirst ) : this.comparator;
if ( !isSorted( cmp, this ) || ( !ignorePrimitive && !cmp && isPrimitiveArray( this ) ) )
{
AP.sort.call( this, cmp );
this.trigger( Collection.Events.Sort, [this] );
}
return this;
},
/**
* Resets the values in this collection with a new collection of values.
*
* @method
* @memberof Rekord.Collection#
* @param {Any[]} [values] -
* The new array of values in this collection.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#reset
*/
reset: function(values)
{
this.length = 0;
if ( isArray( values ) )
{
AP.push.apply( this, values );
}
else if ( isValue( values ) )
{
AP.push.call( this, values );
}
this.trigger( Collection.Events.Reset, [this] );
this.sort( undefined, undefined, true );
return this;
},
/**
* Creates a limited view of this collection known as a page. The resulting
* page object changes when this collection changes. At the very least the
* page size is required, and a starting page index can be specified.
*
* @method
* @memberof Rekord.Collection#
* @param {Number} pageSize -
* The maximum number of elements allowed in the page at once.
* @param {Number} [pageIndex=0]
* The starting page offset. This isn't an element offset, but the element
* offset can be calculated by multiplying the page index by the page size.
* @return {Rekord.Page} -
* The newly created Page.
*/
page: function(pageSize, pageIndex)
{
return new Page( this, pageSize, pageIndex );
},
/**
* Creates a sub view of this collection known as a filtered collection. The
* resulting collection changes when this collection changes. Any time an
* element is added or removed to this collection it may be added or removed
* from the filtered collection if it fits the filter function. The filter
* function is created by passing the arguments of this function to
* {@link Rekord.createWhere}.
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @return {Rekord.FilteredCollection} -
* The newly created live filtered view of this collection.
* @see Rekord.createWhere
*/
filtered: function(whereProperties, whereValue, whereEquals)
{
var filter = createWhere( whereProperties, whereValue, whereEquals );
return FilteredCollection.create( this, filter );
},
/**
* Creates a copy of this collection with elements that match the supplied
* parameters. The parameters are passed to the {@link Rekord.createWhere}
* to generate a function which tests each element of this collection for
* inclusion in the newly created collection.
*
* ```javascript
* var isEven = function() { return x % 2 == 0; };
* var c = Rekord.collect(1, 2, 3, 4, 5);
* var w = c.where(isEven); // [2, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that match.
* @return {Rekord.Collection} -
* The copy of this collection ran through a filtering function.
* @see Rekord.createWhere
*/
where: function(whereProperties, whereValue, whereEquals, out)
{
var where = createWhere( whereProperties, whereValue, whereEquals );
var target = out || this.cloneEmpty();
for (var i = 0; i < this.length; i++)
{
var a = this[ i ];
if ( where( a ) )
{
target.push( a );
}
}
return target;
},
/**
* Returns a collection with elements that exist in this collection but does
* not exist in the given collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* var b = Rekord.collect(1, 3, 5);
* var c = a.subtract( b ); // [2, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Array} collection -
* The array of elements that shouldn't exist in the resulting collection.
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that exist in this collection but not in
* the given collection. If this is not given - a collection of this type
* will be created.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to an element that exists in the given
* collection.
* @return {Array} -
* The collection of elements that exist in this collection and not the
* given collection.
*/
subtract: function(collection, out, equals)
{
var target = out || this.cloneEmpty();
var equality = equals || equalsStrict;
for (var i = 0; i < this.length; i++)
{
var a = this[ i ];
var exists = false;
for (var j = 0; j < collection.length && !exists; j++)
{
exists = equality( a, collection[ j ] );
}
if (!exists)
{
target.push( a );
}
}
return target;
},
/**
* Returns a collection of elements that are shared between this collection
* and the given collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* var b = Rekord.collect(1, 3, 5);
* var c = a.intersect( b ); // [1, 3]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Array} collection -
* The collection of elements to intersect with this collection.
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that exist in both this collection and
* the given collection. If this is not given - a collection of this type
* will be created.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to an element that exists in the given
* collection.
* @return {Array} -
* The collection of elements that exist in both collections.
*/
intersect: function(collection, out, equals)
{
var target = out || this.cloneEmpty();
var equality = equals || equalsStrict;
for (var i = 0; i < collection.length; i++)
{
var a = collection[ i ];
var exists = false;
for (var j = 0; j < this.length && !exists; j++)
{
exists = equality( a, this[ j ] );
}
if (exists)
{
target.push( a );
}
}
return target;
},
/**
* Returns a collection of elements that exist in the given collection but
* not in this collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* var b = Rekord.collect(1, 3, 5);
* var c = a.complement( b ); // [5]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Array} collection -
* The array of elements that could exist in the resulting collection.
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that exist in given collection but not
* in this collection. If this is not given - a collection of this type
* will be created.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to an element that exists in the given
* collection.
* @return {Array} -
* The collection of elements that exist in the given collection and not
* this collection.
*/
complement: function(collection, out, equals)
{
var target = out || this.cloneEmpty();
var equality = equals || equalsStrict;
for (var i = 0; i < collection.length; i++)
{
var a = collection[ i ];
var exists = false;
for (var j = 0; j < this.length && !exists; j++)
{
exists = equality( a, this[ j ] );
}
if (!exists)
{
target.push( a );
}
}
return target;
},
/**
* Clears all elements from this collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* a.clear(); // []
* ```
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#sort
*/
clear: function()
{
this.length = 0;
this.trigger( Collection.Events.Cleared, [this] );
return this;
},
/**
* Adds an element to this collection - sorting the collection if a
* comparator is set on this collection and `delaySort` is not a specified or
* a true value.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* a.add( 5 ); // [1, 2, 3, 4, 5]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Any} value -
* The value to add to this collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#add
* @emits Rekord.Collection#sort
*/
add: function(value, delaySort)
{
var i = this.length;
AP.push.call( this, value );
this.trigger( Collection.Events.Add, [this, value, i] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
return this;
},
/**
* Adds one or more elements to the end of this collection - sorting the
* collection if a comparator is set on this collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* a.push( 5, 6, 7 ); // 7
* a // [1, 2, 3, 4, 5, 6, 7]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {...Any} value -
* The values to add to this collection.
* @return {Number} -
* The new length of this collection.
* @emits Rekord.Collection#add
* @emits Rekord.Collection#sort
*/
push: function()
{
var values = AP.slice.apply(arguments);
var i = this.length;
AP.push.apply( this, values );
this.trigger( Collection.Events.Adds, [this, values, i] );
this.sort( undefined, undefined, true );
return this.length;
},
/**
* Adds one or more elements to the beginning of this collection - sorting the
* collection if a comparator is set on this collection.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* a.unshift( 5, 6, 7 ); // 7
* a // [5, 6, 7, 1, 2, 3, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {...Any} value -
* The values to add to this collection.
* @return {Number} -
* The new length of this collection.
* @emits Rekord.Collection#adds
* @emits Rekord.Collection#sort
*/
unshift: function()
{
var values = arguments;
AP.unshift.apply( this, values );
this.trigger( Collection.Events.Adds, [this, AP.slice.apply(values), 0] );
this.sort( undefined, undefined, true );
return this.length;
},
/**
* Adds all elements in the given array to this collection - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* not specified or a true value.
*
* ```javascript
* var a = Rekord.collect(1, 2, 3, 4);
* a.addAll( [5, 6] ); // [1, 2, 3, 4, 5, 6]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Any[]} values -
* The values to add to this collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#adds
* @emits Rekord.Collection#sort
*/
addAll: function(values, delaySort)
{
if ( isArray( values ) && values.length )
{
var i = this.length;
AP.push.apply( this, values );
this.trigger( Collection.Events.Adds, [this, values, i] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
}
return this;
},
/**
* Inserts an element into this collection at the given index - sorting the
* collection if a comparator is set on this collection and `delaySort` is not
* specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.insertAt( 0, 0 ); // [0, 1, 2, 3, 4]
* c.insertAt( 2, 1.5 ); // [0, 1, 1.5, 2, 3, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Number} i -
* The index to insert the element at.
* @param {Any} value -
* The value to insert into the collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#add
* @emits Rekord.Collection#sort
*/
insertAt: function(i, value, delaySort)
{
AP.splice.call( this, i, 0, value );
this.trigger( Collection.Events.Add, [this, value, i] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
return this;
},
/**
* Removes the last element in this collection and returns it - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* no specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.pop(); // 4
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Any} -
* The element removed from the end of the collection.
* @emits Rekord.Collection#remove
* @emits Rekord.Collection#sort
*/
pop: function(delaySort)
{
var removed = AP.pop.apply( this );
var i = this.length;
this.trigger( Collection.Events.Remove, [this, removed, i] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
return removed;
},
/**
* Removes the first element in this collection and returns it - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* no specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.shift(); // 1
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Any} -
* The element removed from the beginning of the collection.
* @emits Rekord.Collection#remove
* @emits Rekord.Collection#sort
*/
shift: function(delaySort)
{
var removed = AP.shift.apply( this );
this.trigger( Collection.Events.Remove, [this, removed, 0] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
return removed;
},
/**
* Removes the element in this collection at the given index `i` - sorting
* the collection if a comparator is set on this collection and `delaySort` is
* not specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.removeAt( 1 ); // 2
* c.removeAt( 5 ); // undefined
* c // [1, 3, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Number} i -
* The index of the element to remove.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Any} -
* The element removed, or undefined if the index was invalid.
* @emits Rekord.Collection#remove
* @emits Rekord.Collection#sort
*/
removeAt: function(i, delaySort)
{
var removing;
if (i >= 0 && i < this.length)
{
removing = this[ i ];
AP.splice.call( this, i, 1 );
this.trigger( Collection.Events.Remove, [this, removing, i] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
}
return removing;
},
/**
* Removes the given value from this collection if it exists - sorting the
* collection if a comparator is set on this collection and `delaySort` is not
* specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.remove( 1 ); // 1
* c.remove( 5 ); // undefined
* c // [2, 3, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Any} value -
* The value to remove from this collection if it exists.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to the given value.
* @return {Any} -
* The element removed from this collection.
* @emits Rekord.Collection#remove
* @emits Rekord.Collection#sort
*/
remove: function(value, delaySort, equals)
{
var i = this.indexOf( value, equals );
var element = this[ i ];
if ( i !== -1 )
{
this.removeAt( i, delaySort );
}
return element;
},
/**
* Removes the given values from this collection - sorting the collection if
* a comparator is set on this collection and `delaySort` is not specified or
* a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.removeAll( [1, 5] ); // [1]
* c // [2, 3, 4]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Any[]} values -
* The values to remove from this collection if they exist.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to any of the given values.
* @return {Any[]} -
* The elements removed from this collection.
* @emits Rekord.Collection#removes
* @emits Rekord.Collection#sort
*/
removeAll: function(values, delaySort, equals)
{
var removed = [];
var removedIndices = [];
if ( isArray( values ) && values.length )
{
for (var i = 0; i < values.length; i++)
{
var value = values[ i ];
var k = this.indexOf( value, equals );
if ( k !== -1 )
{
removedIndices.push( k );
removed.push( value );
}
}
removedIndices.sort();
for (var i = removedIndices.length - 1; i >= 0; i--)
{
AP.splice.call( this, removedIndices[ i ], 1 );
}
this.trigger( Collection.Events.Removes, [this, removed, removedIndices] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
}
return removed;
},
/**
* Removes elements from this collection that meet the specified criteria. The
* given criteria are passed to {@link Rekord.createWhere} to create a filter
* function. All elements removed are returned
*
* ```javascript
* var isEven = function(x) { return x % 2 === 0; };
* var c = Rekord.collect(1, 2, 3, 4);
* c.removeWhere( isEven ); // [2, 4];
* c // [1, 3]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that match.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#removes
* @emits Rekord.Collection#sort
* @see Rekord.createWhere
*/
removeWhere: function(whereProperties, whereValue, whereEquals, out, delaySort)
{
var where = createWhere( whereProperties, whereValue, whereEquals );
var removed = out || this.cloneEmpty();
var removedIndices = [];
for (var i = 0; i < this.length; i++)
{
var value = this[ i ];
if ( where( value ) )
{
removedIndices.push( i );
removed.push( value );
}
}
for (var i = removedIndices.length - 1; i >= 0; i--)
{
AP.splice.call( this, removedIndices[ i ], 1 );
}
this.trigger( Collection.Events.Removes, [this, removed, removedIndices] );
if ( !delaySort )
{
this.sort( undefined, undefined, true );
}
return removed;
},
/**
* Splices elements out of and into this collection - sorting the collection
* if a comparator is set on this collection.
*
* @method
* @memberof Rekord.Collection#
* @param {Number} start -
* Index at which to start changing the array (with origin 0). If greater
* than the length of the array, actual starting index will be set to the
* length of the array. If negative, will begin that many elements from the end.
* @param {Number} deleteCount -
* An integer indicating the number of old array elements to remove. If
* deleteCount is 0, no elements are removed. In this case, you should
* specify at least one new element. If deleteCount is greater than the
* number of elements left in the array starting at start, then all of the
* elements through the end of the array will be deleted.
* If deleteCount is omitted, deleteCount will be equal to (arr.length - start).
* @param {...Any} values -
* The elements to add to the array, beginning at the start index. If you
* don't specify any elements, splice() will only remove elements from the array.
* @return {Any[]} -
* The array of deleted elements.
* @emits Rekord.Collection#removes
* @emits Rekord.Collection#adds
* @emits Rekord.Collection#sort
*/
splice: function(start, deleteCount)
{
var adding = AP.slice.call( arguments, 2 );
var removed = AP.splice.apply( this, arguments );
if ( deleteCount )
{
this.trigger( Collection.Events.Removes, [this, removed, start, deleteCount] );
}
if ( adding.length )
{
this.trigger( Collection.Events.Adds, [this, adding, start] );
}
this.sort( undefined, undefined, true );
return removed;
},
/**
* Reverses the order of elements in this collection.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.reverse(); // [4, 3, 2, 1]
* ```
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to this collection.
* @emits Rekord.Collection#updates
*/
reverse: function()
{
if ( AP.reverse )
{
AP.reverse.apply( this );
}
else
{
reverse( this );
}
this.trigger( Collection.Events.Updates, [this] );
return this;
},
/**
* Returns the index of the given element in this collection or returns -1
* if the element doesn't exist in this collection.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.indexOf( 1 ); // 0
* c.indexOf( 2 ); // 1
* c.indexOf( 5 ); // -1
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Any} value -
* The value to search for.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to the given value.
* @return {Number} -
* The index of the element in this collection or -1 if it was not found.
* @see Rekord.equals
* @see Rekord.equalsStrict
*/
indexOf: function(value, equals)
{
var equality = equals || equalsStrict;
for (var i = 0; i < this.length; i++)
{
if ( equality( value, this[ i ] ) )
{
return i;
}
}
return -1;
},
/**
* Returns the element with the minimum value given a comparator.
*
* ```javascript
* var c = Rekord.collect({age: 4}, {age: 5}, {age: 6}, {age: 3});
* c.minModel('age'); // {age: 3}
* c.minModel('-age'); // {age: 6}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {comparatorInput} comparator -
* The comparator which calculates the minimum model.
* @param {Any} [startingValue]
* The initial minimum value. If a value is specified, it's compared
* against all elements in this collection until the comparator function
* finds a more minimal value. If it doesn't - this is the value returned.
* @return {Any} -
* The minimum element in the collection given the comparator function.
* @see Rekord.createComparator
*/
minModel: function(comparator, startingValue)
{
var cmp = createComparator( comparator || this.comparator, false );
var min = startingValue;
for (var i = 0; i < this.length; i++)
{
if ( cmp( min, this[i] ) > 0 )
{
min = this[i];
}
}
return min;
},
/**
* Returns the element with the maximum value given a comparator.
*
* ```javascript
* var c = Rekord.collect({age: 4}, {age: 5}, {age: 6}, {age: 3});
* c.maxModel('age'); // {age: 6}
* c.maxModel('-age'); // {age: 3}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {comparatorInput} comparator -
* The comparator which calculates the maximum model.
* @param {Any} [startingValue] -
* The initial maximum value. If a value is specified, it's compared
* against all elements in this collection until the comparator function
* finds a more maximal value. If it doesn't - this is the value returned.
* @return {Any} -
* The maximum element in the collection given the comparator function.
* @see Rekord.createComparator
*/
maxModel: function(comparator, startingValue)
{
var cmp = createComparator( comparator || this.comparator, true );
var max = startingValue;
for (var i = 0; i < this.length; i++)
{
if ( cmp( max, this[i] ) < 0 )
{
max = this[i];
}
}
return max;
},
/**
* Returns the minimum value for the given property expression out of all the
* elements this collection.
*
* ```javascript
* var c = Rekord.collect({age: 6}, {age: 5}, {notage: 5});
* c.min('age'); // 5
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [properties] -
* The expression which takes an element in this container and resolves a
* value that can be compared to the current minimum.
* @param {Any} [startingValue] -
* The initial minimum value. If a value is specified, it's compared
* against all elements in this collection until the comparator function
* finds a more minimal value. If it doesn't - this is the value returned.
* @param {compareCallback} [compareFunction=Rekord.compare] -
* A comparison function to use.
* @return {Any} -
* The minimum value found.
* @see Rekord.createPropertyResolver
* @see Rekord.compare
*/
min: function(properties, startingValue, compareFunction)
{
var comparator = compareFunction || compare;
var resolver = createPropertyResolver( properties );
var min = startingValue;
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( comparator( min, resolved, false ) > 0 )
{
min = resolved;
}
}
return min;
},
/**
* Returns the maximum value for the given property expression out of all the
* elements this collection.
*
* ```javascript
* var c = Rekord.collect({age: 6}, {age: 5}, {notage: 5});
* c.max('age'); // 6
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [properties] -
* The expression which takes an element in this container and resolves a
* value that can be compared to the current maximum.
* @param {Any} [startingValue] -
* The initial maximum value. If a value is specified, it's compared
* against all elements in this collection until the comparator function
* finds a more maximal value. If it doesn't - this is the value returned.
* @param {compareCallback} [compareFunction=Rekord.compare] -
* A comparison function to use.
* @return {Any} -
* The maximum value found.
* @see Rekord.createPropertyResolver
* @see Rekord.compare
*/
max: function(properties, startingValue, compareFunction)
{
var comparator = compareFunction || compare;
var resolver = createPropertyResolver( properties );
var max = startingValue;
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( comparator( max, resolved, true ) < 0 )
{
max = resolved;
}
}
return max;
},
/**
* Returns the first element where the given expression is true.
*
* ```javascript
* var c = Rekord.collect([{x: 5}, {y: 6}, {y: 6, age: 8}, {z: 7}]);
* c.firstWhere('y', 6); // {x: 6}
* c.firstWhere(); // {x: 5}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [whereProperties] -
* The expression used to create a function to test the elements in this
* collection.
* @param {Any} [whereValue] -
* When the first argument is a string this argument will be treated as a
* value to compare to the value of the named property on the object passed
* through the filter function.
* @param {equalityCallback} [whereEquals=Rekord.equalsStrict] -
* An alternative function can be used to compare to values.
* @return {Any} -
* The first element in this collection that matches the given expression.
* @see Rekord.createWhere
*/
firstWhere: function(whereProperties, whereValue, whereEquals)
{
var where = createWhere( whereProperties, whereValue, whereEquals );
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
return model;
}
}
return null;
},
/**
* Returns the first non-null value in this collection given a property
* expression. If no non-null values exist for the given property expression,
* then undefined will be returned.
*
* ```javascript
* var c = Rekord.collect([{x: 5}, {y: 6}, {y: 4}, {z: 7}]);
* c.first('y'); // 6
* c.first(); // {x: 5}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [properties] -
* The expression which converts one value into another.
* @return {Any} -
* @see Rekord.createPropertyResolver
* @see Rekord.isValue
*/
first: function(properties)
{
var resolver = createPropertyResolver( properties );
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( isValue( resolved ) )
{
return resolved;
}
}
},
/**
* Returns the last element where the given expression is true.
*
* ```javascript
* var c = Rekord.collect([{x: 5}, {y: 6}, {y: 6, age: 8}, {z: 7}]);
* c.lastWhere('y', 6); // {x: 6, age: 8}
* c.lastWhere(); // {z: 7}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [properties] -
* The expression used to create a function to test the elements in this
* collection.
* @param {Any} [value] -
* When the first argument is a string this argument will be treated as a
* value to compare to the value of the named property on the object passed
* through the filter function.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* An alternative function can be used to compare to values.
* @return {Any} -
* The last element in this collection that matches the given expression.
* @see Rekord.createWhere
*/
lastWhere: function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
for (var i = this.length - 1; i >= 0; i--)
{
var model = this[ i ];
if ( where( model ) )
{
return model;
}
}
return null;
},
/**
* Returns the last non-null value in this collection given a property
* expression. If no non-null values exist for the given property expression,
* then undefined will be returned.
*
* ```javascript
* var c = Rekord.collect([{x: 5}, {y: 6}, {y: 4}, {z: 7}]);
* c.last('y'); // 4
* c.last(); // {z: 7}
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [properties] -
* The expression which converts one value into another.
* @return {Any} -
* @see Rekord.createPropertyResolver
* @see Rekord.isValue
*/
last: function(properties)
{
var resolver = createPropertyResolver( properties );
for (var i = this.length - 1; i >= 0; i--)
{
var resolved = resolver( this[ i ] );
if ( isValue( resolved ) )
{
return resolved;
}
}
},
/**
* Iterates over all elements in this collection and passes them through the
* `resolver` function. The returned value is passed through the `validator`
* function and if that returns true the resolved value is passed through the
* `process` function. After iteration, the `getResult` function is executed
* and the returned value is returned by this function.
*
* @method
* @memberof Rekord.Collection#
* @param {Function} resolver -
* The function which takes an element in this collection and returns a
* value based on that element.
* @param {Function} validator -
* The function which takes the resolved value and determines whether it
* passes some test.
* @param {Function} process -
* The function which is given the resolved value if it passes the test.
* @param {Function} getResult -
* The function which is executed at the end of iteration and the result is
* is returned by this function.
* @return {Any} -
* The value returned by `getResult`.
*/
aggregate: function(resolver, validator, process, getResult)
{
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( validator( resolved ) )
{
process( resolved );
}
}
return getResult();
},
/**
* Sums all numbers resolved from the given property expression and returns
* the result.
*
* ```javascript
* var c = Rekord.collect([2, 3, 4]);
* c.sum(); // 9
* var d = Rekord.collect([{age: 5}, {age: 4}, {age: 2}]);
* d.sum('age'); // 11
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [numbers]
* The expression which converts an element in this collection to a number.
* @return {Number} -
* The sum of all valid numbers found in this collection.
* @see Rekord.createNumberResolver
*/
sum: function(numbers)
{
var resolver = createNumberResolver( numbers );
var result = 0;
function process(x)
{
result += x;
}
function getResult()
{
return result;
}
return this.aggregate( resolver, isNumber, process, getResult );
},
/**
* Averages all numbers resolved from the given property expression and
* returns the result.
*
* ```javascript
* var c = Rekord.collect([2, 3, 4]);
* c.avg(); // 3
* var d = Rekord.collect([{age: 5}, {age: 4}, {age: 2}]);
* d.avg('age'); // 3.66666
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [numbers]
* The expression which converts an element in this collection to a number.
* @return {Number} -
* The average of all valid numbers found in this collection.
* @see Rekord.createNumberResolver
*/
avg: function(numbers)
{
var resolver = createNumberResolver( numbers );
var result = 0;
var total = 0;
function process(x)
{
result += x;
total++;
}
function getResult()
{
return total === 0 ? 0 : result / total;
}
return this.aggregate( resolver, isNumber, process, getResult );
},
/**
* Counts the number of elements in this collection that past the test
* function generated by {@link Rekord.createWhere}.
*
* ```javascript
* var c = Rekord.collect([{name: 't1', done: 1}, {name: 't2', done: 0}, {name: 't3', done: 1}, {name: 't4'}]);
* c.countWhere('done'); // 3
* c.countWhere('done', 0); // 1
* c.countWhere('done', 1); // 2
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [properties] -
* The expression used to create a function to test the elements in this
* collection.
* @param {Any} [value] -
* When the first argument is a string this argument will be treated as a
* value to compare to the value of the named property on the object passed
* through the filter function.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* An alternative function can be used to compare to values.
* @return {Number} -
* The number of elements in the collection that passed the test.
* @see Rekord.createWhere
*/
countWhere: function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
var met = 0;
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
met++;
}
}
return met;
},
/**
* Counts the number of elements in this collection that has a value for the
* given property expression.
*
* ```javascript
* var c = Rekord.collect([{age: 2}, {age: 3}, {taco: 4}]);
* c.count('age'); // 2
* c.count('taco'); // 1
* c.count(); // 3
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [properties] -
* The expression which converts one value into another.
* @return {Number} -
* The number of elements that had values for the property expression.
* @see Rekord.createPropertyResolver
* @see Rekord.isValue
*/
count: function(properties)
{
if ( !isValue( properties ) )
{
return this.length;
}
var resolver = createPropertyResolver( properties );
var result = 0;
for (var i = 0; i < this.length; i++)
{
var resolved = resolver( this[ i ] );
if ( isValue( resolved ) )
{
result++;
}
}
return result;
},
/**
* Plucks values from elements in the collection. If only a `values` property
* expression is given the result will be an array of resolved values. If the
* `keys` property expression is given, the result will be an object where the
* property of the object is determined by the key expression.
*
* ```javascript
* var c = Rekord.collect([{age: 2, nm: 'T'}, {age: 4, nm: 'R'}, {age: 5, nm: 'G'}]);
* c.pluck(); // c
* c.pluck('age'); // [2, 4, 5]
* c.pluck('age', 'nm'); // {T: e, R: 4, G: 5}
* c.pluck(null, 'nm'); // {T: {age: 2, nm: 'T'}, R: {age: 4, nm: 'R'}, G: {age: 5, nm: 'G'}}
* c.pluck('{age}-{nm}'); // ['2-T', '4-R', '5-G']
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {propertyResolverInput} [values] -
* The expression which converts an element into a value to pluck.
* @param {propertyResolverInput} [keys] -
* The expression which converts an element into an object property (key).
* @return {Array|Object} -
* The plucked values.
* @see Rekord.createPropertyResolver
*/
pluck: function(values, keys)
{
var valuesResolver = createPropertyResolver( values );
if ( keys )
{
var keysResolver = createPropertyResolver( keys );
var result = {};
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var value = valuesResolver( model );
var key = keysResolver( model );
result[ key ] = value;
}
return result;
}
else
{
var result = [];
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var value = valuesResolver( model );
result.push( value );
}
return result;
}
},
/**
* Iterates over each element in this collection and passes the element and
* it's index to the given function. An optional function context can be given.
*
* @method
* @memberof Rekord.Collection#
* @param {Function} callback -
* The function to invoke for each element of this collection passing the
* element and the index where it exists.
* @param {Object} [context] -
* The context to the callback function.
* @return {Rekord.Collection} -
* The reference to this collection.
*/
each: function(callback, context)
{
var callbackContext = context || this;
for (var i = 0; i < this.length; i++)
{
var item = this[ i ];
callback.call( callbackContext, item, i );
if ( this[ i ] !== item )
{
i--;
}
}
return this;
},
/**
* Iterates over each element in this collection that matches the where
* expression and passes the element and it's index to the given function.
*
* @method
* @memberof Rekord.Collection#
* @param {Function} callback -
* The function to invoke for each element of this collection passing the
* element and the index where it exists.
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Rekord.Collection} -
* The reference to this collection.
* @see Rekord.createWhere
*/
eachWhere: function(callback, properties, values, equals)
{
var where = createWhere( properties, values, equals );
for (var i = 0; i < this.length; i++)
{
var item = this[ i ];
if ( where( item ) )
{
callback.call( this, item, i );
if ( this[ i ] !== item )
{
i--;
}
}
}
return this;
},
/**
* Reduces all the elements of this collection to a single value. All elements
* are passed to a function which accepts the currently reduced value and the
* current element and returns the new reduced value.
*
* ```javascript
* var reduceIt = function(curr, elem) {
* return curr + ( elem[0] * elem[1] );
* };
* var c = Rekord.collect([[2, 1], [3, 2], [5, 6]]);
* c.reduce( reduceIt, 0 ); // 38
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Function} reducer -
* A function which accepts the current reduced value and an element and
* returns the new reduced value.
* @param {Any} [initialValue] -
* The first value to pass to the reducer function.
* @return {Any} -
* The reduced value.
*/
reduce: function(reducer, initialValue)
{
for (var i = 0; i < this.length; i++)
{
initialValue = reducer( initialValue, this[ i ] );
}
return initialValue;
},
/**
* Returns a random element in this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Any} -
* The randomly chosen element from this collection.
*/
random: function()
{
var i = Math.floor( Math.random() * this.length );
return this[ i ];
},
/**
* Breaks up the collection into an array of arrays of a maximum size (chunks).
* A destination array can be used to avoid re-allocating arrays.
*
* ```javascript
* var c = Rekord.collect([1, 2, 3, 4, 5, 6, 7, 8, 9]);
* c.chunk(4); // [[1, 2, 3, 4], [5, 6, 7, 8], [9]]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Number} chunkSize -
* The maximum number of elements that can exist in a chunk.
* @param {Array} [out] -
* The destination array to place the chunks.
* @return {Array} -
* The array of chunks of elements taken from this collection.
*/
chunk: function(chunkSize, out)
{
var outer = out || [];
var outerIndex = 0;
var inner = outer[ outerIndex ] = outer[ outerIndex ] || [];
var innerIndex = 0;
for (var i = 0; i < this.length; i++)
{
inner[ innerIndex ] = this[ i ];
if ( ++innerIndex >= chunkSize )
{
innerIndex = 0;
outerIndex++;
inner.length = chunkSize;
inner = outer[ outerIndex ] = outer[ outerIndex ] || [];
}
}
if ( innerIndex !== 0 )
{
outerIndex++;
}
inner.length = innerIndex;
outer.length = outerIndex;
return outer;
},
/**
* Determines whether at least one element in this collection matches the
* given criteria.
*
* ```javascript
* var c = Rekord.collect([{age: 2}, {age: 6}]);
* c.contains('age', 2); // true
* c.contains('age', 3); // false
* c.contains('age'); // true
* c.contains('name'); // false
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {whereInput} [properties] -
* The expression used to create a function to test the elements in this
* collection.
* @param {Any} [value] -
* When the first argument is a string this argument will be treated as a
* value to compare to the value of the named property on the object passed
* through the filter function.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* An alternative function can be used to compare to values.
* @return {Boolean} -
* True if any of the elements passed the test function, otherwise false.
* @see Rekord.createWhere
*/
contains: function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
return true;
}
}
return false;
},
/**
* Groups the elements into sub collections given some property expression to
* use as the value to group by.
*
* ```javascript
* var c = Rekord.collect([
* { name: 'Tom', age: 6, group: 'X' },
* { name: 'Jon', age: 7, group: 'X' },
* { name: 'Rob', age: 8, group: 'X' },
* { name: 'Bon', age: 9, group: 'Y' },
* { name: 'Ran', age: 10, group: 'Y' },
* { name: 'Man', age: 11, group: 'Y' },
* { name: 'Tac', age: 12, group: 'Z' }
* ]);
*
* c.group({by: 'group'});
* // [{group: 'X', $count: 3, $group: [...]},
* // {group: 'Y', $count: 3, $group: [...]},
* // {group: 'Z', $count: 1, $group: [.]}]
*
* c.group({by: 'group', select: {age: 'avg', name: 'first'}});
* // [{group: 'X', age: 7, name: 'Tom', $count: 3, $group: [...]},
* // {group: 'Y', age: 9, name: 'Bon', $count: 3, $group: [...]},
* // {group: 'Z', age: 12, name: 'Tac', $count: 1, $group: [.]}]
*
* c.group({by: 'group', track: false, count: false});
* // [{group: 'X'}, {group: 'Y'}, {group: 'Z'}]
*
* var havingMoreThanOne = function(grouping, groupElements) {
* return groupElements.length > 0;
* };
* c.group({by: 'group', select: {age: 'avg'}, comparator: '-age', having: havingMoreThanOne, track: false, count: false});
* // [{group: 'Y', age: 9},
* // {group: 'X', age: 7}]
* ```
*
* @method
* @memberof Rekord.Collection#
* @param {Object} grouping -
* An object specifying how elements in this collection are to be grouped
* and what properties from the elements should be aggregated in the
* resulting groupings.
* - `by`: A property expression that resolves how elements will be grouped.
* - `select`: An object which contains properties that should be aggregated where the value is the aggregate collection function to call (sum, avg, count, first, last, etc).
* - `having`: A having expression which takes a grouping and the grouped elements and determines whether the grouping should be in the final result.
* - `comparator`: A comparator for sorting the resulting collection of groupings.
* - `comparatorNullsFirst`: Whether nulls should be sorted to the top.
* - `track`: Whether all elements in the group should exist in a collection in the `$group` property of each grouping.
* - `count`: Whether the number of elements in the group should be placed in the `$count` property of each grouping.
* @return {Rekord.Collection} -
* A collection of groupings.
*/
group: function(grouping)
{
var by = createPropertyResolver( grouping.by );
var having = createWhere( grouping.having, grouping.havingValue, grouping.havingEquals );
var select = grouping.select || {};
var map = {};
if ( isString( grouping.by ) )
{
if ( !(grouping.by in select) )
{
select[ grouping.by ] = 'first';
}
}
else if ( isArray( grouping.by ) )
{
for (var prop in grouping.by)
{
if ( !(prop in select) )
{
select[ prop ] = 'first';
}
}
}
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
var key = by( model );
var group = map[ key ];
if ( !group )
{
group = map[ key ] = this.cloneEmpty();
}
group.add( model, true );
}
var groupings = this.cloneEmpty();
groupings.setComparator( grouping.comparator, grouping.comparatorNullsFirst );
for (var key in map)
{
var grouped = {};
var groupArray = map[ key ];
for (var propName in select)
{
var aggregator = select[ propName ];
if ( isString( aggregator ) )
{
grouped[ propName ] = groupArray[ aggregator ]( propName );
}
else if ( isFunction( aggregator ) )
{
grouped[ propName ] = aggregator( groupArray, propName );
}
}
if ( grouping.track !== false )
{
grouped.$group = groupArray;
}
if ( grouping.count !== false )
{
grouped.$count = groupArray.length;
}
if ( having( grouped, groupArray ) )
{
groupings.push( grouped );
}
}
groupings.sort();
return groupings;
},
/**
* Returns a copy of this collection as a plain Array.
*
* @method
* @memberof Rekord.Collection#
* @return {Array} -
* The copy of this collection as a plain array.
*/
toArray: function()
{
return this.slice();
},
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
clone: function()
{
return this.constructor.create( this );
},
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
cloneEmpty: function()
{
return this.constructor.create();
}
});
addEventful( Collection );
/**
* Adds a listener for change events on this collection.
*
* @method change
* @memberof Rekord.Collection#
* @param {Function} callback -
* A function to call every time a change occurs in this collection.
* @param {Object} [context] -
* The desired context (this) for the given callback function.
* @return {Function} -
* A function to call to stop listening for change events.
* @see Rekord.Collection#event:changes
*/
addEventFunction( Collection, 'change', Collection.Events.Changes );
// The methods necessary for a filtered collection.
var Filtering = {
bind: function()
{
Class.props(this, {
onAdd: bind( this, Filtering.handleAdd ),
onAdds: bind( this, Filtering.handleAdds ),
onRemove: bind( this, Filtering.handleRemove ),
onRemoves: bind( this, Filtering.handleRemoves ),
onReset: bind( this, Filtering.handleReset ),
onUpdates: bind( this, Filtering.handleUpdates ),
onCleared: bind( this, Filtering.handleCleared )
});
},
init: function(base, filter)
{
if ( this.base !== base )
{
if ( this.base )
{
this.disconnect();
}
Class.prop( this, 'base', base );
this.connect();
}
Class.prop( this, 'filter', filter );
this.sync();
return this;
},
setFilter: function(whereProperties, whereValue, whereEquals)
{
this.filter = createWhere( whereProperties, whereValue, whereEquals );
this.sync();
return this;
},
connect: function()
{
this.base.on( Collection.Events.Add, this.onAdd );
this.base.on( Collection.Events.Adds, this.onAdds );
this.base.on( Collection.Events.Remove, this.onRemove );
this.base.on( Collection.Events.Removes, this.onRemoves );
this.base.on( Collection.Events.Reset, this.onReset );
this.base.on( Collection.Events.Updates, this.onUpdates );
this.base.on( Collection.Events.Cleared, this.onCleared );
return this;
},
disconnect: function()
{
this.base.off( Collection.Events.Add, this.onAdd );
this.base.off( Collection.Events.Adds, this.onAdds );
this.base.off( Collection.Events.Remove, this.onRemove );
this.base.off( Collection.Events.Removes, this.onRemoves );
this.base.off( Collection.Events.Reset, this.onReset );
this.base.off( Collection.Events.Updates, this.onUpdates );
this.base.off( Collection.Events.Cleared, this.onCleared );
return this;
},
sync: function()
{
var base = this.base;
var filter = this.filter;
var matches = [];
for (var i = 0; i < base.length; i++)
{
var value = base[ i ];
if ( filter( value ) )
{
matches.push( value );
}
}
return this.reset( matches );
},
handleAdd: function(collection, value)
{
var filter = this.filter;
if ( filter( value ) )
{
this.add( value );
}
},
handleAdds: function(collection, values)
{
var filter = this.filter;
var filtered = [];
for (var i = 0; i < values.length; i++)
{
var value = values[ i ];
if ( filter( value ) )
{
filtered.push( value );
}
}
this.addAll( filtered );
},
handleRemove: function(collection, value)
{
this.remove( value );
},
handleRemoves: function(collection, values)
{
this.removeAll( values );
},
handleReset: function(collection)
{
this.sync();
},
handleUpdates: function(collection, updates)
{
var filter = this.filter;
for (var i = 0; i < updates.length; i++)
{
var value = updates[ i ];
if ( filter( value ) )
{
this.add( value, true );
}
else
{
this.remove( value, true );
}
}
this.sort();
},
handleCleared: function(collection)
{
this.clear();
},
clone: function()
{
return this.constructor.create( this.base, this.filter );
},
cloneEmpty: function()
{
return this.constructor.create( this.base, this.filter );
}
};
/**
*
* @constructor
* @memberof Rekord
* @augments Rekord.Eventful
*/
function Page(collection, pageSize, pageIndex)
{
this.onChanges = bind( this, this.handleChanges );
this.pageSize = pageSize;
this.pageIndex = pageIndex || 0;
this.pageCount = 0;
this.setCollection( collection );
}
Page.Events =
{
Change: 'change',
Changes: 'change'
};
Class.extend( Array, Page,
{
setPageSize: function(pageSize)
{
this.pageSize = pageSize;
this.handleChanges();
},
setPageIndex: function(pageIndex)
{
this.goto( pageIndex );
},
setCollection: function(collection)
{
if ( collection !== this.collection )
{
if ( this.collection )
{
this.disconnect();
}
this.collection = collection;
this.connect();
this.handleChanges( true );
}
},
connect: function()
{
this.collection.on( Collection.Events.Changes, this.onChanges );
},
disconnect: function()
{
this.collection.off( Collection.Events.Changes, this.onChanges );
},
goto: function(pageIndex)
{
var actualIndex = this.page( pageIndex );
if ( actualIndex !== this.pageIndex )
{
this.pageIndex = actualIndex;
this.update();
this.trigger( Page.Events.Change, [ this ] );
}
},
next: function()
{
this.goto( this.pageIndex + 1 );
},
prev: function()
{
this.goto( this.pageIndex - 1 );
},
jump: function(to)
{
this.goto( to );
},
first: function()
{
this.goto( 0 );
},
last: function()
{
this.goto( this.pageCount - 1 );
},
total: function()
{
return this.collection.length;
},
pages: function()
{
return Math.ceil( this.total() / this.pageSize );
},
page: function(index)
{
return Math.max( 0, Math.min( index, this.pages() - 1 ) );
},
can: function(index)
{
return this.total() && index >= 0 && index < this.pageCount;
},
canFirst: function()
{
return this.canPrev();
},
canLast: function()
{
return this.canNext();
},
canPrev: function()
{
return this.total() && this.pageIndex > 0;
},
canNext: function()
{
return this.total() && this.pageIndex < this.pageCount - 1;
},
handleChanges: function(forceApply)
{
var pageCount = this.pages();
var pageIndex = this.page( this.pageIndex );
var apply = forceApply || this.pageIndex !== pageIndex || this.length !== this.pageSize;
var changes = apply || this.pageCount !== pageCount;
this.pageIndex = pageIndex;
this.pageCount = pageCount;
if ( apply )
{
this.update();
}
if ( changes )
{
this.trigger( Page.Events.Change, [ this ] );
}
},
update: function()
{
var source = this.collection;
var n = source.length;
var start = this.pageIndex * this.pageSize;
var end = Math.min( start + this.pageSize, n );
var length = end - start;
this.length = 0;
for (var i = 0; i < length; i++)
{
this.push( source[ start++ ] );
}
},
more: function(pages)
{
var source = this.collection;
var limit = source.length;
var pageCount = pages || 1;
var offset = this.pageIndex * this.pageSize;
var start = offset + this.length;
var adding = this.pageSize * pageCount;
var desiredEnd = start + adding;
var actualEnd = Math.min( limit, desiredEnd );
while (start < actualEnd)
{
this.push( source[ start++ ] );
}
},
toArray: function()
{
return this.slice();
}
});
addEventful( Page );
addEventFunction( Page, 'change', Page.Events.Changes );
/**
* An extension of the {@link Rekord.Collection} class which is a filtered view
* of another collection.
*
* ```javascript
* var isEven = function(x) { return x % 2 === 0; };
* var c = Rekord.collect([1, 2, 3, 4, 5, 6, 7]);
* var f = c.filtered( isEven );
* f; // [2, 4, 6]
* c.add( 8 );
* c.remove( 2 );
* f; // [4, 6, 8]
* ```
*
* @constructor
* @memberof Rekord
* @extends Rekord.Collection
* @param {Rekord.Collection} base -
* The collection to listen to for changes to update this collection.
* @param {whereCallback} filter -
* The function which determines whether an element in the base collection
* should exist in this collection.
* @see Rekord.Collection#filtered
*/
function FilteredCollection(base, filter)
{
this.bind();
this.init( base, filter );
}
/**
* The collection to listen to for changes to update this collection.
*
* @memberof Rekord.FilteredCollection#
* @member {Rekord.Collection} base
*/
/**
* The function which determines whether an element in the base collection
* should exist in this collection.
*
* @memberof Rekord.FilteredCollection#
* @member {whereCallback} filter
*/
Class.extend( Collection, FilteredCollection,
{
/**
* Generates the handlers which are passed to the base collection when this
* filtered collection is connected or disconnected - which happens on
* initialization and subsequent calls to {@link FilteredCollection#init}.
*
* @method
* @memberof Rekord.FilteredCollection#
*/
bind: Filtering.bind,
/**
* Initializes the filtered collection by setting the base collection and the
* filtering function.
*
* @method
* @memberof Rekord.FilteredCollection#
* @param {Rekord.Collection} base -
* The collection to listen to for changes to update this collection.
* @param {whereCallback} filter -
* The function which determines whether an element in the base collection
* should exist in this collection.
* @return {Rekord.FilteredCollection} -
* The reference to this collection.
* @emits Rekord.Collection#reset
*/
init: Filtering.init,
/**
* Sets the filter function of this collection and re-sychronizes it with the
* base collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @return {Rekord.FilteredCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @emits Rekord.Collection#reset
*/
setFilter: Filtering.setFilter,
/**
* Registers callbacks with events of the base collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @return {Rekord.FilteredCollection} -
* The reference to this collection.
*/
connect: Filtering.connect,
/**
* Unregisters callbacks with events from the base collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @return {Rekord.FilteredCollection} -
* The reference to this collection.
*/
disconnect: Filtering.disconnect,
/**
* Synchronizes this collection with the base collection. Synchronizing
* involves iterating over the base collection and passing each element into
* the filter function and if it returns a truthy value it's added to this
* collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @return {Rekord.FilteredCollection} -
* The reference to this collection.
* @emits Rekord.Collection#reset
*/
sync: Filtering.sync,
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @return {Rekord.FilteredCollection} -
* The reference to a clone collection.
*/
clone: Filtering.clone,
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.FilteredCollection#
* @return {Rekord.FilteredCollection} -
* The reference to a clone collection.
*/
cloneEmpty: Filtering.cloneEmpty
});
/**
* An extension of the {@link Rekord.Collection} class for {@link Rekord.Model}
* instances.
*
* @constructor
* @memberof Rekord
* @extends Rekord.Collection
* @param {Rekord.Database} database -
* The database for the models in this collection.
* @param {modelInput[]} [models] -
* The initial array of models in this collection.
* @param {Boolean} [remoteData=false] -
* If the models array is from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
* @see Rekord.Models.boot
* @see Rekord.Models.collect
*/
function ModelCollection(database, models, remoteData)
{
this.init( database, models, remoteData );
}
/**
* The map of models which keeps an index (by model key) of the models.
*
* @memberof Rekord.ModelCollection#
* @member {Rekord.Map} map
*/
/**
* The database for the models in this collection.
*
* @memberof Rekord.ModelCollection#
* @member {Rekord.Database} database
*/
Class.extend( Collection, ModelCollection,
{
/**
* Initializes the model collection by setting the database, the initial set
* of models, and whether the initial set of models is from a remote source.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Rekord.Database} database -
* The database for the models in this collection.
* @param {modelInput[]} [models] -
* The initial array of models in this collection.
* @param {Boolean} [remoteData=false] -
* If the models array is from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#reset
*/
init: function(database, models, remoteData)
{
Class.props(this, {
database: database,
map: new Map()
});
this.map.values = this;
this.reset( models, remoteData );
return this;
},
/**
* Documented in Collection.js
*/
sort: function(comparator, comparatorNullsFirst)
{
var cmp = comparator ? createComparator( comparator, comparatorNullsFirst ) : this.comparator;
if ( !isSorted( cmp, this ) )
{
this.map.sort( cmp );
this.trigger( Collection.Events.Sort, [this] );
}
return this;
},
/**
* Takes input provided to the collection for adding, removing, or querying
* and generates the key which uniquely identifies a model.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput} input -
* The input to convert to a key.
* @return {modelKey} -
* The key built from the input.
*/
buildKeyFromInput: function(input)
{
return this.database.keyHandler.buildKeyFromInput( input );
},
/**
* Takes input provided to this collection for adding, removing, or querying
* and returns a model instance. An existing model can be referenced or a new
* model can be created on the spot.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput} input -
* The input to convert to a model instance.
* @param {Boolean} [remoteData=false] -
* If the model is from a remote source. Remote sources place the model
* directly into the database while local sources aren't stored in the
* database until they're saved.
* @return {Rekord.Model} -
* A model instance parsed from the input.
*/
parseModel: function(input, remoteData)
{
return this.database.parseModel( input, remoteData );
},
/**
* Creates a sub view of this collection known as a filtered collection. The
* resulting collection changes when this collection changes. Any time an
* element is added or removed to this collection it may be added or removed
* from the filtered collection if it fits the filter function. The filter
* function is created by passing the arguments of this function to
* {@link Rekord.createWhere}.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @return {Rekord.FilteredModelCollection} -
* The newly created live filtered view of this collection.
* @see Rekord.createWhere
*/
filtered: function(whereProperties, whereValue, whereEquals)
{
var filter = createWhere( whereProperties, whereValue, whereEquals );
return FilteredModelCollection.create( this, filter );
},
/**
* Documented in Collection.js
*
* @see Rekord.ModelCollection#buildKeyFromInput
*/
subtract: function(models, out)
{
var target = out || this.cloneEmpty();
for (var i = 0; i < this.length; i++)
{
var a = this[ i ];
var key = a.$key();
var exists = false;
if ( models instanceof ModelCollection )
{
exists = models.has( key );
}
else
{
for (var k = 0; k < models.length && !exists; k++)
{
var modelKey = this.buildKeyFromInput( models[ k ] );
exists = (key === modelKey);
}
}
if (!exists)
{
target.push( a );
}
}
return target;
},
/**
* Documented in Collection.js
*/
intersect: function(models, out)
{
var target = out || this.cloneEmpty();
for (var i = 0; i < models.length; i++)
{
var a = models[ i ];
var key = this.buildKeyFromInput( a );
if ( this.has( key ) )
{
target.push( a );
}
}
return target;
},
/**
* Documented in Collection.js
*/
complement: function(models, out)
{
var target = out || this.cloneEmpty();
for (var i = 0; i < models.length; i++)
{
var a = models[ i ];
var key = this.buildKeyFromInput( a );
if ( !this.has( key ) )
{
target.push( a );
}
}
return target;
},
/**
* Documented in Collection.js
*/
clear: function()
{
var cleared = this.map.reset();
this.trigger( Collection.Events.Cleared, [this] );
return cleared;
},
/**
* Resets the models in this collection with a new collection of models.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput[]} [models] -
* The initial array of models in this collection.
* @param {Boolean} [remoteData=false] -
* If the models array is from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.ModelCollection#parseModel
* @emits Rekord.ModelCollection#reset
*/
reset: function(models, remoteData)
{
var map = this.map;
map.reset();
if ( isArray( models ) )
{
for (var i = 0; i < models.length; i++)
{
var model = models[ i ];
var parsed = this.parseModel( model, remoteData );
if ( parsed )
{
map.put( parsed.$key(), parsed );
}
}
}
else if ( isObject( models ) )
{
var parsed = this.parseModel( models, remoteData );
if ( parsed )
{
map.put( parsed.$key(), parsed );
}
}
this.trigger( Collection.Events.Reset, [this] );
this.sort();
return this;
},
/**
* Returns whether this collection contains a model with the given key.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelKey} key -
* The key of the model to check for existence.
* @return {Boolean} -
* True if a model with the given key exists in this collection, otherwise
* false.
*/
has: function(key)
{
return this.map.has( key );
},
/**
* Returns the model in this collection with the given key.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelKey} key -
* The key of the model to return.
* @return {Rekord.Model} -
* The model instance for the given key, or undefined if a model wasn't
* found.
*/
get: function(key)
{
return this.map.get( key );
},
/**
* Places a model in this collection providing a key to use.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelKey} key -
* The key of the model.
* @param {Rekord.Model} model -
* The model instance to place in the collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#add
* @emits Rekord.ModelCollection#sort
*/
put: function(key, model, delaySort)
{
this.map.put( key, model );
this.trigger( Collection.Events.Add, [this, model, this.map.indices[ key ]] );
if ( !delaySort )
{
this.sort();
}
},
/**
* Adds a model to this collection - sorting the collection if a comparator
* is set on this collection and `delaySort` is not a specified or a true
* value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput} input -
* The model to add to this collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @param {Boolean} [remoteData=false] -
* If the model is from a remote source. Remote sources place the model
* directly into the database while local sources aren't stored in the
* database until they're saved.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#add
* @emits Rekord.ModelCollection#sort
*/
add: function(input, delaySort, remoteData)
{
var model = this.parseModel( input, remoteData );
var key = model.$key();
this.map.put( key, model );
this.trigger( Collection.Events.Add, [this, model, this.map.indices[ key ]] );
if ( !delaySort )
{
this.sort();
}
return this;
},
/**
* Adds one or more models to the end of this collection - sorting the
* collection if a comparator is set on this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {...modelInput} value -
* The models to add to this collection.
* @return {Number} -
* The new length of this collection.
* @emits Rekord.ModelCollection#add
* @emits Rekord.ModelCollection#sort
*/
push: function()
{
var values = AP.slice.apply( arguments );
var indices = [];
for (var i = 0; i < values.length; i++)
{
var model = this.parseModel( values[ i ] );
var key = model.$key();
this.map.put( key, model );
indices.push( this.map.indices[ key ] );
}
this.trigger( Collection.Events.Adds, [this, values, indices] );
this.sort();
return this.length;
},
/**
* @method
* @memberof Rekord.ModelCollection#
* @see Rekord.ModelCollection#push
* @param {...modelInput} value -
* The values to add to this collection.
* @return {Number} -
* The new length of this collection.
* @emits Rekord.ModelCollection#adds
* @emits Rekord.ModelCollection#sort
*/
unshift: function()
{
return this.push.apply( this, arguments );
},
/**
* Adds all models in the given array to this collection - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* not specified or a true value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput[]} models -
* The models to add to this collection.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @param {Boolean} [remoteData=false] -
* If the model is from a remote source. Remote sources place the model
* directly into the database while local sources aren't stored in the
* database until they're saved.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#adds
* @emits Rekord.ModelCollection#sort
*/
addAll: function(models, delaySort, remoteData)
{
if ( isArray( models ) )
{
var indices = [];
for (var i = 0; i < models.length; i++)
{
var model = this.parseModel( models[ i ], remoteData );
var key = model.$key();
this.map.put( key, model );
indices.push( this.map.indices[ key ] );
}
this.trigger( Collection.Events.Adds, [this, models, indices] );
if ( !delaySort )
{
this.sort();
}
}
},
/**
* @method
* @memberof Rekord.ModelCollection#
* @see Rekord.ModelCollection#add
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#add
* @emits Rekord.ModelCollection#sort
*/
insertAt: function(i, value, delaySort)
{
return this.add( value, delaySort );
},
/**
* Removes the last model in this collection and returns it - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* no specified or a true value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @return {Rekord.Model} -
* The model removed from the end of the collection.
* @emits Rekord.ModelCollection#remove
* @emits Rekord.ModelCollection#sort
*/
pop: function(delaySort)
{
var i = this.length - 1;
var removed = this[ i ];
this.map.removeAt( i );
this.trigger( Collection.Events.Remove, [this, removed, i] );
if ( !delaySort )
{
this.sort();
}
return removed;
},
/**
* Removes the first model in this collection and returns it - sorting the
* collection if a comparator is set on this collection and `delaySort` is
* no specified or a true value.
*
* ```javascript
* var c = Rekord.collect(1, 2, 3, 4);
* c.shift(); // 1
* ```
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @return {Rekord.Model} -
* The model removed from the beginning of the collection.
* @emits Rekord.ModelCollection#remove
* @emits Rekord.ModelCollection#sort
*/
shift: function(delaySort)
{
var removed = this[ 0 ];
this.map.removeAt( 0 );
this.trigger( Collection.Events.Remove, [this, removed, 0] );
if ( !delaySort )
{
this.sort();
}
return removed;
},
/**
* Removes the model in this collection at the given index `i` - sorting
* the collection if a comparator is set on this collection and `delaySort` is
* not specified or a true value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Number} i -
* The index of the model to remove.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @return {Rekord.Model} -
* The model removed, or undefined if the index was invalid.
* @emits Rekord.ModelCollection#remove
* @emits Rekord.ModelCollection#sort
*/
removeAt: function(i, delaySort)
{
var removing;
if (i >= 0 && i < this.length)
{
removing = this[ i ];
this.map.removeAt( i );
this.trigger( Collection.Events.Remove, [this, removing, i] );
if ( !delaySort )
{
this.sort();
}
}
return removing;
},
/**
* Removes the given model from this collection if it exists - sorting the
* collection if a comparator is set on this collection and `delaySort` is not
* specified or a true value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput} input -
* The model to remove from this collection if it exists.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* The function which determines whether one of the elements that exist in
* this collection are equivalent to the given value.
* @return {Rekord.Model} -
* The element removed from this collection.
* @emits Rekord.ModelCollection#remove
* @emits Rekord.ModelCollection#sort
*/
remove: function(input, delaySort)
{
var key = this.buildKeyFromInput( input );
var removing = this.map.get( key );
if ( removing )
{
var i = this.map.indices[ key ];
this.map.remove( key );
this.trigger( Collection.Events.Remove, [this, removing, i] );
if ( !delaySort )
{
this.sort();
}
}
return removing;
},
/**
* Removes the given models from this collection - sorting the collection if
* a comparator is set on this collection and `delaySort` is not specified or
* a true value.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput[]} inputs -
* The models to remove from this collection if they exist.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.ModelCollection#sort sort}.
* @return {Rekord.Model[]} -
* The models removed from this collection.
* @emits Rekord.ModelCollection#removes
* @emits Rekord.ModelCollection#sort
*/
removeAll: function(inputs, delaySort)
{
var map = this.map;
var removed = [];
var removedIndices = [];
for (var i = 0; i < inputs.length; i++)
{
var key = this.buildKeyFromInput( inputs[ i ] );
var removing = map.get( key );
if ( removing )
{
removedIndices.push( map.indices[ key ] );
removed.push( removing );
}
}
removedIndices.sort();
for (var i = removedIndices.length - 1; i >= 0; i--)
{
map.removeAt( removedIndices[ i ] );
}
this.trigger( Collection.Events.Removes, [this, removed, removedIndices] );
if ( !delaySort )
{
this.sort();
}
return removed;
},
/**
* Returns the index of the given model in this collection or returns -1
* if the model doesn't exist in this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {modelInput} input -
* The model to search for.
* @return {Number} -
* The index of the model in this collection or -1 if it was not found.
*/
indexOf: function(input)
{
var key = this.buildKeyFromInput( input );
var index = this.map.indices[ key ];
return index === undefined ? -1 : index;
},
/**
* Rebuilds the internal index which maps keys to the index of the model in
* this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @return {Rekord.ModelCollection} -
* The reference to this collection.
*/
rebuild: function()
{
this.map.rebuildIndex();
},
/**
* Returns the array of keys that correspond to the models in this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @return {modelKey[]} -
* The array of model keys.
*/
keys: function()
{
return this.map.keys;
},
/**
* Reverses the order of models in this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#updates
*/
reverse: function()
{
this.map.reverse();
this.trigger( Collection.Events.Updates, [this] );
return this;
},
/**
* Splices elements out of and into this collection - sorting the collection
* if a comparator is set on this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Number} start -
* Index at which to start changing the array (with origin 0). If greater
* than the length of the array, actual starting index will be set to the
* length of the array. If negative, will begin that many elements from the end.
* @param {Number} deleteCount -
* An integer indicating the number of old array elements to remove. If
* deleteCount is 0, no elements are removed. In this case, you should
* specify at least one new element. If deleteCount is greater than the
* number of elements left in the array starting at start, then all of the
* elements through the end of the array will be deleted.
* If deleteCount is omitted, deleteCount will be equal to (arr.length - start).
* @param {...Any} values -
* The elements to add to the array, beginning at the start index. If you
* don't specify any elements, splice() will only remove elements from the array.
* @return {Any[]} -
* The array of deleted elements.
* @emits Rekord.ModelCollection#removes
* @emits Rekord.ModelCollection#adds
* @emits Rekord.ModelCollection#sort
*/
splice: function(start, deleteCount)
{
var adding = AP.slice.call( arguments, 2 );
var addingKeys = [start, deleteCount];
for (var i = 0; i < adding.length; i++)
{
addingKeys.push( this.buildKeyFromInput( adding[ i ] ) );
}
var removed = AP.splice.apply( this, arguments );
AP.splice.apply( this.map.keys, addingKeys );
if ( deleteCount )
{
this.trigger( Collection.Events.Removes, [this, removed, start, deleteCount] );
}
if ( adding.length )
{
this.trigger( Collection.Events.Adds, [this, adding, start] );
}
this.sort();
return removed;
},
/**
* Removes the models from this collection where the given expression is true.
* The first argument, if `true`, can call {@link Rekord.Model#$remove} on each
* model removed from this colleciton.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [callRemove=false] -
* Whether {@link Rekord.Model#$remove} should be called on each removed model.
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @param {Array} [out=this.cloneEmpty()] -
* The array to place the elements that match.
* @param {Boolean} [delaySort=false] -
* Whether automatic sorting should be delayed until the user manually
* calls {@link Rekord.Collection#sort sort}.
* @return {Rekord.Model[]} -
* An array of models removed from this collection.
* @emits Rekord.ModelCollection#removes
* @emits Rekord.ModelCollection#sort
*/
removeWhere: function(callRemove, whereProperties, whereValue, whereEquals, out, delaySort, cascade, options)
{
var where = createWhere( whereProperties, whereValue, whereEquals );
var removed = out || this.cloneEmpty();
var removedIndices = [];
batchExecute(function()
{
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
removedIndices.push( i );
removed.push( model );
}
}
for (var i = 0; i < removed.length; i++)
{
var model = removed[ i ];
var key = model.$key();
this.map.remove( key );
if ( callRemove )
{
model.$remove( cascade, options );
}
}
}, this );
this.trigger( Collection.Events.Removes, [this, removed, removedIndices] );
if ( !delaySort )
{
this.sort();
}
return removed;
},
/**
* Updates the given property(s) in all models in this collection with the
* given value. If `avoidSave` is not a truthy value then
* {@link Rekord.Model#$save} is called on every model in this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {String|Object} props -
* The property or properties to update.
* @param {Any} [value] -
* The value to set if a String `props` is given.
* @param {Boolean} [remoteData=false] -
* If the properties are from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
* @param {Boolean} [avoidSave=false] -
* True for NOT calling {@link Rekord.Model#$save}, otherwise false.
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @emits Rekord.ModelCollection#updates
* @emits Rekord.ModelCollection#sort
*/
update: function(props, value, remoteData, avoidSave, cascade, options)
{
batchExecute(function()
{
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
model.$set( props, value, remoteData );
if ( !avoidSave )
{
model.$save( cascade, options );
}
}
}, this );
this.trigger( Collection.Events.Updates, [this, this] );
this.sort();
return this;
},
/**
* Updates the given property(s) in models in this collection which pass the
* `where` function with the given value. If `avoidSave` is not a truthy value
* then {@link Rekord.Model#$save} is called on every model in this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereCallback} where -
* The function which determines whether a model should be updated.
* @param {String|Object} props -
* The property or properties to update.
* @param {*} [value] -
* The value to set if a String `props` is given.
* @param {Boolean} [remoteData=false] -
* If the properties are from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
* @param {Boolean} [avoidSave=false] -
* True for NOT calling {@link Rekord.Model#$save}, otherwise false.
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.Model[]} -
* An array of models updated.
* @emits Rekord.ModelCollection#updates
* @emits Rekord.ModelCollection#sort
*/
updateWhere: function(where, props, value, remoteData, avoidSave, cascade, options)
{
var updated = [];
batchExecute(function()
{
for (var i = 0; i < this.length; i++)
{
var model = this[ i ];
if ( where( model ) )
{
model.$set( props, value, remoteData );
if ( !avoidSave )
{
model.$save( cascade, options );
}
updated.push( model );
}
}
}, this );
this.trigger( Collection.Events.Updates, [this, updated] );
this.sort();
return updated;
},
/**
* Calls {@link Rekord.Model#$push} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {String[]} [fields] -
* The set of fields to save for later popping or discarding. If not
* specified, all model fields will be saved.
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$push
*/
pushWhere: function(fields, properties, value, equals)
{
function pushIt(model)
{
model.$push( fields );
}
return this.eachWhere( pushIt, properties, value, equals );
},
/**
* Calls {@link Rekord.Model#$pop} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [dontDiscard=false] -
* Whether to remove the saved state after the saved state has been applied
* back to the model. A falsy value will result in
* {@link Rekord.Model#$discard} being called.
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$pop
*/
popWhere: function(dontDiscard, properties, value, equals)
{
function popIt(model)
{
model.$pop( dontDiscard );
}
return this.eachWhere( popIt, properties, value, equals );
},
/**
* Calls {@link Rekord.Model#$discard} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$discard
*/
discardWhere: function(properties, value, equals)
{
function discardIt(model)
{
model.$discard();
}
return this.eachWhere( discardIt, properties, value, equals );
},
/**
* Calls {@link Rekord.Model#$cancel} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [reset=false] -
* If reset is true and the model doesn't have a saved state -
* {@link Rekord.Model#$reset} will be called.
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$cancel
*/
cancelWhere: function(reset, properties, value, equals)
{
function cancelIt(model)
{
model.$cancel( reset );
}
batchExecute(function()
{
this.eachWhere( cancelIt, properties, value, equals );
}, this );
return this;
},
/**
* Calls {@link Rekord.Model#$refresh} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$refresh
*/
refreshWhere: function(properties, value, equals, cascade, options)
{
function refreshIt(model)
{
model.$refresh( cascade, options );
}
batchExecute(function()
{
this.eachWhere( refreshIt, properties, value, equals );
}, this );
return this;
},
/**
* Calls {@link Rekord.Model#$save} on models in this collection that meet
* the given where expression.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @param {Object} [props={}] -
* Properties to apply to each model in the collection that pass the where
* expression.
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.ModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$refresh
*/
saveWhere: function(properties, value, equals, props, cascade, options)
{
function saveIt(model)
{
model.$save( props, cascade, options );
}
batchExecute(function()
{
this.eachWhere( saveIt, properties, value, equals );
}, this );
return this;
},
/**
* Returns whether this collection has at least one model with changes. An
* additional where expression can be given to only check certain models.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @return {Boolean} -
* True if at least one model has changes, otherwise false.
* @see Rekord.createWhere
* @see Rekord.Model#$hasChanges
*/
hasChanges: function(properties, value, equals)
{
var where = createWhere( properties, value, equals );
var hasChanges = function( model )
{
return where( model ) && model.$hasChanges();
};
return this.contains( hasChanges );
},
/**
* Returns a collection of all changes for each model. The changes are keyed
* into the collection by the models key. An additional where expression can
* be given to only check certain models.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals=Rekord.equalsStrict] -
* See {@link Rekord.createWhere}
* @param {Rekord.ModelCollection} [out] -
* The collection to add the changes to.
* @return {Rekord.ModelCollection} -
* The collection with all changes to models in this collection.
* @see Rekord.createWhere
* @see Rekord.Model#$hasChanges
* @see Rekord.Model#$getChanges
*/
getChanges: function(properties, value, equals, out)
{
var where = createWhere( properties, value, equals );
var changes = out && out instanceof ModelCollection ? out : this.cloneEmpty();
this.each(function(model)
{
if ( where( model ) && model.$hasChanges() )
{
changes.put( model.$key(), model.$getChanges() );
}
});
return changes;
},
// TODO
project: function(projectionInput, out)
{
var target = out || [];
var projection = Projection.parse( this.database, projectionInput );
for (var i = 0; i < this.length; i++)
{
target.push( projection.project( this[ i ] ) );
}
return target;
},
/**
* Converts this collection into an object where the keys of the models are
* the object properties and the models are the values.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Object} [out] -
* The object to place the models in.
* @return {Object} -
* The object containing the models in this collection.
*/
toObject: function(out)
{
return this.map.toObject( out );
},
/**
* Returns a clone of this collection. Optionally the models in this
* collection can also be cloned.
*
* @method
* @memberof Rekord.ModelCollection#
* @param {Boolean} [cloneModels=false] -
* Whether or not the models should be cloned as well.
* @param {Boolean} [cloneProperties] -
* The properties object which defines what fields should be given a
* different (non-cloned) value and which relations need to be cloned.
* @return {Rekord.ModelCollection} -
* The reference to a clone collection.
* @see Rekord.Model#$clone
*/
clone: function(cloneModels, cloneProperties)
{
var source = this;
if ( cloneModels )
{
source = [];
for (var i = 0; i < this.length; i++)
{
source[ i ] = this[ i ].$clone( cloneProperties );
}
}
return ModelCollection.create( this.database, source, true );
},
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.ModelCollection#
* @return {Rekord.ModelCollection} -
* The reference to a clone collection.
*/
cloneEmpty: function()
{
return ModelCollection.create( this.database );
}
});
/**
* An extension of the {@link Rekord.ModelCollection} class which is a filtered
* view of another model collection. Changes made to the base collection are
* reflected in the filtered collection - possibly resulting in additions and
* removals from the filtered collection.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var finished = Task.filtered('done', true);
* finished; // will always contain tasks that are done
* ```
*
* @constructor
* @memberof Rekord
* @extends Rekord.ModelCollection
* @param {Rekord.ModelCollection} base -
* The model collection to listen to for changes to update this collection.
* @param {whereCallback} filter -
* The function which determines whether a model in the base collection
* should exist in this collection.
* @see Rekord.Collection#filtered
*/
function FilteredModelCollection(base, filter)
{
this.bind();
this.init( base, filter );
}
/**
* The collection to listen to for changes to update this collection.
*
* @memberof Rekord.FilteredModelCollection#
* @member {Rekord.ModelCollection} base
*/
/**
* The function which determines whether an element in the base collection
* should exist in this collection.
*
* @memberof Rekord.FilteredModelCollection#
* @member {whereCallback} filter
*/
Class.extend( ModelCollection, FilteredModelCollection,
{
/**
* Generates the handlers which are passed to the base collection when this
* filtered collection is connected or disconnected - which happens on
* initialization and subsequent calls to {@link FilteredModelCollection#init}.
*
* @method
* @memberof Rekord.FilteredModelCollection#
*/
bind: function()
{
Filtering.bind.apply( this );
Class.props(this, {
onModelUpdated: bind( this, this.handleModelUpdate )
});
},
/**
* Initializes the filtered collection by setting the base collection and the
* filtering function.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @param {Rekord.ModelCollection} base -
* The model collection to listen to for changes to update this collection.
* @param {whereCallback} filter -
* The function which determines whether a model in the base collection
* should exist in this collection.
* @return {Rekord.FilteredModelCollection} -
* The reference to this collection.
* @emits Rekord.Collection#reset
*/
init: function(base, filter)
{
if ( this.base )
{
this.base.database.off( Database.Events.ModelUpdated, this.onModelUpdated );
}
ModelCollection.prototype.init.call( this, base.database );
Filtering.init.call( this, base, filter );
base.database.on( Database.Events.ModelUpdated, this.onModelUpdated );
return this;
},
/**
* Sets the filter function of this collection and re-sychronizes it with the
* base collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @param {whereInput} [whereProperties] -
* See {@link Rekord.createWhere}
* @param {Any} [whereValue] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [whereEquals] -
* See {@link Rekord.createWhere}
* @return {Rekord.FilteredModelCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @emits Rekord.Collection#reset
*/
setFilter: Filtering.setFilter,
/**
* Registers callbacks with events of the base collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @return {Rekord.FilteredModelCollection} -
* The reference to this collection.
*/
connect: Filtering.connect,
/**
* Unregisters callbacks with events from the base collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @return {Rekord.FilteredModelCollection} -
* The reference to this collection.
*/
disconnect: Filtering.disconnect,
/**
* Synchronizes this collection with the base collection. Synchronizing
* involves iterating over the base collection and passing each element into
* the filter function and if it returns a truthy value it's added to this
* collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @return {Rekord.FilteredModelCollection} -
* The reference to this collection.
* @emits Rekord.Collection#reset
*/
sync: Filtering.sync,
/**
* Handles the ModelUpdated event from the database.
*/
handleModelUpdate: function(model)
{
var exists = this.has( model.$key() );
var matches = this.filter( model );
if ( exists && !matches )
{
this.remove( model );
}
if ( !exists && matches )
{
this.add( model );
}
},
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @return {Rekord.FilteredModelCollection} -
* The reference to a clone collection.
*/
clone: Filtering.clone,
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.FilteredModelCollection#
* @return {Rekord.FilteredModelCollection} -
* The reference to a clone collection.
*/
cloneEmpty: Filtering.cloneEmpty
});
/**
* An extension of the {@link Rekord.ModelCollection} class for relationships.
*
* @constructor
* @memberof Rekord
* @extends Rekord.ModelCollection
* @param {Rekord.Database} database -
* The database for the models in this collection.
* @param {Rekord.Model} model -
* The model instance all models in this collection are related to.
* @param {Rekord.Relation} relator -
* The relation instance responsible for relating/unrelating models.
* @param {modelInput[]} [models] -
* The initial array of models in this collection.
* @param {Boolean} [remoteData=false] -
* If the models array is from a remote source. Remote sources place the
* model directly into the database while local sources aren't stored in the
* database until they're saved.
*/
function RelationCollection(database, model, relator, models, remoteData)
{
Class.props(this, {
model: model,
relator: relator
});
this.init( database, models, remoteData );
}
/**
* The model instance all models in this collection are related to.
*
* @memberof Rekord.RelationCollection#
* @member {Rekord.Model} model
*/
/**
* The relation instance responsible for relating/unrelating models.
*
* @memberof Rekord.RelationCollection#
* @member {Rekord.Relation} relator
*/
Class.extend( ModelCollection, RelationCollection,
{
/**
* Sets the entire set of models which are related. If a model is specified
* that doesn't exist in this collection a relationship is added. If a model
* in this collection is not specified in the `input` the relationship is
* removed. Depending on the relationship, adding and removing relationships
* may result in the saving or deleting of models.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {modelInput|modelInput[]} [input] -
* The model or array of models to relate. If input isn't specified, all
* models currently related are unrelated.
* @param {boolean} [remoteData=false] -
* Whether this change is due to remote changes or changes that should not
* trigger removes or saves.
* @return {Rekord.RelationCollection} -
* The reference to this collection.
*/
set: function(input, remoteData)
{
this.relator.set( this.model, input, remoteData );
return this;
},
/**
* Relates one or more models to this collection's model. If a model is
* specified that is already related then it has no effect.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {modelInput|modelInput[]} input -
* The model or array of models to relate.
* @param {boolean} [remoteData=false] -
* Whether this change is due to remote changes or changes that should not
* trigger removes or saves.
* @return {Rekord.RelationCollection} -
* The reference to this collection.
*/
relate: function(input, remoteData)
{
this.relator.relate( this.model, input, remoteData );
return this;
},
/**
* Unrelates one or more models from this collection's model. If a model is
* specified that is not related then it has no effect. If no models are
* specified then all models in this collection are unrelated.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {modelInput|modelInput[]} input -
* The model or array of models to relate.
* @param {boolean} [remoteData=false] -
* Whether this change is due to remote changes or changes that should not
* trigger removes or saves.
* @return {Rekord.RelationCollection} -
* The reference to this collection.
*/
unrelate: function(input, remoteData)
{
this.relator.unrelate( this.model, input, remoteData );
return this;
},
/**
* Syncrhonizes the related models in this collection by re-evaluating all
* models for a relationship.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {boolean} [removeUnrelated=false] -
* Whether to remove models that are no longer related. The $remove
* function is not called on these models.
* @return {Rekord.RelationCollection} -
* The reference to this collection.
*/
sync: function(removeUnrelated)
{
this.relator.sync( this.model, removeUnrelated );
return this;
},
/**
* Unrelates any models in this collection which meet the where expression.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {whereInput} [properties] -
* See {@link Rekord.createWhere}
* @param {Any} [value] -
* See {@link Rekord.createWhere}
* @param {equalityCallback} [equals] -
* See {@link Rekord.createWhere}
* @return {Rekord.RelationCollection} -
* The reference to this collection.
* @see Rekord.createWhere
* @see Rekord.RelationCollection.unrelate
* @see Rekord.RelationCollection.where
*/
unrelateWhere: function(properties, value, equals)
{
return this.unrelate( this.where( properties, value, equals, [] ) );
},
/**
* Determines whether one or more models all exist in this collection.
*
* @method
* @memberof Rekord.RelationCollection#
* @param {modelInput|modelInput[]} input -
* The model or array of models to check for existence.
* @return {Boolean} -
* True if all models are related - otherwise false.
*/
isRelated: function(input)
{
return this.relator.isRelated( this.model, input );
},
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.RelationCollection#
* @return {Rekord.RelationCollection} -
* The reference to a clone collection.
*/
clone: function()
{
return RelationCollection.create( this.database, this.model, this.relator, this, true );
},
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.RelationCollection#
* @return {Rekord.RelationCollection} -
* The reference to a clone collection.
*/
cloneEmpty: function()
{
return RelationCollection.create( this.database, this.model, this.relator );
}
});
/**
* Overrides functions in the given model collection to turn it into a collection
* which contains models with a discriminator field.
*
* @param {Rekord.ModelCollection} collection -
* The collection instance with discriminated models.
* @param {String} discriminator -
* The name of the field which contains the discriminator.
* @param {Object} discriminatorsToModel -
* A map of discriminators to the Rekord instances.
* @return {Rekord.ModelCollection} -
* The reference to the given collection.
*/
function DiscriminateCollection(collection, discriminator, discriminatorsToModel)
{
Class.props( collection,
{
discriminator: discriminator,
discriminatorsToModel: discriminatorsToModel
});
// Original Functions
var buildKeyFromInput = collection.buildKeyFromInput;
var parseModel = collection.parseModel;
var clone = collection.clone;
var cloneEmpty = collection.cloneEmpty;
Class.props( collection,
{
/**
* Builds a key from input. Discriminated collections only accept objects as
* input - otherwise there's no way to determine the discriminator. If the
* discriminator on the input doesn't map to a Rekord instance OR the input
* is not an object the input will be returned instead of a model instance.
*
* @param {modelInput} input -
* The input to create a key for.
* @return {Any} -
* The built key or the given input if a key could not be built.
*/
buildKeyFromInput: function(input)
{
if ( isObject( input ) )
{
var discriminatedValue = input[ this.discriminator ];
var model = this.discriminatorsToModel[ discriminatedValue ];
if ( model )
{
return model.Database.keyHandler.buildKeyFromInput( input );
}
}
return input;
},
/**
* Takes input and returns a model instance. The input is expected to be an
* object, any other type will return null.
*
* @param {modelInput} input -
* The input to parse to a model instance.
* @param {Boolean} [remoteData=false] -
* Whether or not the input is coming from a remote source.
* @return {Rekord.Model} -
* The model instance parsed or null if none was found.
*/
parseModel: function(input, remoteData)
{
if ( input instanceof Model )
{
return input;
}
var discriminatedValue = isValue( input ) ? input[ this.discriminator ] : null;
var model = this.discriminatorsToModel[ discriminatedValue ];
return model ? model.Database.parseModel( input, remoteData ) : null;
},
/**
* Returns a clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
clone: function()
{
return DiscriminateCollection( clone.apply( this ), discriminator, discriminatorsToModel );
},
/**
* Returns an empty clone of this collection.
*
* @method
* @memberof Rekord.Collection#
* @return {Rekord.Collection} -
* The reference to a clone collection.
*/
cloneEmpty: function()
{
return DiscriminateCollection( cloneEmpty.apply( this ), discriminator, discriminatorsToModel );
}
});
return collection;
}
/**
* Options you can pass to {@link Rekord.Search} or {@link Rekord.Model.search}.
*
* @typedef {Object} searchOptions
* @property {Function} [$encode] -
* A function which converts the search into an object to pass to the
* specified methods.
* @property {Function} [$decode] -
* A function which takes the data returned from the server and returns
* The array of models which are to be placed in the
* {@link Rekord.Search#$results} property.
*/
/**
*
* @constructor
* @memberof Rekord
*/
function Search(database, url, options, props, run)
{
this.$init( database, url, options, props, run );
}
Search.Defaults =
{
};
Class.create( Search,
{
$getDefaults: function()
{
return Search.Defaults;
},
$init: function(database, url, options, props, run)
{
applyOptions( this, options, this.$getDefaults(), true );
Class.prop( this, '$db', database );
this.$append = false;
this.$url = url;
this.$set( props );
this.$results = ModelCollection.create( database );
this.$results.$search = this;
this.$promise = Promise.resolve( this );
if ( run )
{
this.$run();
}
},
$set: function(props)
{
if ( isObject( props ) )
{
transfer( props, this );
}
return this;
},
$unset: function()
{
for (var prop in this)
{
if ( prop.charAt(0) !== '$' )
{
delete this[ prop ];
}
}
return this;
},
$run: function(url, props)
{
this.$url = url || this.$url;
this.$set( props );
var promise = new Promise();
var encoded = this.$encode();
var success = bind( this, this.$handleSuccess( promise ) );
var failure = bind( this, this.$handleFailure( promise ) );
var options = this.$options || this.$db.queryOptions;
batchExecute(function()
{
this.$cancel();
this.$promise = promise;
this.$db.rest.query( this.$url, encoded, options, success, failure );
}, this );
return this.$promise;
},
$handleSuccess: function(promise)
{
return function(response)
{
if ( !this.$promise.isPending() || promise !== this.$promise )
{
return;
}
var models = this.$decode.apply( this, arguments );
if ( this.$append )
{
this.$results.addAll( models, false, true );
}
else
{
this.$results.reset( models, true );
}
this.$promise.resolve( this, response, this.$results );
};
},
$handleFailure: function(promise)
{
return function(response, status)
{
if ( !this.$promise.isPending() || promise !== this.$promise )
{
return;
}
var offline = RestStatus.Offline[ status ];
if ( offline )
{
Rekord.checkNetworkStatus();
offline = !Rekord.online;
}
if ( offline )
{
this.$promise.noline( this, response, status );
}
else
{
this.$promise.reject( this, response, status );
}
};
},
$cancel: function()
{
this.$promise.cancel();
},
$clear: function()
{
this.$results.clear();
},
$encode: function()
{
return cleanFunctions( copy( this ) );
},
$decode: function(models)
{
return models;
},
$key: function()
{
return '';
},
$change: function(callback, context)
{
return this.$results.change( callback, context );
}
});
/**
* Options you can pass to {@link Rekord.SearchPaged} or
* {@link Rekord.Model.searchPaged}.
*
* @typedef {Object} searchPageOptions
* @property {Number} [page_size=10] -
* The size of the pages.
* @property {Number} [page_index=0] -
* The index of the search page.
* @property {Number} [total=0] -
* The total number of models that exist in the search without pagination
* - this is expected to be provided by the remote search response.
* @property {Function} [$encode] -
* A function which converts the search into an object to pass to the
* specified methods.
* @property {Function} [$decode] -
* A function which takes the data returned from the server and updates
* this search with the results and paging information.
* @property {Function} [$decodeResults] -
* A function which takes the data returned from the server and returns the
* array of models which are to be placed in the
* {@link Rekord.Search#$results} property.
* @property {Function} [$updatePageSize] -
* A function which takes the data returned from the server and sets an
* updated page size of the search.
* @property {Function} [$updatePageIndex] -
* A function which takes the data returned from the server and sets an
* updated page index of the search.
* @property {Function} [$updateTotal] -
* A function which takes the data returned from the server and sets an
* updated total of the search.
*/
function SearchPaged(database, url, options, props, run)
{
this.$init( database, url, options, props, run );
}
SearchPaged.Defaults =
{
page_size: 10,
page_index: 0,
total: 0
};
Class.extend( Search, SearchPaged,
{
$getDefaults: function()
{
return SearchPaged.Defaults;
},
$goto: function(index, dontRun)
{
var pageIndex = this.$getPageIndex();
var pageCount = this.$getPageCount();
var desired = Math.max( 0, Math.min( index, pageCount - 1 ) );
if ( pageIndex !== desired )
{
this.$setPageIndex( desired );
if ( !dontRun )
{
this.$append = false;
this.$run();
}
}
return this.$promise;
},
$more: function()
{
var next = this.$getPageIndex() + 1;
if ( next < this.$getPageCount() )
{
this.$setPageIndex( next );
this.$append = true;
this.$run();
this.$promise.complete( this.$onMoreEnd, this );
}
return this.$promise;
},
$onMoreEnd: function()
{
this.$append = false;
},
$first: function(dontRun)
{
return this.$goto( 0, dontRun );
},
$last: function(dontRun)
{
return this.$goto( this.$getPageCount() - 1, dontRun );
},
$prev: function(dontRun)
{
return this.$goto( this.$getPageIndex() - 1, dontRun );
},
$next: function(dontRun)
{
return this.$goto( this.$getPageIndex() + 1, dontRun );
},
$total: function()
{
return this.$getTotal();
},
$pages: function()
{
return this.$getPageCount();
},
$page: function(index)
{
return Math.max( 0, Math.min( index, this.$pages() - 1 ) );
},
$can: function(index)
{
return this.$getTotal() && index >= 0 && index < this.$getPageCount();
},
$canFirst: function()
{
return this.$canPrev();
},
$canLast: function()
{
return this.$canNext();
},
$canPrev: function()
{
return this.$getTotal() && this.$getPageIndex() > 0;
},
$canNext: function()
{
return this.$getTotal() && this.$getPageIndex() < this.$getPageCount() - 1;
},
$decode: function(response)
{
this.$updatePageSize( response );
this.$updatePageIndex( response );
this.$updateTotal( response );
return this.$decodeResults( response );
},
$decodeResults: function(response)
{
return response.results;
},
$updatePageSize: function(response)
{
if ( isNumber( response.page_size ) )
{
this.page_size = response.page_size;
}
},
$setPageSize: function(page_size)
{
this.page_size = page_size;
},
$getPageSize: function()
{
return this.page_size;
},
$updatePageIndex: function(response)
{
if ( isNumber( response.page_index ) )
{
this.page_index = response.page_index;
}
},
$setPageIndex: function(page_index)
{
this.page_index = page_index || 0;
},
$getPageIndex: function()
{
return this.page_index;
},
$getPageOffset: function()
{
return this.page_index * this.page_size;
},
$updateTotal: function(response)
{
if ( isNumber( response.total ) )
{
this.total = response.total;
}
},
$setTotal: function(total)
{
this.total = total || 0;
},
$getTotal: function()
{
return this.total;
},
$getPageCount: function()
{
return Math.ceil( this.$getTotal() / this.$getPageSize() );
}
});
function Promise(executor, cancelable)
{
this.status = Promise.Status.Pending;
this.cancelable = cancelable !== false;
this.nexts = [];
Class.prop( this, 'results', null );
if ( isFunction( executor ) )
{
executor(
bind(this, this.resolve),
bind(this, this.reject),
bind(this, this.noline),
bind(this, this.cancel)
);
}
}
Promise.Status =
{
Pending: 'pending',
Success: 'success',
Failure: 'failure',
Offline: 'offline',
Canceled: 'canceled'
};
Promise.Events =
{
Success: 'success',
Failure: 'failure',
Offline: 'offline',
Canceled: 'canceled',
Unsuccessful: 'failure offline canceled',
Complete: 'success failure offline canceled'
};
Promise.all = function(iterable)
{
var all = new Promise();
var successes = 0;
var goal = iterable.length;
var results = [];
function handleSuccess()
{
results.push( AP.slice.apply( arguments ) );
if ( ++successes === goal )
{
all.resolve( results );
}
}
for (var i = 0; i < iterable.length; i++)
{
var p = iterable[ i ];
if ( p instanceof Promise )
{
p.then( handleSuccess, all.reject, all.noline, all.cancel, all );
}
else
{
goal--;
}
}
return all;
};
Promise.race = function(iterable)
{
var race = new Promise();
for (var i = 0; i < iterable.length; i++)
{
var p = iterable[ i ];
if ( p instanceof Promise )
{
p.bind( race );
}
}
return race;
};
Promise.reject = function(reason)
{
var p = new Promise();
p.reject.apply( p, arguments );
return p;
};
Promise.resolve = function()
{
var p = new Promise();
p.resolve.apply( p, arguments );
return p;
};
Promise.noline = function(reason)
{
var p = new Promise();
p.noline.apply( p, arguments );
return p;
};
Promise.cancel = function()
{
var p = new Promise();
p.cancel.apply( p, arguments );
return p;
};
Promise.then = function()
{
var p = new Promise();
p.resolve();
return p.then.apply( p, arguments );
};
Promise.singularity = (function()
{
var singularity = null;
var singularityResult = null;
var consuming = false;
var promiseCount = 0;
var promiseComplete = 0;
function handleSuccess()
{
if ( ++promiseComplete === promiseCount )
{
singularity.resolve( singularityResult );
}
}
function bindPromise(promise)
{
promiseCount++;
promise.then( handleSuccess, singularity.reject, singularity.noline, null, singularity );
}
return function(promiseOrContext, contextOrCallback, callbackOrNull)
{
var promise = promiseOrContext;
var context = contextOrCallback;
var callback = callbackOrNull;
if (!(promise instanceof Promise))
{
promise = false;
context = promiseOrContext;
callback = contextOrCallback;
}
if ( !consuming )
{
consuming = true;
singularity = new Promise( null, false );
singularityResult = context;
promiseCount = 0;
promiseComplete = 0;
if (promise)
{
bindPromise( promise );
}
try
{
callback.call( context, singularity );
}
catch (ex)
{
Rekord.trigger( Rekord.Events.Error, [ex] );
throw ex;
}
finally
{
consuming = false;
}
}
else
{
if (promise)
{
bindPromise( promise );
}
callback.call( context, singularity );
}
if (promiseCount === 0)
{
singularity.resolve();
}
return singularity;
};
})();
Class.create( Promise,
{
resolve: function()
{
this.finish( Promise.Status.Success, Promise.Events.Success, arguments );
},
reject: function()
{
this.finish( Promise.Status.Failure, Promise.Events.Failure, arguments );
},
noline: function()
{
this.finish( Promise.Status.Offline, Promise.Events.Offline, arguments );
},
cancel: function()
{
if ( this.cancelable )
{
this.finish( Promise.Status.Canceled, Promise.Events.Canceled, arguments );
}
},
bind: function(promise)
{
this.success( promise.resolve, promise );
this.failure( promise.reject, promise );
this.offline( promise.noline, promise );
this.canceled( promise.cancel, promise );
},
then: function(success, failure, offline, canceled, context, persistent )
{
// The promise which can be resolved if any of the callbacks return
// a Promise which is resolved.
var next = new Promise();
this.success( success, context, persistent, next );
this.failure( failure, context, persistent, next );
this.offline( offline, context, persistent, next );
this.canceled( canceled, context, persistent, next );
this.addNext( next );
return next;
},
addNext: function(next)
{
var nexts = this.nexts;
if (nexts.length === 0)
{
// If this promise is not successful, let all chained promises know.
this.unsuccessful(function()
{
for (var i = 0; i < nexts.length; i++)
{
nexts[ i ].finish( this.status, this.status, arguments );
}
});
}
nexts.push( next );
},
reset: function(clearListeners)
{
this.status = Promise.Status.Pending;
if ( clearListeners )
{
this.off();
}
return this;
},
finish: function(status, events, results)
{
if ( this.status === Promise.Status.Pending )
{
this.results = AP.slice.apply( results );
this.status = status;
this.trigger( events, results );
}
},
listenFor: function(immediate, events, callback, context, persistent, next)
{
if ( isFunction( callback ) )
{
var handleEvents = function()
{
var result = callback.apply( context || this, this.results );
if ( result instanceof Promise &&
next instanceof Promise &&
next.isPending() )
{
result.bind( next );
}
};
if ( this.status === Promise.Status.Pending )
{
if ( persistent )
{
this.on( events, handleEvents, this );
}
else
{
this.once( events, handleEvents, this );
}
}
else if ( immediate )
{
handleEvents.apply( this );
}
}
return this;
},
success: function(callback, context, persistent, next)
{
return this.listenFor( this.isSuccess(), Promise.Events.Success, callback, context, persistent, next );
},
unsuccessful: function(callback, context, persistent, next)
{
return this.listenFor( this.isUnsuccessful(), Promise.Events.Unsuccessful, callback, context, persistent, next );
},
failure: function(callback, context, persistent, next)
{
return this.listenFor( this.isFailure(), Promise.Events.Failure, callback, context, persistent, next );
},
catch: function(callback, context, persistent, next)
{
return this.listenFor( this.isFailure(), Promise.Events.Failure, callback, context, persistent, next );
},
offline: function(callback, context, persistent, next)
{
return this.listenFor( this.isOffline(), Promise.Events.Offline, callback, context, persistent, next );
},
canceled: function(callback, context, persistent, next)
{
return this.listenFor( this.isCanceled(), Promise.Events.Canceled, callback, context, persistent, next );
},
complete: function(callback, context, persistent, next)
{
return this.listenFor( true, Promise.Events.Complete, callback, context, persistent, next );
},
isSuccess: function()
{
return this.status === Promise.Status.Success;
},
isUnsuccessful: function()
{
return this.status !== Promise.Status.Success && this.status !== Promise.Status.Pending;
},
isFailure: function()
{
return this.status === Promise.Status.Failure;
},
isOffline: function()
{
return this.status === Promise.Status.Offline;
},
isCanceled: function()
{
return this.status === Promise.Status.Canceled;
},
isPending: function()
{
return this.status === Promise.Status.Pending;
},
isComplete: function()
{
return this.status !== Promise.Status.Pending;
}
});
addEventful( Promise );
function Operation()
{
}
Class.create( Operation,
{
reset: function(model, cascade, options)
{
this.model = model;
this.cascade = isNumber( cascade ) ? cascade : Cascade.All;
this.options = options;
this.db = model.$db;
this.next = null;
this.finished = false;
},
canCascade: function(cascade)
{
var expected = cascade || this.cascading;
var actual = this.cascade;
return (expected & actual) !== 0;
},
notCascade: function(expected)
{
var actual = this.cascade;
return (expected & actual) === 0;
},
queue: function(operation)
{
if ( this.next && !operation.interrupts )
{
this.next.queue( operation );
}
else
{
this.next = operation;
this.model.$trigger( Model.Events.OperationsStarted );
}
},
tryNext: function(OperationType)
{
var setNext = !this.next;
if ( setNext )
{
this.next = new OperationType( this.model, this.cascade, this.options );
}
return setNext;
},
insertNext: function(OperationType)
{
var op = new OperationType( this.model, this.cascade, this.options );
op.next = this.next;
this.next = op;
},
execute: function()
{
if ( this.db.pendingOperations === 0 )
{
this.db.trigger( Database.Events.OperationsStarted );
}
this.db.pendingOperations++;
try
{
this.run( this.db, this.model );
}
catch (ex)
{
this.finish();
Rekord.trigger( Rekord.Events.Error, [ex] );
throw ex;
}
},
run: function(db, model)
{
throw 'Operation.run Not implemented';
},
finish: function()
{
if ( !this.finished )
{
this.finished = true;
this.model.$operation = this.next;
if ( this.next )
{
this.next.execute();
}
this.db.pendingOperations--;
if ( !this.next )
{
this.model.$trigger( Model.Events.OperationsFinished );
}
if ( this.db.pendingOperations === 0 )
{
this.db.onOperationRest();
this.db.trigger( Database.Events.OperationsFinished );
}
}
return this;
},
success: function()
{
return bind( this, this.handleSuccess );
},
handleSuccess: function()
{
try
{
this.onSuccess.apply( this, arguments );
}
catch (ex)
{
Rekord.trigger( Rekord.Events.Error, [ex] );
throw ex;
}
finally
{
this.finish();
}
},
onSuccess: function()
{
},
failure: function()
{
return bind( this, this.handleFailure );
},
handleFailure: function()
{
try
{
this.onFailure.apply( this, arguments );
}
catch (ex)
{
Rekord.trigger( Rekord.Events.Error, [ex] );
throw ex;
}
finally
{
this.finish();
}
},
onFailure: function()
{
}
});
function GetLocal(model, cascade, options)
{
this.reset( model, cascade, options );
}
Class.extend( Operation, GetLocal,
{
cascading: Cascade.Local,
interrupts: false,
type: 'GetLocal',
run: function(db, model)
{
if ( model.$isDeleted() )
{
model.$trigger( Model.Events.LocalGetFailure, [model] );
this.finish();
}
else if ( this.canCascade() && db.cache === Cache.All )
{
db.store.get( model.$key(), this.success(), this.failure() );
}
else
{
Rekord.debug( Rekord.Debugs.GET_LOCAL_SKIPPED, model );
model.$trigger( Model.Events.LocalGet, [model] );
this.insertNext( GetRemote );
this.finish();
}
},
onSuccess: function(key, encoded)
{
var model = this.model;
if ( isObject( encoded ) )
{
model.$set( encoded );
}
Rekord.debug( Rekord.Debugs.GET_LOCAL, model, encoded );
model.$trigger( Model.Events.LocalGet, [model] );
if ( this.canCascade( Cascade.Rest ) && !model.$isDeleted() )
{
this.insertNext( GetRemote );
}
},
onFailure: function(e)
{
var model = this.model;
Rekord.debug( Rekord.Debugs.GET_LOCAL, model, e );
model.$trigger( Model.Events.LocalGetFailure, [model] );
if ( this.canCascade( Cascade.Rest ) && !model.$isDeleted() )
{
this.insertNext( GetRemote );
}
}
});
function GetRemote(model, cascade, options)
{
this.reset( model, cascade, options );
}
Class.extend( Operation, GetRemote,
{
cascading: Cascade.Rest,
interrupts: false,
type: 'GetRemote',
run: function(db, model)
{
if ( model.$isDeleted() )
{
model.$trigger( Model.Events.RemoteGetFailure, [model] );
this.finish();
}
else if ( this.canCascade() )
{
batchExecute(function()
{
db.rest.get( model, this.options || db.getOptions, this.success(), this.failure() );
}, this );
}
else
{
model.$trigger( Model.Events.RemoteGet, [model] );
this.finish();
}
},
onSuccess: function(response)
{
var db = this.db;
var data = db.resolveModel( response );
var model = this.model;
if ( isObject( data ) )
{
db.putRemoteData( data, model.$key(), model, true );
}
Rekord.debug( Rekord.Debugs.GET_REMOTE, model, data );
model.$trigger( Model.Events.RemoteGet, [model] );
},
onFailure: function(response, status)
{
var db = this.db;
var model = this.model;
Rekord.debug( Rekord.Debugs.GET_REMOTE_ERROR, model, response, status );
if ( RestStatus.NotFound[ status ] )
{
this.insertNext( RemoveNow );
db.destroyModel( model );
model.$trigger( Model.Events.RemoteGetFailure, [model, response] );
}
else if ( RestStatus.Offline[ status ] )
{
model.$trigger( Model.Events.RemoteGetOffline, [model, response] );
}
else
{
model.$trigger( Model.Events.RemoteGetFailure, [model, response] );
}
}
});
function RemoveCache(model, cascade)
{
this.reset( model, cascade );
}
Class.extend( Operation, RemoveCache,
{
cascading: Cascade.None,
interrupts: true,
type: 'RemoveCache',
run: function(db, model)
{
if ( db.cache === Cache.None )
{
this.finish();
}
else
{
db.store.remove( model.$key(), this.success(), this.failure() );
}
}
});
function RemoveLocal(model, cascade)
{
this.reset( model, cascade );
}
Class.extend( Operation, RemoveLocal,
{
cascading: Cascade.Local,
interrupts: true,
type: 'RemoveLocal',
run: function(db, model)
{
model.$status = Model.Status.RemovePending;
if ( db.cache === Cache.None || !model.$local || !this.canCascade() )
{
Rekord.debug( Rekord.Debugs.REMOVE_LOCAL_NONE, model );
model.$trigger( Model.Events.LocalRemove, [model] );
this.insertNext( RemoveRemote );
this.finish();
}
else if ( model.$saved && this.canCascade( Cascade.Rest ) )
{
model.$local.$status = model.$status;
db.store.put( model.$key(), model.$local, this.success(), this.failure() );
}
else
{
Rekord.debug( Rekord.Debugs.REMOVE_LOCAL_UNSAVED, model );
db.store.remove( model.$key(), this.success(), this.failure() );
}
},
onSuccess: function(key, encoded, previousValue)
{
var model = this.model;
Rekord.debug( Rekord.Debugs.REMOVE_LOCAL, model );
model.$trigger( Model.Events.LocalRemove, [model] );
if ( model.$saved && this.canCascade( Cascade.Remote ) )
{
model.$addOperation( RemoveRemote, this.cascade, this.options );
}
},
onFailure: function(e)
{
var model = this.model;
Rekord.debug( Rekord.Debugs.REMOVE_LOCAL_ERROR, model, e );
model.$trigger( Model.Events.LocalRemoveFailure, [model] );
if ( model.$saved && this.canCascade( Cascade.Remote ) )
{
model.$addOperation( RemoveRemote, this.cascade, this.options );
}
}
});
function RemoveNow(model, cascade)
{
this.reset( model, cascade );
}
Class.extend( Operation, RemoveNow,
{
cascading: Cascade.Local,
interrupts: true,
type: 'RemoveNow',
run: function(db, model)
{
var key = model.$key();
model.$status = Model.Status.RemovePending;
db.removeFromModels( model );
if ( db.cache === Cache.None || !this.canCascade() )
{
this.finishRemove();
this.finish();
}
else
{
db.store.remove( key, this.success(), this.failure() );
}
},
onSuccess: function()
{
this.finishRemove();
},
onFailure: function()
{
this.finishRemove();
},
finishRemove: function()
{
var model = this.model;
model.$status = Model.Status.Removed;
delete model.$local;
delete model.$saving;
delete model.$publish;
delete model.$saved;
}
});
function RemoveRemote(model, cascade, options)
{
this.reset( model, cascade, options );
}
Class.extend( Operation, RemoveRemote,
{
cascading: Cascade.Remote,
interrupts: true,
type: 'RemoveRemote',
run: function(db, model)
{
if ( this.notCascade( Cascade.Rest ) )
{
this.liveRemove();
model.$trigger( Model.Events.RemoteRemove, [model] );
this.finish();
}
else
{
model.$status = Model.Status.RemovePending;
batchExecute(function()
{
db.rest.remove( model, this.options || this.removeOptions, this.success(), this.failure() );
}, this );
}
},
onSuccess: function(data)
{
this.finishRemove();
},
onFailure: function(response, status)
{
var model = this.model;
var key = model.$key();
if ( RestStatus.NotFound[ status ] )
{
Rekord.debug( Rekord.Debugs.REMOVE_MISSING, model, key );
this.finishRemove( true );
}
else if ( RestStatus.Offline[ status ] )
{
// Looks like we're offline!
Rekord.checkNetworkStatus();
// If we are offline, wait until we're online again to resume the delete
if (!Rekord.online)
{
model.$listenForOnline( this.cascade );
model.$trigger( Model.Events.RemoteRemoveOffline, [model, response] );
}
else
{
model.$trigger( Model.Events.RemoteRemoveFailure, [model, response] );
}
Rekord.debug( Rekord.Debugs.REMOVE_OFFLINE, model, response );
}
else
{
Rekord.debug( Rekord.Debugs.REMOVE_ERROR, model, status, key, response );
model.$trigger( Model.Events.RemoteRemoveFailure, [model, response] );
}
},
finishRemove: function(notLive)
{
var db = this.db;
var model = this.model;
var key = model.$key();
Rekord.debug( Rekord.Debugs.REMOVE_REMOTE, model, key );
// Successfully removed!
model.$status = Model.Status.Removed;
// Successfully Removed!
model.$trigger( Model.Events.RemoteRemove, [model] );
// Remove from local storage now
this.insertNext( RemoveNow );
// Remove it live!
if ( !notLive )
{
this.liveRemove();
}
// Remove the model reference for good!
db.removeReference( key );
},
liveRemove: function()
{
if ( this.canCascade( Cascade.Live ) )
{
var db = this.db;
var model = this.model;
var key = model.$key();
// Publish REMOVE
Rekord.debug( Rekord.Debugs.REMOVE_PUBLISH, model, key );
db.live.remove( model );
}
}
});
function SaveLocal(model, cascade, options)
{
this.reset( model, cascade, options );
}
Class.extend( Operation, SaveLocal,
{
cascading: Cascade.Local,
interrupts: false,
type: 'SaveLocal',
run: function(db, model)
{
if ( model.$isDeleted() )
{
Rekord.debug( Rekord.Debugs.SAVE_LOCAL_DELETED, model );
model.$trigger( Model.Events.LocalSaveFailure, [model] );
this.finish();
}
else if ( db.cache === Cache.None || !this.canCascade() )
{
if ( this.canCascade( Cascade.Remote ) )
{
if ( this.tryNext( SaveRemote ) )
{
this.markSaving( db, model );
}
}
model.$trigger( Model.Events.LocalSave, [model] );
this.finish();
}
else
{
var key = model.$key();
var local = model.$toJSON( false );
this.markSaving( db, model );
if ( model.$local )
{
transfer( local, model.$local );
}
else
{
model.$local = local;
if ( model.$saved )
{
model.$local.$saved = model.$saved;
}
}
model.$local.$status = model.$status;
model.$local.$saving = model.$saving;
model.$local.$publish = model.$publish;
db.store.put( key, model.$local, this.success(), this.failure() );
}
},
markSaving: function(db, model)
{
var remote = model.$toJSON( true );
var changes = model.$getChanges( remote );
var saving = db.fullSave ? remote : this.grabAlways( db.saveAlways, changes, remote );
var publish = db.fullPublish ? remote : this.grabAlways( db.publishAlways, changes, remote );
model.$status = Model.Status.SavePending;
model.$saving = saving;
model.$publish = publish;
},
grabAlways: function(always, changes, encoded)
{
var changesCopy = null;
if ( always.length )
{
for (var i = 0; i < always.length; i++)
{
var prop = always[ i ];
if ( !(prop in changes) )
{
if ( !changesCopy )
{
changesCopy = copy( changes );
}
changesCopy[ prop ] = encoded[ prop ];
}
}
}
return changesCopy || changes;
},
clearLocal: function(model)
{
model.$status = Model.Status.Synced;
model.$local.$status = model.$status;
delete model.$local.$saving;
delete model.$local.$publish;
this.insertNext( SaveNow );
},
onSuccess: function(key, encoded, previousValue)
{
var model = this.model;
Rekord.debug( Rekord.Debugs.SAVE_LOCAL, model );
if ( this.cascade )
{
this.tryNext( SaveRemote );
}
else
{
this.clearLocal( model );
}
model.$trigger( Model.Events.LocalSave, [model] );
},
onFailure: function(e)
{
var model = this.model;
Rekord.debug( Rekord.Debugs.SAVE_LOCAL_ERROR, model, e );
if ( this.cascade )
{
this.tryNext( SaveRemote );
}
else
{
this.clearLocal( model );
}
model.$trigger( Model.Events.LocalSaveFailure, [model] );
}
});
function SaveNow(model, cascade)
{
this.reset( model, cascade );
}
Class.extend( Operation, SaveNow,
{
cascading: Cascade.Local,
interrupts: false,
type: 'SaveNow',
run: function(db, model)
{
var key = model.$key();
var local = model.$local;
if ( db.cache === Cache.All && key && local && this.canCascade() )
{
db.store.put( key, local, this.success(), this.failure() );
}
else
{
this.finish();
}
}
});
function SaveRemote(model, cascade, options)
{
this.reset( model, cascade, options );
}
Class.extend( Operation, SaveRemote,
{
cascading: Cascade.Remote,
interrupts: false,
type: 'SaveRemote',
run: function(db, model)
{
if ( model.$isDeleted() )
{
Rekord.debug( Rekord.Debugs.SAVE_REMOTE_DELETED, model );
this.markSynced( model, true, Model.Events.RemoteSaveFailure, null );
this.finish();
}
else if ( !model.$dependents.isSaved( this.tryAgain, this ) )
{
this.finish();
}
else if ( !db.hasData( model.$saving ) || this.notCascade( Cascade.Rest ) )
{
this.liveSave();
this.markSynced( model, true, Model.Events.RemoteSave, null );
this.finish();
}
else
{
model.$status = Model.Status.SavePending;
batchExecute(function()
{
if ( model.$saved )
{
db.rest.update( model, model.$saving, this.options || db.updateOptions || db.saveOptions, this.success(), this.failure() );
}
else
{
db.rest.create( model, model.$saving, this.options || db.createOptions || db.saveOptions, this.success(), this.failure() );
}
}, this );
}
},
onSuccess: function(response)
{
var db = this.db;
var data = db.resolveModel( response );
var model = this.model;
Rekord.debug( Rekord.Debugs.SAVE_REMOTE, model );
this.handleData( data );
},
onFailure: function(response, status)
{
var operation = this;
var db = this.db;
var data = db.resolveModel( response );
var model = this.model;
// A non-zero status means a real problem occurred
if ( RestStatus.Conflict[ status ] ) // 409 Conflict
{
Rekord.debug( Rekord.Debugs.SAVE_CONFLICT, model, data );
this.handleData( data );
}
else if ( RestStatus.NotFound[ status ] )
{
Rekord.debug( Rekord.Debugs.SAVE_UPDATE_FAIL, model );
this.insertNext( RemoveNow );
db.destroyModel( model );
model.$trigger( Model.Events.RemoteSaveFailure, [model, response] );
}
else if ( RestStatus.Offline[ status ] )
{
// Check the network status right now
Rekord.checkNetworkStatus();
// If not online for sure, try saving once online again
if (!Rekord.online)
{
model.$listenForOnline( this.cascade );
model.$trigger( Model.Events.RemoteSaveOffline, [model, response] );
}
else
{
this.markSynced( model, true, Model.Events.RemoteSaveFailure, response );
}
Rekord.debug( Rekord.Debugs.SAVE_OFFLINE, model, response );
}
else
{
Rekord.debug( Rekord.Debugs.SAVE_ERROR, model, status );
this.markSynced( model, true, Model.Events.RemoteSaveFailure, response );
}
},
markSynced: function(model, saveNow, eventType, response)
{
model.$status = Model.Status.Synced;
this.clearPending( model );
if ( saveNow )
{
this.insertNext( SaveNow );
}
if ( eventType )
{
model.$trigger( eventType, [model, response] );
}
},
clearPending: function(model)
{
delete model.$saving;
delete model.$publish;
if ( model.$local )
{
model.$local.$status = model.$status;
delete model.$local.$saving;
delete model.$local.$publish;
}
},
handleData: function(data)
{
var db = this.db;
var model = this.model;
var saving = model.$saving;
// Check deleted one more time before updating model.
if ( model.$isDeleted() )
{
Rekord.debug( Rekord.Debugs.SAVE_REMOTE_DELETED, model, data );
return this.clearPending( model );
}
Rekord.debug( Rekord.Debugs.SAVE_VALUES, model, saving );
// If the model hasn't been saved before - create the record where the
// local and model point to the same object.
if ( !model.$saved )
{
model.$saved = model.$local ? (model.$local.$saved = {}) : {};
}
// Tranfer all saved fields into the saved object
transfer( saving, model.$saved );
// Update the model with the return data
if ( !isEmpty( data ) )
{
db.putRemoteData( data, model.$key(), model );
}
this.liveSave( data );
this.markSynced( model, false, Model.Events.RemoteSave, null );
if ( db.cache === Cache.Pending )
{
this.insertNext( RemoveCache );
}
else
{
this.insertNext( SaveNow );
}
},
liveSave: function(data)
{
var db = this.db;
var model = this.model;
if ( isObject(data) )
{
transfer( data, model.$publish );
}
if ( this.canCascade( Cascade.Live ) && db.hasData( model.$publish ) )
{
// Publish saved data to everyone else
Rekord.debug( Rekord.Debugs.SAVE_PUBLISH, model, model.$publish );
db.live.save( model, model.$publish );
}
},
tryAgain: function()
{
var model = this.model;
model.$addOperation( SaveLocal, this.cascade, this.options );
}
});
function Relation()
{
}
Rekord.Relations = {};
Relation.Defaults =
{
model: null,
lazy: false,
store: Store.None,
save: Save.None,
auto: true,
autoCascade: Cascade.All,
autoOptions: null,
property: true,
preserve: true,
clearKey: true,
dynamic: false,
discriminator: 'discriminator',
discriminators: {},
discriminatorToModel: {}
};
Class.create( Relation,
{
debugQuery: null,
debugQueryResults: null,
hasDiscriminator: false,
getDefaults: function(database, field, options)
{
return Relation.Defaults;
},
/**
* Initializes this relation with the given database, field, and options.
*
* @param {Rekord.Database} database [description]
* @param {String} field [description]
* @param {Object} options [description]
*/
init: function(database, field, options)
{
applyOptions( this, options, this.getDefaults( database, field, options ) );
this.database = database;
this.name = field;
this.options = options;
this.initialized = false;
this.property = this.property || (indexOf( database.fields, this.name ) !== false);
this.discriminated = !isEmpty( this.discriminators );
if ( this.discriminated )
{
if ( !Polymorphic )
{
throw 'Polymorphic feature is required to use the discriminated option.';
}
Class.props( this, Polymorphic );
}
this.setReferences( database, field, options );
},
setReferences: function(database, field, options)
{
if ( !isRekord( this.model ) )
{
Rekord.get( this.model ).complete( this.setModelReference( database, field, options ), this );
}
else
{
this.onInitialized( database, field, options );
}
},
/**
*
*/
setModelReference: function(database, field, options)
{
return function(rekord)
{
this.model = rekord;
this.onInitialized( database, field, options );
};
},
/**
*
*/
onInitialized: function(database, fields, options)
{
},
finishInitialization: function()
{
this.initialized = true;
this.load.open();
},
/**
* Loads the model.$relation variable with what is necessary to get, set,
* relate, and unrelate models. If property is true, look at model[ name ]
* to load models/keys. If it contains values that don't exist or aren't
* actually related
*
* @param {Rekord.Model} model [description]
*/
load: Gate(function(model, initialValue, remoteData, skipInitial)
{
}),
setInitial: function(model, initialValue, remoteData)
{
},
set: function(model, input, remoteData)
{
},
relate: function(model, input, remoteData)
{
},
unrelate: function(model, input, remoteData)
{
},
sync: function(model, removeUnrelated)
{
},
isRelated: function(model, input)
{
},
preClone: function(model, clone, properties)
{
},
postClone: function(model, clone, properties)
{
},
get: function(model)
{
return model.$relations[ this.name ].related;
},
encode: function(model, out, forSaving)
{
var relation = model.$relations[ this.name ];
var mode = forSaving ? this.save : this.store;
if ( relation && mode )
{
var related = relation.related;
if ( isArray( related ) )
{
out[ this.name ] = this.getStoredArray( related, mode );
}
else // if ( isObject( related ) )
{
out[ this.name ] = this.getStored( related, mode );
}
}
},
ready: function(callback)
{
this.model.Database.ready( callback, this );
},
listenToModelAdded: function(callback)
{
this.model.Database.on( Database.Events.ModelAdded, callback, this );
},
executeQuery: function(model)
{
if ( !Search )
{
throw 'Search feature is required to use the query option.';
}
var queryOption = this.query;
var queryOptions = this.queryOptions;
var queryData = this.queryData;
var query = isString( queryOption ) ? format( queryOption, model ) : queryOption;
var search = this.model.search( query, queryOptions, queryData );
Rekord.debug( this.debugQuery, this, model, search, queryOption, query, queryData );
var promise = search.$run();
promise.complete( this.handleExecuteQuery( model ), this );
return search;
},
handleExecuteQuery: function(model)
{
return function onExecuteQuery(search)
{
var results = search.$results;
Rekord.debug( this.debugQueryResults, this, model, search );
for (var i = 0; i < results.length; i++)
{
this.relate( model, results[ i ], true );
}
};
},
createRelationCollection: function(model)
{
return RelationCollection.create( this.model.Database, model, this );
},
createCollection: function(initial)
{
return ModelCollection.create( this.model.Database, initial );
},
parseModel: function(input, remoteData, relation)
{
return this.model.Database.parseModel( input, remoteData );
},
grabInitial: function( model, fields )
{
if ( hasFields( model, fields, isValue ) )
{
return pull( model, fields );
}
},
grabModel: function(input, callback, remoteData, relation)
{
this.model.Database.grabModel( input, callback, this, remoteData );
},
grabModels: function(relation, initial, callback, remoteData)
{
var db = this.model.Database;
for (var i = 0; i < initial.length; i++)
{
var input = initial[ i ];
var key = db.keyHandler.buildKeyFromInput( input );
relation.pending[ key ] = true;
if ( input instanceof Model )
{
callback.call( this, input );
}
else
{
db.grabModel( input, callback, this, remoteData );
}
}
},
buildKey: function(input)
{
},
setProperty: function(relation)
{
if ( this.property )
{
var model = relation.parent;
var propertyName = this.name;
var applied = !!relation.dynamicSet;
if ( !applied && this.dynamic && Object.defineProperty )
{
var relator = this;
Object.defineProperty( model, propertyName,
{
enumerable: true,
set: function(input)
{
relator.set( model, input );
},
get: function()
{
return relation.related;
}
});
applied = relation.dynamicSet = true;
}
if ( !applied )
{
model[ propertyName ] = relation.related;
}
if ( relation.lastRelated !== relation.related )
{
model.$trigger( Model.Events.RelationUpdate, [this, relation] );
relation.lastRelated = relation.related;
}
}
},
isModelArray: function(input)
{
if ( !isArray( input ) )
{
return false;
}
var relatedDatabase = this.model.Database;
var relatedKey = relatedDatabase.key;
if ( !isArray( relatedKey ) )
{
return true;
}
if ( relatedKey.length !== input.length )
{
return true;
}
for ( var i = 0; i < input.length; i++ )
{
if ( !isNumber( input[ i ] ) && !isString( input[ i ] ) )
{
return true;
}
}
return false;
},
clearFields: function(target, targetFields, remoteData, cascade)
{
var changes = clearFieldsReturnChanges( target, targetFields );
if ( changes && !remoteData && this.auto && !target.$isNew() )
{
target.$save( cascade || this.autoCascade, this.autoOptions );
}
return changes;
},
updateFields: function(target, targetFields, source, sourceFields, remoteData)
{
var changes = updateFieldsReturnChanges( target, targetFields, source, sourceFields );
if ( changes )
{
if ( this.auto && !target.$isNew() && !remoteData )
{
target.$save( this.autoCascade, this.autoOptions );
}
target.$trigger( Model.Events.KeyUpdate, [target, source, targetFields, sourceFields] );
}
return changes;
},
updateForeignKey: function(target, source, remoteData)
{
var targetFields = this.getTargetFields( target );
var sourceFields = this.getSourceFields( source );
var targetKey = target.$key();
var targetKeyHandler = target.$db.keyHandler;
var keyChanges = target.$db.keyChanges;
Rekord.debug( this.debugUpdateKey, this, target, targetFields, source, sourceFields );
this.updateFields( target, targetFields, source, sourceFields, remoteData );
if ( keyChanges && remoteData )
{
var targetNewKey = targetKeyHandler.getKey( target, true );
if ( targetKeyHandler.inKey( targetFields ) && targetNewKey !== targetKey )
{
target.$setKey( targetNewKey, true );
}
}
},
clearForeignKey: function(related, remoteData)
{
var key = this.getTargetFields( related );
Rekord.debug( this.debugClearKey, this, related, key );
this.clearFields( related, key, remoteData );
},
getTargetFields: function(target)
{
return target.$db.key;
},
getSourceFields: function(source)
{
return source.$db.key;
},
getStoredArray: function(relateds, mode)
{
if ( !mode )
{
return null;
}
var stored = [];
for (var i = 0; i < relateds.length; i++)
{
var related = this.getStored( relateds[ i ], mode );
if ( related !== null )
{
stored.push( related );
}
}
return stored;
},
getStored: function(related, mode)
{
if ( related )
{
switch (mode)
{
case Save.Model:
return related.$toJSON( true );
case Store.Model:
if ( related.$local )
{
return related.$local;
}
var local = related.$toJSON( false );
if ( related.$saved )
{
local.$saved = related.$saved;
}
return local;
case Save.Key:
case Store.Key:
return related.$key();
case Save.Keys:
case Store.Keys:
return related.$keys();
}
}
return null;
}
});
function RelationSingle()
{
}
Class.extend( Relation, RelationSingle,
{
debugInit: null,
debugClearModel: null,
debugSetModel: null,
debugLoaded: null,
debugClearKey: null,
debugUpdateKey: null,
hasDiscriminator: true,
onInitialized: function(database, field, options)
{
if ( !this.discriminated )
{
var relatedDatabase = this.model.Database;
this.local = this.local || ( relatedDatabase.name + '_' + relatedDatabase.key );
}
Rekord.debug( this.debugInit, this );
this.finishInitialization();
},
set: function(model, input, remoteData)
{
if ( isEmpty( input ) )
{
this.unrelate( model, undefined, remoteData );
}
else
{
var relation = model.$relations[ this.name ];
var related = this.parseModel( input, remoteData, relation );
if ( related && relation.related !== related )
{
this.clearModel( relation, remoteData );
this.setRelated( relation, related, remoteData );
}
}
},
relate: function(model, input, remoteData)
{
var relation = model.$relations[ this.name ];
var related = this.parseModel( input, remoteData, relation );
if ( related && relation.related !== related )
{
this.clearModel( relation, remoteData );
this.setRelated( relation, related, remoteData );
}
},
unrelate: function(model, input, remoteData)
{
var relation = model.$relations[ this.name ];
var related = this.parseModel( input, remoteData, relation );
if ( !related || relation.related === related )
{
this.clearRelated( relation, remoteData );
}
},
isRelated: function(model, input)
{
var relation = model.$relations[ this.name ];
var related = this.parseModel( input, false, relation );
return related === relation.related;
},
setRelated: function(relation, related, remoteData)
{
if ( !related.$isDeleted() )
{
this.setModel( relation, related );
this.updateForeignKey( relation.parent, related, remoteData );
this.setProperty( relation );
}
},
clearRelated: function(relation, remoteData, dontClear)
{
if ( remoteData )
{
var related = relation.related;
if ( related && related.$isSaving() )
{
return;
}
}
this.clearModel( relation, remoteData, dontClear );
this.setProperty( relation );
},
clearModel: function(relation, remoteData, dontClear)
{
var related = relation.related;
if ( related )
{
Rekord.debug( this.debugClearModel, this, relation );
if (relation.onSaved)
{
related.$off( Model.Events.Saved, relation.onSaved );
}
if (relation.onRemoved)
{
related.$off( Model.Events.Removed, relation.onRemoved );
}
relation.related = null;
relation.dirty = true;
relation.loaded = true;
relation.parent.$dependents.remove( related );
if ( !dontClear && !remoteData )
{
if ( this.clearKey )
{
this.clearForeignKey( relation.parent, remoteData );
}
}
}
},
setModel: function(relation, related)
{
if (relation.onSaved)
{
related.$on( Model.Events.Saved, relation.onSaved, this );
}
if (relation.onRemoved)
{
related.$on( Model.Events.Removed, relation.onRemoved, this );
}
relation.related = related;
relation.dirty = true;
relation.loaded = true;
if ( this.isDependent( relation, related ) )
{
relation.parent.$dependents.add( related, this );
}
Rekord.debug( this.debugSetModel, this, relation );
},
isDependent: function(relation, related)
{
return true;
},
handleModel: function(relation, remoteData, ignoreLoaded)
{
return function(related)
{
var model = relation.parent;
Rekord.debug( this.debugLoaded, this, model, relation, related );
if ( relation.loaded === false || ignoreLoaded )
{
if ( related && !related.$isDeleted() )
{
this.setModel( relation, related, remoteData );
this.updateForeignKey( model, related, remoteData );
}
else
{
if ( this.query )
{
relation.query = this.executeQuery( model );
}
else if ( !this.preserve )
{
this.clearForeignKey( model, remoteData );
}
}
relation.loaded = true;
this.setProperty( relation );
}
};
},
isRelatedFactory: function(model)
{
var local = this.local;
return function hasForeignKey(related)
{
return propsMatch( model, local, related, related.$db.key );
};
},
getTargetFields: function(target)
{
return this.local;
},
buildKey: function(input)
{
var related = input[ this.name ];
var key = this.local;
if ( isObject( related ) && this.model )
{
var modelDatabase = this.model.Database;
var foreign = modelDatabase.key;
modelDatabase.keyHandler.copyFields( input, key, related, foreign );
}
}
});
function RelationMultiple()
{
}
Class.extend( Relation, RelationMultiple,
{
debugAutoSave: null,
debugInitialGrabbed: null,
debugSort: null,
handleExecuteQuery: function(model)
{
return function onExecuteQuery(search)
{
var relation = model.$relations[ this.name ];
var results = search.$results;
Rekord.debug( this.debugQueryResults, this, model, search );
this.bulk( relation, function()
{
for (var i = 0; i < results.length; i++)
{
this.addModel( relation, results[ i ], true );
}
});
this.sort( relation );
this.checkSave( relation, true );
};
},
bulk: function(relation, callback, remoteData)
{
relation.delaySorting = true;
relation.delaySaving = true;
callback.apply( this );
relation.delaySorting = false;
relation.delaySaving = false;
this.sort( relation );
this.checkSave( relation, remoteData );
},
set: function(model, input, remoteData)
{
if ( isEmpty( input ) )
{
this.unrelate( model, undefined, remoteData );
}
else
{
var relation = model.$relations[ this.name ];
var existing = relation.related;
var given = this.createCollection();
if ( this.isModelArray( input ) )
{
for (var i = 0; i < input.length; i++)
{
var related = this.parseModel( input[ i ], remoteData, relation );
if ( related )
{
given.add( related );
}
}
}
else
{
var related = this.parseModel( input, remoteData, relation );
if ( related )
{
given.add( related );
}
}
var removing = existing.subtract( given );
var adding = given.subtract( existing );
this.bulk( relation, function()
{
for (var i = 0; i < adding.length; i++)
{
this.addModel( relation, adding[ i ], remoteData );
}
for (var i = 0; i < removing.length; i++)
{
this.removeModel( relation, removing[ i ], remoteData );
}
}, remoteData);
}
},
relate: function(model, input, remoteData)
{
var relation = model.$relations[ this.name ];
if ( this.isModelArray( input ) )
{
this.bulk( relation, function()
{
for (var i = 0; i < input.length; i++)
{
var related = this.parseModel( input[ i ], remoteData, relation );
if ( related )
{
this.addModel( relation, related, remoteData );
}
}
}, remoteData );
}
else if ( isValue( input ) )
{
var related = this.parseModel( input, remoteData, relation );
if ( related )
{
this.addModel( relation, related, remoteData );
}
}
},
unrelate: function(model, input, remoteData)
{
var relation = model.$relations[ this.name ];
if ( this.isModelArray( input ) )
{
this.bulk( relation, function()
{
for (var i = 0; i < input.length; i++)
{
var related = this.parseModel( input[ i ], remoteData, relation );
if ( related )
{
this.removeModel( relation, related, remoteData );
}
}
}, remoteData );
}
else if ( isValue( input ) )
{
var related = this.parseModel( input, remoteData, relation );
if ( related )
{
this.removeModel( relation, related, remoteData );
}
}
else
{
var all = relation.related;
this.bulk( relation, function()
{
for (var i = all.length - 1; i >= 0; i--)
{
this.removeModel( relation, all[ i ], remoteData );
}
}, remoteData );
}
},
isRelated: function(model, input)
{
var relation = model.$relations[ this.name ];
var existing = relation.related;
if ( this.isModelArray( input ) )
{
for (var i = 0; i < input.length; i++)
{
var related = this.parseModel( input[ i ], false, relation );
if ( related && !existing.has( related.$key() ) )
{
return false;
}
}
return input.length > 0;
}
else if ( isValue( input ) )
{
var related = this.parseModel( input, false, relation );
return related && existing.has( related.$key() );
}
return false;
},
canRemoveRelated: function(related, remoteData)
{
return !remoteData || !related.$isSaving();
},
checkSave: function(relation, remoteData)
{
if ( !relation.delaySaving && !remoteData && relation.parent.$exists() )
{
if ( this.store === Store.Model || this.save === Save.Model )
{
Rekord.debug( this.debugAutoSave, this, relation );
relation.parent.$save( this.saveParentCascade, this.saveParentOptions );
}
}
},
handleModel: function(relation, remoteData, ignoreLoaded)
{
return function (related)
{
var pending = relation.pending;
var key = related.$key();
if ( key in pending || ignoreLoaded )
{
Rekord.debug( this.debugInitialGrabbed, this, relation, related );
this.addModel( relation, related, remoteData );
delete pending[ key ];
}
};
},
sort: function(relation)
{
var related = relation.related;
if ( !relation.delaySorting )
{
Rekord.debug( this.debugSort, this, relation );
related.sort( this.comparator );
relation.parent.$trigger( Model.Events.RelationUpdate, [this, relation] );
}
}
});
function BelongsTo()
{
}
Rekord.Relations.belongsTo = BelongsTo;
BelongsTo.Defaults =
{
model: null,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
auto: true,
autoCascade: Cascade.All,
autoOptions: null,
property: true,
preserve: true,
clearKey: true,
dynamic: false,
local: null,
cascade: Cascade.Local,
cascadeRemoveOptions: null,
discriminator: 'discriminator',
discriminators: {},
discriminatorToModel: {}
};
Class.extend( RelationSingle, BelongsTo,
{
type: 'belongsTo',
debugInit: Rekord.Debugs.BELONGSTO_INIT,
debugClearModel: Rekord.Debugs.BELONGSTO_CLEAR_MODEL,
debugSetModel: Rekord.Debugs.BELONGSTO_SET_MODEL,
debugLoaded: Rekord.Debugs.BELONGSTO_LOADED,
debugClearKey: Rekord.Debugs.BELONGSTO_CLEAR_KEY,
debugUpdateKey: Rekord.Debugs.BELONGSTO_UPDATE_KEY,
debugQuery: Rekord.Debugs.BELONGSTO_QUERY,
debugQueryResults: Rekord.Debugs.BELONGSTO_QUERY_RESULTS,
getDefaults: function(database, field, options)
{
return BelongsTo.Defaults;
},
load: Gate(function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ] =
{
parent: model,
isRelated: this.isRelatedFactory( model ),
related: null,
loaded: false,
onRemoved: function()
{
Rekord.debug( Rekord.Debugs.BELONGSTO_NINJA_REMOVE, this, model, relation );
model.$remove( this.cascade, this.cascadeRemoveOptions );
this.clearRelated( relation, false, true );
},
onSaved: function()
{
Rekord.debug( Rekord.Debugs.BELONGSTO_NINJA_SAVE, this, model, relation );
if ( !relation.isRelated( relation.related ) )
{
this.clearRelated( relation, false, true );
}
}
};
model.$on( Model.Events.PostRemove, this.postRemove, this );
model.$on( Model.Events.KeyUpdate, this.onKeyUpdate, this );
this.setInitial( model, initialValue, remoteData );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
if ( isEmpty( initialValue ) )
{
initialValue = this.grabInitial( model, this.local );
if ( initialValue )
{
Rekord.debug( Rekord.Debugs.BELONGSTO_INITIAL_PULLED, this, model, initialValue );
}
}
if ( !isEmpty( initialValue ) )
{
Rekord.debug( Rekord.Debugs.BELONGSTO_INITIAL, this, model, initialValue );
this.grabModel( initialValue, this.handleModel( relation, remoteData ), remoteData, relation );
}
else if ( this.query )
{
relation.query = this.executeQuery( model );
}
},
sync: function(model, removeUnrelated)
{
var relation = model.$relations[ this.name ];
var relatedValue = this.grabInitial( model, this.local );
var remoteData = true;
var ignoreLoaded = true;
var dontClear = true;
if ( relation )
{
if ( !isEmpty( relatedValue ) )
{
this.grabModel( relatedValue, this.handleModel( relation, remoteData, ignoreLoaded ), remoteData );
}
else if ( removeUnrelated )
{
this.clearRelated( relation, remoteData, dontClear );
}
}
},
postRemove: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation )
{
Rekord.debug( Rekord.Debugs.BELONGSTO_POSTREMOVE, this, model, relation );
this.clearModel( relation );
this.setProperty( relation );
}
},
onKeyUpdate: function(model, related, modelFields, relatedFields)
{
if ( this.local === modelFields )
{
var relation = model.$relations[ this.name ];
if ( relation && related !== relation.related )
{
this.clearModel( relation, false, true );
this.setModel( relation, related );
this.setProperty( relation );
}
}
}
});
function HasOne()
{
}
Rekord.Relations.hasOne = HasOne;
HasOne.Defaults =
{
model: null,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
saveCascade: Cascade.All,
saveOptions: null,
auto: true,
autoCascade: Cascade.All,
autoOptions: null,
property: true,
preserve: true,
clearKey: true,
dynamic: false,
local: null,
cascade: Cascade.All,
cascadeRemoveOptions: null,
discriminator: 'discriminator',
discriminators: {},
discriminatorToModel: {}
};
Class.extend( RelationSingle, HasOne,
{
type: 'hasOne',
debugInit: Rekord.Debugs.HASONE_INIT,
debugClearModel: Rekord.Debugs.HASONE_CLEAR_MODEL,
debugSetModel: Rekord.Debugs.HASONE_SET_MODEL,
debugLoaded: Rekord.Debugs.HASONE_LOADED,
debugClearKey: Rekord.Debugs.HASONE_CLEAR_KEY,
debugUpdateKey: Rekord.Debugs.HASONE_UPDATE_KEY,
debugQuery: Rekord.Debugs.HASONE_QUERY,
debugQueryResults: Rekord.Debugs.HASONE_QUERY_RESULTS,
getDefaults: function(database, field, options)
{
return HasOne.Defaults;
},
load: Gate(function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ] =
{
parent: model,
isRelated: this.isRelatedFactory( model ),
related: null,
loaded: false,
dirty: false,
saving: false,
child: equals( this.local, model.$db.key ),
onRemoved: function()
{
Rekord.debug( Rekord.Debugs.HASONE_NINJA_REMOVE, this, model, relation );
this.clearRelated( relation, false, true );
}
};
model.$on( Model.Events.PreSave, this.preSave, this );
model.$on( Model.Events.PostRemove, this.postRemove, this );
this.setInitial( model, initialValue, remoteData );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
if ( isEmpty( initialValue ) )
{
initialValue = this.grabInitial( model, this.local );
if ( initialValue )
{
Rekord.debug( Rekord.Debugs.HASONE_INITIAL_PULLED, this, model, initialValue );
}
}
if ( !isEmpty( initialValue ) )
{
Rekord.debug( Rekord.Debugs.HASONE_INITIAL, this, model, initialValue );
this.populateInitial( initialValue, relation, model );
this.grabModel( initialValue, this.handleModel( relation, remoteData ), remoteData, relation );
}
else if ( this.query )
{
relation.query = this.executeQuery( model );
}
},
populateInitial: function(initialValue, relation, model)
{
if ( isObject( initialValue ) && relation.child )
{
var src = toArray( this.local );
var dst = toArray( this.model.Database.key );
for (var k = 0; k < src.length; k++)
{
initialValue[ dst[ k ] ] = model[ src[ k ] ];
}
}
},
sync: function(model, removeUnrelated)
{
var relation = model.$relations[ this.name ];
var relatedValue = this.grabInitial( model, this.local );
var remoteData = true;
var ignoreLoaded = true;
var dontClear = true;
if ( relation )
{
if ( !isEmpty( relatedValue ) )
{
this.populateInitial( relatedValue, relation, model );
this.grabModel( relatedValue, this.handleModel( relation, remoteData, ignoreLoaded ), remoteData, relation );
}
else if ( removeUnrelated )
{
this.clearRelated( relation, remoteData, dontClear );
}
}
},
isDependent: function(relation, related)
{
return !relation.child;
},
preClone: function(model, clone, properties)
{
var related = this.get( model );
if ( related )
{
var relatedClone = related.$clone( properties );
updateFieldsReturnChanges( clone, this.local, relatedClone, relatedClone.$db.key );
clone[ this.name ] = relatedClone;
}
},
preSave: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation && relation.related )
{
var related = relation.related;
if ( relation.dirty || related.$hasChanges() )
{
Rekord.debug( Rekord.Debugs.HASONE_PRESAVE, this, model, relation );
relation.saving = true;
related.$save( this.saveCascade, this.saveOptions );
relation.saving = false;
relation.dirty = false;
}
}
},
postRemove: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation )
{
if ( this.cascade )
{
Rekord.debug( Rekord.Debugs.HASONE_POSTREMOVE, this, model, relation );
this.clearModel( relation );
}
}
},
clearModel: function(relation, remoteData)
{
var related = relation.related;
if ( related )
{
Rekord.debug( this.debugClearModel, this, relation );
related.$off( Model.Events.Removed, relation.onRemoved );
if ( this.cascade && !related.$isDeleted() )
{
related.$remove( this.cascade, this.cascadeRemoveOptions );
}
relation.related = null;
relation.dirty = true;
relation.loaded = true;
relation.parent.$dependents.remove( related );
if ( this.clearKey )
{
this.clearForeignKey( relation.parent, remoteData );
}
}
}
});
function HasMany()
{
}
Rekord.Relations.hasMany = HasMany;
HasMany.Defaults =
{
model: null,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
auto: true,
autoCascade: Cascade.All,
autoOptions: null,
property: true,
preserve: true,
clearKey: true,
dynamic: false,
foreign: null,
comparator: null,
comparatorNullsFirst: false,
listenForRelated: true,
loadRelated: true,
where: false,
saveParentCascade: Cascade.All,
saveParentOptions: null,
cascadeRemove: Cascade.Local,
cascadeRemoveOptions: null,
cascadeSave: Cascade.None,
cascadeSaveOptions: null,
discriminator: 'discriminator',
discriminators: {},
discriminatorToModel: {}
};
Class.extend( RelationMultiple, HasMany,
{
type: 'hasMany',
debugAutoSave: Rekord.Debugs.HASMANY_AUTO_SAVE,
debugInitialGrabbed: Rekord.Debugs.HASMANY_INITIAL_GRABBED,
debugSort: Rekord.Debugs.HASMANY_SORT,
debugQuery: Rekord.Debugs.HASMANY_QUERY,
debugQueryResults: Rekord.Debugs.HASMANY_QUERY_RESULTS,
debugUpdateKey: Rekord.Debugs.HASMANY_UPDATE_KEY,
getDefaults: function(database, field, options)
{
return HasMany.Defaults;
},
onInitialized: function(database, field, options)
{
this.foreign = this.foreign || ( database.name + '_' + database.key );
this.comparator = createComparator( this.comparator, this.comparatorNullsFirst );
Rekord.debug( Rekord.Debugs.HASMANY_INIT, this );
this.finishInitialization();
},
load: Gate(function(model, initialValue, remoteData)
{
var relator = this;
var relation = model.$relations[ this.name ] =
{
parent: model,
pending: {},
isRelated: this.isRelatedFactory( model ),
related: this.createRelationCollection( model ),
saving: false,
delaySorting: false,
delaySaving: false,
onRemoved: function() // this = model removed
{
Rekord.debug( Rekord.Debugs.HASMANY_NINJA_REMOVE, relator, model, this, relation );
relator.removeModel( relation, this, true, true );
},
onSaved: function() // this = model saved
{
if ( relation.saving )
{
return;
}
Rekord.debug( Rekord.Debugs.HASMANY_NINJA_SAVE, relator, model, this, relation );
if ( !relation.isRelated( this ) )
{
relator.removeModel( relation, this, false, true );
}
else
{
relator.sort( relation );
relator.checkSave( relation );
}
},
onChange: function()
{
if ( relation.saving )
{
return;
}
if ( relator.where && !relator.where( this, relation ) )
{
relator.removeModel( relation, this, false, true );
}
}
};
model.$on( Model.Events.PostSave, this.postSave, this );
model.$on( Model.Events.PreRemove, this.preRemove, this );
// When models are added to the related database, check if it's related to this model
if ( this.listenForRelated )
{
this.listenToModelAdded( this.handleModelAdded( relation ) );
}
// If the model's initial value is an array, populate the relation from it!
this.setInitial( model, initialValue, remoteData );
// We only need to set the property once since the underlying array won't change.
this.setProperty( relation );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
if ( isArray( initialValue ) )
{
Rekord.debug( Rekord.Debugs.HASMANY_INITIAL, this, model, relation, initialValue );
this.grabModels( relation, initialValue, this.handleModel( relation, remoteData ), remoteData );
}
else if ( this.query )
{
relation.query = this.executeQuery( model );
}
else if ( this.loadRelated )
{
Rekord.debug( Rekord.Debugs.HASMANY_INITIAL_PULLED, this, model, relation );
this.ready( this.handleLazyLoad( relation ) );
}
},
sync: function(model, removeUnrelated)
{
var relation = model.$relations[ this.name ];
if ( relation )
{
var existing = relation.related;
var remoteData = true;
var dontClear = true;
var relator = this;
var onRelated = function(related)
{
if ( removeUnrelated )
{
var given = this.createCollection();
given.reset( related );
existing.each(function(existingModel)
{
if ( !given.has( existingModel.$key() ) )
{
relator.removeModel( relation, existingModel, remoteData, dontClear );
}
});
}
};
this.ready( this.handleLazyLoad( relation, onRelated ) );
}
},
postClone: function(model, clone, properties)
{
var related = this.get( model );
if ( related )
{
var relatedClones = [];
updateFieldsReturnChanges( properties, this.foreign, clone, model.$db.key );
properties[ this.foreign ] = clone[ model.$db.key ];
for (var i = 0; i < related.length; i++)
{
relatedClones.push( related[ i ].$clone( properties ) );
}
clone[ this.name ] = relatedClones;
}
},
postSave: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation && this.cascadeSave )
{
Rekord.debug( Rekord.Debugs.HASMANY_POSTSAVE, this, model, relation );
batchExecute(function()
{
relation.saving = true;
relation.delaySaving = true;
var models = relation.related;
for (var i = 0; i < models.length; i++)
{
var related = models[ i ];
if ( !related.$isDeleted() && related.$hasChanges() )
{
related.$save( this.cascadeSave, this.cascadeSaveOptions );
}
}
relation.saving = false;
relation.delaySaving = false;
}, this );
}
},
preRemove: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation && this.cascadeRemove )
{
Rekord.debug( Rekord.Debugs.HASMANY_PREREMOVE, this, model, relation );
batchExecute(function()
{
this.bulk( relation, function()
{
var models = relation.related;
for (var i = models.length - 1; i >= 0; i--)
{
var related = models[ i ];
related.$remove( this.cascadeRemove, this.cascadeRemoveOptions );
}
});
}, this );
}
},
handleModelAdded: function(relation)
{
return function (related, remoteData)
{
if ( relation.isRelated( related ) )
{
Rekord.debug( Rekord.Debugs.HASMANY_NINJA_ADD, this, relation, related );
this.addModel( relation, related, remoteData );
}
};
},
handleLazyLoad: function(relation, onRelated)
{
return function (relatedDatabase)
{
var related = relatedDatabase.filter( relation.isRelated );
Rekord.debug( Rekord.Debugs.HASMANY_LAZY_LOAD, this, relation, related );
if ( onRelated )
{
onRelated.call( this, related );
}
if ( related.length )
{
this.bulk( relation, function()
{
for (var i = 0; i < related.length; i++)
{
this.addModel( relation, related[ i ] );
}
});
}
else if ( this.query )
{
relation.query = this.executeQuery( relation.parent );
}
};
},
addModel: function(relation, related, remoteData)
{
if ( related.$isDeleted() || (this.where && !this.where( related, relation ) ) )
{
return;
}
var model = relation.parent;
var target = relation.related;
var key = related.$key();
var adding = !target.has( key );
if ( adding )
{
Rekord.debug( Rekord.Debugs.HASMANY_ADD, this, relation, related );
target.put( key, related );
related.$on( Model.Events.Removed, relation.onRemoved );
related.$on( Model.Events.SavedRemoteUpdate, relation.onSaved );
if ( this.where )
{
related.$on( Model.Events.Change, relation.onChange );
}
related.$dependents.add( model, this );
this.updateForeignKey( related, model, remoteData );
this.sort( relation );
this.checkSave( relation, remoteData );
}
return adding;
},
removeModel: function(relation, related, remoteData, dontClear)
{
if ( !this.canRemoveRelated( related, remoteData ) )
{
return;
}
var model = relation.parent;
var target = relation.related;
var pending = relation.pending;
var key = related.$key();
var removing = target.has( key );
if ( removing )
{
Rekord.debug( Rekord.Debugs.HASMANY_REMOVE, this, relation, related );
target.remove( key );
related.$off( Model.Events.Removed, relation.onRemoved );
related.$off( Model.Events.SavedRemoteUpdate, relation.onSaved );
related.$off( Model.Events.Change, relation.onChange );
related.$dependents.remove( model );
if ( !dontClear )
{
if ( this.clearKey )
{
this.clearForeignKey( related, remoteData );
}
if ( this.cascadeRemove )
{
if ( remoteData )
{
if ( canCascade( this.cascadeRemove, Cascade.Local ) )
{
related.$remove( Cascade.Local );
}
}
else
{
related.$remove( this.cascadeRemove, this.cascadeRemoveOptions );
}
}
}
this.sort( relation );
this.checkSave( relation, remoteData );
}
delete pending[ key ];
return removing;
},
isRelatedFactory: function(model)
{
var foreign = this.foreign;
var local = model.$db.key;
return function(related)
{
return propsMatch( related, foreign, model, local );
};
},
getTargetFields: function(target)
{
return this.foreign;
}
});
function HasManyThrough()
{
}
Rekord.Relations.hasManyThrough = HasManyThrough;
HasManyThrough.Defaults =
{
model: null,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
auto: true,
autoCascade: Cascade.All,
autoOptions: null,
property: true,
dynamic: false,
through: undefined,
local: null,
foreign: null,
comparator: null,
comparatorNullsFirst: false,
listenForRelated: true,
loadRelated: true,
where: false,
cascadeRemove: Cascade.NoRest,
cascadeSave: Cascade.All,
cascadeSaveOptions: null,
cascadeSaveRelated: Cascade.None,
cascadeSaveRelatedOptions: null,
saveParentCascade: Cascade.All,
saveParentOptions: null,
cascadeRemoveThroughOptions: null,
discriminator: 'discriminator',
discriminators: {},
discriminatorToModel: {}
};
Class.extend( RelationMultiple, HasManyThrough,
{
type: 'hasManyThrough',
debugAutoSave: Rekord.Debugs.HASMANYTHRU_AUTO_SAVE,
debugInitialGrabbed: Rekord.Debugs.HASMANYTHRU_INITIAL_GRABBED,
debugSort: Rekord.Debugs.HASMANYTHRU_SORT,
debugQuery: Rekord.Debugs.HASMANYTHRU_QUERY,
debugQueryResults: Rekord.Debugs.HASMANYTHRU_QUERY_RESULTS,
debugUpdateKey: Rekord.Debugs.HASMANYTHRU_UPDATE_KEY,
getDefaults: function(database, field, options)
{
return HasManyThrough.Defaults;
},
onInitialized: function(database, field, options)
{
if ( !this.discriminated )
{
var relatedDatabase = this.model.Database;
this.foreign = this.foreign || ( relatedDatabase.name + '_' + relatedDatabase.key );
}
this.local = this.local || ( database.name + '_' + database.key );
this.comparator = createComparator( this.comparator, this.comparatorNullsFirst );
if ( !isRekord( options.through ) )
{
Rekord.get( options.through ).complete( this.setThrough, this );
}
else
{
this.setThrough( options.through );
}
Rekord.debug( Rekord.Debugs.HASMANYTHRU_INIT, this );
},
setThrough: function(through)
{
this.through = through;
this.finishInitialization();
},
load: Gate(function(model, initialValue, remoteData)
{
var relator = this;
var throughDatabase = this.through.Database;
var relation = model.$relations[ this.name ] =
{
parent: model,
isRelated: this.isRelatedFactory( model ),
pending: {},
related: this.createRelationCollection( model ),
throughs: new Map(),
saving: false,
delaySorting: false,
delaySaving: false,
onRemoved: function() // this = model removed
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_NINJA_REMOVE, relator, model, this, relation );
relator.removeModel( relation, this );
},
onSaved: function() // this = model saved
{
if ( relation.saving )
{
return;
}
Rekord.debug( Rekord.Debugs.HASMANYTHRU_NINJA_SAVE, relator, model, this, relation );
relator.sort( relation );
relator.checkSave( relation );
},
onChange: function()
{
if ( relation.saving )
{
return;
}
if ( relator.where && !relator.where( this, relation ) )
{
relator.removeModel( relation, this );
}
},
onThroughRemoved: function() // this = through removed
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_NINJA_THRU_REMOVE, relator, model, this, relation );
relator.removeModelFromThrough( relation, this );
}
};
// Populate the model's key if it's missing
model.$on( Model.Events.PostSave, this.postSave, this );
model.$on( Model.Events.PreRemove, this.preRemove, this );
// When models are added to the related database, check if it's related to this model
if ( this.listenForRelated )
{
throughDatabase.on( Database.Events.ModelAdded, this.handleModelAdded( relation ), this );
}
// If the model's initial value is an array, populate the relation from it!
this.setInitial( model, initialValue, remoteData );
// We only need to set the property once since the underlying array won't change.
this.setProperty( relation );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
var throughDatabase = this.through.Database;
if ( isArray( initialValue ) )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_INITIAL, this, model, relation, initialValue );
this.grabModels( relation, initialValue, this.handleModel( relation, remoteData ), remoteData );
}
else if ( this.query )
{
relation.query = this.executeQuery( model );
}
else if ( this.loadRelated )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_INITIAL_PULLED, this, model, relation );
throughDatabase.ready( this.handleLazyLoad( relation ), this );
}
},
sync: function(model, removeUnrelated)
{
var throughDatabase = this.through.Database;
var relation = model.$relations[ this.name ];
if ( relation )
{
var existing = relation.throughs.values;
var remoteData = true;
var relator = this;
var onRelated = function(throughs)
{
if ( removeUnrelated )
{
var given = this.createCollection();
given.reset( throughs );
for (var i = 0; i < existing.length; i++)
{
var existingThrough = existing[ i ];
if ( !given.has( existingThrough.$key() ) )
{
relator.removeModelFromThrough( relation, existingThrough, remoteData );
}
}
}
};
throughDatabase.ready( this.handleLazyLoad( relation, onRelated ), this );
}
},
preClone: function(model, clone, properties)
{
var related = this.get( model );
if ( related )
{
clone[ this.name ] = related.slice();
}
},
postSave: function(model)
{
var relation = model.$relations[ this.name ];
batchExecute(function()
{
if ( relation && this.cascadeSave )
{
var throughs = relation.throughs.values;
for (var i = 0; i < throughs.length; i++)
{
var through = throughs[ i ];
if ( !through.$isDeleted() && through.$hasChanges() )
{
through.$save( this.cascadeSave, this.cascadeSaveOptions );
}
}
}
if ( relation && this.cascadeSaveRelated )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_PRESAVE, this, model, relation );
relation.saving = true;
relation.delaySaving = true;
var models = relation.related;
for (var i = 0; i < models.length; i++)
{
var related = models[ i ];
if ( !related.$isDeleted() && related.$hasChanges() )
{
related.$save( this.cascadeSaveRelated, this.cascadeSaveRelatedOptions );
}
}
relation.saving = false;
relation.delaySaving = false;
}
}, this );
},
preRemove: function(model)
{
var relation = model.$relations[ this.name ];
if ( relation && this.cascadeRemove )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_PREREMOVE, this, model, relation );
batchExecute(function()
{
this.bulk( relation, function()
{
var throughs = relation.throughs.values;
for (var i = 0; i < throughs.length; i++)
{
var through = throughs[ i ];
through.$remove( this.cascadeRemove, this.cascadeRemoveThroughOptions );
}
});
}, this );
}
},
handleModelAdded: function(relation)
{
return function (through, remoteData)
{
if ( relation.isRelated( through ) && !relation.throughs.has( through.$key() ) )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_NINJA_ADD, this, relation, through );
this.addModelFromThrough( relation, through, remoteData );
}
};
},
handleLazyLoad: function(relation, onRelated)
{
return function (throughDatabase)
{
var throughs = throughDatabase.filter( relation.isRelated );
Rekord.debug( Rekord.Debugs.HASMANYTHRU_LAZY_LOAD, this, relation, throughs );
if ( onRelated )
{
onRelated.call( this, throughs );
}
if ( throughs.length )
{
this.bulk( relation, function()
{
for (var i = 0; i < throughs.length; i++)
{
this.addModelFromThrough( relation, throughs[ i ] );
}
});
}
else if ( this.query )
{
relation.query = this.executeQuery( relation.parent );
}
};
},
addModel: function(relation, related, remoteData)
{
if ( related.$isDeleted() || (this.where && !this.where( related, relation ) ) )
{
return;
}
var adding = this.finishAddModel( relation, related, remoteData );
if ( adding )
{
this.addThrough( relation, related, remoteData );
}
return adding;
},
addThrough: function(relation, related, remoteData)
{
var throughDatabase = this.through.Database;
var throughKey = this.createThroughKey( relation, related );
throughDatabase.grabModel( throughKey, this.onAddThrough( relation, remoteData ), this, remoteData );
},
onAddThrough: function(relation, remoteData)
{
return function onAddThrough(through)
{
this.finishAddThrough( relation, through, remoteData );
};
},
addModelFromThrough: function(relation, through, remoteData)
{
if ( through.$isDeleted() )
{
return;
}
// TODO polymoprhic logic
var relatedDatabase = this.model.Database;
var relatedKey = relatedDatabase.keyHandler.buildKey( through, this.foreign );
relatedDatabase.grabModel( relatedKey, this.onAddModelFromThrough( relation, through, remoteData ), this, remoteData );
},
onAddModelFromThrough: function(relation, through, remoteData)
{
return function onAddModelFromThrough(related)
{
if ( related && ( !this.where || this.where( related, relation ) ) )
{
this.finishAddThrough( relation, through, remoteData );
this.finishAddModel( relation, related, remoteData );
}
};
},
finishAddThrough: function(relation, through, remoteData)
{
var model = relation.parent;
var throughs = relation.throughs;
var throughKey = through.$key();
var added = !throughs.has( throughKey );
if ( added )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_THRU_ADD, this, relation, through );
throughs.put( throughKey, through );
through.$on( Model.Events.Removed, relation.onThroughRemoved );
through.$dependents.add( model, this );
if ( !remoteData && this.cascadeSave )
{
if ( model.$isSaved() )
{
through.$save( this.cascadeSave, this.cascadeSaveOptions );
}
else
{
through.$save( Cascade.None );
}
}
}
return added;
},
finishAddModel: function(relation, related, remoteData)
{
var relateds = relation.related;
var relatedKey = related.$key();
var adding = !relateds.has( relatedKey );
if ( adding )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_ADD, this, relation, related );
relateds.put( relatedKey, related );
related.$on( Model.Events.Removed, relation.onRemoved );
related.$on( Model.Events.SavedRemoteUpdate, relation.onSaved );
if ( this.where )
{
related.$on( Model.Events.Change, relation.onChange );
}
this.sort( relation );
if ( !remoteData )
{
this.checkSave( relation );
}
}
return adding;
},
removeModel: function(relation, related, remoteData)
{
var relatedKey = related.$key();
var relateds = relation.related;
var actualRelated = relateds.get( relatedKey );
if ( actualRelated )
{
if ( this.removeThrough( relation, related, remoteData ) )
{
this.finishRemoveRelated( relation, relatedKey, remoteData );
}
}
},
removeThrough: function(relation, related, remoteData)
{
var throughDatabase = this.through.Database;
var keyObject = this.createThroughKey( relation, related );
var key = throughDatabase.keyHandler.getKey( keyObject );
var throughs = relation.throughs;
var through = throughs.get( key );
return this.finishRemoveThrough( relation, through, related, true, remoteData );
},
removeModelFromThrough: function(relation, through, remoteData)
{
var relatedDatabase = this.model.Database;
var relatedKey = relatedDatabase.keyHandler.buildKey( through, this.foreign );
if ( this.finishRemoveThrough( relation, through, undefined, undefined, remoteData ) )
{
this.finishRemoveRelated( relation, relatedKey, remoteData );
}
},
finishRemoveThrough: function(relation, through, related, callRemove, remoteData)
{
var model = relation.parent;
var removing = !!through;
if ( removing )
{
if ( !this.canRemoveRelated( through, remoteData ) )
{
return false;
}
Rekord.debug( Rekord.Debugs.HASMANYTHRU_THRU_REMOVE, this, relation, through, related );
var throughs = relation.throughs;
var throughKey = through.$key();
through.$off( Model.Events.Removed, relation.onThroughRemoved );
through.$dependents.remove( model );
if ( callRemove )
{
through.$remove( remoteData ? Cascade.Local : Cascade.All, this.cascadeRemoveThroughOptions );
}
throughs.remove( throughKey );
}
return removing;
},
finishRemoveRelated: function(relation, relatedKey, remoteData)
{
var pending = relation.pending;
var relateds = relation.related;
var related = relateds.get( relatedKey );
if ( related )
{
Rekord.debug( Rekord.Debugs.HASMANYTHRU_REMOVE, this, relation, related );
relateds.remove( relatedKey );
related.$off( Model.Events.Removed, relation.onRemoved );
related.$off( Model.Events.SavedRemoteUpdate, relation.onSaved );
related.$off( Model.Events.Change, relation.onChange );
this.sort( relation );
this.checkSave( relation, remoteData );
}
delete pending[ relatedKey ];
return related;
},
isRelatedFactory: function(model)
{
var foreign = model.$db.key;
var local = this.local;
return function(through)
{
return propsMatch( through, local, model, foreign );
};
},
createThroughKey: function(relation, related)
{
var model = relation.parent;
var modelKeys = model.$db.keyHandler;
var relatedKeys = this.model.Database.keyHandler;
var throughDatabase = this.through.Database;
var throughKey = throughDatabase.key;
var key = {};
for (var i = 0; i < throughKey.length; i++)
{
var prop = throughKey[ i ];
modelKeys.setKeyField( key, prop, related, this.foreign );
relatedKeys.setKeyField( key, prop, model, this.local );
}
return key;
},
getTargetFields: function(target)
{
return this.local;
}
});
function HasRemote()
{
}
Rekord.Relations.hasRemote = HasRemote;
HasRemote.Defaults =
{
model: undefined,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
auto: false,
property: true,
dynamic: false,
comparator: null,
comparatorNullsFirst: false,
where: false,
autoRefresh: false // Model.Events.RemoteGets
};
Class.extend( RelationMultiple, HasRemote,
{
type: 'hasRemote',
debugSort: Rekord.Debugs.HASREMOTE_SORT,
debugQuery: Rekord.Debugs.HASREMOTE_QUERY,
debugQueryResults: Rekord.Debugs.HASREMOTE_QUERY_RESULTS,
getDefaults: function(database, field, options)
{
return HasRemote.Defaults;
},
onInitialized: function(database, field, options)
{
this.comparator = createComparator( this.comparator, this.comparatorNullsFirst );
Rekord.debug( Rekord.Debugs.HASREMOTE_INIT, this );
this.finishInitialization();
},
load: Gate(function(model, initialValue, remoteData)
{
var relator = this;
var relation = model.$relations[ this.name ] =
{
parent: model,
pending: {},
related: this.createRelationCollection( model ),
delaySorting: false,
delaySaving: false,
onRemoved: function() // this = model removed
{
Rekord.debug( Rekord.Debugs.HASREMOTE_NINJA_REMOVE, relator, model, this, relation );
relator.removeModel( relation, this, true );
},
onSaved: function() // this = model saved
{
Rekord.debug( Rekord.Debugs.HASREMOTE_NINJA_SAVE, relator, model, this, relation );
relator.sort( relation );
relator.checkSave( relation );
},
onChange: function()
{
if ( relation.saving )
{
return;
}
if ( relator.where && !relator.where( this, relation ) )
{
relator.removeModel( relation, this, true );
}
}
};
// Populate the model's key if it's missing
model.$key();
// If auto refresh was specified, execute the query on refresh
if ( this.autoRefresh )
{
model.$on( this.autoRefresh, this.onRefresh( relation ), this );
}
// Execute query!
relation.query = this.executeQuery( model );
// We only need to set the property once since the underlying array won't change.
this.setProperty( relation );
}),
onRefresh: function(relation)
{
return function handleRefresh()
{
relation.query = this.executeQuery( relation.parent );
};
},
addModel: function(relation, related, remoteData)
{
if ( related.$isDeleted() || (this.where && !this.where( related, relation ) ) )
{
return;
}
var model = relation.parent;
var target = relation.related;
var key = related.$key();
var adding = !target.has( key );
if ( adding )
{
Rekord.debug( Rekord.Debugs.HASMANY_ADD, this, relation, related );
target.put( key, related );
related.$on( Model.Events.Removed, relation.onRemoved );
related.$on( Model.Events.SavedRemoteUpdate, relation.onSaved );
if ( this.where )
{
related.$on( Model.Events.Change, relation.onChange );
}
this.sort( relation );
this.checkSave( relation, remoteData );
}
return adding;
},
removeModel: function(relation, related, remoteData)
{
if ( !this.canRemoveRelated( related, remoteData ) )
{
return;
}
var model = relation.parent;
var target = relation.related;
var pending = relation.pending;
var key = related.$key();
if ( target.has( key ) )
{
Rekord.debug( Rekord.Debugs.HASMANY_REMOVE, this, relation, related );
target.remove( key );
related.$off( Model.Events.Removed, relation.onRemoved );
related.$off( Model.Events.SavedRemoteUpdate, relation.onSaved );
related.$off( Model.Events.Change, relation.onChange );
this.sort( relation );
this.checkSave( relation, remoteData );
}
delete pending[ key ];
}
});
function HasList()
{
}
Rekord.Relations.hasList = HasList;
HasList.Defaults =
{
model: undefined,
lazy: false,
store: Store.Model,
save: Save.Model,
auto: false,
property: true,
dynamic: false,
comparator: null,
comparatorNullsFirst: false
};
Class.extend( RelationMultiple, HasList,
{
type: 'hasList',
debugSort: Rekord.Debugs.HASLIST_SORT,
getDefaults: function(database, field, options)
{
return HasList.Defaults;
},
onInitialized: function(database, field, options)
{
this.comparator = createComparator( this.comparator, this.comparatorNullsFirst );
Rekord.debug( Rekord.Debugs.HASLIST_INIT, this );
this.finishInitialization();
},
load: Gate(function(model, initialValue, remoteData)
{
var relator = this;
var relation = model.$relations[ this.name ] =
{
parent: model,
pending: {},
related: this.createRelationCollection( model ),
delaySorting: false,
delaySaving: false,
onRemoved: function() // this = model removed
{
Rekord.debug( Rekord.Debugs.HASLIST_NINJA_REMOVE, relator, model, this, relation );
relator.removeModel( relation, this, true );
},
onSaved: function() // this = model saved
{
Rekord.debug( Rekord.Debugs.HASLIST_NINJA_SAVE, relator, model, this, relation );
relator.sort( relation );
relator.checkSave( relation );
}
};
// If the model's initial value is an array, populate the relation from it!
this.setInitial( model, initialValue, remoteData );
// We only need to set the property once since the underlying array won't change.
this.setProperty( relation );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
if ( isArray( initialValue ) )
{
Rekord.debug( Rekord.Debugs.HASLIST_INITIAL, this, model, relation, initialValue );
this.grabModels( relation, initialValue, this.handleModel( relation, remoteData ), remoteData );
}
},
addModel: function(relation, related, remoteData)
{
if ( related.$isDeleted() )
{
return;
}
var model = relation.parent;
var target = relation.related;
var key = related.$key();
var adding = !target.has( key );
if ( adding )
{
Rekord.debug( Rekord.Debugs.HASLIST_ADD, this, relation, related );
target.put( key, related );
related.$on( Model.Events.Removed, relation.onRemoved );
related.$on( Model.Events.SavedRemoteUpdate, relation.onSaved );
this.sort( relation );
if ( !remoteData )
{
this.checkSave( relation );
}
}
return adding;
},
removeModel: function(relation, related, remoteData)
{
if ( !this.canRemoveRelated( related, remoteData ) )
{
return;
}
var model = relation.parent;
var target = relation.related;
var pending = relation.pending;
var key = related.$key();
if ( target.has( key ) )
{
Rekord.debug( Rekord.Debugs.HASLIST_REMOVE, this, relation, related );
target.remove( key );
related.$off( Model.Events.Removed, relation.onRemoved );
related.$off( Model.Events.SavedRemoteUpdate, relation.onSaved );
this.sort( relation );
this.checkSave( relation );
}
delete pending[ key ];
},
postClone: function(model, clone, properties)
{
var related = this.get( model );
if ( related )
{
var relatedClones = [];
for (var i = 0; i < related.length; i++)
{
relatedClones.push( related[ i ].$clone() );
}
clone[ this.name ] = relatedClones;
}
}
});
function HasReference()
{
}
Rekord.Relations.hasReference = HasReference;
HasReference.Defaults =
{
model: null,
lazy: false,
query: false,
store: Store.None,
save: Save.None,
property: true,
dynamic: false
};
Class.extend( RelationSingle, HasReference,
{
type: 'hasReference',
debugInit: Rekord.Debugs.HASREFERENCE_INIT,
debugClearModel: Rekord.Debugs.HASREFERENCE_CLEAR_MODEL,
debugSetModel: Rekord.Debugs.HASREFERENCE_SET_MODEL,
debugLoaded: Rekord.Debugs.HASREFERENCE_LOADED,
debugQuery: Rekord.Debugs.HASREFERENCE_QUERY,
debugQueryResults: Rekord.Debugs.HASREFERENCE_QUERY_RESULTS,
getDefaults: function(database, field, options)
{
return HasReference.Defaults;
},
load: Gate(function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ] =
{
parent: model,
related: null,
loaded: false,
dirty: false,
onRemoved: function()
{
Rekord.debug( Rekord.Debugs.HASREFERENCE_NINJA_REMOVE, this, model, relation );
this.clearRelated( relation, false, true );
}
};
this.setInitial( model, initialValue, remoteData );
}),
setInitial: function(model, initialValue, remoteData)
{
var relation = model.$relations[ this.name ];
if ( !isEmpty( initialValue ) )
{
Rekord.debug( Rekord.Debugs.HASREFERENCE_INITIAL, this, model, initialValue );
this.grabModel( initialValue, this.handleModel( relation ), remoteData, relation );
}
else if ( this.query )
{
relation.query = this.executeQuery( model );
}
},
preClone: function(model, clone, properties)
{
var related = this.get( model );
if ( related )
{
clone[ this.name ] = related.$clone( properties );
}
},
isDependent: function(relation, related)
{
return false;
},
updateForeignKey: function()
{
// nothing
},
clearForeignKey: function()
{
// nothing
},
});
var Polymorphic =
{
setReferences: function(database, field, options)
{
this.isRelatedFactory = this.isRelatedDiscriminatedFactory( this.isRelatedFactory );
this.loadDiscriminators(function()
{
this.onInitialized( database, field, options );
});
},
isRelatedDiscriminatedFactory: function(isRelatedFactory)
{
return function (model)
{
var isRelated = isRelatedFactory.call( this, model );
var discriminatorField = this.discriminator;
if (this.hasDiscriminator)
{
return function(related)
{
if ( !isRelated( related ) )
{
return false;
}
var discriminator = this.getDiscriminatorForModel( related );
return equals( discriminator, model[ discriminatorField ] );
};
}
else
{
var discriminator = this.getDiscriminatorForModel( model );
return function (related)
{
if ( !isRelated( related ) )
{
return false;
}
return equals( discriminator, related[ discriminatorField ] );
};
}
};
},
loadDiscriminators: function(onLoad)
{
var discriminators = this.discriminators;
var total = sizeof( discriminators );
var loaded = 0;
function handleLoaded()
{
if ( ++loaded === total )
{
onLoad.apply( this );
}
}
for (var name in discriminators)
{
var discriminator = discriminators[ name ];
Rekord.get( name ).complete( this.setDiscriminated( discriminator, handleLoaded ), this );
}
},
setDiscriminated: function(discriminator, onLoad)
{
return function(rekord)
{
this.discriminators[ rekord.Database.name ] = discriminator;
this.discriminators[ rekord.Database.className ] = discriminator;
this.discriminatorToModel[ discriminator ] = rekord;
onLoad.apply( this );
};
},
createRelationCollection: function(model)
{
return DiscriminateCollection( RelationCollection.create( undefined, model, this ), this.discriminator, this.discriminatorToModel );
},
createCollection: function()
{
return DiscriminateCollection( ModelCollection.create(), this.discriminator, this.discriminatorToModel );
},
ready: function(callback)
{
var models = this.discriminatorToModel;
for ( var prop in models )
{
var model = models[ prop ];
model.Database.ready( callback, this );
}
},
listenToModelAdded: function(callback)
{
var models = this.discriminatorToModel;
for ( var prop in models )
{
var model = models[ prop ];
model.Database.on( Database.Events.ModelAdded, callback, this );
}
},
executeQuery: function(model)
{
var queryOption = this.query;
var queryOptions = this.queryOptions;
var queryData = this.queryData;
var query = isString( queryOption ) ? format( queryOption, model ) : queryOption;
var search = model.search( query, queryOptions );
if ( isObject( queryData ) )
{
search.$set( queryData );
}
DiscriminateCollection( search.$results, this.discriminator, this.discriminatorToModel );
var promise = search.$run();
promise.complete( this.handleExecuteQuery( model ), this );
return search;
},
parseModel: function(input, remoteData, relation)
{
if ( input instanceof Model )
{
return input;
}
else if ( isObject( input ) )
{
var db = this.hasDiscriminator ?
this.getDiscriminatorDatabase( relation.parent ) :
this.getDiscriminatorDatabase( input );
if ( db )
{
return db.parseModel( input, remoteData );
}
}
return false;
},
clearFields: function(target, targetFields, remoteData)
{
var changes = clearFieldsReturnChanges( target, targetFields );
if ( target[ this.discriminator ] )
{
target[ this.discriminator ] = null;
changes = true;
}
if ( changes && !remoteData && this.auto && !target.$isNew() )
{
target.$save( this.autoCascade, this.autoOptions );
}
return changes;
},
updateFields: function(target, targetFields, source, sourceFields, remoteData)
{
var changes = updateFieldsReturnChanges( target, targetFields, source, sourceFields );
var targetField = this.discriminator;
var targetValue = target[ targetField ];
var sourceValue = this.getDiscriminatorForModel( source );
if ( !equals( targetValue, sourceValue ) )
{
target[ targetField ] = sourceValue;
changes = true;
}
if ( changes )
{
if ( this.auto && !target.$isNew() && !remoteData )
{
target.$save( this.autoCascade, this.autoOptions );
}
target.$trigger( Model.Events.KeyUpdate, [target, source, targetFields, sourceFields] );
}
return changes;
},
grabInitial: function( model, fields )
{
if ( this.hasDiscriminator && hasFields( model, fields, isValue ) )
{
var related = this.getDiscriminatorDatabase( model );
if ( related )
{
var initial = {};
updateFieldsReturnChanges( initial, related.key, model, fields );
return initial;
}
}
},
grabModel: function(input, callback, remoteData, relation)
{
if ( input instanceof Model )
{
callback.call( this, input );
}
// At the moment I don't think this will ever work - if we are given a plain
// object we can't really determine the related database.
else if ( isObject( input ) )
{
var db = this.hasDiscriminator ?
this.getDiscriminatorDatabase( relation.parent ) :
this.getDiscriminatorDatabase( input );
if ( db !== false )
{
db.grabModel( input, callback, this, remoteData );
}
}
},
grabModels: function(relation, initial, callback, remoteData)
{
for (var i = 0; i < initial.length; i++)
{
var input = initial[ i ];
if ( input instanceof Model )
{
relation.pending[ input.$key() ] = true;
callback.call( this, input );
}
// At the moment I don't think this will ever work - if we are given a plain
// object we can't really determine the related database.
else if ( isObject( input ) )
{
var db = this.getDiscriminatorDatabase( input );
if ( db )
{
var key = db.keyHandler.buildKeyFromInput( input );
relation.pending[ key ] = true;
db.grabModel( input, callback, this, remoteData );
}
}
}
},
ownsForeignKey: function()
{
return true;
},
isModelArray: function(input)
{
return isArray( input );
},
getDiscriminator: function(model)
{
return model[ this.discriminator ];
},
getDiscriminatorDatabase: function(model)
{
var discriminator = this.getDiscriminator( model );
var model = this.discriminatorToModel[ discriminator ];
return model ? model.Database : false;
},
getDiscriminatorForModel: function(model)
{
return this.discriminators[ model.$db.name ];
}
};
Rekord.shard = function(methods)
{
return function createRestSharding(database)
{
var shard = new Shard( database );
Class.props( shard, methods );
shard.initialize( database );
return shard;
};
};
function Shard(database)
{
this.database = database;
}
Class.create( Shard,
{
STATUS_FAIL_ALL: 500,
STATUS_FAIL_GET: 500,
STATUS_FAIL_CREATE: 500,
STATUS_FAIL_UPDATE: 500,
STATUS_FAIL_REMOVE: 500,
STATUS_FAIL_QUERY: 500,
ATOMIC_ALL: false,
ATOMIC_GET: false,
ATOMIC_CREATE: true,
ATOMIC_UPDATE: true,
ATOMIC_REMOVE: false,
ATOMIC_QUERY: true,
getShards: function(forRead)
{
throw 'getShards not implemented';
},
getShardForModel: function(model, forRead)
{
throw 'getShardForModel not implemented';
},
getShardsForModel: function(model, forRead)
{
var single = this.getShardForModel( model, forRead );
return single ? [ single ] : this.getShards( forRead );
},
getShardsForQuery: function(url, query)
{
return this.getShards();
},
initialize: function(database)
{
},
all: function(options, success, failure)
{
var shards = this.getShards( true );
var all = [];
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.all( options, onShardSuccess, onShardFailure );
}
function onSuccess(models)
{
if ( isArray( models ) )
{
all.push.apply( all, models );
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( successful || (all.length && !this.ATOMIC_ALL) )
{
success( all );
}
else if ( !alreadyFailed )
{
failure( all, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_ALL );
}
}
this.multiplex( shards, this.ATOMIC_ALL, invoke, onSuccess, failure, onComplete );
},
get: function(model, options, success, failure)
{
var shards = this.getShardsForModel( model, true );
var gotten = null;
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.get( model, options, onShardSuccess, onShardFailure );
}
function onSuccess(data)
{
if ( gotten === null && isObject( data ) )
{
gotten = data;
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( gotten !== null )
{
success( gotten );
}
else
{
failure( gotten, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_GET );
}
}
this.multiplex( shards, this.ATOMIC_GET, invoke, onSuccess, noop, onComplete );
},
create: function( model, encoded, options, success, failure )
{
var shards = this.getShardsForModel( model, false );
var returned = null;
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.create( model, encoded, options, onShardSuccess, onShardFailure );
}
function onSuccess(data)
{
if ( returned === null && isObject( returned ) )
{
returned = data;
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( successful )
{
success( returned );
}
else
{
failure( returned, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_CREATE );
}
}
this.multiplex( shards, this.ATOMIC_CREATE, invoke, onSuccess, noop, onComplete );
},
update: function( model, encoded, options, success, failure )
{
var shards = this.getShardsForModel( model, false );
var returned = null;
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.update( model, encoded, options, onShardSuccess, onShardFailure );
}
function onSuccess(data)
{
if ( returned === null && isObject( returned ) )
{
returned = data;
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( successful )
{
success( returned );
}
else
{
failure( returned, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_UPDATE );
}
}
this.multiplex( shards, this.ATOMIC_UPDATE, invoke, onSuccess, noop, onComplete );
},
remove: function( model, options, success, failure )
{
var shards = this.getShardsForModel( model, false );
var returned = null;
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.remove( model, options, onShardSuccess, onShardFailure );
}
function onSuccess(data)
{
if ( returned === null && isObject( returned ) )
{
returned = data;
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( successful )
{
success( returned );
}
else
{
failure( returned, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_REMOVE );
}
}
this.multiplex( shards, this.ATOMIC_REMOVE, invoke, onSuccess, noop, onComplete );
},
query: function( url, query, options, success, failure )
{
var shards = this.getShardsForQuery( url, query );
var results = [];
function invoke(shard, onShardSuccess, onShardFailure)
{
shard.query( url, query, options, onShardSuccess, onShardFailure );
}
function onSuccess(models)
{
if ( isArray( models ) )
{
results.push.apply( results, models );
}
}
function onComplete(successful, alreadyFailed, failedStatus)
{
if ( successful || (results.length && !this.ATOMIC_QUERY) )
{
success( results );
}
else if ( !alreadyFailed )
{
failure( results, isDefined( failedStatus ) ? failedStatus : this.STATUS_FAIL_QUERY );
}
}
this.multiplex( shards, this.ATOMIC_QUERY, invoke, onSuccess, noop, onComplete );
},
multiplex: function(shards, atomic, invoke, onSuccess, onFailure, onComplete)
{
var successful = true;
var failureCalled = false;
var failedStatus;
var total = 0;
function onShardComplete()
{
if ( ++total === shards.length )
{
onComplete.call( this, successful, failureCalled, failedStatus );
}
}
function onShardSuccess(data)
{
if ( successful || !atomic )
{
onSuccess.apply( this, arguments );
}
onShardComplete();
}
function onShardFailure(data, status)
{
if ( successful )
{
successful = false;
if ( atomic )
{
failureCalled = true;
onFailure.apply( this, arguments );
}
}
if ( isNumber( status ) && (failedStatus === undefined || status < failedStatus) )
{
failedStatus = status;
}
onShardComplete();
}
if ( !isArray( shards ) || shards.length === 0 )
{
onComplete.call( this, false, false, failedStatus );
}
else
{
for (var i = 0; i < shards.length; i++)
{
invoke.call( this, shards[ i ], onShardSuccess, onShardFailure );
}
}
}
});
addPlugin(function(model, db, options)
{
/**
* Returns the reference to the collection which contains all saved models.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var t0 = Task.create({name: 't0', done: true}); // saves
* var t1 = new Task({name: 't1'});
* Task.all(); // [t0]
* ```
*
* @method all
* @memberof Rekord.Model
* @return {Rekord.ModelCollection} -
* The reference to the collection of models.
*/
model.all = function()
{
return db.models;
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a collection of models.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var t0 = Task.create({id: 34, name: 't0'});
* var t1 = new Task({name: 't1'});
* var t2 = {name: 't2'};
*
* var c = Task.collect( 34, t1, t2 ); // or Task.collect( [34, t1, t2] )
* c; // [t0, t1, t2]
* ```
*
* @method collect
* @memberof Rekord.Model
* @param {modelInput[]|...modelInput} models -
* The array of models to to return as a collection.
* @return {Rekord.ModelCollection} -
* The collection created.
*/
model.array = function(a)
{
var models = arguments.length > 1 || !isArray(a) ?
AP.slice.call( arguments ) : a;
return ModelCollection.native( db, models );
};
});
addPlugin(function(model, db, options)
{
/**
* Returns the model at the given index.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var t0 = Task.create({name: 't0', done: true}); // saves
* var t1 = new Task({name: 't1'});
* Task.at( 0 ); // t0
* ```
*
* @method at
* @memberof Rekord.Model
* @param {Number} index -
* The index of the model to return.
* @return {Rekord.Model} -
* The reference to the model at the given index.
*/
model.at = function(index)
{
return db.models[ index ];
};
});
addPlugin(function(model, db, options)
{
/**
* Returns an instance of a model or model collection with remote data (from
* the server). If the model(s) exist locally then the values passed in will
* overwrite the current values of the models. This is typically used to
* bootstrap data from the server in your webpage.
*
* ```javascript
* var User = Rekord({
* fields: ['name', 'email']
* });
* var currentUser = User.boot({
* id: 1234,
* name: 'Administrator',
* email: 'rekordjs@gmail.com'
* });
* var friends = User.boot([
* { id: 'c1', name: 'Cat 1', email: 'cat1@gmail.com' },
* { id: 'c2', name: 'Cat 2', email: 'cat2@gmail.com' }
* ]);
* ```
*
* @method boot
* @memberof Rekord.Model
* @param {modelInput[]|Object}
* @return {Rekord.ModelCollection|Rekord.Model} -
* The collection or model bootstrapped.
*/
model.boot = function( input )
{
if ( isArray( input ) )
{
return ModelCollection.create( db, input, true );
}
else if ( isObject( input ) )
{
return db.putRemoteData( input );
}
return input;
};
});
addPlugin(function(model, db, options)
{
model.clear = function(removeListeners)
{
return db.clear( removeListeners );
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a collection of models.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var t0 = Task.create({id: 34, name: 't0'});
* var t1 = new Task({name: 't1'});
* var t2 = {name: 't2'};
*
* var c = Task.collect( 34, t1, t2 ); // or Task.collect( [34, t1, t2] )
* c; // [t0, t1, t2]
* ```
*
* @method collect
* @memberof Rekord.Model
* @param {modelInput[]|...modelInput} models -
* The array of models to to return as a collection.
* @return {Rekord.ModelCollection} -
* The collection created.
*/
model.collect = function(a)
{
var models = arguments.length > 1 || !isArray(a) ?
AP.slice.call( arguments ) : a;
return ModelCollection.create( db, models );
};
});
addPlugin(function(model, db, options)
{
/**
* Counts the number of models which pass the given where expression.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var t0 = Task.create({name: 't0', done: true}); // saves
* var t1 = Task.create({name: 't1', done: false});
* Task.count('done', true); // 1
* ```
*
* @method count
* @memberof Rekord.Model
* @return {Number} -
* The number of models which pass the given where expression.
*/
model.count = function(properties, value, equals)
{
return db.models.countWhere( properties, value, equals );
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a model instance, saves it, and returns it.
*
* ```javascript
* var Task = Rekord({
* fields: ['name'],
* defaults: {
* name: 'New Task'
* }
* });
* var t0 = Task.create({id: 34, name: 't0'});
* var t1 = Task.create({name: 't1'}); // id generated with uuid
* var t2 = Task.create(); // name populated with default 'New Task'
* ```
*
* @method create
* @memberof Rekord.Model
* @param {Object} [props] -
* The initial values for the new model - if any.
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.Model} -
* The saved model instance.
*/
model.create = function( props, cascade, options )
{
var instance = isObject( props ) ?
db.createModel( props ) :
db.instantiate();
instance.$save( cascade, options );
return instance;
};
});
addPlugin(function(model, db, options)
{
var dynamics = collapse( options.dynamic, Defaults.dynamic );
if ( !isEmpty( dynamics ) )
{
for ( var property in dynamics )
{
addDynamicProperty( model.prototype, property, dynamics[ property ] );
}
}
});
function addDynamicProperty(modelPrototype, property, definition)
{
var get = isFunction( definition ) ? definition :
( isObject( definition ) && isFunction( definition.get ) ? definition.get : noop );
var set = isObject( definition ) && isFunction( definition.set ) ? definition.set : noop;
if ( Object.defineProperty )
{
Object.defineProperty( modelPrototype, property,
{
configurable: false,
enumerable: true,
get: get,
set: set
});
}
else
{
var $init = modelPrototype.$init;
modelPrototype.$init = function()
{
$init.apply( this, arguments );
var lastCalculatedValue = this[ property ] = get.apply( this );
var handleChange = function()
{
var current = this[ property ];
if ( current !== lastCalculatedValue )
{
set.call( this, current );
}
else
{
lastCalculatedValue = this[ property ] = get.apply( this );
}
};
this.$after( Model.Events.Changes, handleChange, this );
};
}
}
addPlugin(function(model, db, options)
{
var events = collapse( options.events, Defaults.events );
if ( !isEmpty( events ) )
{
var modelEvents = [];
var databaseEvents = [];
for ( var eventType in events )
{
var callback = events[ eventType ];
var eventName = toCamelCase( eventType );
var databaseEventString = Database.Events[ eventName ];
var modelEventString = Model.Events[ eventName ];
if ( databaseEventString )
{
parseEventListeners( databaseEventString, callback, false, databaseEvents );
}
if ( modelEventString )
{
parseEventListeners( modelEventString, callback, true, modelEvents );
}
}
applyEventListeners( db, databaseEvents );
if ( modelEvents.length )
{
Class.replace( model, '$init', function($init)
{
return function()
{
$init.apply( this, arguments );
applyEventListeners( this, modelEvents );
};
});
}
}
});
function parseEventListeners(events, callback, secret, out)
{
var map = {
on: secret ? '$on' : 'on',
once: secret ? '$once' : 'once',
after: secret ? '$after' : 'after'
};
var listeners = out || [];
if ( isFunction( callback ) )
{
listeners.push(
{
when: map.on,
events: events,
invoke: callback
});
}
else if ( isArray( callback ) && callback.length === 2 && isFunction( callback[0] ) )
{
listeners.push(
{
when: map.on,
events: events,
invoke: callback[0],
context: callback[1]
});
}
else if ( isObject( callback ) )
{
for ( var eventType in callback )
{
if ( eventType in map )
{
var subcallback = callback[ eventType ];
var when = map[ eventType ];
if ( isFunction( subcallback ) )
{
listeners.push(
{
when: when,
events: events,
invoke: subcallback
});
}
else if ( isArray( subcallback ) && subcallback.length === 2 && isFunction( subcallback[0] ) )
{
listeners.push(
{
when: when,
events: events,
invoke: subcallback[0],
context: subcallback[1]
});
}
}
}
}
return listeners;
}
function applyEventListeners(target, listeners)
{
for (var i = 0; i < listeners.length; i++)
{
var l = listeners[ i ];
target[ l.when ]( l.events, l.invoke, l.context );
}
}
addPlugin(function(model, db, options)
{
var extend = options.extend || Defaults.extend;
if ( !isRekord( extend ) )
{
return;
}
var defaults = Defaults;
var edb = extend.Database;
var eoptions = edb.options;
function tryOverwrite(option)
{
if ( !options[ option ] )
{
db[ option ] = edb[ option ];
}
}
function tryMerge(option)
{
var dbo = db[ option ];
var edbo = edb[ option ];
for (var prop in edbo)
{
if ( !(prop in dbo ) )
{
dbo[ prop ] = edbo[ prop ];
}
}
}
function tryUnshift(options, sourceOptions)
{
var source = edb[ sourceOptions || options ];
var target = db[ options ];
for (var i = source.length - 1; i >= 0; i--)
{
var k = indexOf( target, source[ i ] );
if ( k !== false )
{
target.splice( k, 1 );
}
target.unshift( source[ i ] );
}
}
tryOverwrite( 'keySeparator' );
tryMerge( 'defaults' );
tryMerge( 'ignoredFields' );
tryOverwrite( 'loadRelations' );
tryOverwrite( 'load' );
tryOverwrite( 'autoRefresh' );
tryOverwrite( 'cache' );
tryOverwrite( 'fullSave' );
tryOverwrite( 'fullPublish' );
tryMerge( 'encodings' );
tryMerge( 'decodings' );
tryOverwrite( 'summarize' );
tryUnshift( 'fields' );
tryUnshift( 'saveFields', 'fields' );
if ( !options.comparator )
{
db.setComparator( eoptions.comparator, eoptions.comparatorNullsFirst );
}
if ( !options.revision )
{
db.setRevision( eoptions.revision );
}
if ( !options.summarize )
{
db.setSummarize( eoptions.summarize );
}
for (var name in edb.relations)
{
if ( name in db.relations )
{
continue;
}
var relation = edb.relations[ name ];
var relationCopy = new relation.constructor();
relationCopy.init( db, name, relation.options );
if ( relationCopy.save )
{
db.saveFields.push( name );
}
db.relations[ name ] = relationCopy;
db.relationNames.push( name );
}
db.rest = Rekord.rest( db );
db.store = Rekord.store( db );
db.live = Rekord.live( db );
});
addPlugin(function(model, db, options)
{
/**
* Gets the local model matching the given input (or creates one) and loads
* it from the remote source ({@link Rekord.rest}). If `callback` is specified
* then it is invoked with the instance once it's loaded.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var t0 = Task.fetch( 34, function(task) {
* task; // {id: 34 name: 'Remotely Loaded'}
* });
* t0; // {id: 34} until remotely loaded
* ```
*
* @method fetch
* @memberof Rekord.Model
* @param {modelInput} input -
* The model input used to determine the key and load the model.
* @param {Any} [options] -
* The options to pass to the REST service.
* @param {Function} [callback] -
* The function to invoke passing the reference of the model once it's
* successfully remotely loaded.
* @param {Object} [context] -
* The context (this) for the callback.
* @return {Rekord.Model} -
* The model instance.
*/
model.fetch = function( input, options, callback, context )
{
var key = db.keyHandler.buildKeyFromInput( input );
var instance = db.get( key );
if ( !instance )
{
instance = db.keyHandler.buildObjectFromKey( key );
if ( isObject( input ) )
{
instance.$set( input );
}
}
if ( isFunction( callback ) )
{
var callbackContext = context || this;
instance.$once( Model.Events.RemoteGets, function()
{
callback.call( callbackContext, instance );
});
}
instance.$refresh( Cascade.Rest, options );
return instance;
};
});
addPlugin(function(model, db, options)
{
/**
* Returns the collection of all local models and tries to reload them (and
* any additional models returned) from a remote source ({@link Rekord.rest}).
* If `callback` is specified then it is invoked with the collections all
* models once it's loaded.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var tasks0 = Task.fetchAll( function(tasks1) {
* tasks0 // tasks1
* });
* ```
*
* @method fetchAll
* @memberof Rekord.Model
* @param {Function} [callback] -
* The function to invoke passing the reference of the model collection
* when it's successfully remotely loaded.
* @param {Object} [context] -
* The context (this) for the callback.
* @return {Rekord.ModelCollection} -
* The collection of all models of this type.
*/
model.fetchAll = function(callback, context)
{
db.refresh( callback, context );
return db.models;
};
});
addPlugin(function(model, db, options)
{
var files = options.files || Defaults.files;
if ( !isObject( files ) )
{
return;
}
if ( !isFilesSupported() )
{
Rekord.trigger( Rekord.Events.FilesNotSupported );
return;
}
for (var field in files)
{
var fieldOption = files[ field ];
if ( isString( fieldOption ) )
{
fieldOption = {
type: fieldOption
};
}
db.decodings[ field ] = FileDecodings[ fieldOption.type ]( db, fieldOption );
db.encodings[ field ] = FileEncoder;
}
});
/**
files: {
field: {
type: 'text', // base64, dataURL, resource
processor: 'processor_name',
capacity: 1024 * 1024, // maximum bytes
types: ['image/png', 'image/jpg', 'image/gif'], // acceptable MIME types
autoSave: true,
store: true,
save: true
}
}
**/
Rekord.fileProcessors = {};
Rekord.Events.FilesNotSupported = 'files-not-supported';
Rekord.Events.FileTooLarge = 'file-too-large';
Rekord.Events.FileWrongType = 'file-wrong-type';
Rekord.Events.FileOffline = 'file-offline';
// {
// fileToValue(file, model, field, callback),
// valueToUser(value, model, field, callback)
// }
Rekord.addFileProcessor = function(name, methods)
{
Rekord.fileProcessors[ name ] = methods;
};
Rekord.fileProperties =
[
'lastModifiedDate', 'name', 'size', 'type'
];
function isFilesSupported()
{
return win.File && win.FileReader && win.FileList;
}
function toFile(input)
{
if ( input instanceof win.File )
{
return input;
}
else if ( input instanceof win.Blob )
{
return input;
}
else if ( input instanceof win.FileList && input.length > 0 )
{
return input[0];
}
return false;
}
function convertNone(x)
{
return x;
}
function convertBase64(x)
{
var i = isString( x ) ? x.indexOf(';base64,') : -1;
return i === -1 ? x : x.substring( i + 8 );
}
function trySave(model, options)
{
if ( options.autoSave && model.$isSaved() )
{
model.$save();
}
}
function putFileCache(model, property, value, file, options)
{
model.$files = model.$files || {};
model.$files[ property ] = {
value: value,
user: value,
file: file,
options: options
};
}
function setFilesValue(processor, value, model, property, options)
{
var result;
var done = false;
if ( processor && processor.valueToUser )
{
processor.valueToUser( value, model, property, function(user)
{
model.$files[ property ].user = user;
if ( done )
{
model[ property ] = user;
trySave( model, options );
}
else
{
result = user;
}
});
}
else
{
result = value;
}
done = true;
return result;
}
function fileReader(method, converter, options)
{
var processor = Rekord.fileProcessors[ options.processor ];
if ( !(method in win.FileReader.prototype) )
{
Rekord.trigger( Rekord.Events.FilesNotSupported );
}
return function(input, model, property)
{
var file = toFile( input );
if ( file !== false )
{
var reader = new win.FileReader();
var result;
var done = false;
reader.onload = function(e)
{
var value = converter( e.target.result );
putFileCache( model, property, value, file, options );
result = setFilesValue( processor, value, model, property, options );
if ( done )
{
model[ property ] = result;
trySave( model, options );
}
};
reader[ method ]( file );
done = true;
return result;
}
else if ( isObject( input ) && input.FILE )
{
var result;
var setter = function(value)
{
result = value;
};
Rekord.trigger( Rekord.Events.FileOffline, [input, model, property, setter] );
return result;
}
else
{
putFileCache( model, property, input, null, options );
return setFilesValue( processor, input, model, property, options );
}
};
}
var FileDecodings =
{
text: function(db, options)
{
return fileReader( 'readAsText', convertNone, options );
},
dataURL: function(db, options)
{
return fileReader( 'readAsDataURL', convertNone, options );
},
base64: function(db, options)
{
return fileReader( 'readAsDataURL', convertBase64, options );
},
resource: function(db, options)
{
return function(input, model, property)
{
var file = toFile( input );
var processor = Rekord.fileProcessors[ options.processor ];
if ( !processor )
{
throw 'Processor required for resource files.';
}
if ( file !== false )
{
if ( isNumber( options.capacity ) && isNumber( file.size ) && file.size > options.capacity )
{
Rekord.trigger( Rekord.Events.FileTooLarge, [file, model, property] );
return;
}
if ( isArray( options.types ) && isString( file.type ) && indexOf( options.types, file.type ) === false )
{
Rekord.trigger( Rekord.Events.FileWrongType, [file, model, property] );
return;
}
var result;
var done = false;
processor.fileToValue( file, model, property, function(value)
{
putFileCache( model, property, value, file, options );
result = setFilesValue( processor, value, model, property, options );
if ( done )
{
model[ property ] = result;
trySave( model, options );
}
});
done = true;
return result;
}
else if ( isObject( input ) && input.FILE )
{
Rekord.trigger( Rekord.Events.FileOffline, [input, model, property] );
}
else
{
putFileCache( model, property, input, null, options );
return setFilesValue( processor, input, model, property, options );
}
};
}
};
function FileEncoder(input, model, field, forSaving)
{
if ( model.$files && field in model.$files )
{
var cached = model.$files[ field ];
if ( (forSaving && cached.save === false) || (!forSaving && cached.store === false) )
{
return;
}
if ( !forSaving && cached.file )
{
var props = grab( cached.file, Rekord.fileProperties, false );
props.FILE = true;
return props;
}
if ( input === cached.user )
{
if ( forSaving && cached.file )
{
model.$once( Model.Events.RemoteSave, function()
{
delete cached.file;
model.$addOperation( SaveLocal, Cascade.Local );
});
}
return cached.value;
}
}
return input;
}
addPlugin(function(model, db, options)
{
model.filtered = function(whereProperties, whereValue, whereEquals)
{
return db.models.filtered( whereProperties, whereValue, whereEquals );
};
});
addPlugin(function(model, db, options)
{
model.first = model.find = function(whereProperties, whereValue, whereEquals)
{
return db.models.firstWhere( whereProperties, whereValue, whereEquals );
};
});
addPlugin(function(model, db, options)
{
/**
* Finds or creates a model instance based on the given values. The key for
* the model must be derivable from the given values - or this function will
* always create a new model instance.
*
* ```javascript
* var ListItem = Rekord({
* key: ['list_id', 'iten_id'],
* fields: ['quantity'],
* belongsTo: {
* list: { model: 'list' },
* item: { model: 'item' }
* }
* });
*
* var listItem = ListItem.findOrCreate({
* list: someList,
* item: someItem,
* quantity: 23
* });
* // do stuff with listItem
* ```
*
* @method persist
* @memberof Rekord.Model
* @param {Object} [input] -
* The values to set in the model instance found or created.
* @param {Number} [cascade] -
* Which operations should be performed out of: store, rest, & live.
* @param {Any} [options] -
* The options to pass to the REST service.
* @return {Rekord.Model} -
* The saved model instance or undefined if the model database has not
* finished loading.
*/
model.findOrCreate = function( input, cascade, options, callback, context )
{
var callbackContext = context || this;
var instance = db.get( input );
var created = false;
if ( !instance )
{
db.grabModel( input, function(grabbed)
{
if ( !grabbed )
{
instance = model.create( input, cascade, options );
created = true;
}
else
{
instance = grabbed;
instance.$set( input );
// grab model created an instance that needs to be "created"
if ( !instance.$isSaved() )
{
instance.$save( cascade, options );
}
}
if ( callback )
{
callback.call( callbackContext, instance, created );
}
});
}
else
{
instance.$set( input );
if ( callback )
{
callback.call( callbackContext, instance, created );
}
}
return instance;
};
});
addPlugin(function(model, db, options)
{
/**
* Returns the model instance identified with the given input. This includes
* saved and unsaved models. If a `callback` is given the model will be passed
* to the function. The `callback` method is useful for waiting for Rekord
* to finish initializing (which includes loading models from local storage
* followed by remote storage if configured) and returning a model instance.
* If Rekord has finished initializing and the model doesn't exist locally
* then it is fetched from the remoute source using {@link Rekord.rest}.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var t0 = Task.get( 34 ); // only looks at models currently loaded
* var t1 = Task.get( 23, function(model) {
* model; // local or remotely loaded if it didn't exist locally - could be null if it doesn't exist at all
* })
* ```
*
* @method get
* @memberof Rekord.Model
* @param {modelInput} input -
* The model input used to determine the key and load the model.
* @param {Function} [callback] -
* The function to invoke passing the reference of the model when it's
* successfully found.
* @param {Object} [context] -
* The context (this) for the callback.
* @return {Rekord.Model} -
* The model instance if `callback` is not given - or undefined if the
* input doesn't resolve to a model or `callback` is given.
*/
model.get = function( input, callback, context )
{
if ( isFunction( callback ) )
{
db.grabModel( input, callback, context );
}
else
{
return db.get( input );
}
};
});
addPlugin(function(model, db, options)
{
/**
* Gets the model instance identified with the given input and passes it to the
* `callback` function. If Rekord is not finished initializing this function
* will wait until it is and check for the model. If it still doesn't exist
* locally it is loaded from a remote source using {@link Rekord.rest}. If the
* model doesn't exist at all a null value will be returned to the function.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var t1 = Task.grab( 23, function(model) {
* model; // local or remotely loaded if it didn't exist locally - could be null if it doesn't exist at all
* })
* ```
*
* @method grab
* @memberof Rekord.Model
* @param {modelInput} input -
* The model input used to determine the key and load the model.
* @param {Function} callback -
* The function to invoke passing the reference of the model when it's
* successfully found.
* @param {Object} [context] -
* The context (this) for the callback.
* @return {Rekord.Model} -
* The model instance of it exists locally at the moment, or undefined
* if the model hasn't been loaded yet.
*/
model.grab = function( input, options, callback, context )
{
var callbackContext = context || this;
var instance = db.get( input );
if ( instance )
{
callback.call( callbackContext, instance );
}
else
{
db.grabModel( input, function(instance)
{
if ( instance )
{
callback.call( callbackContext, instance );
}
else
{
model.fetch( input, options, callback, context );
}
});
}
return instance;
};
});
addPlugin(function(model, db, options)
{
/**
* Gets all model instances currently loaded, locally loaded, or remotely
* loaded and passes it to the `callback` function.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* var tasks = Task.grabAll( function(models) {
* models; // local or remotely loaded if it didn't exist locally.
* })
* ```
*
* @method grabAll
* @memberof Rekord.Model
* @param {Function} callback -
* The function to invoke passing the reference of the model collection
* when it's loaded.
* @param {Object} [context] -
* The context (this) for the callback.
* @return {Rekord.Model} -
* The model collection of it exists locally at the moment, or undefined
* if models haven't been loaded yet.
*/
model.grabAll = function( callback, context )
{
var callbackContext = context || this;
var models = db.models;
if ( models.length )
{
callback.call( callbackContext, models );
}
else
{
db.ready(function()
{
if ( models.length )
{
callback.call( callbackContext, models );
}
else
{
db.refresh(function()
{
callback.call( callbackContext, models );
});
}
});
}
return models;
};
});
addPlugin( function(model, db, options)
{
model.hasTrait = function(trait, comparator)
{
return db.hasTrait(trait, comparator);
};
model.hasTraits = function(traits, comparator)
{
return db.hasTraits(traits, comparator);
};
});
addPlugin( function(model, db, options)
{
if ( options.keyChanges )
{
enableKeyChanges();
}
});
var Map_put = Map.prototype.put;
var Map_remove = Map.prototype.remove;
function mapKeyChangeListener(map)
{
return function onKeyChange(model, oldKey, newKey)
{
var index = map.indices[ oldKey ];
if ( isNumber( index ) )
{
var listener = map.listeners[ oldKey ];
delete map.indices[ oldKey ];
delete map.listeners[ oldKey ];
map.keys[ index ] = newKey;
map.indices[ newKey ] = index;
map.listeners[ newKey ] = listener;
}
};
}
function mapKeyChangePut(key, value)
{
Map_put.apply( this, arguments );
if ( value instanceof Model && value.$db.keyChanges )
{
this.listeners = this.listeners || {};
this.listeners[ key ] = value.$on( Model.Events.KeyChange, mapKeyChangeListener( this ) );
}
return this;
}
function mapKeyChangeRemove(key)
{
var index = this.indices[ key ];
if ( isNumber( index ) )
{
if ( this.listeners )
{
evaluate( this.listeners[ key ] );
delete this.listeners[ key ];
}
this.removeAt( index );
}
return this;
}
function enableKeyChanges()
{
Class.method( Map, 'put', mapKeyChangePut );
Class.method( Map, 'remove', mapKeyChangeRemove );
}
function disableKeyChanges()
{
Class.method( Map, 'put', Map_put );
Class.method( Map, 'remove', Map_remove );
}
addPlugin(function(model, db, options)
{
var methods = collapse( options.methods, Defaults.methods );
if ( !isEmpty( methods ) )
{
Class.methods( model, methods );
}
});
addPlugin(function(model, db, options)
{
/**
* Persists model values, creating a model instance if none exists already
* (determined by the key derived from the input).
*
* ```javascript
* var ListItem = Rekord({
* key: ['list_id', 'iten_id'],
* fields: ['quantity'],
* belongsTo: {
* list: { model: 'list' },
* item: { model: 'item' }
* }
* });
*
* var listItem = ListItem.persist({ // creates relationship if it doesn't exist already - updates existing
* list: someList,
* item: someItem,
* quantity: 23
* });
* ```
*
* @method persist
* @memberof Rekord.Model
* @param {Object} [input] -
* The values to persist in the model instance found or created.
* @return {Rekord.Model} -
* The saved model instance or undefined if the model database has not
* finished loading.
*/
model.persist = function( input, cascade, options, callback, context )
{
var callbackContext = context || this;
return model.findOrCreate( input, cascade, options, function(instance, created)
{
if ( !created )
{
instance.$save( cascade, options );
}
if ( callback )
{
callback.call( callbackContext, instance );
}
});
};
});
addPlugin(function(model, db, options)
{
model.projection = function(projectionInput)
{
return Projection.parse( db, projectionInput );
};
});
addPlugin(function(model, db, options)
{
/**
* Invokes a function when Rekord has loaded. It's considered loaded when
* it's loaded locally, remotely, or neither (depending on the options
* passed to the database). The `callback` can also be invoked `persistent`ly
* on any load event - which includes {@link Rekord.Database#refresh}.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* Task.ready( function(db) {
* // Tasks have been loaded, lets do something about it!
* });
* ```
*
* @method ready
* @memberof Rekord.Model
* @param {Function} callback -
* The function to invoke passing the reference of the database when it's
* loaded.
* @param {Object} [context] -
* The context (this) for the callback.
* @param {Boolean} [persistent=false] -
* Whether the `callback` function should be invoked multiple times.
* Depending on the state of initializing, the callback can be invoked when
* models are loaded locally (if the `cache` is not equal to `None`),
* models are loaded remotely (if `load` is Rekord.Load.All), and every time
* {@link Rekord.Database#refresh} is called manually OR if `autoRefresh`
* is specified as true and the application changes from offline to online.
*/
model.ready = function( callback, context, persistent )
{
db.ready( callback, context, persistent );
};
});
addPlugin(function(model, db, options)
{
/**
* Refreshs the model database from the remote source by calling
* {@link Rekord.Database#refresh}. A `callback` can be passed to be invoked
* when the model database has refreshed (or failed to refresh) where all
* models that have been loaded will be passed as the first argument.
*
* ```javascript
* var Task = Rekord({
* fields: ['name']
* });
* Task.refresh( function(models) {
* models; // The collection of models loaded remotely (or current models if it failed to load them remotely.
* });
* ```
*
* @method refresh
* @memberof Rekord.Model
* @param {Function} callback -
* The function to invoke passing the reference model collection.
* @param {Object} [context] -
* The context (this) for the callback.
*/
model.refresh = function( callback, context )
{
return db.refresh( callback, context );
};
});
addPlugin(function(model, db, options)
{
model.reset = function(failOnPendingChanges, removeListeners)
{
return db.reset( failOnPendingChanges, removeListeners );
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a new search for model instances and returns the results collection.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var results = Task.results('/api/task/search', {name: 'like this', done: true});
* // results populated when search finishes running.
* // results.$search is the Search object.
* // results.$search.$promise is the promise of the search.
* ```
*
* @method results
* @memberof Rekord.Model
* @param {String} url -
* A URL to send the search data to.
* @param {Object} [props] -
* Initial set of properties on the search.
* @param {searchOptions} [options] -
* Options for the search.
* @return {Rekord.ModelCollection} -
* A collection containing the results of the search.
*/
model.results = function(url, props, options)
{
return new Search( db, url, options, props, true ).$results;
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a new search for model instances. A search is an object with
* properties that are passed to a configurable {@link Rekord.rest} function
* which expect an array of models to be returned from the remote call that
* match the search parameters.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var search = Task.search('/api/task/search');
* search.name = 'like this';
* search.done = true;
* search.anyProperty = [1, 3, 4];
* var promise = search.$run();
* promise.success( function(search) {
* search.$results; // collection of returned results
* });
* ```
*
* @method search
* @memberof Rekord.Model
* @param {String} url -
* A URL to send the search data to.
* @param {searchOptions} [options] -
* Options for the search.
* @param {Object} [props] -
* Initial set of properties on the search.
* @param {Boolean} [run=false] -
* Whether or not to run the search immediately.
* @return {Rekord.Search} -
* A new search for models.
*/
model.search = function(url, options, props, run)
{
return new Search( db, url, options, props, run );
};
});
addPlugin(function(model, db, options)
{
model.searchAt = function(index, url, paging, options, props, success, failure)
{
var page = {page_index: index, page_size: 1};
var search = paging ?
new SearchPaged( db, url, collapse( options, page ), props ) :
new Search( db, url, options, props );
var promise = new Promise();
promise.success( success );
promise.failure( failure );
search.$run().then(
function onSuccess(search, response, results) {
promise.resolve( results[ paging ? 0 : index ] );
},
function onFailure() {
promise.reject();
},
function onOffline() {
promise.noline();
}
);
return promise;
};
});
addPlugin(function(model, db, options)
{
/**
* Creates a new search with pagination for model instances. A paginated
* search is an object with properties that are passed to a configurable
* {@link Rekord.rest} function which expect an array of models to be returned
* as well as paging information from the remote call. Special properties are
* passed to the server (`page_index`, `page_size`) which dictate which
* chunk of data should be returned. A special `total` property is expected to
* be returned with `results` which tells the search how many records would've
* been returned without the pagination.
*
* ```javascript
* var Task = Rekord({
* fields: ['name', 'done']
* });
* var search = Task.searchPaged('/api/task/searchPaged');
* search.name = 'like this';
* search.done = true;
* search.anyProperty = [1, 3, 4];
* var promise = search.$run();
* promise.success( function(search) {
* search.$results; // collection of returned results
* search.total; // number of results that would've been returned without pagination
* search.page_index; // the zero-based page index
* search.page_size; // the number of results to be returned
* });
* search.$next(); // increase page_index, get the next page
* ```
*
* @method searchPaged
* @memberof Rekord.Model
* @param {String} url -
* A URL to send the search data to.
* @param {searchPageOptions} [options] -
* Options for the search.
* @param {Object} [props] -
* Initial set of properties on the search.
* @param {Boolean} [run=false] -
* Whether or not to run the search immediately.
* @return {Rekord.SearchPaged} -
* A new paginated search for models.
*/
model.searchPaged = function(url, options, props, run)
{
return new SearchPaged( db, url, options, props, run );
};
});
addPlugin(function(options)
{
var shard = options.shard || Defaults.shard;
if ( !isObject( shard ) )
{
return;
}
options.createRest = Rekord.shard( shard );
}, true );
addPlugin(function(model, db, options)
{
var staticMethods = collapse( options.staticMethods, Defaults.staticMethods );
if ( !isEmpty( staticMethods ) )
{
Class.props( model, staticMethods );
}
});
addPlugin(function(model, db, options)
{
var time = options.timestamps || Defaults.timestamps;
var timeFormat = collapseOption( options.timestampFormat, Defaults.timestampFormat );
var timeType = collapseOption( options.timestampType, Defaults.timestampType );
var timeUTC = collapseOption( options.timestampUTC, Defaults.timestampUTC );
var timeCurrent = options.timestampCurrent || Defaults.timestampCurrent;
if ( !time )
{
return;
}
function collapseOption(option, defaultValue)
{
if ( isObject( option ) && isObject( defaultValue ) )
{
return collapse( option, defaultValue );
}
return option || defaultValue;
}
function hasDefault(field)
{
return timeCurrent === true || indexOf( timeCurrent, field ) !== false;
}
function fieldSpecific(field, map)
{
return isObject( map ) ? map[ field ] : map;
}
function currentTimestamp(field)
{
var to = fieldSpecific( field, timeType );
return function()
{
return convertDate( new Date(), to );
};
}
function encode(x, model, field, forSaving)
{
var to = fieldSpecific( field, timeFormat );
var encoded = convertDate( x, to );
return encoded || x;
}
function decode(x, rawData, field)
{
var to = fieldSpecific( field, timeType );
var utc = fieldSpecific( field, timeUTC );
var decoded = convertDate( x, to, utc );
return decoded || x;
}
function addTimestamp(field)
{
var i = indexOf( db.fields, field );
if ( i === false )
{
db.fields.push( field );
db.saveFields.push( field );
}
if ( hasDefault( field ) && !(field in db.defaults) )
{
db.defaults[ field ] = currentTimestamp( field );
}
if ( timeFormat && !(field in db.encodings) )
{
db.encodings[ field ] = encode;
}
if ( timeType && !(field in db.decodings ) )
{
db.decodings[ field ] = decode;
}
}
function addCreatedAt(field)
{
addTimestamp( field );
db.ignoredFields[ field ] = true;
}
function addUpdatedAt(field)
{
addTimestamp( field );
db.ignoredFields[ field ] = true;
Class.replace( model, '$save', function($save)
{
return function()
{
this[ field ] = evaluate( db.defaults[ field ] );
return $save.apply( this, arguments );
};
});
}
function addTimestampField(type, field)
{
switch (type) {
case 'created_at':
return addCreatedAt( field );
case 'updated_at':
return addUpdatedAt( field );
default:
return addTimestamp( field );
}
}
if ( isString( time ) )
{
addTimestampField( time, time );
}
else if ( isArray( time ) )
{
for (var i = 0; i < time.length; i++)
{
addTimestampField( time[ i ], time[ i ] );
}
}
else if ( isObject( time ) )
{
for (var prop in time)
{
addTimestampField( prop, time[ prop ] );
}
}
else
{
addCreatedAt( 'created_at' );
addUpdatedAt( 'updated_at' );
}
});
var Timestamp = {
Date: 'date',
Millis: 'millis',
Seconds: 'seconds'
};
Defaults.timestampFormat = Timestamp.Millis;
Defaults.timestampType = Timestamp.Date;
Defaults.timestampUTC = false;
Defaults.timestampCurrent = ['created_at', 'updated_at'];
function convertDate(x, to, utc)
{
var date = parseDate( x, utc );
if ( date === false )
{
return false;
}
if ( !to )
{
return date;
}
switch (to)
{
case Timestamp.Date:
return date;
case Timestamp.Millis:
return date.getTime();
case Timestamp.Seconds:
return Math.floor( date.getTime() / 1000 );
default:
return Rekord.formatDate( date, to );
}
}
Rekord.Timestamp = Timestamp;
Rekord.formatDate = noop;
Rekord.convertDate = convertDate;
var IGNORE_TRAITS = { traits: true };
addPlugin(function(options)
{
var traits = options.traits || Defaults.traits;
if ( !isEmpty( traits ) )
{
if ( isFunction( traits ) )
{
traits = traits( options );
}
if ( isArray( traits ) )
{
for (var i = 0; i < traits.length; i++)
{
var trait = traits[ i ];
if ( isFunction( trait ) )
{
trait = trait( options );
}
if ( isObject( trait ) )
{
merge( options, trait, IGNORE_TRAITS );
}
else
{
throw 'traits are expected to be an object or a function which returns an object of methods';
}
}
}
else
{
throw 'traits are expected to be an array or a function which returns an array';
}
}
}, true );
addPlugin(function(model, db, options)
{
model.where = function(whereProperties, whereValue, whereEquals, out)
{
return db.models.where(whereProperties, whereValue, whereEquals, out);
};
});
/* Classes */
Rekord.Model = Model;
Rekord.Database = Database;
Rekord.Defaults = Defaults;
Rekord.Relation = Relation;
Rekord.Operation = Operation;
Rekord.Search = Search;
Rekord.SearchPaged = SearchPaged;
Rekord.Promise = Promise;
Rekord.Dependents = Dependents;
Rekord.Shard = Shard;
/* Keys */
Rekord.KeyHandler = KeyHandler;
Rekord.KeySimple = KeySimple;
Rekord.KeyComposite = KeyComposite;
Rekord.enableKeyChanges = enableKeyChanges;
Rekord.disableKeyChanges = disableKeyChanges;
/* Enums */
Rekord.Cascade = Cascade;
Rekord.Cache = Cache;
Rekord.Store = Store;
Rekord.Save = Save;
Rekord.Load = Load;
Rekord.RestStatus = RestStatus;
/* Collections */
Rekord.Map = Map;
Rekord.Collection = Collection;
Rekord.FilteredCollection = FilteredCollection;
Rekord.ModelCollection = ModelCollection;
Rekord.FilteredModelCollection = FilteredModelCollection;
Rekord.RelationCollection = RelationCollection;
Rekord.Page = Page;
Rekord.Context = Context;
/* Relationships */
Rekord.HasOne = HasOne;
Rekord.BelongsTo = BelongsTo;
Rekord.HasMany = HasMany;
Rekord.HasManyThrough = HasManyThrough;
Rekord.HasRemote = HasRemote;
Rekord.HasList = HasList;
Rekord.HasReference = HasReference;
Rekord.RelationMultiple = RelationMultiple;
Rekord.RelationSingle = RelationSingle;
/* Operations */
Rekord.GetLocal = GetLocal;
Rekord.GetRemote = GetRemote;
Rekord.RemoveCache = RemoveCache;
Rekord.RemoveLocal = RemoveLocal;
Rekord.RemoveNow = RemoveNow;
Rekord.RemoveRemote = RemoveRemote;
Rekord.SaveLocal = SaveLocal;
Rekord.SaveNow = SaveNow;
Rekord.SaveRemote = SaveRemote;
/* Projections */
Rekord.Filters = {};
Rekord.Projection = Projection;
/* Common Functions */
Rekord.isRekord = isRekord;
Rekord.isDefined = isDefined;
Rekord.isFunction = isFunction;
Rekord.isString = isString;
Rekord.isNumber = isNumber;
Rekord.isBoolean = isBoolean;
Rekord.isDate = isDate;
Rekord.isRegExp = isRegExp;
Rekord.isArray = isArray;
Rekord.isObject = isObject;
Rekord.isValue = isValue;
Rekord.noop = noop;
Rekord.bind = bind;
Rekord.uuid = uuid;
Rekord.sizeof = sizeof;
Rekord.isEmpty = isEmpty;
Rekord.evaluate = evaluate;
Rekord.addPlugin = addPlugin;
Rekord.now = now;
Rekord.merge = merge;
/* Morphing Functions */
Rekord.Gate = Gate;
Rekord.DiscriminateCollection = DiscriminateCollection;
/* Morphing Objects */
Rekord.Filtering = Filtering;
Rekord.Polymorphic = Polymorphic;
/* Array Functions */
Rekord.toArray = toArray;
Rekord.indexOf = indexOf;
Rekord.collect = collect;
Rekord.array = collectArray;
Rekord.swap = swap;
Rekord.reverse = reverse;
Rekord.isSorted = isSorted;
Rekord.isPrimitiveArray = isPrimitiveArray;
/* Class Functions */
Rekord.Settings = Settings;
Rekord.Class = Class;
Rekord.extend = Class.extend;
Rekord.extendArray = Class.extend;
Rekord.addMethod = Rekord.setProperty = Class.prop;
Rekord.addMethods = Rekord.setProperties = Class.props;
Rekord.replaceMethod = Class.replace;
Rekord.copyConstructor = Class.copyConstructor;
Rekord.factory = Class.factory;
/* Comparator Functions */
Rekord.Comparators = Comparators;
Rekord.saveComparator = saveComparator;
Rekord.addComparator = addComparator;
Rekord.createComparator = createComparator;
/* Comparison Functions */
Rekord.equalsStrict = equalsStrict;
Rekord.equalsWeak = equalsWeak;
Rekord.equalsCompare = equalsCompare;
Rekord.equals = equals;
Rekord.compareNumbers = compareNumbers;
Rekord.compare = compare;
/* Eventful Functions */
Rekord.addEventFunction = addEventFunction;
Rekord.addEventful = addEventful;
/* Object Functions */
Rekord.applyOptions = applyOptions;
Rekord.propsMatch = propsMatch;
Rekord.hasFields = hasFields;
Rekord.updateFieldsReturnChanges = updateFieldsReturnChanges;
Rekord.clearFieldsReturnChanges = clearFieldsReturnChanges;
Rekord.grab = grab;
Rekord.pull = pull;
Rekord.transfer = transfer;
Rekord.collapse = collapse;
Rekord.clean = clean;
Rekord.cleanFunctions = cleanFunctions;
Rekord.copy = copy;
Rekord.diff = diff;
/* Parse Functions */
Rekord.isParseInput = isParseInput;
Rekord.parse = parse;
Rekord.createParser = createParser;
Rekord.isFormatInput = isFormatInput;
Rekord.format = format;
Rekord.createFormatter = createFormatter;
Rekord.parseDate = parseDate;
/* Resolver Functions */
Rekord.NumberResolvers = NumberResolvers;
Rekord.saveNumberResolver = saveNumberResolver;
Rekord.createNumberResolver = createNumberResolver;
Rekord.PropertyResolvers = PropertyResolvers;
Rekord.savePropertyResolver = savePropertyResolver;
Rekord.createPropertyResolver = createPropertyResolver;
/* String Functions */
Rekord.toCamelCase = toCamelCase;
Rekord.split = split;
/* Where Functions */
Rekord.Wheres = Wheres;
Rekord.saveWhere = saveWhere;
Rekord.createWhere = createWhere;
Rekord.expr = expr;
Rekord.not = not;
Rekord.oneOf = oneOf;
Rekord.isExpr = isExpr;
Rekord.exprEqualsTester = exprEqualsTester;
Rekord.exprEquals = exprEquals;
/* Services */
Rekord.Stores = Stores;
Rekord.Lives = Lives;
Rekord.Rests = Rests;
return Rekord;
}));
|
//directive for building the book spines in the virtual bookcase
angular.module('portfolioApp')
.directive('onFinishRender', function ($compile, $timeout, $rootScope) {
return {
restrict: 'A',
link: function (scope, element) {
var classArray = [],
currentClass,
gradient,
titleContainer,
authorContainer,
title,
author,
symbolContainer,
titleTop,
titleHeight,
authorTop,
symbol,
symbolSpace,
color,
weight,
family,
size,
width,
height,
bookTop;
//calculates each of the attributes of a given book using randomization to make each book unique
for (var i = 0; i < 7; i++) {
if (i === 0) {
currentClass = Math.floor((Math.random() * 7) + 1); //color of the book spine
} else if (i === 2) {
currentClass = Math.floor((Math.random() * 5) + 1); //font weight of the title and author
} else if (i === 3) {
currentClass = Math.floor((Math.random() * 8) + 20); //font family of the title and author
} else if (i === 4) {
currentClass = Math.floor((Math.random() * 50) + 75); //font size of the title and author
} else if (i === 5) {
currentClass = Math.floor((Math.random() * 100) + 400); //height of the spine
} else {
currentClass = Math.floor((Math.random() * 12) + 1); //symbol in the middle of the spine
}
classArray.push(currentClass); //push calculated attribute to the classArray
}
color = classArray[0];
weight = classArray[1];
family = classArray[2];
size = classArray[3];
width = classArray[4];
height = classArray[5];
symbol = classArray[6];
gradient = scope.gradient; //sets the gradient of the spine
titleContainer = scope.titleContainer; //sets the title container element
authorContainer = scope.authorContainer; //sets the author container element
bookTop = Math.floor(550 - height); //sets the margin-top style of the book.
// This aligns each book to the bottom of the shelf by subtracting the height of book from the total height of the shelf
element.addClass('color-' + color).css({ //Set color class, margin-top, min-width, and height of book
'margin-top': bookTop,
'min-width': width,
'height': height
});
gradient.css('height', height); //set height of gradient overlay to the height of the book
titleContainer.css('font-size', size) //set font size, font-weight, font-family of title
.addClass('font-weight-' + weight + ' ' + 'font-family-' + family);
authorContainer.css('font-size', size) //set font size, font-weight, font-family of author
.addClass('font-weight-' + weight + ' ' + 'font-family-' + family);
title = scope.title; //bind title
author = scope.author; //bind author
titleHeight = title.height(); //set height of title
titleTop = title.prop('offsetTop'); //set top of title
authorTop = author.prop('offsetTop'); //set top of author
symbolSpace = Math.floor((authorTop - (titleTop + titleHeight)) / 2); //find remaining available space for center symbol based on height of title and author
symbolContainer = scope.symbol; //bind symbol
symbolContainer.css({'height': symbolSpace}) //set calculated symbol height and class
.addClass('icon-book-symbol-' + symbol);
}
};
})
//directive to build out shelf based on how many books are listed
.directive('shelf', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
//watch for number of books to change
scope.$watch(function () {
var books = element.find(angular.element(document.querySelectorAll('.book-spine'))), //declare books on shelf
shelf = element.parent().find(angular.element(document.querySelectorAll('.shelf'))), //declare scroll area parent container of books
shelfWidth = 0; //set initial width to 0
for(var i in books) { //loop through books
if(books[i].clientWidth && books[i].className.indexOf('book-spine') > -1) { //add the width of the book to the shelfWidth variable
shelfWidth = shelfWidth + books[i].getBoundingClientRect().width;
}
}
element.css('width', Math.round(shelfWidth) + 100); //set width of shelf based on total width of books
})
}
}
});
|
/*
* raphael.zoom 0.0.4
*
* Copyright (c) 2010 Wout Fierens - http://boysabroad.com
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
*/
// get all elements in the paper
Raphael.fn.elements = function() {
var b = this.bottom,
r = [];
while (b) {
r.push(b);
b = b.next;
}
return r;
}
// initialize zoom of paper
Raphael.fn.initZoom = function(zoom) {
var elements = this.elements();
this.zoom = zoom || 1;
for (var i = 0; i < elements.length; i++) {
elements[i].initZoom();
}
return this;
}
// set the zoom of all elements
Raphael.fn.setZoom = function(zoom) {
if (!zoom) return;
var elements = this.elements();
if (!this.zoom)
this.initZoom();
for (var i = 0; i < elements.length; i++) {
elements[i].setZoom(zoom);
}
this.zoom = zoom;
return this;
}
// initialize zoom of element
Raphael.el.initZoom = function(zoom) {
var sw = parseFloat(this.attr("stroke-width")) || 0;
zoom = zoom || this.paper.zoom;
if (this.type != "text") sw /= zoom;
this.zoom = zoom;
this.zoom_memory = {
"stroke-width": sw,
rotation: 360
};
this.setStrokeWidth(sw / zoom);
if (this.type == "text") {
var fs = parseFloat(this.attr("font-size")) || 0
this.zoom_memory["font-size"] = fs;
this.zoom_memory["x"] = (parseFloat(this.attrs["x"]) || 0) / zoom;
this.zoom_memory["y"] = (parseFloat(this.attrs["y"]) || 0) / zoom;
}
return this;
}
// zoom element preserving some original values
Raphael.el.setZoom = function(zoom) {
if (!zoom) return;
if (!this.zoom_memory)
this.initZoom();
// scale to zoom
var new_zoom = zoom / this.zoom;
this.scale(new_zoom, new_zoom, 0, 0);
this.applyScale();
// save new zoom
this.zoom = zoom;
this.setStrokeWidth(this.zoom_memory["stroke-width"]);
if (this.type == "text")
this.attr({
"font-size": this.zoom_memory["font-size"] * zoom,
"x": this.zoom_memory["x"] * zoom,
"y": this.zoom_memory["y"] * zoom
});
return this;
}
// set element zoomed attributes
Raphael.el.setAttr = function() {
if (typeof arguments[0] == "string") {
attr = {};
attr[arguments[0]] = arguments[1];
} else {
attr = arguments[0];
}
for (var key in attr) {
switch(key) {
case "stroke-width":
this.setStrokeWidth(attr[key]);
break;
case "font-size":
this.setFontSize(attr[key]);
break;
case "x":
case "y":
if (this.type == "text")
this.zoom_memory[key] = attr[key] / this.zoom;
this.attr(key, attr[key]);
break;
default:
this.attr(key, attr[key]);
break;
}
}
return this;
}
// set element translation
Raphael.el.setTranslation = function(x, y) {
if (this.type == "text")
this.setAttr({
x: this.attrs["x"] + x,
y: this.attrs["y"] + y
});
else
this.translate(x,y);
return this;
}
// set element rotation
Raphael.el.setRotation = function(angle, x, y) {
if (!this.zoom_memory) this.initZoom();
if (angle == 0)
angle = 360;
this.rotate(angle, x, y);
this.zoom_memory.rotation = angle;
this.transformations = [];
this._.rt = { cx: null, cy: undefined, deg: 360 };
return this;
}
// set element zoomed stroke width
Raphael.el.setStrokeWidth = function(value) {
if (value == 0 || (value = parseFloat(value))) {
this.attr({ "stroke-width": value * this.zoom });
this.zoom_memory["stroke-width"] = value;
}
return this;
}
// set element font size
Raphael.el.setFontSize = function(value) {
if (value == 0 || (value = parseFloat(value))) {
this.attr({ "font-size": value * this.zoom });
this.zoom_memory["font-size"] = value;
}
return this;
}
// apply the current scale and reset it to 1
Raphael.el.applyScale = function() {
this._.sx = 1;
this._.sy = 1;
this.scale(1, 1);
return this;
}
|
var opts = {
authUrl: '/token',
modalComponent: null
};
var modalContainer = null;
var modalProps = {
visible: m.prop(false),
error: m.prop(null),
message: m.prop(null)
};
var localUser = m.prop(null);
var loginDeferred = null;
var getSavedToken = function() {
return core.cookie.getItem('session') || localStorage.getItem('token');
};
var saveToken = function(token) {
core.cookie.setItem('session', token, 0, '/');
localStorage.setItem('session', token);
};
var unsetToken = function() {
core.cookie.removeItem('session', '/');
localStorage.removeItem('session');
};
var requestToken = function(email, password) {
modalProps.error(null);
return m.request({
method: 'POST',
url: opts.authUrl,
data: {
email: email,
password: password
}
}).then(function(data) {
if (data.id && data.user) {
saveToken(data.id);
data.user.token = data.id;
localUser(data.user);
loginDeferred.resolve();
loginDeferred = null;
modalProps.visible(false);
} else {
modalProps.error('Login failed.');
}
}, function() {
modalProps.error('Login failed.');
});
};
core.auth = {
config: function(options) {
_.assign(opts, options);
},
user: function() {
return localUser();
},
login: function() {
var headers = {};
var localToken = getSavedToken();
if (localToken) {
localUser({
token: localToken
});
}
return core.request({
method: 'GET',
url: opts.authUrl,
headers: headers
}).then(function (data) {
saveToken(data.id);
data.user.token = data.id;
localUser(data.user);
});
},
logout: function() {
unsetToken();
return core.Promise.resolve();
},
resolve: function() {
if (!modalContainer) {
modalContainer = document.createElement('div');
document.body.appendChild(modalContainer);
m.mount(modalContainer, opts.modalComponent(modalProps, requestToken));
}
if (!loginDeferred) {
loginDeferred = m.deferred();
modalProps.visible(true);
}
return loginDeferred.promise;
},
checkAccess: function(op) {
if (Auth.checkRole('admin')) {
return true;
}
var user = localUser();
if (user && _.isArray(user.operations)) {
return user.operations.indexOf(op) !== -1;
}
return false;
},
checkRole: function(role) {
var user = localUser();
if (user && _.isArray(user.roles)) {
return user.roles.indexOf(role) !== -1;
}
return false;
}
}; |
let userController = (function() {
function login(ctx) {
if (userService.isLoggedIn()) {
ctx.redirect('#/activeReceipt');
return;
}
let username = ctx.params["username-login"];
let password = ctx.params["password-login"];
if (username.length < 5) {
infoService.showError('A username should be at least 5 characters long.');
return;
}
if (password.length === 0) {
infoService.showError('Password should not be empty.');
return;
}
userService.login(username, password)
.then(function(res) {
userService.saveSession(res);
ctx.redirect('#/activeReceipt');
infoService.showInfo('Login successful.');
}).catch(function(err) {
infoService.handleAjaxError(err);
});
}
function register(ctx) {
if (userService.isLoggedIn()) {
ctx.redirect('#/home');
return;
}
let username = ctx.params["username-register"];
let password = ctx.params["password-register"];
let repeatPassword = ctx.params["password-register-check"];
if (username.length < 5) {
infoService.showError('A username should be at least 5 characters long.');
return;
}
if (password.length === 0) {
infoService.showError('Password should not be empty.');
return;
}
if (password !== repeatPassword) {
infoService.showError('Repeated password is different.');
return;
}
userService.register(username, password)
.then(function(res) {
userService.login(username, password).then(function() {
userService.saveSession(res);
ctx.redirect('#/activeReceipt');
infoService.showInfo('User registration successful.');
}).catch(function(err) {
infoService.handleAjaxError(err);
});
}).catch(function(err) {
infoService.handleAjaxError(err);
});
}
function logout(ctx) {
if (!userService.isLoggedIn()) {
ctx.redirect('#/home');
return;
}
userService.logout()
.then(function(res) {
sessionStorage.clear();
infoService.showInfo('Logout success!');
ctx.redirect('#/home');
}).catch(function(err) {
infoService.handleAjaxError(err);
});
}
return {
login,
register,
logout
}
})();
|
var assert = require("assert");
var Lib = require("./../ramda");
describe('find', function() {
var find = Lib.find;
var obj1 = {x: 100};
var obj2 = {x: 200};
var a = [11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0];
var even = function(x) { return x % 2 === 0; };
var gt100 = function(x) { return x > 100; };
var isStr = function(x) { return typeof x === "string"; };
var xGt100 = function(o) { return o && o.x > 100; };
it("returns the first element that satisfies the predicate", function() {
assert.equal(find(even, a), 10);
assert.equal(find(gt100, a), 200);
assert.equal(find(isStr, a), 'cow');
assert.equal(find(xGt100, a), obj2);
});
it("returns `undefined` when no element satisfies the predicate", function() {
assert.equal(find(even, 'zing'), undefined);
});
});
describe('findIndex', function() {
var findIndex = Lib.findIndex;
var obj1 = {x: 100};
var obj2 = {x: 200};
var a = [11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0];
var even = function(x) { return x % 2 === 0; };
var gt100 = function(x) { return x > 100; };
var isStr = function(x) { return typeof x === "string"; };
var xGt100 = function(o) { return o && o.x > 100; };
it("returns the index of the first element that satisfies the predicate", function() {
assert.equal(findIndex(even, a), 1);
assert.equal(findIndex(gt100, a), 8);
assert.equal(findIndex(isStr, a), 3);
assert.equal(findIndex(xGt100, a), 10);
});
it("returns `undefined` when no element satisfies the predicate", function() {
assert.equal(findIndex(even, 'zing'), undefined);
});
});
describe('findLast', function() {
var findLastIndex = Lib.findLastIndex;
var obj1 = {x: 100};
var obj2 = {x: 200};
var a = [11, 10, 9, 'cow', obj1, 8, 7, 100, 200, 300, obj2, 4, 3, 2, 1, 0];
var even = function(x) { return x % 2 === 0; };
var gt100 = function(x) { return x > 100; };
var isStr = function(x) { return typeof x === "string"; };
var xGt100 = function(o) { return o && o.x > 100; };
it("returns the index of the last element that satisfies the predicate", function() {
assert.equal(findLastIndex(even, a), 15);
assert.equal(findLastIndex(gt100, a), 9);
assert.equal(findLastIndex(isStr, a), 3);
assert.equal(findLastIndex(xGt100, a), 10);
});
it("returns `undefined` when no element satisfies the predicate", function() {
assert.equal(findLastIndex(even, 'zing'), undefined);
});
});
|
exports = module.exports = function PageObject_Skeleton(client){
this.getCurrentPageTitle = function(cb) {
return client.title(function(err, result){
cb(err, result && result.value);
});
};
this.navigateTo = function(href){
return client.click('a[href="' + href + '"]')
.waitForHttpDone();
};
};
|
var qwest = require('qwest');
var CartService = {
getCart: function(){
return qwest.get('/api/v1/cart');
},
addItem: function(bookId, qty){
return qwest.post('/api/v1/cart/books/' + bookId, { qty : qty });
},
removeItem: function(bookId){
return qwest.delete('/api/v1/cart/books/' + bookId);
}
};
module.exports = CartService; |
// app.mainNavBackground
var Backbone = require ('backbone');
var $ = require ('jquery');
module.exports = Backbone.View.extend({
el: '#page',
lockBackground: function(backgroundScroll) {
var bgStyle = '';
bgStyle += 'position: fixed;';
bgStyle += 'top: -' + backgroundScroll + 'px;';
this.$el.attr('style', bgStyle);
},
unlockBackground: function() {
this.$el.removeAttr('style');
}
});
|
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
collectCoverage: true,
collectCoverageFrom: [
'**/*.ts',
'!compiler/grammar.ts',
'!docs/**',
'!dst/**',
'!**/node_modules/**'
],
coverageDirectory: 'docs'
};
|
// most of these tests are meaningless but they're better than nothing, right?
Stamp = require("../models/stamp")
describe("the stamp model", function(){
var testStamp = new Stamp({
createdAt: Date(),
data: {
languages: {"test":5000},
commitMessages: {"test":5000},
averageMessageLength: Math.random(),
langTotals: {"test":5000},
langAverages: {"test":5000}
}
});
it("should have an id", function(){
expect(testStamp.id).toEqual(jasmine.any(String));
});
it("should have a time stamp", function(){
expect(testStamp.createdAt).toEqual(jasmine.any(Date));
});
it("should have data", function(){
expect(testStamp.data.languages.test).toEqual(5000);
});
it("should have data", function(){
expect(testStamp.data.commitMessages.test).toEqual(5000);
});
it("should have data", function(){
expect(testStamp.data.averageMessageLength).toEqual(jasmine.any(Number));
});
it("should have data", function(){
expect(testStamp.data.langTotals.test).toEqual(5000);
});
it("should have data", function(){
expect(testStamp.data.langAverages.test).toEqual(5000);
});
});
|
if(typeof(require) == 'function'){
var Chance = require('chance');
var async = require('async');
}
var fake = {}
fake.create = function(modeler, iterator, callback) {
if(typeof(Chance) === 'undefined'){
console.error('Fakejs require Chance');
return;
}
if(typeof(async) === 'undefined'){
console.error('Fakejs require Async');
return;
}
var chance = new Chance();
iterator = iterator || 1;
async.times(iterator, function(i, next){
createModel(modeler, function(err, model) {
next(err, model)
})
}, function(err, models) {
//console.log(models);
callback(models)
});
function createModel(modeler, callback){
var model = {};
for(m in modeler) {
if(typeof(modeler[m]) == 'string'){
if(modeler[m] in chance){
model[m] = chance[modeler[m]]();
}else{
model[m] = modeler[m]
}
}else if(typeof(modeler[m]) == 'function'){
model[m] = modeler[m]();
}else {
model[m] = modeler[m];
}
}
callback(null, model);
}
}
if (typeof(module) !== 'undefined' && 'exports' in module) {
module.exports = fake;
} |
if(!steal.build){
steal.build = {};
}
steal('steal','steal/build/css',function( steal ) {
/**
* @class steal.build.js
* @parent steal.build
* @hide
*
* An object that contains functions for creating a package of scripts, minifying it,
* and cleaning it.
*/
var js = steal.build.js = {};
/**
* @function makePackage
*
* `steal.build.js.makePackage(moduleOptions, dependencies, cssPackage, buildOptions)`
* creates JavaScript and CSS packages. For example:
*
* steal.build.js.makePackage( [
* { buildType : "js", id : "a.js", text: "a" },
* { buildType : "js", id : "b.js", text: "b" },
* { buildType : "css", id : "c.css", text: "c" }
* ],
* { "package/1.js" : ["jquery/jquery.js"] },
* "package/css.css",
* {stealOwnModules: true}
* )
*
* ... produces an object with minified js that looks like the following
* unminified source:
*
* // indicates these modules are loading
* steal.has("a.js","b.js");
*
* // steal any packages this package depends on
* // waits makes them wait until the prior steal has finished
* steal({id:"package/1.js",waits:true,has:["jquery/jquery.js"]});
* steal({id:"package/css.css",waits:true,has:["c.css"]});
*
* // steal the modules required by production.js
* // so that it can be marked completed
* // at the right time
* steal("a.js","b.js");
*
* // temporarily saves and empties the pending
* // queue because the content's of other files
* // will add to it and steal.excuted will clear it.
* steal.pushPending();
* // the files and executed contexts
* a;
* steal.executed("a.js");
* b;
* steal.executed("b.js");
*
* // pop production.js's pending state back into
* // the pending queue.
* // When production.js is done loading, steal
* // will use pending as production.js's dependencies.
* steal.popPending();
*
*
*
* @param {Array} moduleOptions like:
*
* [{id: "jquery/jquery.js", text: "var a;", baseType: "js"}]
*
* Each moduleOption should have:
*
* - id - the moduleId
* - text - the JS or CSS text of the module
* - baseType - either "css" or "js"
*
* @param {Object} dependencies An object of dependency moduleIds mapped
* to the moduleIds of the modules they contain:
*
* {"package/package.js": ['jquery/jquery.js']}
*
* The package being created will wait until all dependencies in this
* object have been [steal.Module.states].
*
* @param {String} cssPackage the css package name, added as dependency if
* there is css in files.
*
* @param {Array} buildOptions An object that indicates certain behavior
* patterns. For example:
*
* {
* exclude: ["jquery/jquery.js"],
* stealOwnModules: true
* }
*
* Supported options are:
*
* - exclude - exclude these modules from any build
* - stealOwnModules - if the package should steal the modules it contains.
*
* @return {Object} an object with the css and js
* code that make up this package unminified
*
* {
* js: "steal.has('plugin1','plugin2', ... )"+
* "steal({src: 'package/package.js', has: ['jquery/jquery.js']})"+
* "plugin1 content"+
* "steal.executed('plugin1')",
* css : "concated css content"
* }
*
*/
js.makePackage = function(moduleOptions, dependencies, cssPackage, buildOptions){
// put it somewhere ...
// add to dependencies ...
// seperate out css and js
buildOptions = buildOptions || {};
var excludes = buildOptions.exclude || [];
var jses = [],
csses = [],
lineMap = {},
lineNum = 0,
numLines = function(text){
var matches = text.match(/\n/g);
return matches? matches.length + 1 : 1
};
// if even one file has compress: false, we can't compress the whole package at once
var canCompressPackage = true;
moduleOptions.forEach(function(file){
if(file.minify === false){
canCompressPackage = false;
}
});
if(!canCompressPackage){
moduleOptions.forEach(function(file){
if(file.buildType == 'js'){
var source = steal.build.js.clean(file.text);
if(file.minify !== false){
try{
source = steal.build.js.minify(source);
} catch(error){
print("ERROR minifying "+file.id+"\n"+error.err)
}
}
file.text = source;
}
});
}
moduleOptions.forEach(function(file){
if ( file.packaged === false ) {
steal.print(' not packaging ' + file.id);
return;
}
// ignore
if ( file.ignore ) {
steal.print(' ignoring ' + file.id);
return;
}
/**
* Match the strings in the array and return result.
*/
var matchStr = function(str){
var has = false;
if(excludes.length){
for(var i=0;i<excludes.length;i++){
//- Match wildcard strings if they end in '/'
//- otherwise match the string exactly
//- Example `exclude: [ 'jquery/' ]` would exclude all of jquery++
//- however `exclude: [ 'jquery' ]` would only exclude the file
var exclude = excludes[i];
if((exclude[exclude.length - 1] === "/" &&
str.indexOf(exclude) === 0) || str === exclude){
has = true;
break;
}
}
}
return has;
};
if ( file.exclude || matchStr(''+file.id)){
steal.print(' excluding '+file.id)
return;
}
if(file.buildType == 'js'){
jses.push(file)
} else if(file.buildType == 'css'){
csses.push(file)
} else if(file.buildType == 'less'){
csses.push(file)
}
})
// add to dependencies
if(csses.length && dependencies){
dependencies[cssPackage] = csses.map(function(css){
return css.id;
})
}
// this now needs to handle css and such
var loadingCalls = jses.map(function(file){
return file.id;
});
//create the dependencies ...
var dependencyCalls = [];
for (var key in dependencies){
dependencyCalls.push(
"steal({id: '"+key+"', waits: true, has: ['"+dependencies[key].join("','")+"']})"
)
}
// make 'loading'
var code = ["steal.has('"+loadingCalls.join("','")+"');"];
// add dependencies
code.push.apply(code,dependencyCalls);
if(buildOptions.stealOwnModules){
// this makes production.js wait for these moduleOptions to complete
// this was removing the rootSteal and causing problems
// but having it might cause a circular dependency in
// the apps scenario
code.push("steal('"+loadingCalls.join("','")+"')")
}
code.push("steal.pushPending()")
lineNum += code.length
// add js code
jses.forEach(function(file){
code.push( file.text, "steal.executed('"+file.id+"')" );
lineMap[lineNum] = file.id+"";
var linesCount = numLines(file.text)+1;
lineNum += linesCount;
});
var jsCode = code.join(";\n") + ";\nsteal.popPending();\n";
if(canCompressPackage){
jsCode = steal.build.js.clean(jsCode);
jsCode = steal.build.js.minify(jsCode,{currentLineMap: lineMap, compressor: buildOptions.compressor});
}
var csspackage = steal.build.css.makePackage(csses, cssPackage);
return {
js: jsCode,
css: csspackage
}
}
}).then('./jsminify');
|
var filter = require('../../lib/filter');
var filterCheck = require('./filter_check');
describe('custom filter (to true if over 10, and false else)', function() {
var values = [
{ title: '10 => true', from : 10, to: true },
{ title: '9 => false', from : 9, to: false },
{ title: 'foo => false', from : 'foo', to: false }
];
var custome = filter.custom(function (val, callback) {
if (typeof val === 'number' && val >= 10) {
callback(null, true);
} else {
callback(null, false);
}
});
values.forEach(function (value) {
filterCheck(custome, value.title, value.from, value.to);
});
}); |
import React from 'react'
import _ from 'lodash'
import { GraphQLClient } from 'graphql-request'
import * as graphql from 'graphql'
import * as State from '../../state'
import * as U from '../../state/update'
import { connectHelper, disconnectDB } from '../generic'
export { disconnectDB, getStagingValue } from '../generic'
import { GraphQLDocs } from './graphql-docs'
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint'
import 'codemirror-graphql/hint'
import 'codemirror-graphql/lint'
import 'codemirror-graphql/mode'
export const key = 'graphql'
export const name = 'GraphQL'
export const syntax = 'graphql'
export class Configure extends React.Component {
render() {
const { connect, config } = this.props
const credentialHints = {
endpoint: 'endpoint address',
token: 'authorization token (optional)',
}
let credentials = (config.credentials && config.credentials.graphql) || {}
const Field = (type, icon, className = '') => (
<div className="pt-input-group">
{icon ? <span className={className + ' pt-icon pt-icon-' + icon} /> : null}
<input
type={type === 'password' ? 'password' : 'text'}
disabled={connect.status == 'connected' || connect.status === 'connecting'}
className="pt-input"
value={credentials[type] || ''}
onChange={(e) =>
State.apply(
'config',
'graphql',
'credentials',
type,
U.replace(e.target.value)
)
}
placeholder={credentialHints[type]}
/>
</div>
)
return (
<div>
<img src={require('../img/graphql.svg')} style={{ height: 60 }} />
<p>{Field('endpoint', 'globe')}</p>
<p>{Field('token', 'lock')}</p>
<p>
{connect.status != 'connected' ? (
connect.status == 'connecting' ? (
<button
disabled
type="button"
className="pt-button pt-large pt-intent-primary"
onClick={(e) => connectDB()}
>
Connect
<span className="pt-icon-standard pt-icon-arrow-right pt-align-right" />
</button>
) : (
<button
type="button"
className="pt-button pt-large pt-intent-primary"
onClick={(e) => connectDB()}
>
Connect
<span className="pt-icon-standard pt-icon-arrow-right pt-align-right" />
</button>
)
) : (
<button
type="button"
className="pt-button pt-large pt-intent-danger"
onClick={(e) => disconnectDB()}
>
Disconnect
<span className="pt-icon-standard pt-icon-offline pt-align-right" />
</button>
)}
</p>
{connect.status != 'connected' && (
<p>
Or connect to a sample endpoint{' '}
<a
href="javascript:void(0)"
onClick={(e) => connectEndpoint('https://graphql-pokemon.now.sh/')}
>
Pokemon Example
</a>
</p>
)}
</div>
)
}
}
function connectEndpoint(endpoint) {
State.apply('config', 'credentials', 'graphql', 'token', U.replace(''))
State.apply('config', 'credentials', 'graphql', 'endpoint', U.replace(endpoint))
connectDB()
}
export async function run(query) {
var db = State.get('connect', '_db')
const results = await fetcher({ query })
let result = {}
const data = results.data[Object.keys(results.data)[0]]
if (data != null) {
result = formatResults(data)
}
result.query = query
State.apply('connect', 'graphqlschema', U.replace(await getSchema()))
return result
}
export function reference(name) {
return '#' + name
}
const database = () => {
const { endpoint, token } = State.get('config', 'credentials', 'graphql')
const options = token ? { headers: { Authorization: `Bearer ${token}` } } : {}
return new GraphQLClient(endpoint, options)
}
const fetcher = ({ query, variables, operationName, context }) => {
const db = State.get('connect', '_db')
return db.request(query, variables).then((data) => {
return { data }
})
}
const getSchema = async () => {
return await fetcher({
query: graphql.introspectionQuery,
})
}
function formatResults(data) {
if (Array.isArray(data)) {
return {
object: data,
columns: Object.keys(data[0]),
values: data.map((d) => Object.values(d)),
}
} else {
return {
object: data,
columns: Object.keys(data),
values: [Object.values(data)],
}
}
}
export const buildGQLSchema = _.memoize((result) => {
if (!result) return null
return graphql.buildClientSchema(result.data)
})
export function Clippy(props) {
return (
<div className="clippy-wrap">
<div className="clippy">
{props.connect.graphqlschema ? (
<GraphQLDocs schema={props.connect.graphqlschema.data} />
) : null}
</div>
</div>
)
}
export async function connectDB() {
console.log('connectDB started')
await connectHelper(async function() {
State.apply('connect', '_db', U.replace(database()))
State.apply('connect', 'graphqlschema', U.replace(await getSchema()))
})
}
export function CodeMirrorOptions(connect, virtualSchema) {
return {
mode: 'graphql',
hintOptions: {
hint: CodeMirror.hint.graphql,
schema: buildGQLSchema(connect.graphqlschema),
},
lint: buildGQLSchema(connect.graphqlschema),
}
}
|
/**
* @module whynot
*/
define(
[
'./Generation'
],
function(
Generation
) {
'use strict';
/**
* Schedules Threads to run in the current or a future Generation.
*
* @class Scheduler
* @constructor
*
* @param {Number} numGenerations Number of Generations to plan ahead
* @param {Number} programLength Length of the program being run
* @param {Thread[]} oldThreadList Array used for recycling Thread objects
*/
function Scheduler(numGenerations, programLength, oldThreadList) {
// The active and scheduled generations
this._generations = [];
for (var i = 0; i < numGenerations; ++i) {
this._generations.push(new Generation(programLength, oldThreadList, i));
}
// The number of generations executed so far
this._generationsCompleted = 0;
}
/**
* Resets the Scheduler for reuse.
*
* @method reset
*/
Scheduler.prototype.reset = function() {
// Reset each generation
for (var i = 0, l = this._generations.length; i < l; ++i) {
this._generations[i].reset(i);
}
this._generationsCompleted = 0;
};
function getRelativeGeneration(scheduler, generationOffset) {
// Determine generation to insert the new thread for
var numGenerations = scheduler._generations.length;
if (generationOffset >= numGenerations) {
throw new Error('Not enough active generations to schedule that far ahead');
}
var generationNumber = scheduler._generationsCompleted + generationOffset;
return scheduler._generations[generationNumber % numGenerations];
}
/**
* Adds a Thread to the Generation at the given offset relative to the current one.
*
* @method addThread
*
* @param {Number} generationOffset Offset of the target generation, relative to the current
* @param {Number} pc Program counter for the new Thread
* @param {Thread} [parentThread] Thread which spawned the new Thread
* @param {Number} [badness] Increasing badness decreases thread priority
*
* @return {Thread|null} The Thread that was added, or null if no thread was added
*/
Scheduler.prototype.addThread = function(generationOffset, pc, parentThread, badness) {
var generationForThread = getRelativeGeneration(this, generationOffset);
// Add thread to the generation
return generationForThread.addThread(pc, parentThread, badness);
};
/**
* Returns the next thread to run in the current Generation.
*
* @method getNextThread
*
* @return {Thread|null} The next Thread to run, or null if there are none left
*/
Scheduler.prototype.getNextThread = function() {
var currentGeneration = getRelativeGeneration(this, 0);
return currentGeneration.getNextThread();
};
/**
* Switches to the next Generation.
*
* @method nextGeneration
*/
Scheduler.prototype.nextGeneration = function() {
// Recycle current generation and move to next
var currentGeneration = getRelativeGeneration(this, 0);
currentGeneration.reset(this._generationsCompleted + this._generations.length);
++this._generationsCompleted;
};
return Scheduler;
}
);
|
/*
Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
if(!dojo._hasResource["dojox.charting.themes.PlotKit.cyan"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.charting.themes.PlotKit.cyan"] = true;
dojo.provide("dojox.charting.themes.PlotKit.cyan");
dojo.require("dojox.charting.themes.PlotKit.base");
(function(){
var dc = dojox.charting, pk = dc.themes.PlotKit;
pk.cyan = pk.base.clone();
pk.cyan.chart.fill = pk.cyan.plotarea.fill = "#e6f1f5";
pk.cyan.colors = dc.Theme.defineColors({hue: 194, saturation: 60, low: 40, high: 88});
})();
}
|
/** @jsx jsx */
import { Editor } from 'slate'
import { jsx } from '../../..'
export const input = (
<editor>
<block>
<text>
w<anchor />
or
<focus />d
</text>
</block>
</editor>
)
export const run = editor => {
Editor.insertText(editor, 'x', { at: { path: [0, 0], offset: 2 } })
}
export const output = (
<editor>
<block>
w<anchor />
oxr
<focus />d
</block>
</editor>
)
|
//ECMAScript6
include("assets/asset.js", true);
include("assets/assetmanager.js", true);
class ImageAsset extends EN.Asset
{
//////////////////////////////////////////////////////////
//region Constructor
constructor(sFileName, cOptions)
{
super(sFileName);
this.Renderable = true;
var cDefaults = {
visibleWidth: null,
visibleHeight: null,
offset: {x: 0, y: 0},
baseImage: null,
tile: false
};
this.m_cOptions = extend(cDefaults, isset(cOptions) ? cOptions : {});
this.m_cBaseImage = null;
this.m_cBasePattern = null;
this.m_bLoaded = false;
this.Anchor = new EN.Vector(0, 0);
this.Offset = new EN.Vector(this.m_cOptions.offset.x, this.m_cOptions.offset.y);
this.ImageWidth = 0;
this.ImageHeight = 0;
this.Alpha = 1;
if (this.m_cOptions.baseImage)
{
this.__InitImage(this.m_cOptions.baseImage);
}
}
//endregion
//////////////////////////////////////////////////////////
//region Static Methods
static Clone(cOtherImageAsset)
{
var cNewImageAsset = new ImageAsset(cOtherImageAsset.FileName, cOtherImageAsset.m_cOptions);
cNewImageAsset.__InitImage(cNewImageAsset.m_cBaseImage);
return cNewImageAsset;
}
//endregion
//////////////////////////////////////////////////////////
//region Public Methods
GetImage()
{
return this.m_cBaseImage;
}
Load(fOnLoad)
{
var self = this;
EN.AssetManager.LoadImage(this.m_sFileName, function(cErr, cImage){
if (cErr)
{
throw cErr;
}
else
{
self.__InitImage(cImage);
fOnLoad();
}
});
}
Draw(cRenderer)
{
if (!this.m_bLoaded)
{
throw new Error("Image Asset NOT LOADED: " + this.m_sFileName);
}
super.Draw(cRenderer);
if (this.m_cOptions.tile)
{
throw new Error("NOT YET IMPLEMENTED");
//Lazy Load Required Pattern
/*if (!this.m_cBasePattern)
{
this.m_cBasePattern = cRenderer.CreatePattern(this.m_cBaseImage);
}
cRenderer.DrawTiledImage(this.GlobalTransform, this.m_cBasePattern, this.Width, this.Height, this.Anchor, this.Alpha);*/
}
else
{
cRenderer.DrawImage(this);
}
}
Destroy()
{
super.Destroy();
EN.AssetManager.ReleaseImage(this.m_sFileName);
};
//endregion
//////////////////////////////////////////////////////////
//region Private Methods
__InitImage(cImage)
{
this.m_cBaseImage = cImage;
this.ImageWidth = this.m_cOptions.visibleWidth || cImage.width;
this.ImageHeight = this.m_cOptions.visibleHeight || cImage.height;
this.Width = this.ImageWidth;
this.Height = this.ImageHeight;
this.m_bLoaded = true;
}
//endregion
}
EN.ImageAsset = ImageAsset;
|
/*global define, describe, it, expect*/
define([
"CanvasShapes"
], function(
CanvasShapes
) {
describe('CanvasShapes.Point', function () {
it('instantiating', function () {
var error1 = new CanvasShapes.Error(1011);
// no coordinates passed
expect(function () {
new CanvasShapes.Point();
}).toThrow(error1);
// wrong format of coordinates passed
expect(function () {
new CanvasShapes.Point([]);
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point({});
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point(1);
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point('string');
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point(true);
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point(['a', 'b']);
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point([['a', 'b'], ['a', 'b']]);
}).toThrow(error1);
expect(function () {
new CanvasShapes.Point([0]);
}).toThrow(error1);
// all good with initialisation
expect(function () {
new CanvasShapes.Point([0, 0]);
}).not.toThrow();
});
it('correctly sets UUID', function () {
var shape1 = new CanvasShapes.Point([0, 0]),
regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
expect(regex.test(shape1.getUUID())).toBe(true);
});
it('correctly sets min and max coordinates variables', function () {
var point1 = new CanvasShapes.Point([0, 0]);
expect(point1.MIN_COORDINATES).toBe(1);
expect(point1.MAX_COORDINATES).toBe(1);
});
it('rendering', function () {
var scene = new CanvasShapes.Scene({
element: document.createElement('div'),
width: 200,
height: 200
}),
layer = new CanvasShapes.SceneLayer(scene),
point = new CanvasShapes.Point([0, 0]);
expect(function () {
point.render(layer);
}).not.toThrow();
});
it('getting coordinates', function () {
var point = new CanvasShapes.Point([0, 0]);
expect(point.getCoordinates()).toEqual([0, 0]);
});
it('setting scene interface handlers', function () {
var i,
point1 = new CanvasShapes.Point([0, 0]),
point2 = new CanvasShapes.Point(
[0, 0],
CanvasShapes.Point.FACES.CIRCLE
),
sceneInterfaceHandlers = {
newLayer: function () {},
getLayer: function () {},
addShape: function () {}
};
// there is no face, therefore it shouldn't set anything
point1.setSceneInterfaceHandlers(sceneInterfaceHandlers);
expect(point1._sceneInterfaceHandlers[0])
.toBe(sceneInterfaceHandlers);
expect(point1._face).toBe(undefined);
point2.setSceneInterfaceHandlers(sceneInterfaceHandlers);
expect(point2._face._sceneInterfaceHandlers[0])
.toBe(sceneInterfaceHandlers);
for (i in sceneInterfaceHandlers) {
expect(point1._sceneInterfaceHandlers[i]).toBeDefined();
expect(point2._sceneInterfaceHandlers[i]).toBeDefined();
expect(point2._face._sceneInterfaceHandlers[i]).toBeDefined();
expect(point1._sceneInterfaceHandlers[0][i]).toBeDefined();
expect(point2._sceneInterfaceHandlers[0][i]).toBeDefined();
expect(point2._face._sceneInterfaceHandlers[0][i]).toBeDefined();
expect(CanvasShapes._.isFunction(point1._sceneInterfaceHandlers[i]))
.toBe(true);
expect(CanvasShapes._.isFunction(point2._sceneInterfaceHandlers[i]))
.toBe(true);
expect(CanvasShapes._.isFunction(point2._face._sceneInterfaceHandlers[i]))
.toBe(true);
expect(CanvasShapes._.isFunction(point1._sceneInterfaceHandlers[0][i]))
.toBe(true);
expect(CanvasShapes._.isFunction(point2._sceneInterfaceHandlers[0][i]))
.toBe(true);
expect(CanvasShapes._.isFunction(point2._face._sceneInterfaceHandlers[0][i]))
.toBe(true);
}
});
it('setting and getting style', function () {
var point1 = new CanvasShapes.Point([0, 0]),
point2 = new CanvasShapes.Point(
[0, 0],
CanvasShapes.Point.FACES.CIRCLE
),
style = new CanvasShapes.Style(function (context) {
context.fill();
});
// it should return null when point doesn't have a face
style.addToShapes(point1);
expect(point1.getStyle()).toBe(null);
style.addToShapes(point2);
expect(point2.getStyle()).toBe(style);
});
it('setting face', function () {
var error1 = new CanvasShapes.Error(1008),
error2 = new CanvasShapes.Error(1026),
point = new CanvasShapes.Point([0, 0]);
expect(function () {
point.setFace('circle');
point.setFace('circle', 100);
point.setFace('none');
point.setFace(new CanvasShapes.Line([[0, 0], [1, 1]]));
}).not.toThrow();
// wrong face string passed
expect(function () {
point.setFace('non-existing face');
}).toThrow(error1);
// wrong type of face passed
expect(function () {
point.setFace({});
}).toThrow(error2);
expect(function () {
point.setFace([]);
}).toThrow(error2);
expect(function () {
point.setFace(1);
}).toThrow(error2);
expect(function () {
point.setFace(true);
}).toThrow(error2);
});
it('sets relative rendering correctly', function () {
var point = new CanvasShapes.Point([0, 0]);
point.setFace('circle');
expect(point.getRelativeRendering()).toBe(false);
expect(point._face.getRelativeRendering()).toBe(false);
point.setRelativeRendering(true);
expect(point.getRelativeRendering()).toBe(true);
expect(point._face.getRelativeRendering()).toBe(true);
// newly added face will inherit relative rendering from point
point.setFace('circle', 100);
expect(point._face.getRelativeRendering()).toBe(true);
});
it('returns undefined in `isShapeOpen` method', function () {
var shape = new CanvasShapes.Point([0, 0]);
expect(shape.isShapeOpen()).toBeUndefined();
});
it('returns undefined in `isShapeClosed` method', function () {
var shape = new CanvasShapes.Point([0, 0]);
expect(shape.isShapeClosed()).toBeUndefined();
});
it('returns true in `isShapeContinuous` method', function () {
var shape = new CanvasShapes.Point([0, 0]);
expect(shape.isShapeContinuous()).toBe(true);
});
});
});
|
"use strict";
var fs = require('fs'),
path = require('path'),
http = require('http'),
tiptoe = require('tiptoe'),
async = require('async');
function createDir(dir, callback) {
var dir = path.join(__dirname, dir);
fs.mkdir(dir, function(e) {
if (!e)
return(setImmediate(callback));
if (e.code == 'EEXIST')
return(setImmediate(callback));
throw(e);
});
}
function downloadJSON(url, fn, callback) {
function getData() {
var retData = undefined;
fs.readFile(fn, 'utf8', function(err, data) {
if (!err) {
retData = data;
}
if (callback)
callback(undefined, retData);
})
}
var request = http.get(url, function(response) {
var file = fs.createWriteStream(fn);
response.pipe(file);
file.on('finish', function() {
file.close(getData);
});
}).on('error', function(err) {
if (callback)
callback(err.message);
});
}
function downloadVersionJSON(callback) {
var url = 'http://mtgjson.com/json/version.json';
var fn = path.join(__dirname, 'json', 'version.json');
downloadJSON(url, fn, callback);
}
function finish(err) {
console.log('done');
if (err)
throw(err);
}
// Read current version
var curVer = 0;
var remoteVer = 0;
function readVersion(callback) {
fs.readFile(path.join(__dirname, 'json', 'version.json'), 'utf8', function(err, data) {
if (err) {
console.log("no version information found.");
}
else {
curVer = data;
}
if (callback)
callback();
});
}
var csvFields = [
'name',
'manaCost',
'cmc',
'colorIdentity',
'artist',
'number',
'type',
'text',
'printings',
'flavor',
'layout',
'multiverseid',
'power',
'toughness',
'rarity',
'subtypes',
'types'
];
function saveSet(setName, cards, callback) {
var fn = path.join(__dirname, 'csv', setName + '.csv');
fs.open(fn, 'w', function (err, fd) {
if (err)
return(setImmediate(function() {
if (callback) callback(err);
}));
tiptoe(
function header() {
fs.write(fd, csvFields.join(',') + "\n", this);
},
function body() {
async.eachSeries(cards, function(card, cardCB) {
var i;
var contents = [];
for (i = 0; i < csvFields.length; i++) {
var curEntry = card[csvFields[i]];
if (!curEntry)
curEntry = "";
if (Array.isArray(curEntry)) {
curEntry = curEntry.join(',');
};
if ((typeof curEntry) === 'number') {
curEntry = '' + curEntry;
}
if ((typeof curEntry) !== 'string') {
console.log("Something is wrong!");
console.log(curEntry);
}
curEntry = curEntry.replace(/\n/g, '\\n');
curEntry = curEntry.replace(/"/g, '""');
if (curEntry.indexOf(',') >= 0 || curEntry.indexOf('"') >= 0) {
curEntry = '"' + curEntry + '"';
}
contents.push(curEntry);
}
fs.write(fd, contents.join(',') + "\n", cardCB);
}, this);
},
function finish(err) {
if (err)
throw(err);
fs.close(fd, callback);
}
);
});
}
tiptoe(
function init() {
createDir('json', this.parallel());
createDir('csv', this.parallel());
},
function() {
var fn = path.join(__dirname, 'json', 'AllSets-x.json');
fs.exists(fn, function(e) {
if (e) {
fs.readFile(fn, 'utf8', this);
}
else {
console.log("Downloading...");
var url = 'http://mtgjson.com/json/AllSets-x.json';
downloadJSON(url, fn, this);
}
}.bind(this));
},
function processFile(data) {
var setData = JSON.parse(data);
var keys = Object.keys(setData);
var i;
async.eachSeries(keys, function(setName, foreachCB) {
saveSet(setName, setData[setName].cards, foreachCB);
}, this);
},
function finish(err) {
if (err)
throw(err);
console.log('done');
}
);
|
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BlogSchema = new Schema({
id: String,
tags: Array,
title: String,
content: String,
time: String
});
module.exports = BlogSchema; |
'use strict';
var gulp = require('gulp');
var paths = gulp.paths;
var $ = require('gulp-load-plugins')();
gulp.task('scripts', function () {
return gulp.src(paths.src + '/{,scripts}/**/*.coffee')
.pipe($.coffeelint())
.pipe($.coffeelint.reporter())
.pipe($.coffee())
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe(gulp.dest(paths.tmp + '/serve/'))
.pipe($.size())
});
|
var feeds = require('./cloudant.js').feeds;
var articles = require('./cloudant.js').articles;
var async = require('async');
var request = require('request');
var FeedParser = require('feedparser');
var moment = require('moment');
var extractor = require('extractor');
var favicon = require('./favicon.js');
var crypto = require('crypto');
var u = require('url');
var url_details = require('./url_details.js');
// read all the feeds from Cloudant
var readAll = function (callback) {
var retval = [],
i = 0;
feeds.list({include_docs: true}, function (err, data) {
retval = [];
if (!err) {
for (i = 0; i < data.rows.length; i++) {
retval.push(data.rows[i].doc);
}
}
callback(err, retval);
});
};
// fetch 'feed' and callback when done, passing (err, articles)
var fetchFeed = function (feed, callback) {
// check that the feed is valid before fetching
var parsed = u.parse(feed.xmlUrl);
if (parsed.protocol != "http:" && parsed.protocol != "https:" ) {
return callback(true, []);
}
// only get articles newer than this feed's newest article
var newerThan = moment(feed.lastModified),
latest = moment(feed.lastModified),
headers = {'If-Modified-Since' : newerThan.format('ddd, DD MMM YYYY HH:mm:ss Z')},
reqObj = { 'uri': feed.xmlUrl,
'headers': headers,
'timeout': 30000,
'strictSSL': false },
articles = [],
a = {},
shasum = null,
m = null,
stream = null,
data = null;
// use request to fetch the feed and pipe the stream to FeedParser
request(reqObj)
.on('error',function(e){
// this is an error from request e.g. DNS error
console.log("Failed to connect to ",reqObj.uri);
return callback(e,articles);
})
.pipe(new FeedParser({}))
.on('error', function(err) {
// this is an error from FeedParser e.g. parse error
//console.log("parse error", reqObj.uri)
})
.on('readable', function () {
// we have one or more articles to parse
stream = this;
data = null;
while (data = stream.read()) {
a = {};
// use a hash of the articles's url as the document id - to prevent duplicates
if (typeof data.link === 'string') {
shasum = crypto.createHash('sha1');
shasum.update(data.link);
a._id = shasum.digest('hex');
a.feedName = feed.title;
a.tags = feed.tags;
a.title = data.title;
a.description = data.description;
a.pubDate = data.pubDate;
a.link = data.link;
if (typeof feed.icon !== "undefined") {
a.icon = feed.icon;
} else {
a.icon = null;
}
m = moment(data.pubDate);
if (m) {
a.pubDateTS = m.format("X");
a.read = false;
a.starred = false;
if (m.isAfter(newerThan)) {
articles.push(a);
if (m.isAfter(latest)) {
latest = m;
}
}
}
}
}
})
.on('end', function() {
// update last modified date of the feed and return the found articles
feed.lastModified = latest.format('YYYY-MM-DD HH:mm:ss Z');
return callback(null, articles);
});
};
// fetch all the articles from all the feeds
var fetchArticles = function (callback) {
// create a fetch function for each one
var functions = [],
i = 0,
r = 0,
bigresults = [],
feedsToSave = [];
// load all feeds from Cloudant
readAll(function (err, allFeeds) {
// for each feed
for (i = 0; i < allFeeds.length; i++) {
// create a closure to feed to create a functions array of work to do in parallel
(function (feed) {
functions.push(function (cb) {
var before_ts = feed.lastModified;
fetchFeed(feed, function (err, data) {
// if the feed has a new timestamp, put it in an array to write back to the database
if (feed.lastModified > before_ts) {
feedsToSave.push(feed);
}
cb(null, data);
});
});
})(allFeeds[i]);
}
// perform fetches in parallel
async.parallelLimit(functions, 25, function (err, results) {
if (!err) {
// concat all the results arrays into bigresults
bigresults = [];
for (r = 0; r < results.length; r++) {
bigresults = bigresults.concat(results[r]);
}
// write the articles to the database
if (bigresults.length > 0) {
articles.bulk({"docs": bigresults}, function (err, d) {
console.log("Written ", bigresults.length, " articles");
//console.log(bigresults);
});
}
// rewrite the feeds to the database
if (feedsToSave.length > 0) {
feeds.bulk({"docs": feedsToSave}, function (err, d) {
console.log("Written ",feedsToSave.length," feeds");
});
}
callback(err, results);
}
});
});
};
var addFeed = function(xmlurl, htmlurl, type, title, description, callback) {
feed = {};
feed.text = title;
feed.title = title;
feed.type = type;
feed.description = description;
feed.xmlUrl = xmlurl;
feed.htmlUrl = htmlurl;
feed.tags = [];
feed.lastModified = moment().format('YYYY-MM-DD HH:mm:ss Z');
// if we have found a feed
if (feed.xmlUrl) {
// see if we can find a favicon
favicon.find(feed.htmlUrl, function (faviconUrl) {
// add icon to feed
feed.icon = faviconUrl;
// add it to the database
feeds.insert(feed, function (err, data) {
//console.log(err,data);
retval = { success: true, message: "Added feed for " + xmlurl, data:data};
callback(null, retval);
});
});
} else {
callback(true, null);
}
};
// add a feed for this url
var add = function (url, callback) {
var mimeTypes = ["text/xml", "application/rss+xml", "application/rdf+xml", "application/atom+xml", "application/xml"];
url_details.getHeaders(url, function(err, details) {
// if this is an XML feed, then add it
if (mimeTypes.indexOf(details.contentType)>-1) {
addFeed(url, url, "rss", url, url, function(err, data) {
callback(false, { success: true, message: "Successfully added feed"});
})
} else {
// scrape the url looking for link tags
var retval = null,
feed = null,
i = null,
selector = {
'title': 'title',
'links': 'link',
'metadescription': 'meta[name=description]'
};
extractor.scrape(url, selector, function (err, data, env) {
if (err) {
retval = { success: false, message: "Could not fetch" + url};
return callback(true, retval);
}
if (!data.links) {
return callback(true, { success: false, message: "Could not add feed for " + url});
}
// look for matching link tags
var xmlurl = null;
var htmlurl = url;
var type = null;
var description = data.metadescription;
var title = data.title[0].text;
for (i = 0; i < data.links.length; i++) {
if (typeof data.links[i].type !== "undefined") {
if (data.links[i].type === "application/rss+xml") {
xmlurl = data.links[i].href;
type = 'rss';
break;
}
if (data.links[i].type === "application/atom+xml") {
xmlUrl = data.links[i].href;
type = 'rss';
break;
}
if (data.links[i].type === "application/rdf+xml") {
xmlUrl = data.links[i].href;
type = 'rss';
break;
}
}
}
if(xmlUrl) {
// turn relative urls into absolute urls
xmlUrl = u.resolve(url, xmlUrl);
//console.log(feed.xmlUrl);
addFeed(xmlUrl, htmlurl, type, title, description, function(err, data) {
callback(false, { success: true, message: "Successfully added feed"});
});
} else {
retval = { success: false, message: "Could not add feed for " + url};
callback(true, retval);
}
});
}
});
};
// fetch a single feed
var get = function (id, callback) {
feeds.get(id, callback);
};
// add a tag to an existing feed
var addTag = function (id, tag, callback) {
tag = tag.replace(/^ +/, "").replace(/ +$/, "");
feeds.get(id, function (err, data) {
if (!err) {
data.tags.push(tag);
feeds.insert(data, function (err, data) {
callback(null, data);
});
}
});
};
// remove a tag to an existing feed
var removeTag = function (id, tag, callback) {
var i = 0;
feeds.get(id, function (err, data) {
if (!err) {
for (i = 0; i < data.tags.length; i++) {
if (data.tags[i] === tag) {
data.tags.splice(i, 1);
}
}
feeds.insert(data, function (err, data) {
callback(null, data);
});
}
});
};
// remove a feed
var remove = function (id, callback) {
feeds.get(id, function (err, data) {
if (!err) {
feeds.destroy(id, data._rev, function (err, data) {
callback(null, data);
});
}
});
};
// update a feed
var update = function (feed, callback) {
feeds.insert(feed, function (err, data) {
callback(err, data);
});
};
module.exports = {
readAll: readAll,
fetchArticles: fetchArticles,
fetchFeed: fetchFeed,
add: add,
get: get,
addTag: addTag,
removeTag: removeTag,
remove: remove,
update: update
}; |
// @flow
export default {
f_6: {
fontSize: '6rem'
},
f_headline: {
fontSize: '6rem'
},
f_5: {
fontSize: '5rem'
},
f_subheadline: {
fontSize: '5rem'
},
f1: {
fontSize: '3rem'
},
f2: {
fontSize: '2.25rem'
},
f3: {
fontSize: '1.5rem'
},
f4: {
fontSize: '1.25rem'
},
f5: {
fontSize: '1rem'
},
f6: {
fontSize: '0.875rem'
},
f7: {
fontSize: '.75rem'
}
}
|
module.exports = (deps) => {
return function createServer() {
const {
'express': express,
'express-domain-middleware': domainMiddleware,
'node-hook': hook,
'svg-inline-loader': SvgLoader,
'/routes/index': getRoutes,
'/middleware/errorHandler': errorHandler,
'/middleware/logRequests': logRequests,
'/middleware/etagCache': etagCache,
'response-time': responseTime,
compression
} = deps;
const app = express();
app.use(etagCache.setETagHeader);
app.use(responseTime());
hook.hook('.scss', () => {});
hook.hook('.svg', (source) => {
const markup = SvgLoader.getExtractedSVG(source, { removeSVGTagAttrs: false });
return 'module.exports = ' + JSON.stringify(markup);
});
app.set('Accept-Encoding', 'gzip');
app.use(logRequests); //be first to ensure all requests are logged
app.use(compression());
app.use(domainMiddleware);
app.use(getRoutes());
app.use('/public', express.static('public'));
app.use(errorHandler);
return app;
};
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:8d22e9c93a6d0f88d5333874f9835f745ee4c4a0b5e3667ab11eb46600c6e3c4
size 12137
|
/**
* gulp watch
*/
const config = require('../config');
const gulp = require('gulp');
const runSequence = require('run-sequence');
gulp.task('watch', ['compile'], () => {
gulp.watch([`**/*.scss`], { cwd: config.css.scssDir }, ['css'])
.on('change', config.gulp.onChange);
gulp.watch(['**/*'], { cwd: config.svg.srcDir }, ['svg'])
.on('change', config.gulp.onChange);
gulp.watch([`${config.img.srcDir}/**/*`], function (event) {
runSequence('images', 'copy:statixImg');
});
gulp.watch(`${config.js.srcDir}/**/*.js`, ['javascript'])
.on('change', config.gulp.onChange);
gulp.watch('**/*.{md,hbs}', { cwd: config.statix.dir }, ['assemble'])
.on('change', config.gulp.onChange)
});
// Alias of watch task
gulp.task('watcher', ['watch'])
|
module.exports.normalised_to_colour = function(normalised) {
var value = Math.round(normalised*255);
return "#" + value.toString(16) + value.toString(16) + value.toString(16);
};
|
//
// Created on: <1-Aug-2002 16:45:00 fh>
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ Publish
// SOFTWARE RELEASE: 4.1.x
// COPYRIGHT NOTICE: Copyright (C) 1999-2013 eZ Systems AS
// SOFTWARE LICENSE: eZ Business Use License Agreement eZ BUL Version 2.1
// NOTICE: >
// This source file is part of the eZ Publish CMS and is
// licensed under the terms and conditions of the eZ Business Use
// License v2.1 (eZ BUL).
//
// A copy of the eZ BUL was included with the software. If the
// license is missing, request a copy of the license via email
// at license@ez.no or via postal mail at
// Attn: Licensing Dept. eZ Systems AS, Klostergata 30, N-3732 Skien, Norway
//
// IMPORTANT: THE SOFTWARE IS LICENSED, NOT SOLD. ADDITIONALLY, THE
// SOFTWARE IS LICENSED "AS IS," WITHOUT ANY WARRANTIES WHATSOEVER.
// READ THE eZ BUL BEFORE USING, INSTALLING OR MODIFYING THE SOFTWARE.
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//
/*! \file ezjslibmousetracker.js
*/
/*!
\brief
This library contains a mouse tracker. Simply include it and the current mouse
position will be in MouseX and MouseY.
*/
// Global VARS
var MouseX = 0; // Track mouse position
var MouseY = 0;
/**
* mouseHandler is called each time the mouse is moved within the document. We use the
* mouse position to popup the menus where the mouse is located.
*/
function ezjslib_mouseHandler( e )
{
if ( !e )
{
e = window.event;
}
if ( e.pageX || e.pageY )
{
MouseX = e.pageX;
MouseY = e.pageY;
}
else if ( e.clientX || e.clientY ) // IE needs special treatment
{
MouseX = e.clientX + document.documentElement.scrollLeft;
MouseY = e.clientY + document.documentElement.scrollTop;
}
}
// Uncomment the following lines if you want to use the mouseHandler function
// for tracing. Note that this can be slow on IE.
//document.onmousemove = ezjslib_mouseHandler;
//if ( document.captureEvents ) document.captureEvents( Event.MOUSEMOVE ); // NN4
|
version https://git-lfs.github.com/spec/v1
oid sha256:2cd710f5c130aca5358438d9cc117332e0c719ea1b7c58408a1bf3f9e885b260
size 642
|
var keystone = require('keystone'),
Types = keystone.Field.Types;
/**
* Case Model
* ===================
*/
var Case = new keystone.List('Case', {
track: true,
autokey: { from: 'name', path: 'key', unique: true }
});
Case.add({
name: {type: String, required: true, initial: true},
description: {type: Types.Html, wysiwyg: true},
image: { type: Types.CloudinaryImage },
presenter: { type: Types.Relationship, ref: 'User', index: true },
meetup: { type: Types.Relationship, ref: 'Meetup', index: true },
organisation: { type: Types.Relationship, ref: 'Organisation' },
tags: { type: Types.Relationship, ref: 'CaseTag', many: true },
feedback: {type: Types.Html, wysiwyg: true},
date: { type: Types.Date, default: Date.now, index: true }
});
/**
* Registration
* ============
*/
Case.register();
|
const gulp = require('gulp');
const notifier = require('node-notifier');
const _invalidateRequireCacheForFile = function(filePath) {
delete require.cache[require.resolve(filePath)];
};
const requireNoCache = function(filePath) {
_invalidateRequireCacheForFile(filePath);
return require(filePath);
};
gulp.task('watch', () => {
gulp.watch('lib/**/*', function(event) {
const generateServices = requireNoCache('./lib/es6services');
const writeFiles = require('./lib/utils/writeFiles');
let app = require('./test/testApp/server/server');
let options = {
apiUrl: 'http://localhost:3333/api',
};
let output;
try {
output = generateServices(app, options);
} catch (err) {
console.log('err', err);
notifier.notify({
title: 'Compile error',
message: err.message,
});
}
if (output) {
writeFiles(output, 'generatedFiles').then(() => {});
}
});
});
gulp.task('default', ['watch']);
|
import test from 'ava';
import sinon from 'sinon';
import server from './server';
import config from './config';
test('It allows headers from config', (t) => {
config.allowedOrigins.forEach((origin) => {
const req = {
headers: {
origin,
},
};
const res = {
setHeader: sinon.spy(),
};
const next = sinon.spy();
server.getAllowedOrigin(req, res, next);
t.true(res.setHeader.calledWith('Access-Control-Allow-Origin', req.headers.origin));
t.true(next.called);
});
});
test('It does not set headers of invalid origins', (t) => {
const req = {
headers: {
origin: 'http://not-allowed.com',
},
};
const res = {
setHeader: sinon.spy(),
};
const next = sinon.spy();
server.getAllowedOrigin(req, res, next);
t.false(res.setHeader.called);
t.true(next.called);
});
test('Listen does not throw an error.', (t) => {
t.notThrows(server.listen);
});
|
import _ from 'lodash'
let imgImportIdentifiers = {};
let rootScope;
function isReactCreateElement(path) {
return path.get('callee').matchesPattern('React.createElement')
}
function hasImgArgument(path) {
return path.get('arguments').length > 1 &&
path.get('arguments')[0].isStringLiteral({value: 'img'})
}
function hasSvgImageArgument(path) {
return path.get('arguments').length > 1 &&
path.get('arguments')[0].isStringLiteral({value: 'image'})
}
function getPropertyValue(path, propertyName) {
if (path.get('arguments')[1].isObjectExpression()) {
let props = path.get('arguments')[1].get("properties");
for (let prop of props) {
if (!prop.isProperty()) continue;
let key = prop.get("key");
if (key.isIdentifier({name: propertyName})) {
return prop.get("value");
}
}
}
}
function isURL(url) {
let lowerURL = url.toLowerCase()
return lowerURL.startsWith('http://') || lowerURL.startsWith('https://') || lowerURL.startsWith('data:')
}
function transformImgSrcNodePath(imgSrcNodePath, t) {
if (imgSrcNodePath.isStringLiteral() && !imgSrcNodePath._img_import_processed) {
imgSrcNodePath._img_import_processed = true;
return createImport( imgSrcNodePath.node.value , t);
} else {
return imgSrcNodePath;
}
}
function transformSvgImageHrefNodePath(svgImageHrefNodePath, t) {
if (svgImageHrefNodePath.isStringLiteral() && !svgImageHrefNodePath._img_import_processed) {
svgImageHrefNodePath._img_import_processed = true;
return createImport( svgImageHrefNodePath.node.value , t);
} else {
return svgImageHrefNodePath;
}
}
function parseSrcSetValue( srcSetValue ) {
const imgList = srcSetValue.split(',').map(function ( img ) {
const [imgSrc,descriptor]=img.trim().split(' ');
return {imgSrc,descriptor}
})
return imgList;
}
function createImport( imgSrc , t){
// Override transformation
if (imgSrc.startsWith('!')) {
return t.stringLiteral(imgSrc.substring(1));
}
// Ignore if src is an absolute URL
if (isURL(imgSrc)) {
return t.stringLiteral(imgSrc);
}
// cache import identifiers.
let imgImportIdentifier = imgImportIdentifiers[imgSrc]
if (!imgImportIdentifier) {
imgImportIdentifier = rootScope.generateUidIdentifier('image');
imgImportIdentifiers[imgSrc] = imgImportIdentifier
}
// We need to access the default import since Babel shim non
// CommonJS modules.
let imgImportDefaultIdentifier = t.memberExpression(
imgImportIdentifier, t.identifier("default"))
return imgImportDefaultIdentifier;
}
function transformImgSrcSetNodePath(imgSrcSetValueNodePath, t) {
if (imgSrcSetValueNodePath.isStringLiteral() ) {
let srcSetValue = imgSrcSetValueNodePath.node.value;
let srcSetList = parseSrcSetValue(srcSetValue);
const srcSetValues = srcSetList.map(function (srcSetElement) {
const imgSrc = createImport(srcSetElement.imgSrc,t);
const descriptor = ( srcSetElement.descriptor ) ?
t.stringLiteral(srcSetElement.descriptor) : t.stringLiteral('')
return {imgSrc,descriptor}
})
const srcSetExpression = srcSetValues.reduce(function (prev, current,i) {
let exp = t.binaryExpression( '+',
t.binaryExpression( '+', current.imgSrc , t.stringLiteral(' ') ),
current.descriptor );
if ( i < srcSetValues.length - 1 ){
exp = t.binaryExpression( '+', exp, t.stringLiteral(', '))
}
if ( prev ){
exp = t.binaryExpression( '+' , prev , exp )
}
return exp;
},null)
return srcSetExpression;
} else {
return imgSrcSetValueNodePath;
}
}
export default function ({types: t}) {
return {
visitor: {
CallExpression(path, state) {
// is a React.createElement("img" .... )
if (isReactCreateElement(path) && hasImgArgument(path)) {
// process src
let imgSrcValueNodePath = getPropertyValue(path,'src');
if (imgSrcValueNodePath) {
let newSrcValueNodePath = transformImgSrcNodePath(imgSrcValueNodePath, t)
imgSrcValueNodePath.replaceWith(newSrcValueNodePath);
}
// process srcSet
let imgSrcSetValueNodePath = getPropertyValue(path,'srcSet');
if ( imgSrcSetValueNodePath ){
let newSrcSetValueNodePath = transformImgSrcSetNodePath(imgSrcSetValueNodePath, t)
imgSrcSetValueNodePath.replaceWith(newSrcSetValueNodePath)
}
} else if (isReactCreateElement(path) && hasSvgImageArgument(path)) {
// process href
let svgImageHrefValueNodePath = getPropertyValue(path,'href');
if (svgImageHrefValueNodePath) {
let newSvgImageHrefValueNodePath = transformSvgImageHrefNodePath(svgImageHrefValueNodePath, t)
svgImageHrefValueNodePath.replaceWith(newSvgImageHrefValueNodePath);
}
}
},
Program: {
exit(path, state){
const importDeclarations = _.map(imgImportIdentifiers, (imgImportIdentifier, imgSrcLiteral) => {
return t.importDeclaration(
[t.importNamespaceSpecifier(imgImportIdentifier)],
t.stringLiteral(imgSrcLiteral))
})
path.unshiftContainer('body', importDeclarations);
},
enter(path, state){
imgImportIdentifiers = {};
rootScope = path.scope;
}
}
}
}
}
|
import React from 'react';
//import classNames from 'classnames';
class ImgFigure extends React.Component{
/*
* 初始化props
*/
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
/*
* imgFigure 的点击处理函数
*/
handleClick(e) {
if(this.props.arrange.isCenter){
this.props.inverse();
}else{
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
var styleObj = {};
//如果props属性中指定了这张图片的位置,则使用
if (this.props.arrange.pos){
styleObj = this.props.arrange.pos;
}
//设置中心图片的三维深度
if(this.props.arrange.isCenter){
styleObj.zIndex = 11;
}
// 如果图片的旋转角度有值并且不为0, 添加旋转角度
if(this.props.arrange.rotate){
(['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function(value) {
styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)'; //{value}transform: rotate(rotate deg)
}.bind(this))
}
//增加图片翻转 isInverse , 默认为正面
let imgFigureClassName = 'img-figure';
imgFigureClassName += this.props.arrange.isInverse ? ' is-inverse ' : '';
return(
<figure className={ imgFigureClassName } style={ styleObj } onClick={this.handleClick}>
<img src={this.props.data.imageURL}
alt={this.props.data.title}
/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<p>
{this.props.data.title}
</p>
</div>
</figcaption>
</figure>
);
}
}
ImgFigure.propTypes = {
data: React.PropTypes.object.isRequired, // 每张图片的信息,详细结构看下面
arrange: React.PropTypes.object.isRequired, // 每张图片的位置信息,详细结构看下面
inverse: React.PropTypes.func.isRequired, // 翻转当前图片的回调函数
center: React.PropTypes.func.isRequired // 将当前图片设为中心图片,同时调整所有图片位置的回调函数
};
export default ImgFigure;
/**
1. data
{
"fileName": "1.jpg",
"title": "Heaven of time",
"desc": "Here he comes Here comes Speed Racer."
}
2. arrange
{
pos:{ left:0, top:0}
rotate: 0 //旋转角度
isInverse: false // 图片是否正反面
isCenter: false //图片是否居中
}
**/ |
var app = angular.module('soundboard', ['ionic']);
app.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
});
app.controller('SoundBoardCtrl', function ($scope, $window) {
$scope.media = null;
$scope.model = {
showDelete: false,
showMove: false,
sounds: [
{
'title': 'Cow',
'image': 'img/animals/cow-icon.png',
'desc': 'Mooo',
'file': '/sounds/cow.mp3'
},
{
'title': 'Dolphin',
'image': 'img/animals/dolphin-icon.png',
'desc': 'Whistle',
'file': '/sounds/dolphin.mp3'
},
{
'title': 'Frog',
'image': 'img/animals/frog-icon.png',
'desc': 'Croak',
'file': '/sounds/frog.mp3'
},
{
'title': 'Bird',
'image': 'img/animals/bird-icon.png',
'desc': 'Chirp',
'file': '/sounds/bird.mp3'
},
{
'title': 'Pig',
'image': 'img/animals/pig-icon.png',
'desc': 'Oink',
'file': '/sounds/pig.mp3'
},
{
'title': 'Dog',
'image': 'img/animals/puppy-icon.png',
'desc': 'Bark',
'file': '/sounds/dog.mp3'
},
{
'title': 'Cat',
'image': 'img/animals/black-cat-icon.png',
'desc': 'Meow',
'file': '/sounds/cat.mp3'
}
]
};
$scope.deleteSound = function ($index) {
$scope.model.sounds.splice($index, 1);
};
$scope.moveSound = function (sound, fromIndex, toIndex){
$scope.model.sounds.splice(fromIndex, 1);
$scope.model.sounds.splice(toIndex, 0, sound);
};
$scope.play = function (sound) {
if ($scope.media) {
$scope.media.pause();
}
if ($window.cordova) {
console.log("Play called on device");
ionic.Platform.ready(function(){
$scope.media = new $window.Media(sound.file);
$scope.media.play();
});
} else {
$scope.media = new Audio();
$scope.media.src = sound.file;
$scope.media.load();
$scope.media.play();
}
};
});
|
export { default as QuoteList } from './QuoteList.js'
export { default as Search } from './Search.js' |
// Load modules
var Crypto = require('crypto');
var Stream = require('stream');
var Events = require('events');
var Hoek = require('hoek');
var Payload = require('./payload');
// Declare internals
var internals = {};
exports = module.exports = internals.Message = function (source, request, options) {
Events.EventEmitter.call(this);
options = options || {};
this.statusCode = 200;
this.headers = {}; // Incomplete as some headers are stored in flags
this.variety = options.variety || 'plain';
this.app = {};
this.plugins = {};
this.settings = {
encoding: 'utf8',
charset: 'utf-8', // '-' required by IANA
location: null,
ttl: null,
stringify: null,
passThrough: true,
varyEtag: false
};
this.request = request;
this._payload = null; // Readable stream
this._takeover = false;
this._processors = {
marshall: options.marshall,
prepare: options.prepare
};
// Default content-type and type-specific method
if (source === null ||
source === undefined ||
source === '') {
source = null;
}
else if (typeof source === 'string') {
this.type('text/html');
}
else if (Buffer.isBuffer(source)) {
this.type('application/octet-stream');
this.variety = 'buffer';
}
else if (source instanceof Stream) {
this.variety = 'stream';
this.passThrough = this._passThrough; // Expose method
if (source.statusCode) { // Stream is an HTTP response
this.statusCode = source.statusCode;
}
}
else if (this.variety === 'plain') {
this.settings.stringify = {}; // JSON.stringify options
this.replacer = this._replacer;
this.spaces = this._spaces;
this.suffix = this._suffix;
this.type('application/json');
}
this.source = source;
if (request.method === 'post' ||
request.method === 'put') {
this.created = this._created;
}
};
Hoek.inherits(internals.Message, Events.EventEmitter);
internals.Message.prototype.code = function (statusCode) {
this.statusCode = statusCode;
return this;
};
internals.Message.prototype.header = function (key, value, options) {
key = key.toLowerCase();
if (key === 'vary') {
return this.vary(value);
}
return this._header(key, value, options);
};
internals.Message.prototype._header = function (key, value, options) {
options = options || {};
options.append = options.append || false;
options.separator = options.separator || ',';
options.override = options.override !== false;
if ((!options.append && options.override) ||
!this.headers[key]) {
this.headers[key] = value;
}
else if (options.override) {
if (key === 'set-cookie') {
this.headers[key] = [].concat(this.headers[key], value);
}
else {
this.headers[key] = this.headers[key] + options.separator + value;
}
}
return this;
};
internals.Message.prototype.vary = function (value) {
if (value === '*') {
this.headers.vary = '*';
}
else if (!this.headers.vary) {
this.headers.vary = value;
}
else if (this.headers.vary !== '*') {
this._header('vary', value, { append: true });
}
return this;
};
internals.Message.prototype.etag = function (tag, options) {
options = options || {};
this._header('etag', (options.weak ? 'W/' : '') + '"' + tag + '"');
this.settings.varyEtag = !!options.vary && !options.weak;
return this;
};
internals.Message.prototype._varyEtag = function () {
if (this.settings.varyEtag &&
this.headers.etag &&
this.headers.vary) {
var hash = Crypto.createHash('sha1');
hash.update(this.headers.vary.replace(/\s/g, ''));
this.headers.etag = '"' + this.headers.etag.slice(1, -1) + '-' + hash.digest('hex') + '"';
}
};
internals.Message.prototype.type = function (type) {
this._header('content-type', type);
return this;
};
internals.Message.prototype.bytes = function (bytes) {
this._header('content-length', bytes);
return this;
};
internals.Message.prototype.location = function (uri) {
this.settings.location = uri;
return this;
};
internals.Message.prototype._created = function (location) {
this.statusCode = 201;
this.location(location);
return this;
};
internals.Message.prototype._replacer = function (method) {
this.settings.stringify.replacer = method;
return this;
};
internals.Message.prototype._spaces = function (count) {
this.settings.stringify.space = count;
return this;
};
internals.Message.prototype._suffix = function (suffix) {
this.settings.stringify.suffix = suffix;
return this;
};
internals.Message.prototype._passThrough = function (enabled) {
this.settings.passThrough = (enabled !== false); // Defaults to true
return this;
};
internals.Message.prototype.redirect = function (location) {
this.statusCode = 302;
this.location(location);
this.temporary = this._temporary;
this.permanent = this._permanent;
this.rewritable = this._rewritable;
return this;
};
internals.Message.prototype._temporary = function (isTemporary) {
this._setTemporary(isTemporary !== false); // Defaults to true
return this;
};
internals.Message.prototype._permanent = function (isPermanent) {
this._setTemporary(isPermanent === false); // Defaults to true
return this;
};
internals.Message.prototype._rewritable = function (isRewritable) {
this._setRewritable(isRewritable !== false); // Defaults to true
return this;
};
internals.Message.prototype._isTemporary = function () {
return this.statusCode === 302 || this.statusCode === 307;
};
internals.Message.prototype._isRewritable = function () {
return this.statusCode === 301 || this.statusCode === 302;
};
internals.Message.prototype._setTemporary = function (isTemporary) {
if (isTemporary) {
if (this._isRewritable()) {
this.statusCode = 302;
}
else {
this.statusCode = 307;
}
}
else {
if (this._isRewritable()) {
this.statusCode = 301;
}
else {
this.statusCode = 308;
}
}
};
internals.Message.prototype._setRewritable = function (isRewritable) {
if (isRewritable) {
if (this._isTemporary()) {
this.statusCode = 302;
}
else {
this.statusCode = 301;
}
}
else {
if (this._isTemporary()) {
this.statusCode = 307;
}
else {
this.statusCode = 308;
}
}
};
internals.Message.prototype.encoding = function (encoding) {
this.settings.encoding = encoding;
return this;
};
internals.Message.prototype.charset = function (charset) {
this.settings.charset = charset;
return this;
};
internals.Message.prototype.ttl = function (ttl) {
this.settings.ttl = ttl;
return this;
};
internals.Message.prototype.state = function (name, value, options) { // options: see Defaults.state
this.request._setState(name, value, options);
return this;
};
internals.Message.prototype.unstate = function (name) {
this.request._clearState(name);
return this;
};
internals.Message.prototype.takeover = function () {
this._takeover = true;
return this;
};
internals.Message.prototype._marshall = function (callback) {
var self = this;
if (!this._processors.marshall) {
return this._streamify(this.source, callback);
}
this._processors.marshall(this, function (err, source) {
if (err) {
return callback(err);
}
return self._streamify(source, callback);
});
};
internals.Message.prototype._streamify = function (source, callback) {
if (source instanceof Stream) {
this._payload = source;
return callback();
}
var payload = source;
if (this.settings.stringify) {
var space = this.settings.stringify.space || this.request.server.settings.json.space;
var replacer = this.settings.stringify.replacer || this.request.server.settings.json.replacer;
var suffix = this.settings.stringify.suffix || this.request.server.settings.json.suffix || '';
try {
payload = JSON.stringify(payload, replacer, space);
}
catch (err) {
return callback(err);
}
if (suffix) {
payload += suffix;
}
}
this._payload = new Payload(payload, this.settings);
return callback();
};
internals.Message.prototype._tap = function () {
return (this.listeners('finish').length || this.listeners('peek').length ? new internals.Peek(this) : null);
};
internals.Message.prototype._close = function () {
var stream = this._payload || this.source;
if (stream instanceof Stream) {
if (stream.close) {
stream.close();
}
else if (stream.destroy) {
stream.destroy();
}
else {
var read = function () {
stream.read();
};
var end = function () {
stream.removeListener('readable', read);
stream.removeListener('error', end);
stream.removeListener('end', end);
};
stream.on('readable', read);
stream.once('error', end);
stream.once('end', end);
}
}
};
internals.Message.prototype._isPayloadSupported = function () {
return (this.request.method !== 'head' && this.statusCode !== 304 && this.statusCode !== 204);
};
internals.Peek = function (response) {
Stream.Transform.call(this);
this._response = response;
this.once('finish', function () {
response.emit('finish');
});
};
Hoek.inherits(internals.Peek, Stream.Transform);
internals.Peek.prototype._transform = function (chunk, encoding, callback) {
this._response.emit('peek', chunk, encoding);
this.push(chunk, encoding);
callback();
};
|
lmsApp.constant("authorConstants",{
GET_ALL_AUTHORS_URL: "http://localhost:8080/lms/authors?pageNo=1"
, INIT_AUTHOR_URL: "http://localhost:8080/lms/initAuthor"
, ADD_AUTHOR_URL: "http://localhost:8080/lms/addAuthor"
, GET_AUTHOR_BY_PK_URL: "http://localhost:8080/lms/authors/"
}) |
var attr = DS.attr;
var SummaryModel = DS.Model.extend({
"Elapsed": attr('number'),
"MHS av": attr('number'),
"MHS 5s": attr('number'),
"Found Blocks": attr('number'),
"Getworks": attr('number'),
"Accepted": attr('number'),
"Rejected": attr('number'),
"Hardware Errors": attr('number'),
"Utility": attr('number'),
"Discarded": attr('number'),
"Stale": attr('number'),
"Get Failures": attr('number'),
"Local Work": attr('number'),
"Remote Failures": attr('number'),
"Network Blocks": attr('number'),
"Total MH": attr('number'),
"Work Utility": attr('number'),
"Difficulty Accepted": attr('number'),
"Difficulty Rejected": attr('number'),
"Difficulty Stale": attr('number'),
"Best Share": attr('number'),
"Device Hardware%": attr('number'),
"Device Rejected%": attr('number'),
"Pool Rejected%": attr('number'),
"Pool Stale%": attr('number'),
"Last getwork": attr('number')
});
SummaryModel.reopen({
getMHsAv: function(){
return this.get('MHS av');
}.property('MHS av'),
getMHs5s: function(){
return this.get('MHS 5s');
}.property('MHS 5s'),
getFoundBlocks: function(){
return this.get('Found Blocks');
}.property('Found Blocks'),
getHardwareErrors: function(){
return this.get('Hardware Errors');
}.property('Hardware Errors'),
getFailures: function(){
return this.get('Get Failures');
}.property('Get Failures'),
getLocalWork: function(){
return this.get('Local Work');
}.property('Local Work'),
getRemoteFailures: function(){
return this.get('Remote Failures');
}.property('Remote Failures'),
getNetworkBlocks: function(){
return this.get('Network Blocks');
}.property('Network Blocks'),
getTotalMH: function(){
return this.get('Total MH');
}.property('Total MH'),
getWorkUtility: function(){
return this.get('Work Utility');
}.property('Work Utility'),
getDifficultyAccepted: function(){
return this.get('Difficulty Accepted');
}.property('Difficulty Accepted'),
getDifficultyRejected: function(){
return this.get('Difficulty Rejected');
}.property('Difficulty Rejected'),
getDifficultyStale: function(){
return this.get('Difficulty Stale');
}.property('Difficulty Stale'),
getBestShare: function(){
return this.get('Best Share');
}.property('Best Share'),
getDeviceHardwarePercent: function(){
return this.get('Device Hardware%');
}.property('Device Hardware%'),
getDeviceRejectedPercent: function(){
return this.get('Device Rejected%');
}.property('Device Rejected%'),
getPoolRejectedPercent: function(){
return this.get('Pool Rejected%');
}.property('Pool Rejected%'),
getPoolStalePercent: function(){
return this.get('Pool Stale%');
}.property('Pool Stale%'),
getLastGetwork: function(){
return this.get('Last getwork');
}.property('Last getwork')
});
export default SummaryModel; |
$(document).ready(function(){
var magic8Ball = {};
magic8Ball.listOfAnswers = ["Yes", "Probably So", "Quite Possibly", "Vision Hazy. Check back later", "Not Sure", "Better Not Tell You Now", "Probably Not", "Absolutely Not"];
magic8Ball.askQuestion = function(question)
{
$("#8ball").attr("src", "https://s3.amazonaws.com/media.skillcrush.com/skillcrush/wp-content/uploads/2016/09/answerside.png");
var randomNumber = Math.random();
var randomNumberForListOfAnswers = randomNumber * this.listOfAnswers.length;
var randomIndex = Math.floor(randomNumberForListOfAnswers);
var answer = this.listOfAnswers[randomIndex];
$("#answer").text( answer );
$("#answer").fadeIn(4000);
console.log(question);
console.log(answer);
};
$("#answer").hide();
var onClick = function() {
$("#answer").hide();
$("#8ball").attr("src", "https://s3.amazonaws.com/media.skillcrush.com/skillcrush/wp-content/uploads/2016/09/8side.png");
var question = prompt("ASK A YES/NO QUESTION!");
magic8Ball.askQuestion(question);
$("#8ball").effect("shake");
};
$("#questionButton").click( onClick );
});
|
/**
* Each section of the site has its own module. It probably also has
* submodules, though this boilerplate is too simple to demonstrate it. Within
* `src/app/home`, however, could exist several additional folders representing
* additional modules that would then be listed as dependencies of this one.
* For example, a `note` section could have the submodules `note.create`,
* `note.delete`, `note.edit`, etc.
*
* Regardless, so long as dependencies are managed correctly, the build process
* will automatically take take of the rest.
*
* The dependencies block here is also where component dependencies should be
* specified, as shown below.
*/
angular.module('grp.home.designer.decision', [
'grp.draggableObject'
])
.directive( 'decision', function() {
return {
require: ['^draggableObject', 'decision'],
scope: false,
controller: function($scope) {
},
link: function(scope, element, attrs, ctrls) {
var self = ctrls[1];
var parent = ctrls[0];
var d = "M 35,10 L 60 35 L 35 60 L 10 35 L 35 10";
var mark = parent.canvas.path(d);
mark.attr({
fill: 'red'
});
//var rect = parent.canvas.rect(parent.x, parent.y, parent.width, parent.height);
//rect.attr({fill: "blue", "fill-opacity": 0.5, "stroke-width": 0});
//var text = parent.canvas.text(parent.x, parent.y, parent.width, parent.height, "Hello");
//text.attr({fill: 'black', 'text-anchor': 'start'});
parent.set.push(mark);
parent.makeDraggable();
}
};
})
;
|
'use strict';
// generated on 2015-03-06 using generator-tiy-webapp 0.0.11
// Require your modules
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var rimraf = require('rimraf');
var exec = require('child_process').exec;
var prompt = require('gulp-prompt');
gulp.task('styles', function () {
return gulp.src('app/styles/main.scss')
.pipe($.plumber())
.pipe($.rubySass({
style: 'compressed',
precision: 10
}))
.pipe($.autoprefixer('last 1 version'))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('html', ['styles'], function () {
return gulp.src('app/**/*.html')
.pipe($.useref.assets({searchPath: '{.tmp,app}'}))
.pipe($.if('*.css', $.csso()))
.pipe($.useref.restore())
.pipe($.useref())
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('app/images/**/*')
// .pipe($.cache($.imagemin({
// progressive: true,
// interlaced: true
// })))
.pipe(gulp.dest('dist/images'));
});
gulp.task('font', function () {
return gulp.src('app/font/**/*')
.pipe(gulp.dest('dist/font'));
});
gulp.task('fonts', function () {
return gulp.src('app/fonts/**/*')
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('extras', function () {
return gulp.src(['app/*.*', '!app/*.html'], {dot: true})
.pipe(gulp.dest('dist'));
});
gulp.task('clean', function (cb) {
return $.cache.clearAll(cb, function() {
return rimraf('.tmp', function () {
return rimraf('dist', cb);
});
});
});
gulp.task('connect', function () {
var connect = require('connect');
var app = connect()
.use(require('connect-livereload')({port: 35729}))
.use(connect.static('app'))
.use(connect.static('.tmp'))
// paths to bower_components should be relative to the current file
// e.g. in app/index.html you should use ../bower_components
.use('/bower_components', connect.static('bower_components'))
.use(connect.directory('app'));
require('http').createServer(app)
.listen(9000)
.on('listening', function () {
console.log('Started connect web server on http://localhost:9000');
});
});
gulp.task('serve', ['connect', 'styles'], function () {
require('opn')('http://localhost:9000');
});
// inject bower components
gulp.task('wiredep', function () {
var wiredep = require('wiredep').stream;
gulp.src('app/styles/*.scss')
.pipe(wiredep({directory: 'bower_components'}))
.pipe(gulp.dest('app/styles'));
gulp.src('app/*.html')
.pipe(wiredep({
directory: 'bower_components'
}))
.pipe(gulp.dest('app'));
});
gulp.task('watch', ['connect', 'serve'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.html',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.scss', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('build', ['html', 'images', 'font', 'fonts', 'extras'], function () {
return gulp.src('dist/**/*').pipe($.size({title: 'build', gzip: true}));
});
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
// Push a subtree from our `dist` folder
gulp.task('deploy', function() {
gulp.src('/')
.pipe(prompt.prompt({
type: 'confirm',
name: 'task',
message: 'This will deploy to GitHub Pages. Have you already built your application and pushed your updated master branch?'
}, function(res){
if (res.task){
console.log('Attempting: "git subtree push --prefix dist origin gh-pages"');
exec('git subtree push --prefix dist origin gh-pages', function(err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
});
} else { console.log('Please do this first and then run `gulp deploy` again.'); }
}));
});
// Test your app in the browser
// Needs to be better, but needed something quick
gulp.task('test-server', function() {
// Open Test Page
var connect = require('connect');
var app = connect()
.use(require('connect-livereload')({port: 35729}))
.use(connect.static('test'))
.use('/app', connect.static('app'))
.use('/bower_components', connect.static('bower_components'))
.use(connect.directory('test'));
require('http').createServer(app)
.listen(8000)
.on('listening', function () {
console.log('Started connect testing server on http://localhost:8000');
});
require('opn')('http://localhost:8000');
// Watch for changes in either the test/spec folder or app/scripts folder
$.livereload.listen();
gulp.watch([
'app/scripts/**/*.js',
'test/spec/**/*.js'
]).on('change', $.livereload.changed);
});
|
// TODO: comment about the 'no_auto_stylesheet_detection' flag?
module.exports = (function(window, document) { "use strict";
// import dependencies
require('polyfill-dom-console');
require('polyfill-dom-requestAnimationFrame');
var cssSyntax = require('css-syntax');
var domEvents = require('dom-events');
var querySelectorLive = require('dom-query-selector-live');
// define the module
var cssCascade = {
//
// returns the priority of a unique selector (NO COMMA!)
// { the return value is an integer, with the same formula as webkit }
//
computeSelectorPriorityOf: function computeSelectorPriorityOf(selector) {
if(typeof selector == "string") selector = cssSyntax.parse(selector.trim()+"{}").value[0].selector;
var numberOfIDs = 0;
var numberOfClasses = 0;
var numberOfTags = 0;
// TODO: improve this parser, or find one on the web
for(var i = 0; i < selector.length; i++) {
if(selector[i] instanceof cssSyntax.IdentifierToken) {
numberOfTags++;
} else if(selector[i] instanceof cssSyntax.DelimToken) {
if(selector[i].value==".") {
numberOfClasses++; i++;
}
} else if(selector[i] instanceof cssSyntax.ColonToken) {
if(selector[++i] instanceof cssSyntax.ColonToken) {
numberOfTags++; i++;
} else if((selector[i] instanceof cssSyntax.Func) && (/^(not|matches)$/i).test(selector[i].name)) {
var nestedPriority = this.computeSelectorPriorityOf(selector[i].value);
numberOfTags += nestedPriority % 256; nestedPriority /= 256;
numberOfClasses += nestedPriority % 256; nestedPriority /= 256;
numberOfIDs += nestedPriority;
} else {
numberOfClasses++;
}
} else if(selector[i] instanceof cssSyntax.SimpleBlock) {
if(selector[i].name=="[") {
numberOfClasses++;
}
} else if(selector[i] instanceof cssSyntax.HashToken) {
numberOfIDs++;
} else {
// TODO: stop ignoring unknown symbols?
}
}
if(numberOfIDs>255) numberOfIDs=255;
if(numberOfClasses>255) numberOfClasses=255;
if(numberOfTags>255) numberOfTags=255;
return ((numberOfIDs*256)+numberOfClasses)*256+numberOfTags;
},
//
// returns an array of the css rules matching an element
//
findAllMatchingRules: function findAllMatchingRules(element) {
return this.findAllMatchingRulesWithPseudo(element);
},
//
// returns an array of the css rules matching a pseudo-element
//
findAllMatchingRulesWithPseudo: function findAllMatchingRules(element,pseudo) {
pseudo = pseudo ? (''+pseudo).toLowerCase() : pseudo;
// let's look for new results if needed...
var results = [];
// walk the whole stylesheet...
var visit = function(rules) {
try {
for(var r = rules.length; r--; ) {
var rule = rules[r];
// media queries hook
if(rule.disabled) continue;
if(rule instanceof cssSyntax.StyleRule) {
// consider each selector independently
var subrules = rule.subRules || cssCascade.splitRule(rule);
for(var sr = subrules.length; sr--; ) {
var selector = subrules[sr].selector.toCSSString().replace(/ *(\/\*\*\/| ) */g,' ').trim();
if(pseudo) {
// WE ONLY ACCEPT SELECTORS ENDING WITH THE PSEUDO
var selectorLow = selector.toLowerCase();
var newLength = selector.length-pseudo.length-1;
if(newLength<=0) continue;
if(selectorLow.lastIndexOf('::'+pseudo)==newLength-1) {
selector = selector.substr(0,newLength-1);
} else if(selectorLow.lastIndexOf(':'+pseudo)==newLength) {
selector = selector.substr(0,newLength);
} else {
continue;
}
// fix selectors like "#element > :first-child ~ ::before"
if(selector.trim().length == 0) { selector = '*' }
else if(selector[selector.length-1] == ' ') { selector += '*' }
else if(selector[selector.length-1] == '+') { selector += '*' }
else if(selector[selector.length-1] == '>') { selector += '*' }
else if(selector[selector.length-1] == '~') { selector += '*' }
}
// look if the selector matches
var isMatching = false;
try {
if(element.matches) isMatching=element.matches(selector)
else if(element.matchesSelector) isMatching=element.matchesSelector(selector)
else if(element.oMatchesSelector) isMatching=element.oMatchesSelector(selector)
else if(element.msMatchesSelector) isMatching=element.msMatchesSelector(selector)
else if(element.mozMatchesSelector) isMatching=element.mozMatchesSelector(selector)
else if(element.webkitMatchesSelector) isMatching=element.webkitMatchesSelector(selector)
else { throw new Error("no element.matches?") }
} catch(ex) { /*debugger; setImmediate(function() { throw ex; })*/ }
// if yes, add it to the list of matched selectors
if(isMatching) { results.push(subrules[sr]); }
}
} else if(rule instanceof cssSyntax.AtRule && rule.name=="media") {
// visit them
visit(rule.toStylesheet().value);
}
}
} catch (ex) {
setImmediate(function() { throw ex; });
}
}
for(var s=cssCascade.stylesheets.length; s--; ) {
var rules = cssCascade.stylesheets[s];
visit(rules);
}
return results;
},
//
// a list of all properties supported by the current browser
//
allCSSProperties: null,
getAllCSSProperties: function getAllCSSProperties() {
if(this.allCSSProperties) return this.allCSSProperties;
// get all claimed properties
var s = getComputedStyle(document.documentElement); var ps = new Array(s.length);
for(var i=s.length; i--; ) {
ps[i] = s[i];
}
// FIX A BUG WHERE WEBKIT DOESN'T REPORT ALL PROPERTIES
if(ps.indexOf('content')==-1) {ps.push('content');}
if(ps.indexOf('counter-reset')==-1) {
ps.push('counter-reset');
ps.push('counter-increment');
// FIX A BUG WHERE WEBKIT RETURNS SHIT FOR THE COMPUTED VALUE OF COUNTER-RESET
cssCascade.computationUnsafeProperties['counter-reset']=true;
}
// save in a cache for faster access the next times
return this.allCSSProperties = ps;
},
//
// those properties are not safe for computation->specified round-tripping
//
computationUnsafeProperties: {
"block-size" : true,
"bottom" : true,
"direction" : true,
"display" : true,
"font-size" : true,
"height" : true,
"inline-size" : true,
"left" : true,
"line-height" : true,
"margin-left" : true,
"margin-right" : true,
"margin-bottom" : true,
"margin-top" : true,
"max-height" : true,
"max-width" : true,
"min-height" : true,
"min-width" : true,
"padding-left" : true,
"padding-right" : true,
"padding-bottom" : true,
"padding-top" : true,
"right" : true,
"text-align" : true,
"text-align-last" : true,
"top" : true,
"width" : true,
__proto__ : null,
},
//
// a list of property we should inherit...
//
inheritingProperties: {
"border-collapse" : true,
"border-spacing" : true,
"caption-side" : true,
"color" : true,
"cursor" : true,
"direction" : true,
"empty-cells" : true,
"font-family" : true,
"font-size" : true,
"font-style" : true,
"font-variant" : true,
"font-weight" : true,
"font" : true,
"letter-spacing" : true,
"line-height" : true,
"list-style-image" : true,
"list-style-position" : true,
"list-style-type" : true,
"list-style" : true,
"orphans" : true,
"quotes" : true,
"text-align" : true,
"text-indent" : true,
"text-transform" : true,
"visibility" : true,
"white-space" : true,
"widows" : true,
"word-break" : true,
"word-spacing" : true,
"word-wrap" : true,
__proto__ : null,
},
//
// returns the default style for a tag
//
defaultStylesForTag: Object.create ? Object.create(null) : {},
getDefaultStyleForTag: function getDefaultStyleForTag(tagName) {
// get result from cache
var result = this.defaultStylesForTag[tagName];
if(result) return result;
// create dummy virtual element
var element = document.createElement(tagName);
var style = this.defaultStylesForTag[tagName] = getComputedStyle(element);
if(style.display) return style;
// webkit fix: insert the dummy element anywhere (head -> display:none)
document.head.insertBefore(element, document.head.firstChild);
return style;
},
//
// returns the specified style of an element.
// REMARK: may or may not unwrap "inherit" and "initial" depending on implementation
// REMARK: giving "matchedRules" as a parameter allow you to mutualize the "findAllMatching" rules calls
//
getSpecifiedStyle: function getSpecifiedStyle(element, cssPropertyName, matchedRules) {
// hook for css regions
var fragmentSource;
if(fragmentSource=element.getAttribute('data-css-regions-fragment-of')) {
fragmentSource = document.querySelector('[data-css-regions-fragment-source="'+fragmentSource+'"]');
if(fragmentSource) return cssCascade.getSpecifiedStyle(fragmentSource, cssPropertyName);
}
// give IE a thumbs up for this!
if(element.currentStyle && !window.opera) {
// ask IE to manage the style himself...
var bestValue = element.myStyle[cssPropertyName] || element.currentStyle[cssPropertyName] || '';
// return a parsed representation of the value
return cssSyntax.parseAListOfComponentValues(bestValue);
} else {
// TODO: support the "initial" and "inherit" things?
// first, let's try inline style as it's fast and generally accurate
// TODO: what if important rules override that?
try {
if(bestValue = element.style.getPropertyValue(cssPropertyName) || element.myStyle[cssPropertyName]) {
return cssSyntax.parseAListOfComponentValues(bestValue);
}
} catch(ex) {}
// find all relevant style rules
var isBestImportant=false; var bestPriority = 0; var bestValue = new cssSyntax.TokenList();
var rules = matchedRules || (
cssPropertyName in cssCascade.monitoredProperties
? element.myMatchedRules || []
: cssCascade.findAllMatchingRules(element)
);
var visit = function(rules) {
for(var i=rules.length; i--; ) {
// media queries hook
if(rules[i].disabled) continue;
// find a relevant declaration
if(rules[i] instanceof cssSyntax.StyleRule) {
var decls = rules[i].getDeclarations();
for(var j=decls.length-1; j>=0; j--) {
if(decls[j].type=="DECLARATION") {
if(decls[j].name==cssPropertyName) {
// only works if selectors containing a "," are deduplicated
var currentPriority = cssCascade.computeSelectorPriorityOf(rules[i].selector);
if(isBestImportant) {
// only an important declaration can beat another important declaration
if(decls[j].important) {
if(currentPriority >= bestPriority) {
bestPriority = currentPriority;
bestValue = decls[j].value;
}
}
} else {
// an important declaration beats any non-important declaration
if(decls[j].important) {
isBestImportant = true;
bestPriority = currentPriority;
bestValue = decls[j].value;
} else {
// the selector priority has to be higher otherwise
if(currentPriority >= bestPriority) {
bestPriority = currentPriority;
bestValue = decls[j].value;
}
}
}
}
}
}
} else if((rules[i] instanceof cssSyntax.AtRule) && (rules[i].name=="media")) {
// visit them
visit(rules[i].toStylesheet())
}
}
}
visit(rules);
// return our best guess...
return bestValue||null;
}
},
//
// start monitoring a new stylesheet
// (should usually not be used because stylesheets load automatically)
//
stylesheets: [],
loadStyleSheet: function loadStyleSheet(cssText,i) {
// load in order
// parse the stylesheet content
var rules = cssSyntax.parse(cssText).value;
// add the stylesheet into the object model
if(typeof(i)!=="undefined") { cssCascade.stylesheets[i]=rules; }
else { i=cssCascade.stylesheets.push(rules);}
// make sure to monitor the required rules
cssCascade.startMonitoringStylesheet(rules)
},
//
// start monitoring a new stylesheet
// (should usually not be used because stylesheets load automatically)
//
loadStyleSheetTag: function loadStyleSheetTag(stylesheet,i) {
if(stylesheet.hasAttribute('data-css-polyfilled')) {
return;
}
if(stylesheet.tagName=='LINK') {
// oh, no, we have to download it...
try {
// dummy value in-between
cssCascade.stylesheets[i] = new cssSyntax.TokenList();
//
var xhr = new XMLHttpRequest(); xhr.href = stylesheet.href;
xhr.open('GET',stylesheet.href,true); xhr.ruleIndex = i;
xhr.onreadystatechange = function() {
if(this.readyState==4) {
// status 0 is a webkit bug for local files
if(this.status==200||this.status==0) {
cssCascade.loadStyleSheet(this.responseText,this.ruleIndex)
} else {
cssConsole.log("css-cascade polyfill failled to load: " + this.href);
}
}
};
xhr.send();
} catch(ex) {
cssConsole.log("css-cascade polyfill failled to load: " + stylesheet.href);
}
} else {
// oh, cool, we just have to parse the content!
cssCascade.loadStyleSheet(stylesheet.textContent,i);
}
// mark the stylesheet as ok
stylesheet.setAttribute('data-css-polyfilled',true);
},
//
// calling this function will load all currently existing stylesheets in the document
// (should usually not be used because stylesheets load automatically)
//
selectorForStylesheets: "style:not([data-no-css-polyfill]):not([data-css-polyfilled]), link[rel=stylesheet]:not([data-no-css-polyfill]):not([data-css-polyfilled])",
loadAllStyleSheets: function loadAllStyleSheets() {
// for all stylesheets in the <head> tag...
var head = document.head || document.documentElement;
var stylesheets = head.querySelectorAll(cssCascade.selectorForStylesheets);
var intialLength = this.stylesheets.length;
this.stylesheets.length += stylesheets.length
// for all of them...
for(var i = stylesheets.length; i--;) {
//
// load the stylesheet
//
var stylesheet = stylesheets[i];
cssCascade.loadStyleSheetTag(stylesheet,intialLength+i)
}
},
//
// this is where we store event handlers for monitored properties
//
monitoredProperties: Object.create ? Object.create(null) : {},
monitoredPropertiesHandler: {
onupdate: function(element, rule) {
// we need to find all regexps that matches
var mps = cssCascade.monitoredProperties;
var decls = rule.getDeclarations();
for(var j=decls.length-1; j>=0; j--) {
if(decls[j].type=="DECLARATION") {
if(decls[j].name in mps) {
// call all handlers waiting for this
var hs = mps[decls[j].name];
for(var hi=hs.length; hi--;) {
hs[hi].onupdate(element,rule);
};
// don't call twice
break;
}
}
}
}
},
//
// add an handler to some properties (aka fire when their value *MAY* be affected)
// REMARK: because this event does not promise the value changed, you may want to figure it out before relayouting
//
startMonitoringProperties: function startMonitoringProperties(properties, handler) {
for(var i=properties.length; i--; ) {
var property = properties[i];
var handlers = (
cssCascade.monitoredProperties[property]
|| (cssCascade.monitoredProperties[property] = [])
);
handlers.push(handler)
}
for(var s=0; s<cssCascade.stylesheets.length; s++) {
var currentStylesheet = cssCascade.stylesheets[s];
cssCascade.startMonitoringStylesheet(currentStylesheet);
}
},
//
// calling this function will detect monitored rules in the stylesheet
// (should usually not be used because stylesheets load automatically)
//
startMonitoringStylesheet: function startMonitoringStylesheet(rules) {
for(var i=0; i<rules.length; i++) {
// only consider style rules
if(rules[i] instanceof cssSyntax.StyleRule) {
// try to see if the current rule is worth monitoring
if(rules[i].isMonitored) continue;
// for that, let's see if we can find a declaration we should watch
var decls = rules[i].getDeclarations();
for(var j=decls.length-1; j>=0; j--) {
if(decls[j].type=="DECLARATION") {
if(decls[j].name in cssCascade.monitoredProperties) {
// if we found some, start monitoring
cssCascade.startMonitoringRule(rules[i]);
break;
}
}
}
} else if(rules[i] instanceof cssSyntax.AtRule) {
// handle @media
if(rules[i].name == "media" && window.matchMedia) {
cssCascade.startMonitoringMedia(rules[i]);
}
}
}
},
//
// calling this function will detect media query updates and fire events accordingly
// (should usually not be used because stylesheets load automatically)
//
startMonitoringMedia: function startMonitoringMedia(atrule) {
try {
var media = window.matchMedia(atrule.prelude.toCSSString());
// update all the rules when needed
var rules = atrule.toStylesheet().value;
cssCascade.updateMedia(rules, !media.matches, false);
media.addListener(
function(newMedia) { cssCascade.updateMedia(rules, !newMedia.matches, true); }
);
// it seems I like taking risks...
cssCascade.startMonitoringStylesheet(rules);
} catch(ex) {
setImmediate(function() { throw ex; })
}
},
//
// define what happens when a media query status changes
//
updateMedia: function(rules,disabled,update) {
for(var i=rules.length; i--; ) {
rules[i].disabled = disabled;
// TODO: should probably get handled by a setter on the rule...
var sr = rules[i].subRules;
if(sr) {
for(var j=sr.length; j--; ) {
sr[j].disabled = disabled;
}
}
}
// in case of update, all elements matching the selector went potentially updated...
if(update) {
for(var i=rules.length; i--; ) {
var els = document.querySelectorAll(rules[i].selector.toCSSString());
for(var j=els.length; j--; ) {
cssCascade.monitoredPropertiesHandler.onupdate(els[j],rules[i]);
}
}
}
},
//
// splits a rule if it has multiple selectors
//
splitRule: function splitRule(rule) {
// create an array for all the subrules
var rules = [];
// fill the array
var currentRule = new cssSyntax.StyleRule(); currentRule.disabled=rule.disabled;
for(var i=0; i<rule.selector.length; i++) {
if(rule.selector[i] instanceof cssSyntax.DelimToken && rule.selector[i].value==",") {
currentRule.value = rule.value; rules.push(currentRule);
currentRule = new cssSyntax.StyleRule(); currentRule.disabled=rule.disabled;
} else {
currentRule.selector.push(rule.selector[i])
}
}
currentRule.value = rule.value; rules.push(currentRule);
// save the result of the split as subrules
return rule.subRules = rules;
},
//
// ask the css-selector implementation to notify changes for the rules
//
startMonitoringRule: function startMonitoringRule(rule) {
// avoid monitoring rules twice
if(!rule.isMonitored) { rule.isMonitored=true } else { return; }
// split the rule if it has multiple selectors
var rules = rule.subRules || cssCascade.splitRule(rule);
// monitor the rules
for(var i=0; i<rules.length; i++) {
rule = rules[i];
querySelectorLive(rule.selector.toCSSString(), {
onadded: function(e) {
// add the rule to the matching list of this element
(e.myMatchedRules = e.myMatchedRules || []).unshift(rule); // TODO: does not respect priority order
// generate an update event
cssCascade.monitoredPropertiesHandler.onupdate(e, rule);
},
onremoved: function(e) {
// remove the rule from the matching list of this element
if(e.myMatchedRules) e.myMatchedRules.splice(e.myMatchedRules.indexOf(rule), 1);
// generate an update event
cssCascade.monitoredPropertiesHandler.onupdate(e, rule);
}
});
}
},
//
// converts a css property name to a javascript name
//
toCamelCase: function toCamelCase(variable) {
return variable.replace(
/-([a-z])/g,
function(str,letter) {
return letter.toUpperCase();
}
);
},
//
// add some magic code to support properties on the style interface
//
polyfillStyleInterface: function(cssPropertyName) {
var prop = {
get: function() {
// check we know which element we work on
try { if(!this.parentElement) throw new Error("Please use the anHTMLElement.myStyle property to get polyfilled properties") }
catch(ex) { setImmediate(function() { throw ex; }); return ''; }
try {
// non-computed style: return the local style of the element
this.clip = (this.clip===undefined?'':this.clip);
return this.parentElement.getAttribute('data-style-'+cssPropertyName);
} catch (ex) {
// computed style: return the specified style of the element
var value = cssCascade.getSpecifiedStyle(this.parentElement, cssPropertyName, undefined, true);
return value && value.length>0 ? value.toCSSString() : '';
}
},
set: function(v) {
// check that the style is writable
this.clip = (this.clip===undefined?'':this.clip);
// check we know which element we work on
try { if(!this.parentElement) throw new Error("Please use the anHTMLElement.myStyle property to set polyfilled properties") }
catch(ex) { setImmediate(function() { throw ex; }); return; }
// modify the local style of the element
if(this.parentElement.getAttribute('data-style-'+cssPropertyName) != v) {
this.parentElement.setAttribute('data-style-'+cssPropertyName,v);
}
}
};
var styleProtos = [];
try { styleProtos.push(Object.getPrototypeOf(document.documentElement.style) || CSSStyleDeclaration); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(getComputedStyle(document.documentElement))); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(document.documentElement.currentStyle)); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(document.documentElement.runtimeStyle)); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(document.documentElement.specifiedStyle)); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(document.documentElement.cascadedStyle)); } catch (ex) {}
//try { styleProtos.push(Object.getPrototypeOf(document.documentElement.usedStyle)); } catch (ex) {}
for(var i = styleProtos.length; i--;) {
var styleProto = styleProtos[i];
Object.defineProperty(styleProto,cssPropertyName,prop);
Object.defineProperty(styleProto,cssCascade.toCamelCase(cssPropertyName),prop);
}
cssCascade.startMonitoringRule(cssSyntax.parse('[style*="'+cssPropertyName+'"]{'+cssPropertyName+':attr(style)}').value[0]);
cssCascade.startMonitoringRule(cssSyntax.parse('[data-style-'+cssPropertyName+']{'+cssPropertyName+':attr(style)}').value[0]);
// add to the list of polyfilled properties...
cssCascade.getAllCSSProperties().push(cssPropertyName);
cssCascade.computationUnsafeProperties[cssPropertyName] = true;
}
};
//
// polyfill for browsers not support CSSStyleDeclaration.parentElement (all of them right now)
//
domEvents.EventTarget.implementsIn(cssCascade);
Object.defineProperty(Element.prototype,'myStyle',{
get: function() {
var style = this.style;
if(!style.parentElement) style.parentElement = this;
return style;
}
});
//
// load all stylesheets at the time the script is loaded
// then do it again when all stylesheets are downloaded
// and again if some style tag is added to the DOM
//
if(!("no_auto_stylesheet_detection" in window)) {
cssCascade.loadAllStyleSheets();
document.addEventListener("DOMContentLoaded", function() {
cssCascade.loadAllStyleSheets();
querySelectorLive(
cssCascade.selectorForStylesheets,
{
onadded: function(e) {
// TODO: respect DOM order?
cssCascade.loadStyleSheetTag(e);
cssCascade.dispatchEvent('stylesheetadded');
}
}
)
})
}
return cssCascade;
})(window, document);
|
import Tooltip from './src/tooltip.vue'
Tooltip.install = function (Vue) {
Vue.component(Tooltip.name, Tooltip)
}
export default Tooltip
|
version https://git-lfs.github.com/spec/v1
oid sha256:d9b55bf05cdc61680d5e53727805161ecacb342a6da8ef4da72cbc829efcff8d
size 33207
|
import { reducerHash } from '../../../../tooling/ModuleUnderTest'; // REALLY: 'astx-redux-util'
export default reducerHash({
"widget.edit": (widget, action) => action.widget,
"widget.edit.close": (widget, action) => null,
}, null);
|
export { default } from 'modal-components/components/accordion-header'; |
/*
* This report script shows a scatter plot with requests over time
*/
require([
"HoneyProxy/util/formatSize",
"dojox/charting/Chart",
"dojox/charting/themes/Claro",
"dojox/charting/plot2d/Scatter",
"dojox/charting/action2d/Tooltip",
"dojox/charting/action2d/Magnify",
"dojox/charting/plot2d/Markers",
"dojox/charting/axis2d/Default",
], function(formatSize, Chart, theme, Scatter, Tooltip, Magnify, Highlight) {
var hosts = {}; // hostname -> y plot value
var hostcount = 0; //number of known hosts
var data = [];
// Iterate over all flows and sum up content lengths
traffic.query().forEach(function(flow){
var host = flow.request.host;
if(!(host in hosts))
hosts[host] = hostcount++;
data.push(
{
x:flow.request.timestamp_start,
y:hosts[host],
text: flow.request.path,
flow: flow
});
});
// Create the chart within it's "holding" node
a = document.createElement("div");
a.style.width = "100%";
out.appendChild(a);
var chart = new Chart(a,{
title: "Requests over time"
});
// Set the theme
chart.setTheme(theme);
// Add the only/default plot
chart.addPlot("default", {
type: Scatter,
markers: true,
});
var labels = [];
labels.push({text:"",value:-1});
for(i in hosts){
labels.push({text:i,value:hosts[i]})
}
labels.push({text:"",value:hostcount});
a.style.height = (200+labels.length*10)+"px";
//Add axes
chart.addAxis("x", {
fixUpper: "minor",
fixLower: "minor",
labelFunc: function(a){
return (new Date(a*1000)).toLocaleTimeString();
}
});
chart.addAxis("y", {
labels: labels,
vertical: true,
min: -0.5, max: hostcount-0.5,
dropLabels: false,
minorTickStep: 1,
majorTickStep: 1
});
// Add the series of data
chart.addSeries("default",data);
chart.connectToPlot( "default", function(evt){
if(!(evt.type === "onclick" && evt.element === "marker"))
return;
detailView.showDetails(data[evt.index].flow);
chart.resize();
})
//Add tooltip
var tip = new Tooltip(chart,"default");
var magnify = new Magnify(chart, "default");
// Render the chart!
chart.render();
chart.resize();
}); |
'use strict'
angular.module('serinaApp').directive('advancedSettings', function () {
return {
restrict: 'E',
templateUrl: 'views/settings/advanced-settings.html'
}
})
|
var util = require('util'),
connect = require('connect'),
port = 8080;
connect.createServer(connect.static(__dirname)).listen(port);
util.puts('Listening on ' + port + '...');
util.puts('Press Ctrl + C to stop.'); |
import fs from 'fs'
import Path from 'path'
import EventEmitter from 'events'
import Delogger from 'delogger'
import Crypto from 'crypto-js'
import Folder from './folder'
import Config from './config'
const config = new Config({sync: true})
export default class File extends EventEmitter {
constructor (_path, base) {
super()
let parsedPath = parsePath(_path)
this.base = base
this._path = parsedPath.path
this.type = 'file'
this.name = parsedPath.fileName
this.mtime = null
this.locked = false
this.downloadCount = 0
this.downloading = 0
this.initMetadata()
this.initWatch()
this.log = new Delogger('File')
}
initWatch () {
if (this.exist) {
fs.watch(
this.fullPath(), {
recursive: true
},
(eventType, filename) => this.watchChange(eventType, filename)
)
}
}
initMetadata () {
try {
let stats = fs.statSync(this.fullPath())
this.mtime = stats.mtime
this._size = stats.size // Bytes
this.exist = true
} catch (err) {
this.mtime = null
this._size = 0
this.exist = false
}
}
watchChange (eventType, filename) {
this.initMetadata()
this.emit('change')
}
fullPath () {
return `${this._path}/${this.name}`
}
size () {
return this._size
}
lock () {
this.locked = true
this.emit('locked', this)
}
unlock () {
this.locked = false
this.emit('unlocked', this)
}
remove () {
if (this.locked) {
return false
}
this.log.info(`Removing ${this.fullPath()}`)
fs.unlinkSync(this.fullPath())
this.emit('remove', this)
}
addDownloader () {
this.downloadCount++
this.downloading++
this.emit('startDownload', this)
this.lock()
}
removeDownloader () {
this.downloading--
this.emit('finishDownload', this)
if (this.downloading <= 0) {
this.downloading = 0
this.unlock()
}
}
rename (name) {
if (this.locked) {
return false
}
this.log.info(`Renaming ${this.fullPath()} into ${this._path}/${name}`)
fs.renameSync(this.fullPath(), `${this._path}/${name}`)
this.emit('rename', this)
}
create () {
this.log.info(`Creating ${this.fullPath()}`)
fs.writeFileSync(this.fullPath(), '')
this.initWatch()
}
toJSON () {
let cleanBase = this.base.split('/').slice(2).join('/')
let url = Path.join('/folder', cleanBase, this.name)
let download = Path.join('/file', cleanBase, this.name)
let copy = '/dl/' + Crypto.Rabbit.encrypt(Path.join(cleanBase, this.name), config.server.masterKey).toString()
let path = Path.join(cleanBase, this.name)
return {
name: this.name,
type: this.type,
mtime: this.mtime,
locked: this.locked,
downloadCount: this.downloadCount,
size: this.size(),
childs: this.childs,
url,
download: this instanceof Folder ? null : download,
copy: this instanceof Folder ? null : copy,
path: this instanceof Folder ? path : null
}
}
download (res) {
return new Promise((resolve, reject) => {
this.addDownloader()
res.download(this.fullPath(), (err) => {
if (err) this.log.error(err)
this.removeDownloader()
resolve(err)
})
})
}
}
function parsePath (path) {
let temp = path.split('/')
removeBlank(temp, 1)
let name = temp.splice(temp.length - 1, 1)[0]
return { fileName: name, path: temp.join('/') }
}
function removeBlank (array, begin) {
begin = begin || 0
for (var i = begin; i < array.length; i++) { // Begining at 1 to prevent first backslash removing
if (array[i] === '' || array[i] === null) {
array.splice(i, 1)
i--
}
}
return array
}
export { removeBlank, parsePath }
|
"use strict";
const crypto = require("crypto");
const fs = require("fs");
const path = require("path");
const rw = require("rw");
const url = require("url");
const athena = require("commander");
const electron = require("electron");
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const mediaPlugin = fs.readFileSync(path.join(__dirname, "./plugin_media.js"), "utf8");
var bw = null;
var ses = null;
var uriArg = null;
var outputArg = null;
if (!process.defaultApp) {
process.argv.unshift("--");
}
const addHeader = (header, arr) => {
arr.push(header);
return arr;
}
// chrome crashes in docker, more info: https://github.com/GoogleChrome/puppeteer/issues/1834
app.commandLine.appendArgument("disable-dev-shm-usage");
athena
.version("2.16.0")
.description("convert HTML to PDF via stdin or a local / remote URI")
.option("--debug", "show GUI", false)
.option("-T, --timeout <seconds>", "seconds before timing out (default: 120)", parseInt)
.option("-D, --delay <milliseconds>", "milliseconds delay before saving (default: 200)", parseInt)
.option("-P, --pagesize <size>", "page size of the generated PDF (default: A4)", /^(A3|A4|A5|Legal|Letter|Tabloid)$/i, "A4")
.option("-M, --margins <marginsType>", "margins to use when generating the PDF (default: standard)", /^(standard|none|minimal)$/i, "standard")
.option("-Z --zoom <factor>", "zoom factor for higher scale rendering (default: 1 - represents 100%)", parseInt)
.option("-S, --stdout", "write conversion to stdout")
.option("-A, --aggressive", "aggressive mode / runs dom-distiller")
.option("-B, --bypass", "bypasses paywalls on digital publications (experimental feature)")
.option("-H, --http-header <key:value>", "add custom headers to request", addHeader, [])
.option("--proxy <url>", "use proxy to load remote HTML")
.option("--no-portrait", "render in landscape")
.option("--no-background", "omit CSS backgrounds")
.option("--no-cache", "disables caching")
.option("--ignore-certificate-errors", "ignores certificate errors")
.option("--ignore-gpu-blacklist", "Enables GPU in Docker environment")
.option("--wait-for-status", "Wait until window.status === WINDOW_STATUS (default: wait for page to load)")
.arguments("<URI> [output]")
.action((uri, output) => {
uriArg = uri;
outputArg = output;
})
.parse(process.argv);
// Display help information by default
if (!process.argv.slice(2).length) {
athena.outputHelp();
}
if (!uriArg) {
console.error("No URI given. Set the URI to `-` to pipe HTML via stdin.");
process.exit(1);
}
// Handle stdin
if (uriArg === "-") {
let base64Html = new Buffer(rw.readFileSync("/dev/stdin", "utf8"), "utf8").toString("base64");
uriArg = "data:text/html;base64," + base64Html;
// Handle local paths
} else if (!uriArg.toLowerCase().startsWith("http") && !uriArg.toLowerCase().startsWith("chrome://")) {
uriArg = url.format({
protocol: "file",
pathname: path.resolve(uriArg),
slashes: true
});
}
// Generate SHA1 hash if no output is specified
if (!outputArg) {
const shasum = crypto.createHash("sha1");
shasum.update(uriArg);
outputArg = shasum.digest("hex") + ".pdf";
}
// Built-in timeout (exit) when debugging is off
if (!athena.debug) {
setTimeout(() => {
console.error("PDF generation timed out.");
app.exit(2);
}, (athena.timeout || 120) * 1000);
}
if (athena.proxy) {
if (!athena.stdout) {
console.info("Using proxy: ", athena.proxy);
}
app.commandLine.appendSwitch("proxy-server", athena.proxy);
}
if (athena.ignoreCertificateErrors) {
app.commandLine.appendSwitch("ignore-certificate-errors");
}
app.commandLine.appendSwitch('ignore-gpu-blacklist', athena.ignoreGpuBlacklist || "false");
// Preferences
var bwOpts = {
show: (athena.debug || false),
webPreferences: {
nodeIntegration: false,
webSecurity: false,
zoomFactor: (athena.zoom || 1)
}
};
if (process.platform === "linux") {
bwOpts["webPreferences"]["defaultFontFamily"] = {
standard: "Liberation Serif",
serif: "Liberation Serif",
sansSerif: "Liberation Sans",
monospace: "Liberation Mono"
};
}
// Add custom headers if specified
var extraHeaders = athena.httpHeader;
// Toggle cache headers
if (!athena.cache) {
extraHeaders.push("pragma: no-cache");
}
const loadOpts = {
"extraHeaders": extraHeaders.join("\n")
};
// Enum for Electron's marginType codes
const MarginEnum = {
"standard": 0,
"none": 1,
"minimal": 2,
};
const pdfOpts = {
pageSize: athena.pagesize,
marginsType: MarginEnum[athena.margins],
printBackground: athena.background,
landscape: !athena.portrait
};
// Utils
const _complete = () => {
if (!athena.stdout) {
console.timeEnd("PDF Conversion");
}
athena.debug || app.quit();
};
const _output = (data) => {
const outputPath = path.join(process.cwd(), outputArg);
if (athena.stdout) {
process.stdout.write(data, _complete);
} else {
fs.writeFile(outputPath, data, (err) => {
if (err) console.error(err);
console.info(`Converted '${uriArg}' to PDF: '${outputArg}'`);
_complete();
});
}
};
app.on("ready", () => {
if (!athena.stdout) {
console.time("PDF Conversion");
}
bw = new BrowserWindow(bwOpts);
bw.on("closed", () => {
bw = null;
ses = null;
});
bw.loadURL(uriArg, loadOpts);
ses = bw.webContents.session;
if (athena.bypass) {
const _cookieWhitelist = ["nytimes", "ft.com"];
const _inCookieWhitelist = (url) => {
let matches = _cookieWhitelist.filter((safe) => {
return url.indexOf(safe) !== -1;
});
return (matches.length !== 0);
};
ses.webRequest.onBeforeSendHeaders((details, callback) => {
if (details.resourceType === "mainFrame") {
if (!_inCookieWhitelist(details.url)) {
delete details.requestHeaders["Cookie"];
}
details.requestHeaders["Referer"] = "https://www.google.com/";
details.requestHeaders["User-Agent"] = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)";
}
callback({cancel: false, requestHeaders: details.requestHeaders});
});
}
ses.on("will-download", (e, item, webContents) => {
e.preventDefault();
console.error(`Unable to convert an octet-stream, use stdin.`);
app.exit(1);
});
bw.webContents.on("did-fail-load", (e, code, desc, url, isMainFrame) => {
if (parseInt(code, 10) >= -3) return;
console.error(`Failed to load: ${code} ${desc} (${url})`);
if (isMainFrame) {
app.exit(1);
}
});
bw.webContents.on("did-navigate", (e, newURL, httpResponseCode, httpResponseText) => {
if (httpResponseCode >= 400) {
console.error(`Failed to load ${newURL} - got HTTP code ${httpResponseCode}`);
app.exit(1);
}
});
bw.webContents.on("crashed", () => {
console.error(`The renderer process has crashed.`);
app.exit(1);
});
// Load plugins
let plugins = mediaPlugin + "\n";
if (athena.aggressive) {
const distillerPlugin = fs.readFileSync(path.join(__dirname, "./plugin_domdistiller.js"), "utf8");
plugins += distillerPlugin + "\n";
}
if (athena.waitForStatus) {
const windowStatusPlugin = fs.readFileSync(path.join(__dirname, "./plugin_window-status.js"), "utf8");
plugins += windowStatusPlugin + "\n";
}
const printToPDF = () => {
bw.webContents.printToPDF(pdfOpts, (err, data) => {
if (err) console.error(err);
_output(data);
});
};
bw.webContents.executeJavaScript(plugins).then(() => {
if (athena.waitForStatus) {
printToPDF();
}
});
if (!athena.waitForStatus) {
bw.webContents.on("did-finish-load", () => {
setTimeout(printToPDF, athena.delay || 200);
});
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
|
/**
* @fileoverview Rule to flag use of variables before they are defined
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Constants
//------------------------------------------------------------------------------
var NO_FUNC = "nofunc";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = function(context) {
function findDeclaration(name, scope) {
// try searching in the current scope first
for (var i = 0, l = scope.variables.length; i < l; i++) {
if (scope.variables[i].name === name) {
return scope.variables[i];
}
}
// check if there's upper scope and call recursivly till we find the variable
if (scope.upper) {
return findDeclaration(name, scope.upper);
}
}
function findVariables() {
var scope = context.getScope();
var typeOption = context.options[0];
function checkLocationAndReport(reference, declaration) {
if (typeOption !== NO_FUNC || declaration.defs[0].type !== "FunctionName") {
if (declaration.identifiers[0].range[1] > reference.identifier.range[1]) {
context.report(reference.identifier, "{{a}} was used before it was defined", {a: reference.identifier.name});
}
}
}
scope.references.forEach(function(reference) {
// if the reference is resolved check for declaration location
// if not, it could be function invocation, try to find manually
if (reference.resolved && reference.resolved.identifiers.length > 0) {
checkLocationAndReport(reference, reference.resolved);
} else {
var declaration = findDeclaration(reference.identifier.name, scope);
// if there're no identifiers, this is a global environment variable
if (declaration && declaration.identifiers.length !== 0) {
checkLocationAndReport(reference, declaration);
}
}
});
}
return {
"Program": findVariables,
"FunctionExpression": findVariables,
"FunctionDeclaration": findVariables
};
};
|
module.exports = function (gulp, config, $) {
gulp.task('less', [], function () {
var style = config.style;
return gulp.src(style + '**/*/*.less')
.pipe($.less())
.pipe(gulp.dest(function(f) {
return f.base;
}))
});
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.