code stringlengths 2 1.05M |
|---|
// Regular expression that matches all symbols in the `Meroitic_Cursive` script as per Unicode v9.0.0:
/\uD802[\uDDA0-\uDDB7\uDDBC-\uDDCF\uDDD2-\uDDFF]/; |
frappe.ui.Filter = class {
constructor(opts) {
$.extend(this, opts);
if (this.value === null || this.value === undefined) {
this.value = '';
}
this.utils = frappe.ui.filter_utils;
this.conditions = [
["=", __("Equals")],
["!=", __("Not Equals")],
["like", __("Like")],
["not like", __("Not Like")],
["in", __("In")],
["not in", __("Not In")],
[">", ">"],
["<", "<"],
[">=", ">="],
["<=", "<="],
["Between", __("Between")],
["descendants of", __("Descendants Of")],
["ancestors of", __("Ancestors Of")]
];
this.invalid_condition_map = {
Date: ['like', 'not like'],
Datetime: ['like', 'not like'],
Data: ['Between'],
Select: ["Between", "<=", ">=", "<", ">"],
Link: ["Between"],
Currency: ["Between"],
Color: ["Between"]
};
this.make();
this.make_select();
this.set_events();
this.setup();
}
make() {
this.filter_edit_area = $(frappe.render_template("edit_filter", {}))
.appendTo(this.parent.find('.filter-edit-area'));
}
make_select() {
this.fieldselect = new frappe.ui.FieldSelect({
parent: this.filter_edit_area.find('.fieldname-select-area'),
doctype: this.parent_doctype,
filter_fields: this.filter_fields,
select: (doctype, fieldname) => {
this.set_field(doctype, fieldname);
},
filter_options: (doctype, fieldname) => {
return this.filter_items(doctype, fieldname);
}
});
if(this.fieldname) {
this.fieldselect.set_value(this.doctype, this.fieldname);
}
}
set_events() {
this.filter_edit_area.find("a.remove-filter").on("click", () => {
this.remove();
});
this.filter_edit_area.find(".set-filter-and-run").on("click", () => {
this.filter_edit_area.removeClass("new-filter");
this.on_change();
this.update_filter_tag();
});
this.filter_edit_area.find('.condition').change(() => {
if(!this.field) return;
let condition = this.get_condition();
let fieldtype = null;
if(["in", "like", "not in", "not like"].includes(condition)) {
fieldtype = 'Data';
this.add_condition_help(condition);
}
if (['Select', 'MultiSelect'].includes(this.field.df.fieldtype) && ["in", "not in"].includes(condition)) {
fieldtype = 'MultiSelect';
}
this.set_field(this.field.df.parent, this.field.df.fieldname, fieldtype, condition);
});
}
setup() {
const fieldname = this.fieldname || 'name';
// set the field
return this.set_values(this.doctype, fieldname, this.condition, this.value);
}
setup_state(is_new) {
let promise = Promise.resolve();
if (is_new) {
this.filter_edit_area.addClass("new-filter");
} else {
promise = this.update_filter_tag();
}
if(this.hidden) {
promise.then(() => this.$filter_tag.hide());
}
}
freeze() {
this.update_filter_tag();
}
update_filter_tag() {
return this._filter_value_set.then(() => {
!this.$filter_tag ? this.make_tag() : this.set_filter_button_text();
this.filter_edit_area.hide();
});
}
remove() {
this.filter_edit_area.remove();
this.$filter_tag && this.$filter_tag.remove();
this.field = null;
this.on_change(true);
}
set_values(doctype, fieldname, condition, value) {
// presents given (could be via tags!)
this.set_field(doctype, fieldname);
if(this.field.df.original_type==='Check') {
value = (value==1) ? 'Yes' : 'No';
}
if(condition) this.set_condition(condition, true);
// set value can be asynchronous, so update_filter_tag should happen after field is set
this._filter_value_set = Promise.resolve();
if (['in', 'not in'].includes(condition) && Array.isArray(value)) {
value = value.join(',');
}
if (value !== undefined || value !== null) {
this._filter_value_set = this.field.set_value((value + '').trim());
}
return this._filter_value_set;
}
set_field(doctype, fieldname, fieldtype, condition) {
// set in fieldname (again)
let cur = {};
if(this.field) for(let k in this.field.df) cur[k] = this.field.df[k];
let original_docfield = (this.fieldselect.fields_by_name[doctype] || {})[fieldname];
if(!original_docfield) {
frappe.msgprint(__("Field {0} is not selectable.", [fieldname]));
this.remove();
return;
}
let df = copy_dict(original_docfield);
// filter field shouldn't be read only or hidden
df.read_only = 0; df.hidden = 0;
let c = condition ? condition : this.utils.get_default_condition(df);
this.set_condition(c);
this.utils.set_fieldtype(df, fieldtype, this.get_condition());
// called when condition is changed,
// don't change if all is well
if(this.field && cur.fieldname == fieldname && df.fieldtype == cur.fieldtype &&
df.parent == cur.parent) {
return;
}
// clear field area and make field
this.fieldselect.selected_doctype = doctype;
this.fieldselect.selected_fieldname = fieldname;
this.make_field(df, cur.fieldtype);
}
make_field(df, old_fieldtype) {
let old_text = this.field ? this.field.get_value() : null;
this.hide_invalid_conditions(df.fieldtype, df.original_type);
this.hide_nested_set_conditions(df);
let field_area = this.filter_edit_area.find('.filter-field').empty().get(0);
let f = frappe.ui.form.make_control({
df: df,
parent: field_area,
only_input: true,
});
f.refresh();
this.field = f;
if(old_text && f.fieldtype===old_fieldtype) {
this.field.set_value(old_text);
}
// run on enter
$(this.field.wrapper).find(':input').keydown(e => {
if(e.which==13 && this.field.df.fieldtype !== 'MultiSelect') {
this.on_change();
}
});
}
get_value() {
return [
this.fieldselect.selected_doctype,
this.field.df.fieldname,
this.get_condition(),
this.get_selected_value(),
this.hidden
];
}
get_selected_value() {
return this.utils.get_selected_value(this.field, this.get_condition());
}
get_condition() {
return this.filter_edit_area.find('.condition').val();
}
set_condition(condition, trigger_change=false) {
let $condition_field = this.filter_edit_area.find('.condition');
$condition_field.val(condition);
if(trigger_change) $condition_field.change();
}
make_tag() {
this.$filter_tag = this.get_filter_tag_element()
.insertAfter(this.parent.find(".active-tag-filters .add-filter"));
this.set_filter_button_text();
this.bind_tag();
}
bind_tag() {
this.$filter_tag.find(".remove-filter").on("click", this.remove.bind(this));
let filter_button = this.$filter_tag.find(".toggle-filter");
filter_button.on("click", () => {
filter_button.closest('.tag-filters-area').find('.filter-edit-area').show();
this.filter_edit_area.toggle();
});
}
set_filter_button_text() {
this.$filter_tag.find(".toggle-filter").html(this.get_filter_button_text());
}
get_filter_button_text() {
let value = this.utils.get_formatted_value(this.field, this.get_selected_value());
return `${__(this.field.df.label)} ${__(this.get_condition())} ${__(value)}`;
}
get_filter_tag_element() {
return $(`<div class="filter-tag btn-group">
<button class="btn btn-default btn-xs toggle-filter"
title="${ __("Edit Filter") }">
</button>
<button class="btn btn-default btn-xs remove-filter"
title="${ __("Remove Filter") }">
<i class="fa fa-remove text-muted"></i>
</button>
</div>`);
}
add_condition_help(condition) {
let $desc = this.field.desc_area;
if(!$desc) {
$desc = $('<div class="text-muted small">').appendTo(this.field.wrapper);
}
// set description
$desc.html((in_list(["in", "not in"], condition)==="in"
? __("values separated by commas")
: __("use % as wildcard"))+'</div>');
}
hide_invalid_conditions(fieldtype, original_type) {
let invalid_conditions = this.invalid_condition_map[fieldtype] ||
this.invalid_condition_map[original_type] || [];
for (let condition of this.conditions) {
this.filter_edit_area.find(`.condition option[value="${condition[0]}"]`).toggle(
!invalid_conditions.includes(condition[0])
);
}
}
hide_nested_set_conditions(df) {
if ( !( df.fieldtype == "Link" && frappe.boot.nested_set_doctypes.includes(df.options))) {
this.filter_edit_area.find(`.condition option[value="descendants of"]`).hide();
this.filter_edit_area.find(`.condition option[value="not descendants of"]`).hide();
this.filter_edit_area.find(`.condition option[value="ancestors of"]`).hide();
this.filter_edit_area.find(`.condition option[value="not ancestors of"]`).hide();
}else {
this.filter_edit_area.find(`.condition option[value="descendants of"]`).show();
this.filter_edit_area.find(`.condition option[value="not descendants of"]`).show();
this.filter_edit_area.find(`.condition option[value="ancestors of"]`).show();
this.filter_edit_area.find(`.condition option[value="not ancestors of"]`).show();
}
}
};
frappe.ui.filter_utils = {
get_formatted_value(field, value) {
if(field.df.fieldname==="docstatus") {
value = {0:"Draft", 1:"Submitted", 2:"Cancelled"}[value] || value;
} else if(field.df.original_type==="Check") {
value = {0:"No", 1:"Yes"}[cint(value)];
}
return frappe.format(value, field.df, {only_value: 1});
},
get_selected_value(field, condition) {
let val = field.get_value();
if(typeof val==='string') {
val = strip(val);
}
if(field.df.original_type == 'Check') {
val = (val=='Yes' ? 1 :0);
}
if(condition.indexOf('like', 'not like')!==-1) {
// automatically append wildcards
if(val) {
if(val.slice(0,1) !== "%") {
val = "%" + val;
}
if(val.slice(-1) !== "%") {
val = val + "%";
}
}
} else if(in_list(["in", "not in"], condition)) {
if(val) {
val = val.split(',').map(v => strip(v));
}
} if(val === '%') {
val = "";
}
return val;
},
get_default_condition(df) {
if (df.fieldtype == 'Data') {
return 'like';
} else if (df.fieldtype == 'Date' || df.fieldtype == 'Datetime'){
return 'Between';
} else {
return '=';
}
},
set_fieldtype(df, fieldtype, condition) {
// reset
if(df.original_type)
df.fieldtype = df.original_type;
else
df.original_type = df.fieldtype;
df.description = ''; df.reqd = 0;
df.ignore_link_validation = true;
// given
if(fieldtype) {
df.fieldtype = fieldtype;
return;
}
// scrub
if(df.fieldname=="docstatus") {
df.fieldtype="Select",
df.options=[
{value:0, label:__("Draft")},
{value:1, label:__("Submitted")},
{value:2, label:__("Cancelled")}
];
} else if(df.fieldtype=='Check') {
df.fieldtype='Select';
df.options='No\nYes';
} else if(['Text','Small Text','Text Editor','Code','Tag','Comments',
'Dynamic Link','Read Only','Assign'].indexOf(df.fieldtype)!=-1) {
df.fieldtype = 'Data';
} else if(df.fieldtype=='Link' && ['=', '!=', 'descendants of', 'ancestors of', 'not descendants of', 'not ancestors of'].indexOf(condition)==-1) {
df.fieldtype = 'Data';
}
if(df.fieldtype==="Data" && (df.options || "").toLowerCase()==="email") {
df.options = null;
}
if(condition == "Between" && (df.fieldtype == 'Date' || df.fieldtype == 'Datetime')){
df.fieldtype = 'DateRange';
}
}
};
|
goog.provide('ngeo.StateManager');
goog.require('goog.asserts');
goog.require('goog.storage.mechanism.HTML5LocalStorage');
goog.require('ngeo');
goog.require('ngeo.Location');
/**
* Provides a service for managing the application state.
* The application state is written to both the URL and the local storage.
* @constructor
* @param {ngeo.Location} ngeoLocation ngeo location service.
* @ngInject
*/
ngeo.StateManager = function(ngeoLocation) {
/**
* Object representing the application's initial state.
* @type {Object.<string ,string>}
*/
this.initialState = {};
/**
* @type {ngeo.Location}
*/
this.ngeoLocation = ngeoLocation;
/**
* @type {goog.storage.mechanism.HTML5LocalStorage}
*/
this.localStorage = new goog.storage.mechanism.HTML5LocalStorage();
// Populate initialState with the application's initial state. The initial
// state is read from the location URL, or from the local storage if there
// is no state in the location URL.
var paramKeys = ngeoLocation.getParamKeys();
var i, key;
if (paramKeys.length === 0 ||
(paramKeys.length === 1 && paramKeys[0] == 'debug')) {
if (this.localStorage.isAvailable()) {
var count = this.localStorage.getCount();
for (i = 0; i < count; ++i) {
key = this.localStorage.key(i);
goog.asserts.assert(key !== null);
this.initialState[key] = this.localStorage.get(key);
}
}
} else {
var keys = ngeoLocation.getParamKeys();
for (i = 0; i < keys.length; ++i) {
key = keys[i];
this.initialState[key] = ngeoLocation.getParam(key);
}
}
this.ngeoLocation.updateParams({});
};
/**
* Get the state value for `key`.
* @param {string} key State key.
* @return {string|undefined} State value.
*/
ngeo.StateManager.prototype.getInitialValue = function(key) {
return this.initialState[key];
};
/**
* Update the application state with the values in `object`.
* @param {Object.<string, string>} object Object.
*/
ngeo.StateManager.prototype.updateState = function(object) {
this.ngeoLocation.updateParams(object);
if (this.localStorage.isAvailable()) {
var key;
for (key in object) {
this.localStorage.set(key, object[key]);
}
}
};
/**
* Delete a parameter
* @param {string} key Key.
*/
ngeo.StateManager.prototype.deleteParam = function(key) {
this.ngeoLocation.deleteParam(key);
if (this.localStorage.isAvailable()) {
this.localStorage.remove(key);
}
};
ngeo.module.service('ngeoStateManager', ngeo.StateManager);
|
/*!!
* @atlassian/aui - Atlassian User Interface Framework
* @version v7.9.0-alpha-3
* @link https://docs.atlassian.com/aui/latest/
* @license SEE LICENSE IN LICENSE.md
* @author Atlassian Pty Ltd.
*/
// src/js/aui/internal/deprecation/deprecated-adg2-icons.js
(typeof window === 'undefined' ? global : window).__af1a4667f2e6a7121d5ea46bdf9bd702 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var deprecatedIcons = [{
newName: 'menu',
oldName: 'appswitcher'
}, {
newName: 'refresh',
oldName: 'build'
}, {
newName: 'cross',
oldName: 'close-dialog'
}, {
newName: 'chevron-right',
oldName: 'collapsed'
}, {
newName: 'settings',
oldName: 'configure'
}, {
newName: 'copy',
oldName: 'copy-clipboard'
}, {
newName: 'trash',
oldName: 'delete'
}, {
newName: 'detail-view',
oldName: 'details'
}, {
newName: 'arrow-left',
oldName: 'devtools-arrow-left'
}, {
newName: 'arrow-right',
oldName: 'devtools-arrow-right'
}, {
newName: 'sign-in',
oldName: 'devtools-checkout'
}, {
newName: 'import',
oldName: 'devtools-clone'
}, {
newName: 'folder-filled',
oldName: 'devtools-folder-closed'
}, {
newName: 'export',
oldName: 'devtools-pull-request'
}, {
newName: 'tag',
oldName: 'devtools-tag'
}, {
newName: 'tag',
oldName: 'devtools-tag-small'
}, {
newName: 'menu',
oldName: 'drag-vertical'
}, {
newName: 'edit-filled',
oldName: 'edit'
}, {
newName: 'edit-filled',
oldName: 'edit-small'
}, {
newName: 'chevron-up',
oldName: 'expanded'
}, {
newName: 'vid-full-screen-on',
oldName: 'focus'
}, {
newName: 'more-vertical',
oldName: 'handle-horizontal'
}, {
newName: 'question-circle',
oldName: 'help'
}, {
newName: 'home-circle',
oldName: 'homepage'
}, {
newName: 'image',
oldName: 'image-extrasmall'
}, {
newName: 'info-circle',
oldName: 'info'
}, {
newName: 'world',
oldName: 'weblink'
}, {
newName: 'add-circle',
oldName: 'list-add'
}, {
newName: 'cross-circle',
oldName: 'list-remove'
}, {
newName: 'lock-filled',
oldName: 'locked'
}, {
newName: 'lock-filled',
oldName: 'locked-small'
}, {
newName: 'document',
oldName: 'page-blank'
}, {
newName: 'document',
oldName: 'doc'
}, {
newName: 'documents',
oldName: 'pages'
}, {
newName: 'cross-circle',
oldName: 'remove'
}, {
newName: 'cross-circle',
oldName: 'remove-label'
}, {
newName: 'search',
oldName: 'search-small'
}, {
newName: 'person-circle',
oldName: 'space-personal'
}, {
newName: 'star-filled',
oldName: 'star'
}, {
newName: 'check',
oldName: 'success'
}, {
newName: 'recent',
oldName: 'time'
}, {
newName: 'vid-full-screen-off',
oldName: 'unfocus'
}, {
newName: 'unlock-filled',
oldName: 'unlocked'
}, {
newName: 'star',
oldName: 'unstar'
}, {
newName: 'watch',
oldName: 'unwatch'
}, {
newName: 'arrow-up',
oldName: 'up'
}, {
newName: 'arrow-down',
oldName: 'down'
}, {
newName: 'person',
oldName: 'user'
}, {
newName: 'watch-filled',
oldName: 'view'
}, {
newName: 'room-menu',
oldName: 'view-list'
}, {
newName: 'menu',
oldName: 'view-table'
}, {
newName: 'watch-filled',
oldName: 'watch'
}, {
newName: 'tray',
oldName: 'workbox'
}, {
newName: 'bullet-list',
oldName: 'configure-columns'
}, {
newName: 'image',
oldName: 'file-image'
}, {
newName: 'group',
oldName: 'admin-roles'
}, {
newName: 'vid-pause',
oldName: 'pause'
}, {
newName: 'refresh',
oldName: 'refresh-small'
}, {
newName: 'swap',
oldName: 'switch-small'
}, {
newName: 'arrow-down-small',
oldName: 'arrow-down'
}, {
newName: 'arrow-up-small',
oldName: 'arrow-up'
}, {
newName: 'email',
oldName: 'email-large'
}, {
newName: 'documents',
oldName: 'pages-large'
}, {
newName: 'person',
oldName: 'user-large'
}, {
newName: 'documents',
oldName: 'bp-decisions'
}, {
newName: 'documents',
oldName: 'bp-default'
}, {
newName: 'documents',
oldName: 'bp-files'
}, {
newName: 'documents',
oldName: 'bp-requirements'
}, {
newName: 'documents',
oldName: 'bp-howto'
}, {
newName: 'documents',
oldName: 'bp-jira'
}, {
newName: 'documents',
oldName: 'bp-meeting'
}, {
newName: 'documents',
oldName: 'bp-retrospective'
}, {
newName: 'documents',
oldName: 'bp-sharedlinks'
}, {
newName: 'documents',
oldName: 'bp-troubleshooting'
}, {
newName: 'upload',
oldName: 'deploy'
}, {
newName: 'file',
oldName: 'page-default'
}, {
newName: 'shortcut',
oldName: 'sidebar-link'
}, {
newName: 'shortcut',
oldName: 'sidebar-link-large'
}, {
newName: 'incomplete-build',
oldName: 'devtools-task-cancelled'
}, {
newName: 'plan-disabled',
oldName: 'devtools-task-disabled'
}, {
newName: 'queued-build',
oldName: 'devtools-task-in-progress'
}, {
newName: 'branch',
oldName: 'devtools-branch'
}, {
newName: 'branch',
oldName: 'devtools-branch-small'
}, {
newName: 'commits',
oldName: 'devtools-commit'
}, {
newName: 'create-fork',
oldName: 'devtools-for'
}, {
newName: 'bold',
oldName: 'editor-bold'
}, {
newName: 'italic',
oldName: 'editor-italic'
}, {
newName: 'underline',
oldName: 'editor-underline'
}, {
newName: 'text-color',
oldName: 'editor-color'
}, {
newName: 'left-alignment',
oldName: 'editor-align-left'
}, {
newName: 'right-alignment',
oldName: 'editor-align-right'
}, {
newName: 'center-alignment',
oldName: 'editor-align-center'
}, {
newName: 'indent-left-mall',
oldName: 'editor-indent'
}, {
newName: 'indent-right-mall',
oldName: 'editor-outdent'
}, {
newName: 'number-list-mall',
oldName: 'editor-list-number'
}, {
newName: 'bullet-list-mall',
oldName: 'editor-list-bullet'
}, {
newName: 'mention',
oldName: 'editor-mention'
}, {
newName: 'table-of-contents-mall',
oldName: 'editor-macro-toc'
}, {
newName: 'advanced',
oldName: 'editor-style'
}, {
newName: 'symbol',
oldName: 'editor-symbol'
}, {
newName: 'horizontal-rule',
oldName: 'editor-hr'
}, {
newName: 'page-layout-toggle',
oldName: 'editor-layout'
}, {
newName: 'table',
oldName: 'editor-table'
}, {
newName: 'location',
oldName: 'nav-children-large'
}, {
newName: 'location',
oldName: 'nav-children'
}, {
newName: 'single-column',
oldName: 'layout-1col-large'
}, {
newName: 'two-column',
oldName: 'layout-2col-large'
}, {
newName: 'right-side-bar',
oldName: 'layout-2col-left-large'
}, {
newName: 'left-side-bar',
oldName: 'layout-2col-right-large'
}, {
newName: 'three-column-side-bars',
oldName: 'layout-3col-center-large'
}, {
newName: 'three-column',
oldName: 'layout-3col-large'
}, {
newName: 'heading-column',
oldName: 'table-header-column'
}, {
newName: 'heading-row',
oldName: 'table-header-row'
}, {
newName: 'insert-row-after',
oldName: 'table-row-down'
}, {
newName: 'insert-row-before',
oldName: 'table-row-up'
}, {
newName: 'remove-row',
oldName: 'table-row-remove'
}, {
newName: 'remove-column',
oldName: 'table-col-remove'
}, {
newName: 'insert-column-before',
oldName: 'table-col-left'
}, {
newName: 'insert-column-after',
oldName: 'table-col-right'
}, {
newName: 'remove-table',
oldName: 'table-remove'
}, {
newName: 'merge-table-cells',
oldName: 'table-merge'
}, {
newName: 'split-merged-table-cells',
oldName: 'table-split'
}, {
newName: 'copy-table-row',
oldName: 'table-copy-row'
}, {
newName: 'paste-table-row',
oldName: 'table-paste-row'
}, {
newName: 'cut-table-row',
oldName: 'table-cut-row'
}, {
newName: 'team-calendar',
oldName: 'teamcals-large'
}, {
newName: 'team-calendar',
oldName: 'teamcals'
}, {
newName: 'emoji',
oldName: 'editor-emoticon'
}, {
newName: 'help',
oldName: 'editor-help'
}, {
newName: 'task',
oldName: 'editor-task'
}, {
newName: 'like',
oldName: 'like-small'
}, {
newName: 'submodule',
oldName: 'devtools-submodule'
}];
exports.default = deprecatedIcons;
module.exports = exports['default'];
return module.exports;
}).call(this);
// src/js/aui-css-deprecations.js
(typeof window === 'undefined' ? global : window).__7e864afb58ef5a3c65d95f5638a78c87 = (function () {
var module = {
exports: {}
};
var exports = module.exports;
'use strict';
var _deprecation = __921ad9514d56376fef992861d9ec0f51;
var _amdify = __65ca28a9d6b0f244027266ff8e6a6d1c;
var _amdify2 = _interopRequireDefault(_amdify);
var _deprecatedAdg2Icons = __af1a4667f2e6a7121d5ea46bdf9bd702;
var _deprecatedAdg2Icons2 = _interopRequireDefault(_deprecatedAdg2Icons);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
(0, _deprecation.css)('.aui-badge', {
displayName: 'AUI Badges class'
});
(0, _deprecation.css)('.aui-dropdown2-trigger.aui-style-dropdown2triggerlegacy1', {
displayName: 'Dropdown2 legacy trigger'
});
(0, _deprecation.css)('.aui-message span.aui-icon', {
displayName: 'Message icon span'
});
(0, _deprecation.css)('.aui-zebra', {
displayName: 'Zebra table rows'
});
(0, _deprecation.css)('.aui-nav-pagination > li.aui-nav-current', {
alternativeName: 'aui-nav-selected'
});
(0, _deprecation.css)('.aui-tabs.vertical-tabs', {
displayName: 'Vertical tabs'
});
(0, _deprecation.css)('form.aui span.content');
(0, _deprecation.css)(['form.aui .button', 'form.aui .buttons-container'], {
displayName: 'Unprefixed buttons',
alternativeName: 'aui-button and aui-buttons'
});
(0, _deprecation.css)(['form.aui .icon-date', 'form.aui .icon-range', 'form.aui .icon-help', 'form.aui .icon-required', 'form.aui .icon-inline-help', 'form.aui .icon-users', '.aui-icon-date', '.aui-icon-range', '.aui-icon-help', '.aui-icon-required', '.aui-icon-users', '.aui-icon-inline-help'], {
displayName: 'Form icons'
});
(0, _deprecation.css)(['.aui-icon.icon-move-d', '.aui-icon.icon-move', '.aui-icon.icon-dropdown-d', '.aui-icon.icon-dropdown', '.aui-icon.icon-dropdown-active-d', '.aui-icon.icon-dropdown-active', '.aui-icon.icon-minimize-d', '.aui-icon.icon-minimize', '.aui-icon.icon-maximize-d', '.aui-icon.icon-maximize'], {
displayName: 'Core icons'
});
(0, _deprecation.css)(['.aui-message.error', '.aui-message.warning', '.aui-message.hint', '.aui-message.info', '.aui-message.success'], {
displayName: 'Unprefixed message types AUI-2150'
});
(0, _deprecation.css)(['.aui-dropdown2 .active', '.aui-dropdown2 .checked', '.aui-dropdown2 .disabled', '.aui-dropdown2 .interactive'], {
displayName: 'Unprefixed dropdown2 css AUI-2150'
});
(0, _deprecation.css)(['.aui-page-header-marketing', '.aui-page-header-hero'], {
displayName: 'Marketing style headings',
removeVersion: '8.0.0'
});
// 5.9.0
// -----
var fiveNineZero = {
// Inline Dialog
'arrow': 'aui-inline-dialog-arrow',
'contents': 'aui-inline-dialog-contents',
// Messages
'error': 'aui-message-error',
'generic': 'aui-message-generic',
'hint': 'aui-message-hint',
'info': 'aui-message-info',
'success': 'aui-message-success',
'warning': 'aui-message-warning'
};
var name;
for (name in fiveNineZero) {
if (Object.hasOwnProperty.call(fiveNineZero, name)) {
(0, _deprecation.css)(name, {
alternativeName: fiveNineZero[name],
removeVersion: '8.0.0',
sinceVersion: '5.9.0'
});
}
}
// 6.1.0
// -----
(0, _deprecation.css)(['.aui-header-logo-atlassian', '.aui-header-logo-aui', '.aui-header-logo-bamboo', '.aui-header-logo-bitbucket', '.aui-header-logo-stash', '.aui-header-logo-clover', '.aui-header-logo-confluence', '.aui-header-logo-crowd', '.aui-header-logo-crucible', '.aui-header-logo-fecru', '.aui-header-logo-fisheye', '.aui-header-logo-hipchat', '.aui-header-logo-jira', '.aui-header-logo-jira-core', '.aui-header-logo-jira-software', '.aui-header-logo-jira-service-desk', '.aui-header-logo-answer', '.aui-header-logo-community', '.aui-header-logo-developers', '.aui-header-logo-expert', '.aui-header-logo-partner-program', '.aui-header-logo-marketplace', '.aui-header-logo-support', '.aui-header-logo-university', '.aui-header-logo-cloud'], {
displayName: 'Atlassian Brand Logos'
});
// 7.1.0
// -----
(0, _deprecation.css)('.aui-badge', {
displayName: 'AUI Badge CSS class',
alternativeName: 'aui-badge',
sinceVersion: '7.1.0',
extraInfo: 'The badge pattern is best used as a web component instead of a CSS class'
});
// 7.5.0
// -----
(0, _deprecation.css)(['.aui-iconfont-image-extrasmall'], {
displayName: 'Special size icon names',
sinceVersion: '7.5.0',
extraInfo: 'The only size variant allowed for icon names is `-small`.'
});
(0, _deprecation.css)('.aui-icon-dropdown', {
displayName: 'AUI dropdown icon element',
alternativeName: '.aui-icon-chevron-down',
sinceVersion: '7.5.0',
extraInfo: 'Use of an explicit element for the dropdown icon is part of a ' + 'deprecated markup pattern for dropdowns and should not be used. If you must ' + 'render an explicit icon element for a dropdown trigger, use the new ' + 'alternative class name.'
});
// New ADGS names for the old ADG2 icon
_deprecatedAdg2Icons2.default.forEach(function (_ref) {
var newName = _ref.newName,
oldName = _ref.oldName;
return (0, _deprecation.css)('.aui-iconfont-' + oldName, {
displayName: 'ADG2 icon',
alternativeName: '.aui-iconfont-' + newName,
sinceVersion: '7.5.0',
removeVersion: '8.0.0',
extraInfo: 'Use the new ADGS icon CSS class name'
});
});
// 7.8.0
(0, _deprecation.css)('.aui-table-interactive', {
alternativeName: '.aui-table-list',
sinceVersion: '7.8.0',
removeInVersion: '8.0.0',
extraInfo: 'The "interactive" suffix caused some confusion when contrasted with sortable tables.' + 'The name has been updated to reflect its intended purpose: displaying lists of data in a tabular format.'
});
(0, _amdify2.default)('aui/css-deprecation-warnings');
return module.exports;
}).call(this); |
import Loader from 'loader/Loader.js';
export default class LoaderTest {
constructor (key, url) {
this.loader = new Loader();
this.loader.path = 'assets/';
this.loader.binary(key, url, (key, data) => { this.checkFile(key, data); });
}
start () {
this.loader.start();
}
checkFile (key, data) {
console.log('checkFile', this);
return data;
}
}
var test = new LoaderTest('mush', 'mushroom2.png');
test.start();
|
'use strict';
// Local dependencies
var command = require('../lib/command');
/**
* A HELP request asks for human-readable information from the server. The
* server may accept this request with code 211 or 214, or reject it with code
* 502.
*
* A HELP request may include a parameter. The meaning of the parameter is
* defined by the server. Some servers interpret the parameter as an FTP verb,
* and respond by briefly explaining the syntax of the verb:
*
* HELP RETR
* 214 Syntax: RETR <sp> file-name
* HELP FOO
* 502 Unknown command FOO.
*
* I use HELP (without a parameter) in automated surveys of FTP servers. The
* HELP response is a good place for server implementors to declare the
* operating system type and the name of the server program.
*/
command.add('HELP', 'HELP [<sp> command]', function (subCommand, commandChannel) {
if (subCommand && command.exists(subCommand)) {
commandChannel.write(214, command.help(subCommand));
} else if (subCommand) {
commandChannel.write(502, 'Unknown command \'' + subCommand + '\'');
} else {
commandChannel.write(214, '-The following commands are recognized (* =>\'s unimplemented):');
commandChannel.write('CDUP CWD DELE FEAT HELP LIST MKD NOOP');
commandChannel.write('OPTS PASS PASV PORT PWD QUIT REIN RETR');
commandChannel.write('RETR RMD RNFR RNTO SITE SIZE STOR SYST');
commandChannel.write('TYPE USER');
commandChannel.write(214, 'Direct comments to site administrator');
}
});
|
/*!
* Copyright (c) 2015-2019 Cisco Systems, Inc. See LICENSE file.
*/
import '@webex/internal-plugin-conversation';
import '@webex/internal-plugin-mercury';
import {registerPlugin} from '@webex/webex-core';
import Memberships from './memberships';
registerPlugin('memberships', Memberships);
export default Memberships;
|
import lodash from 'lodash';
import { mergeEnvironment } from './config.js';
let config = mergeEnvironment();
let karmaReporters = ['progress'];
karmaReporters.push('coverage');
// Karma configuration
module.exports = function (karmaConfig) {
let karmaFiles = [];
karmaFiles.push('karma.setup.js');
karmaFiles.push('../public/dist/angular.js');
karmaFiles.push('../bower_components/angular-mocks/angular-mocks.js');
karmaFiles.push('../bower_components/angular-material/angular-material-mocks.js');
karmaFiles = lodash.union(karmaFiles, config.files.test.client.coverage, config.files.test.client.tests);
karmaFiles.push('../public/dist/vendor.js');
karmaFiles.push('../public/dist/templates.js');
//karmaFiles.push('modules/core/client/app/core.client.app.loader.js');
//karmaFiles.push('modules/core/client/app/core.client.app.loader.spec.js');
//console.log('Karma::Files', karmaFiles);
karmaConfig.set({
client: {
captureConsole: false,
},
// Frameworks to use
frameworks: ['browserify', 'mocha'],
preprocessors: {
'karma.setup.js': [ 'browserify' ],
'../modules/*/client/views/**/*.html': ['ng-html2js'],
'../modules/*/client/**/*.js': ['coverage']
},
browserify: {
debug: true,
transform: [ 'babelify' ]
},
ngHtml2JsPreprocessor: {
moduleName: 'modernMean',
cacheIdFromPath: function (filepath) {
return filepath;
},
},
// List of files / patterns to load in the browser
files: karmaFiles,
// Test results reporter to use
// Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
reporters: karmaReporters,
// Configure the coverage reporter
coverageReporter: {
dir: '.coverdata/client',
reporters: [
// Reporters not supporting the `file` property
{ type: 'html', subdir: 'report-html' },
{ type: 'lcov', subdir: 'report-lcov' },
// Output coverage to console
{ type: 'text' }
],
instrumenterOptions: {
istanbul: { noCompact: true }
}
},
// Web server port
port: 9876,
// Enable / disable colors in the output (reporters and logs)
colors: true,
// Level of logging
// Possible values: karmaConfig.LOG_DISABLE || karmaConfig.LOG_ERROR || karmaConfig.LOG_WARN || karmaConfig.LOG_INFO || karmaConfig.LOG_DEBUG
logLevel: process.env.KARMA_LOG || karmaConfig.LOG_DISABLE,
// Enable / disable watching file and executing tests whenever any file changes
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['PhantomJS'],
// If browser does not capture in given timeout [ms], kill it
captureTimeout: 60000,
customContextFile: 'karma.context.html'
});
};
|
"use strict";
const conf = require('./protractor.conf.js').config;
const JUnitXmlReporter = require('jasmine-reporters').JUnitXmlReporter;
const oldPrepare = conf.onPrepare;
conf.onPrepare = onPrepare;
conf.seleniumAddress = 'http://localhost:4444/wd/hub';
function onPrepare(){
if(oldPrepare) oldPrepare();
const jUnitReporter = new JUnitXmlReporter({
savePath: 'reports',
filePrefix: 'e2e-tests',
consolidateAll: true
});
jasmine.getEnv().addReporter(jUnitReporter);
}
exports.config = conf;
|
<<<<<<< HEAD
<<<<<<< HEAD
var assert = require('assert'),
nodeuuid = require('../uuid'),
uuidjs = require('uuid-js'),
libuuid = require('uuid').generate,
util = require('util'),
exec = require('child_process').exec,
os = require('os');
// On Mac Os X / macports there's only the ossp-uuid package that provides uuid
// On Linux there's uuid-runtime which provides uuidgen
var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t';
function compare(ids) {
console.log(ids);
for (var i = 0; i < ids.length; i++) {
var id = ids[i].split('-');
id = [id[2], id[1], id[0]].join('');
ids[i] = id;
}
var sorted = ([].concat(ids)).sort();
if (sorted.toString() !== ids.toString()) {
console.log('Warning: sorted !== ids');
} else {
console.log('everything in order!');
}
}
// Test time order of v1 uuids
var ids = [];
while (ids.length < 10e3) ids.push(nodeuuid.v1());
var max = 10;
console.log('node-uuid:');
ids = [];
for (var i = 0; i < max; i++) ids.push(nodeuuid.v1());
compare(ids);
console.log('');
console.log('uuidjs:');
ids = [];
for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString());
compare(ids);
console.log('');
console.log('libuuid:');
ids = [];
var count = 0;
var last = function() {
compare(ids);
}
var cb = function(err, stdout, stderr) {
ids.push(stdout.substring(0, stdout.length-1));
count++;
if (count < max) {
return next();
}
last();
};
var next = function() {
exec(uuidCmd, cb);
};
next();
=======
var assert = require('assert'),
nodeuuid = require('../uuid'),
uuidjs = require('uuid-js'),
libuuid = require('uuid').generate,
util = require('util'),
exec = require('child_process').exec,
os = require('os');
// On Mac Os X / macports there's only the ossp-uuid package that provides uuid
// On Linux there's uuid-runtime which provides uuidgen
var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t';
function compare(ids) {
console.log(ids);
for (var i = 0; i < ids.length; i++) {
var id = ids[i].split('-');
id = [id[2], id[1], id[0]].join('');
ids[i] = id;
}
var sorted = ([].concat(ids)).sort();
if (sorted.toString() !== ids.toString()) {
console.log('Warning: sorted !== ids');
} else {
console.log('everything in order!');
}
}
// Test time order of v1 uuids
var ids = [];
while (ids.length < 10e3) ids.push(nodeuuid.v1());
var max = 10;
console.log('node-uuid:');
ids = [];
for (var i = 0; i < max; i++) ids.push(nodeuuid.v1());
compare(ids);
console.log('');
console.log('uuidjs:');
ids = [];
for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString());
compare(ids);
console.log('');
console.log('libuuid:');
ids = [];
var count = 0;
var last = function() {
compare(ids);
}
var cb = function(err, stdout, stderr) {
ids.push(stdout.substring(0, stdout.length-1));
count++;
if (count < max) {
return next();
}
last();
};
var next = function() {
exec(uuidCmd, cb);
};
next();
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
=======
var assert = require('assert'),
nodeuuid = require('../uuid'),
uuidjs = require('uuid-js'),
libuuid = require('uuid').generate,
util = require('util'),
exec = require('child_process').exec,
os = require('os');
// On Mac Os X / macports there's only the ossp-uuid package that provides uuid
// On Linux there's uuid-runtime which provides uuidgen
var uuidCmd = os.type() === 'Darwin' ? 'uuid -1' : 'uuidgen -t';
function compare(ids) {
console.log(ids);
for (var i = 0; i < ids.length; i++) {
var id = ids[i].split('-');
id = [id[2], id[1], id[0]].join('');
ids[i] = id;
}
var sorted = ([].concat(ids)).sort();
if (sorted.toString() !== ids.toString()) {
console.log('Warning: sorted !== ids');
} else {
console.log('everything in order!');
}
}
// Test time order of v1 uuids
var ids = [];
while (ids.length < 10e3) ids.push(nodeuuid.v1());
var max = 10;
console.log('node-uuid:');
ids = [];
for (var i = 0; i < max; i++) ids.push(nodeuuid.v1());
compare(ids);
console.log('');
console.log('uuidjs:');
ids = [];
for (var i = 0; i < max; i++) ids.push(uuidjs.create(1).toString());
compare(ids);
console.log('');
console.log('libuuid:');
ids = [];
var count = 0;
var last = function() {
compare(ids);
}
var cb = function(err, stdout, stderr) {
ids.push(stdout.substring(0, stdout.length-1));
count++;
if (count < max) {
return next();
}
last();
};
var next = function() {
exec(uuidCmd, cb);
};
next();
>>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
|
const rp = require('request-promise');
/**
* Class representing a Find API
*/
class FindAPI {
/**
* Create a new Find API
* @param {AuthAPI} Auth - Authorization to the API
*/
constructor(Auth) {
this.Auth = Auth;
this.url = `${this.Auth.getHost()}/fmi/data/v1/databases/${this.Auth.getDatabase()}/layouts/${this.Auth.getLayout()}/_find`;
}
/**
* Execute the find
* @param {Object} obj - An object
* @param {Array} obj.requests - An array of {@link Request} Objects
* @param {Array} obj.sorts - An array of {@link Sort} Objects
* @param {number} obj.offset - starting point of records to return
* @param {number} obj.limit - how many records should be returned
* @param {Array} obj.portals - An array of {@link Portal} Objects
* @return {Promise} - A promise that resolves with multiple records
*
*/
exec({ requests, sorts, offset, limit, portals } = {}) {
let body = {};
if(Array.isArray(requests)) {
let r = requests.map(el => el.toObj());
body.query = [...r];
}
if(Array.isArray(sorts)) {
let s = sorts.map(el => el.toObj());
body.sort = [...s];
}
if(offset !== undefined)
body.offset = offset.toString();
if(limit !== undefined)
body.limit = limit.toString();
if(Array.isArray(portals)) {
let portalNames = [];
portals.forEach(el => {
let obj = el.toObj();
if(obj.offset !== null) {
let key = `offset.${obj.name}`;
body[key] = obj.offset.toString();
}
if(obj.limit !== null) {
let key = `limit.${obj.name}`;
body[key] = obj.limit.toString();
}
portalNames.push(obj.name);
});
body.portal = [...portalNames];
}
let json = body;
return rp({
uri: this.url,
method: 'POST',
headers: {
Authorization: this.Auth.tokenString,
'Content-Type': 'application/json'
},
body: json,
json: true
})
.then(body => {
return body;
})
.catch(res => {
return res.error;
});
}
}
module.exports = FindAPI; |
//
// パズル固有スクリプト部 マカロ版 makaro.js
//
(function(pidlist, classbase){
if(typeof module==='object' && module.exports){module.exports = [pidlist, classbase];}
else{ pzpr.classmgr.makeCustom(pidlist, classbase);}
}(
['makaro'], {
//---------------------------------------------------------
// マウス入力系
MouseEvent:{
inputModes : {edit:['border','arrow','number','clear'],play:['number','clear']},
mouseinput_auto : function(){
if(this.puzzle.playmode){
if(this.mousestart){ this.inputqnum();}
}
else if(this.puzzle.editmode){
if(this.mousestart || this.mousemove){
if(this.isBorderMode()){ this.inputborder();}
else { this.inputarrow_cell();}
}
else if(this.mouseend && this.notInputted()){
this.inputqnum();
}
}
},
inputarrow_cell_main : function(cell, dir){
cell.setQnum(-1);
cell.setAnum(-1);
if(cell.qdir!==dir){
cell.setQdir(dir);
cell.setQues(1);
}
else{
cell.setQdir(cell.NDIR);
cell.setQues(0);
}
},
inputqnum_main : function(cell){ // オーバーライド
if(this.puzzle.editmode && this.inputshade_preqnum(cell)){ return;}
if(cell.ques===1){ return;}
this.common.inputqnum_main.call(this,cell);
},
inputshade_preqnum : function(cell){
var val = null;
if(cell.ques===1 && cell.qdir!==cell.NDIR){
val = -3;
}
else if(cell.ques===1 && cell.qdir===cell.NDIR){
if (this.btn==='left') { val = -2;}
else if(this.btn==='right'){ val = -1;}
}
/* inputqnum_mainの空白-?マーク間に黒マスのフェーズを挿入する */
else if(cell.ques===0 && cell.qnum===-1){
if(this.btn==='left'){ val = -3;}
}
else if(cell.qnum===-2){
if(this.btn==='right'){ val = -3;}
}
if(val===-3){
cell.setQues(1);
cell.setQdir(cell.NDIR);
cell.setQnum(-1);
cell.setAnum(-1);
cell.draw();
}
else if(val===-1){
cell.setQues(0);
cell.setQdir(cell.NDIR);
cell.setQnum(-1);
cell.setAnum(-1);
cell.draw();
}
else if(val===-2){
cell.setQues(0);
cell.setQdir(cell.NDIR);
cell.setQnum(-2);
cell.setAnum(-1);
cell.draw();
}
return (val!==null);
}
},
//---------------------------------------------------------
// キーボード入力系
KeyEvent:{
enablemake : true,
enableplay : true,
moveTarget : function(ca){
if(ca.match(/shift/)){ return false;}
return this.moveTCell(ca);
},
keyinput : function(ca){
var cell = this.cursor.getc();
if(this.puzzle.editmode){
if(this.key_inputcell_makaro_edit(cell,ca)){ return;}
}
if(cell.ques!==1){
this.key_inputqnum(ca);
}
},
key_inputcell_makaro_edit : function(cell, ca){
var retval = false;
if(ca===' '){
cell.setQues(0);
cell.setQdir(cell.NDIR);
cell.setQnum(-1);
cell.setAnum(-1);
retval = true;
}
else if(ca==='BS' && cell.ques===1){
if(cell.qdir!==cell.NDIR){
cell.setQdir(cell.NDIR);
}
else{
cell.setQues(0);
cell.setQnum(-1);
cell.setAnum(-1);
}
retval = true;
}
else if(ca==='-'){
cell.setQues(cell.ques===0 ? 1 : 0);
cell.setQdir(cell.NDIR);
cell.setQnum(-1);
cell.setAnum(-1);
retval = true;
}
else if(this.key_inputarrow(ca)){
/* 数字とは排他になる */
cell.setQues(1);
cell.setQnum(-1);
cell.setAnum(-1);
retval = true;
}
if(retval){ cell.draw();}
return retval;
}
},
//---------------------------------------------------------
// 盤面管理系
Cell:{
enableSubNumberArray : true,
maxnum : function(){
return Math.min(99, this.room.clist.length);
}
},
Border:{
isBorder : function(){
return this.isnull || this.ques>0 || !!(this.sidecell[0].ques===1 || this.sidecell[1].ques===1);
}
},
Board:{
hasborder : 1
},
BoardExec:{
adjustBoardData : function(key,d){
this.adjustCellArrow(key,d);
}
},
AreaRoomGraph:{
enabled : true,
isnodevalid : function(cell){ return (cell.ques===0);}
},
//---------------------------------------------------------
// 画像表示系
Graphic:{
gridcolor_type : "LIGHT",
paint : function(){
this.drawBGCells();
this.drawTargetSubNumber();
this.drawGrid();
this.drawQuesCells();
this.drawCellArrows();
this.drawSubNumbers();
this.drawAnsNumbers();
this.drawQuesNumbers();
this.drawBorders();
this.drawChassis();
this.drawCursor();
},
getCellArrowColor : function(cell){
return (cell.qdir!==0 ? "white" : null);
}
},
//---------------------------------------------------------
// URLエンコード/デコード処理
Encode:{
decodePzpr : function(type){
this.decodeBorder();
this.decodeMakaro();
},
encodePzpr : function(type){
this.encodeBorder_makaro();
this.encodeMakaro();
},
decodeMakaro : function(){
var c=0, i=0, bstr = this.outbstr, bd = this.board;
for(i=0;i<bstr.length;i++){
var ca = bstr.charAt(i), cell=bd.cell[c];
if(this.include(ca,"0","9")){ cell.qnum = parseInt(ca,10)+1;}
else if(ca === '-') { cell.qnum = parseInt(bstr.substr(i+1,2),10)+1; i+=2;}
else if(ca>='a' && ca<='e') { cell.ques = 1; cell.qdir = parseInt(ca,36)-10;}
else if(ca>='g' && ca<='z') { c+=(parseInt(ca,36)-16);}
c++;
if(!bd.cell[c]){ break;}
}
this.outbstr = bstr.substr(i+1);
},
encodeMakaro : function(){
var cm = "", count = 0, bd = this.board;
for(var c=0;c<bd.cell.length;c++){
var pstr="", cell=bd.cell[c], qn=cell.qnum;
if (qn>= 1&&qn< 11){ pstr = (qn-1).toString(10);}
else if(qn>=11&&qn<100){ pstr = "-"+(qn-1).toString(10);}
else if(cell.ques===1) { pstr = (cell.qdir+10).toString(36);}
else{ count++;}
if (count=== 0){ cm += pstr;}
else if(pstr || count===20){ cm += ((count+15).toString(36)+pstr); count=0;}
}
if(count>0){ cm += (count+15).toString(36);}
this.outbstr += cm;
},
encodeBorder_makaro : function(){
/* 同じ見た目のパズルにおけるURLを同じにするため、 */
/* 一時的にcell.ques=1にしてURLを出力してから元に戻します */
var bd = this.board, sv_ques = [];
for(var id=0;id<bd.border.length;id++){
sv_ques[id] = bd.border[id].ques;
bd.border[id].ques = (bd.border[id].isBorder() ? 1 : 0);
}
this.encodeBorder();
for(var id=0;id<bd.border.length;id++){
bd.border[id].ques = sv_ques[id];
}
}
},
//---------------------------------------------------------
FileIO:{
decodeData : function(){
this.decodeAreaRoom();
this.decodeCellQuesData_makaro();
this.decodeCellAnumsub();
},
encodeData : function(){
this.encodeAreaRoom();
this.encodeCellQuesData_makaro();
this.encodeCellAnumsub();
},
decodeCellQuesData_makaro : function(){
this.decodeCell( function(cell,ca){
if (ca==="t"){ cell.ques = 1; cell.qdir = 1;}
else if(ca==="b"){ cell.ques = 1; cell.qdir = 2;}
else if(ca==="l"){ cell.ques = 1; cell.qdir = 3;}
else if(ca==="r"){ cell.ques = 1; cell.qdir = 4;}
else if(ca==="#"){ cell.ques = 1; cell.qdir = 0;}
else if(ca==="-"){ cell.qnum = -2;}
else if(ca!=="."){ cell.qnum = +ca;}
});
},
encodeCellQuesData_makaro : function(){
this.encodeCell( function(cell){
if(cell.ques===1){
if (cell.qdir===1){ return "t ";}
else if(cell.qdir===2){ return "b ";}
else if(cell.qdir===3){ return "l ";}
else if(cell.qdir===4){ return "r ";}
else { return "# ";}
}
else if(cell.qnum>=0) { return cell.qnum+" ";}
else if(cell.qnum===-2){ return "- ";}
else{ return ". ";}
});
}
},
//---------------------------------------------------------
// 正解判定処理実行部
AnsCheck:{
checklist : [
"checkDifferentNumberInRoom",
"checkAdjacentDiffNumber",
"checkPointAtBiggestNumber",
"checkNoNumCell+"
],
/* 矢印が盤外を向いている場合も、この関数でエラー判定します */
/* 矢印の先が空白マスである場合は判定をスルーします */
checkPointAtBiggestNumber : function(){
for(var c=0;c<this.board.cell.length;c++){
var cell = this.board.cell[c];
if(cell.ques!==1 || cell.qdir===cell.NDIR){ continue;}
var list = cell.getdir4clist(), maxnum = -1, maxdir = cell.NDIR;
var dupnum = false, isempty = false, invalidarrow = true;
for(var i=0;i<list.length;i++){
var num = list[i][0].getNum();
if(num===-1){ /* 数字が入っていない場合何もしない */ }
else if(num>maxnum){ maxnum=num; maxdir=list[i][1]; dupnum=false;}
else if(num===maxnum){ maxdir=cell.NDIR; dupnum=true;}
if(list[i][1]===cell.qdir){
if(list[i][0].ques===0){ invalidarrow = false;}
if(num===-1){ isempty = true;}
}
}
if(!invalidarrow && (isempty || (!dupnum && cell.qdir===maxdir))){ continue;}
this.failcode.add("arNotMax");
if(this.checkOnly){ break;}
cell.seterr(1);
for(var i=0;i<list.length;i++){
if(list[i][0].getNum()!==-1){ list[i][0].seterr(1);}
}
}
}
},
FailCode:{
bkDupNum : ["1つの部屋に同じ数字が複数入っています。","A room has two or more same numbers."],
arNotMax : ["矢印の先が最も大きい数字でありません。", "An arrow doesn't point out biggest number."]
}
}));
|
{
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(10, "")(2.1),
"2"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "")(2.01),
"2"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "")(2.11),
"2.1"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(10, "e")(2.1),
"2e+0"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "e")(2.01),
"2.0e+0"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "e")(2.11),
"2.1e+0"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(10, "g")(2.1),
"2"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "g")(2.01),
"2.0"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "g")(2.11),
"2.1"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(10, "r")(2.1e6),
"2000000"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "r")(2.01e6),
"2000000"
);
test.equal(
scale
.scalePow()
.domain([0, 9])
.tickFormat(100, "r")(2.11e6),
"2100000"
);
test.equal(
scale
.scalePow()
.domain([0, 0.9])
.tickFormat(10, "p")(0.21),
"20%"
);
test.equal(
scale
.scalePow()
.domain([0.19, 0.21])
.tickFormat(10, "p")(0.201),
"20.1%"
);
test.end();
}
|
"use strict";
var appRoot = process.cwd();
var assert = require('assert');
var sinon = require('sinon');
var Promise = require('bluebird');
var Journal = require(`${appRoot}/journal.js`);
module.exports = function() {
describe('error handling', function() {
it('should throw an error when given an invalid adapter', Promise.coroutine(function *() {
var journal = new Journal();
try {
yield journal.createClient('badadapter');
assert.fail('succeeded', 'failed', "connected to an invalid adapter");
}
catch(err) {
assert.ok(err instanceof TypeError, "did not throw a TypeError");
assert.ok(err.toString().indexOf('"badadapter" is an invalid adapter') !== -1);
}
}));
it('should throw an error when called multiple times', Promise.coroutine(function *() {
var journal = new Journal();
try {
yield journal.createClient('memory');
yield journal.createClient('memory');
}
catch(err) {
assert.ok(err instanceof TypeError, "did not throw a TypeError");
assert.ok(err.toString().indexOf('has already been initialized') !== -1);
}
}));
});
describe('successful operations', Promise.coroutine(function *() {
it('should successfully load the adapter when passed into the constructor', Promise.coroutine(function *() {
var journal = new Journal({adapter: 'memory'});
try {
yield journal.createClient();
assert.equal(journal.adapter.name, 'memory');
}
catch(err) {
console.log(err)
assert.fail(err, undefined, "should not have thrown an error");
}
}));
it('should successfully load the adapter when passed into createClient', Promise.coroutine(function *() {
var journal = new Journal({adapter: 'mongodb'});
try {
yield journal.createClient();
assert.equal(journal.adapter.name, 'memory');
}
catch(err) {
console.log(err)
assert.fail(err, undefined, "should not have thrown an error");
}
}));
}));
}
|
import MatchDialog from './src/MatchDialog'
/* istanbul ignore next */
MatchDialog.install = function(Vue) {
Vue.component(MatchDialog.name, MatchDialog);
};
export default MatchDialog;
|
function randomElementOf(theArray) {
return theArray[Math.floor(Math.random() * theArray.length)];
} // close function
mathematicians = [{
"name" : "Galileo",
"des": "You cannot stand devotion to archaic works that do not stand up to emprical evidence. You may go along to get along, but you'll mutter the truth under your breath.",
"image": "galileo.jpg"
},
{
"name": "Isaac Newton",
"des": "You see further by standing on the shoulders of giants.",
"image": "newton.jpg"
},
{
"name": "Hypatia",
"des": "You are a trailblazer. Literally.",
"image": "hypatia.jpg"
},
{
"name": "Ada Lovelace",
"des": "You take numbers and language and make them work for you.",
"image": "ada.jpg"
},
{
"name": "Archimedes",
"des": "If you had a big enough lever, you could move the world. Some of your best ideas come to you in the bathtub.",
"image": "arch.jpg"
},
{
"name": "Euler",
"des": "You see the beauty in complex trigonometry. Your influence will grow exponentially.",
"image": "euler.jpg"
}
];
mi = randomElementOf(mathematicians);
// Title
document.getElementById("title").innerHTML = "You are " + mi.name;
// image
document.getElementById("image").innerHTML = '<img src="images/' + mi.image + '">';
// heading
document.getElementById("youAre").innerHTML = "You are " + mi.name;
// description
document.getElementById("desc").innerHTML = mi.des;
// meta
var mea = '<meta property="og:title" content="You are ' + mi.name;
mea += '"/><meta property="og:image" content="images/' + mi.image + '" />';
document.getElementById("met").innerHTML = mea;
|
/*
* jQuery Mobile Framework : "listview" plugin
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function($, undefined) {
//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var listCountPerPage = {};
$.widget("mobile.listview", $.mobile.widget, {
options: {
theme: "c",
countTheme: "c",
headerTheme: "b",
dividerTheme: "b",
splitIcon: "arrow-r",
splitTheme: "b",
inset: false,
initSelector: ":jqmData(role='listview')"
},
_create: function() {
var t = this;
// create listview markup
t.element.addClass(function(i, orig) {
return orig + " ui-listview " + ( t.options.inset ? " ui-listview-inset ui-corner-all ui-shadow " : "" );
});
t.refresh(true);
},
_itemApply: function($list, item) {
var $countli = item.find(".ui-li-count");
if ($countli.length) {
item.addClass("ui-li-has-count");
}
$countli.addClass("ui-btn-up-" + ( $list.jqmData("counttheme") || this.options.countTheme ) + " ui-btn-corner-all");
// TODO class has to be defined in markup
item.find("h1, h2, h3, h4, h5, h6").addClass("ui-li-heading").end()
.find("p, dl").addClass("ui-li-desc").end()
.find(">img:eq(0), .ui-link-inherit>img:eq(0)").addClass("ui-li-thumb").each(
function() {
item.addClass($(this).is(".ui-li-icon") ? "ui-li-has-icon" : "ui-li-has-thumb");
}).end()
.find(".ui-li-aside").each(function() {
var $this = $(this);
$this.prependTo($this.parent()); //shift aside to front for css float
});
},
_removeCorners: function(li, which) {
var top = "ui-corner-top ui-corner-tr ui-corner-tl",
bot = "ui-corner-bottom ui-corner-br ui-corner-bl";
li = li.add(li.find(".ui-btn-inner, .ui-li-link-alt, .ui-li-thumb"));
if (which === "top") {
li.removeClass(top);
} else if (which === "bottom") {
li.removeClass(bot);
} else {
li.removeClass(top + " " + bot);
}
},
_refreshCorners: function(create) {
var $li,
$visibleli,
$topli,
$bottomli;
if (this.options.inset) {
$li = this.element.children("li");
// at create time the li are not visible yet so we need to rely on .ui-screen-hidden
$visibleli = create ? $li.not(".ui-screen-hidden") : $li.filter(":visible");
this._removeCorners($li);
// Select the first visible li element
$topli = $visibleli.first()
.addClass("ui-corner-top");
$topli.add($topli.find(".ui-btn-inner"))
.find(".ui-li-link-alt")
.addClass("ui-corner-tr")
.end()
.find(".ui-li-thumb")
.addClass("ui-corner-tl");
// Select the last visible li element
$bottomli = $visibleli.last()
.addClass("ui-corner-bottom");
$bottomli.add($bottomli.find(".ui-btn-inner"))
.find(".ui-li-link-alt")
.addClass("ui-corner-br")
.end()
.find(".ui-li-thumb")
.addClass("ui-corner-bl");
}
},
refresh: function(create) {
this.parentPage = this.element.closest(".ui-page");
this._createSubPages();
var o = this.options,
$list = this.element,
self = this,
dividertheme = $list.jqmData("dividertheme") || o.dividerTheme,
listsplittheme = $list.jqmData("splittheme"),
listspliticon = $list.jqmData("spliticon"),
li = $list.children("li"),
counter = $.support.cssPseudoElement || !$.nodeName($list[ 0 ], "ol") ? 0 : 1,
item, itemClass, itemTheme,
a, last, splittheme, countParent, icon;
if (counter) {
$list.find(".ui-li-dec").remove();
}
for (var pos = 0, numli = li.length; pos < numli; pos++) {
item = li.eq(pos);
itemClass = "ui-li";
// If we're creating the element, we update it regardless
if (create || !item.hasClass("ui-li")) {
itemTheme = item.jqmData("theme") || o.theme;
a = item.children("a");
if (a.length) {
icon = item.jqmData("icon");
item.buttonMarkup({
wrapperEls: "div",
shadow: false,
corners: false,
iconpos: "right",
icon: a.length > 1 || icon === false ? false : icon || "arrow-r",
theme: itemTheme
});
if (( icon != false ) && ( a.length == 1 )) {
item.addClass("ui-li-has-arrow");
}
a.first().addClass("ui-link-inherit");
if (a.length > 1) {
itemClass += " ui-li-has-alt";
last = a.last();
splittheme = listsplittheme || last.jqmData("theme") || o.splitTheme;
last.appendTo(item)
.attr("title", last.text())
.addClass("ui-li-link-alt")
.empty()
.buttonMarkup({
shadow: false,
corners: false,
theme: itemTheme,
icon: false,
iconpos: false
})
.find(".ui-btn-inner")
.append(
$("<span />").buttonMarkup({
shadow: true,
corners: true,
theme: splittheme,
iconpos: "notext",
icon: listspliticon || last.jqmData("icon") || o.splitIcon
})
);
}
} else if (item.jqmData("role") === "list-divider") {
itemClass += " ui-li-divider ui-btn ui-bar-" + dividertheme;
item.attr("role", "heading");
//reset counter when a divider heading is encountered
if (counter) {
counter = 1;
}
} else {
itemClass += " ui-li-static ui-body-" + itemTheme;
}
}
if (counter && itemClass.indexOf("ui-li-divider") < 0) {
countParent = item.is(".ui-li-static:first") ? item : item.find(".ui-link-inherit");
countParent.addClass("ui-li-jsnumbering")
.prepend("<span class='ui-li-dec'>" + (counter++) + ". </span>");
}
item.add(item.children(".ui-btn-inner")).addClass(itemClass);
self._itemApply($list, item);
}
this._refreshCorners(create);
},
//create a string for ID/subpage url creation
_idStringEscape: function(str) {
return str.replace(/[^a-zA-Z0-9]/g, '-');
},
_createSubPages: function() {
var parentList = this.element,
parentPage = parentList.closest(".ui-page"),
parentUrl = parentPage.jqmData("url"),
parentId = parentUrl || parentPage[ 0 ][ $.expando ],
parentListId = parentList.attr("id"),
o = this.options,
dns = "data-" + $.mobile.ns,
self = this,
persistentFooterID = parentPage.find(":jqmData(role='footer')").jqmData("id"),
hasSubPages;
if (typeof listCountPerPage[ parentId ] === "undefined") {
listCountPerPage[ parentId ] = -1;
}
parentListId = parentListId || ++listCountPerPage[ parentId ];
$(parentList.find("li>ul, li>ol").toArray().reverse()).each(
function(i) {
var self = this,
list = $(this),
listId = list.attr("id") || parentListId + "-" + i,
parent = list.parent(),
nodeEls = $(list.prevAll().toArray().reverse()),
nodeEls = nodeEls.length ? nodeEls : $("<span>" + $.trim(parent.contents()[ 0 ].nodeValue) + "</span>"),
title = nodeEls.first().text(),//url limits to first 30 chars of text
id = ( parentUrl || "" ) + "&" + $.mobile.subPageUrlKey + "=" + listId,
theme = list.jqmData("theme") || o.theme,
countTheme = list.jqmData("counttheme") || parentList.jqmData("counttheme") || o.countTheme,
newPage, anchor;
//define hasSubPages for use in later removal
hasSubPages = true;
newPage = list.detach()
.wrap("<div " + dns + "role='page' " + dns + "url='" + id + "' " + dns + "theme='" + theme + "' " + dns + "count-theme='" + countTheme + "'><div " + dns + "role='content'></div></div>")
.parent()
.before("<div " + dns + "role='header' " + dns + "theme='" + o.headerTheme + "'><div class='ui-title'>" + title + "</div></div>")
.after(persistentFooterID ? $("<div " + dns + "role='footer' " + dns + "id='" + persistentFooterID + "'>") : "")
.parent()
.appendTo($.mobile.pageContainer);
newPage.page();
anchor = parent.find('a:first');
if (!anchor.length) {
anchor = $("<a/>").html(nodeEls || title).prependTo(parent.empty());
}
anchor.attr("href", "#" + id);
}).listview();
//on pagehide, remove any nested pages along with the parent page, as long as they aren't active
if (hasSubPages && parentPage.data("page").options.domCache === false) {
var newRemove = function(e, ui) {
var nextPage = ui.nextPage, npURL;
if (ui.nextPage) {
npURL = nextPage.jqmData("url");
if (npURL.indexOf(parentUrl + "&" + $.mobile.subPageUrlKey) !== 0) {
self.childPages().remove();
parentPage.remove();
}
}
};
// unbind the original page remove and replace with our specialized version
parentPage
.unbind("pagehide.remove")
.bind("pagehide.remove", newRemove);
}
},
// TODO sort out a better way to track sub pages of the listview this is brittle
childPages: function() {
var parentUrl = this.parentPage.jqmData("url");
return $(":jqmData(url^='" + parentUrl + "&" + $.mobile.subPageUrlKey + "')");
}
});
//auto self-init widgets
$(document).bind("pagecreate create", function(e) {
$($.mobile.listview.prototype.options.initSelector, e.target).listview();
});
})(jQuery);
|
var Plotly = require('@lib/index');
var Lib = require('@src/lib');
var d3 = require('d3');
var createGraphDiv = require('../assets/create_graph_div');
var destroyGraphDiv = require('../assets/destroy_graph_div');
var failTest = require('../assets/fail_test');
var mouseEvent = require('../assets/mouse_event');
var click = require('../assets/click');
var delay = require('../assets/delay');
var customAssertions = require('../assets/custom_assertions');
var assertHoverLabelContent = customAssertions.assertHoverLabelContent;
var CALLBACK_DELAY = 500;
// Testing constants
// =================
var basicMock = Lib.extendDeep({}, require('@mocks/parcats_basic.json'));
var margin = basicMock.layout.margin;
var domain = basicMock.data[0].domain;
var categoryLabelPad = 40;
var dimWidth = 16;
var catSpacing = 8;
var dimDx = (256 - 2 * categoryLabelPad - dimWidth) / 2;
// Validation helpers
// ==================
function checkDimensionCalc(gd, dimInd, dimProps) {
/** @type {ParcatsModel} */
var calcdata = gd.calcdata[0][0];
var dimension = calcdata.dimensions[dimInd];
for(var dimProp in dimProps) {
if(dimProps.hasOwnProperty(dimProp)) {
expect(dimension[dimProp]).toEqual(dimProps[dimProp]);
}
}
}
function checkCategoryCalc(gd, dimInd, catInd, catProps) {
/** @type {ParcatsModel} */
var calcdata = gd.calcdata[0][0];
var dimension = calcdata.dimensions[dimInd];
var category = dimension.categories[catInd];
for(var catProp in catProps) {
if(catProps.hasOwnProperty(catProp)) {
expect(category[catProp]).toEqual(catProps[catProp]);
}
}
}
function checkParcatsModelView(gd) {
var fullLayout = gd._fullLayout;
var size = fullLayout._size;
// Make sure we have a 512x512 area for traces
expect(size.h).toEqual(512);
expect(size.w).toEqual(512);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
// Check location/size of this trace inside overall traces area
expect(parcatsViewModel.x).toEqual(64 + margin.r);
expect(parcatsViewModel.y).toEqual(128 + margin.t);
expect(parcatsViewModel.width).toEqual(256);
expect(parcatsViewModel.height).toEqual(256);
// Check location of dimensions
expect(parcatsViewModel.dimensions[0].x).toEqual(categoryLabelPad);
expect(parcatsViewModel.dimensions[0].y).toEqual(0);
expect(parcatsViewModel.dimensions[1].x).toEqual(categoryLabelPad + dimDx);
expect(parcatsViewModel.dimensions[1].y).toEqual(0);
expect(parcatsViewModel.dimensions[2].x).toEqual(categoryLabelPad + 2 * dimDx);
expect(parcatsViewModel.dimensions[2].y).toEqual(0);
// Check location of categories
/** @param {Array.<CategoryViewModel>} categories */
function checkCategoryPositions(categories) {
var nextY = (3 - categories.length) * catSpacing / 2;
for(var c = 0; c < categories.length; c++) {
expect(categories[c].y).toEqual(nextY);
nextY += categories[c].height + catSpacing;
}
}
checkCategoryPositions(parcatsViewModel.dimensions[0].categories);
checkCategoryPositions(parcatsViewModel.dimensions[1].categories);
checkCategoryPositions(parcatsViewModel.dimensions[2].categories);
}
function checkParcatsSvg(gd) {
var fullLayout = gd._fullLayout;
var size = fullLayout._size;
// Make sure we have a 512x512 area for traces
expect(size.h).toEqual(512);
expect(size.w).toEqual(512);
// Check trace transform
var parcatsTraceSelection = d3.select('g.trace.parcats');
expect(parcatsTraceSelection.attr('transform')).toEqual(
makeTranslate(
size.w * domain.x[0] + margin.r,
size.h * domain.y[0] + margin.t));
// Check dimension transforms
var dimensionSelection = parcatsTraceSelection
.selectAll('g.dimensions')
.selectAll('g.dimension');
dimensionSelection.each(function(dimension, dimInd) {
var expectedX = categoryLabelPad + dimInd * dimDx;
var expectedY = 0;
var expectedTransform = makeTranslate(expectedX, expectedY);
expect(d3.select(this).attr('transform')).toEqual(expectedTransform);
});
// Check category transforms
dimensionSelection.each(function(dimension, dimDisplayInd) {
var categorySelection = d3.select(this).selectAll('g.category');
var nextY = (3 - categorySelection.size()) * catSpacing / 2;
categorySelection.each(function(category) {
var catSel = d3.select(this);
var catWidth = catSel.datum().width;
var catHeight = catSel.datum().height;
var expectedTransform = 'translate(0, ' + nextY + ')';
expect(catSel.attr('transform')).toEqual(expectedTransform);
nextY += category.height + catSpacing;
// Check category label position
var isRightDim = dimDisplayInd === 2;
var catLabel = catSel.select('text.catlabel');
// Compute expected text properties based on
// whether this is the right-most dimension
var expectedTextAnchor = isRightDim ? 'start' : 'end';
var expectedX = isRightDim ? catWidth + 5 : -5;
var expectedY = catHeight / 2;
expect(catLabel.attr('text-anchor')).toEqual(expectedTextAnchor);
expect(catLabel.attr('x')).toEqual(expectedX.toString());
expect(catLabel.attr('y')).toEqual(expectedY.toString());
});
});
}
function makeTranslate(x, y) {
return 'translate(' + x + ', ' + y + ')';
}
// Test cases
// ==========
describe('Basic parcats trace', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_basic.json'));
});
afterEach(destroyGraphDiv);
// Tests
// -----
it('should create trace properly', function(done) {
Plotly.newPlot(gd, basicMock)
.then(function() {
// Check trace properties
var trace = gd.data[0];
expect(trace.type).toEqual('parcats');
expect(trace.dimensions.length).toEqual(3);
})
.catch(failTest)
.then(done);
});
it('should compute initial model properly', function(done) {
Plotly.newPlot(gd, basicMock)
.then(function() {
// Var check calc data
/** @type {ParcatsModel} */
var calcdata = gd.calcdata[0][0];
// Check cross dimension values
// ----------------------------
expect(calcdata.dimensions.length).toEqual(3);
expect(calcdata.maxCats).toEqual(3);
// Check dimension 0
// -----------------
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkCategoryCalc(gd, 0, 0, {
categoryLabel: 1,
dimensionInd: 0,
categoryInd: 0,
displayInd: 0,
count: 6,
valueInds: [0, 1, 3, 5, 6, 8]});
checkCategoryCalc(gd, 0, 1, {
categoryLabel: 2,
dimensionInd: 0,
categoryInd: 1,
displayInd: 1,
count: 3,
valueInds: [2, 4, 7]});
// Check dimension 1
// -----------------
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dragX: null, dimensionLabel: 'Two', count: 9});
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'A',
dimensionInd: 1,
categoryInd: 0,
displayInd: 0,
count: 3,
valueInds: [0, 2, 6]});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'B',
dimensionInd: 1,
categoryInd: 1,
displayInd: 1,
count: 3,
valueInds: [1, 3, 7]});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
dimensionInd: 1,
categoryInd: 2,
displayInd: 2,
count: 3,
valueInds: [4, 5, 8]});
// Check dimension 2
// -----------------
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dragX: null, dimensionLabel: 'Three', count: 9});
checkCategoryCalc(gd, 2, 0, {
categoryLabel: 11,
dimensionInd: 2,
categoryInd: 0,
displayInd: 0,
count: 9,
valueInds: [0, 1, 2, 3, 4, 5, 6, 7, 8]});
})
.catch(failTest)
.then(done);
});
it('should compute initial data properly', function(done) {
Plotly.newPlot(gd, mock)
.then(function() {
// Check that trace data matches input
expect(gd.data[0]).toEqual(mock.data[0]);
})
.catch(failTest)
.then(done);
});
it('should compute initial fullData properly', function(done) {
Plotly.newPlot(gd, basicMock)
.then(function() {
// Check that some of the defaults are computed properly
var fullTrace = gd._fullData[0];
expect(fullTrace.arrangement).toBe('perpendicular');
expect(fullTrace.bundlecolors).toBe(true);
expect(fullTrace.dimensions[1].visible).toBe(true);
})
.catch(failTest)
.then(done);
});
it('should compute initial model views properly', function(done) {
Plotly.newPlot(gd, basicMock)
.then(function() {
checkParcatsModelView(gd);
})
.catch(failTest)
.then(done);
});
it('should compute initial svg properly', function(done) {
Plotly.newPlot(gd, basicMock)
.then(function() {
checkParcatsSvg(gd);
})
.catch(failTest)
.then(done);
});
});
describe('Dimension reordered parcats trace', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_reordered.json'));
});
afterEach(destroyGraphDiv);
// Tests
// -----
it('should compute initial model properly', function(done) {
Plotly.newPlot(gd, mock)
.then(function() {
// Var check calc data
/** @type {ParcatsModel} */
var calcdata = gd.calcdata[0][0];
// Check cross dimension values
// ----------------------------
expect(calcdata.dimensions.length).toEqual(3);
expect(calcdata.maxCats).toEqual(3);
// Check dimension display order
// -----------------------------
// ### Dimension 0 ###
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dimensionLabel: 'One'});
checkCategoryCalc(gd, 0, 0, {
categoryLabel: 'One',
dimensionInd: 0,
categoryInd: 0,
displayInd: 0});
checkCategoryCalc(gd, 0, 1, {
categoryLabel: 'Two',
dimensionInd: 0,
categoryInd: 1,
displayInd: 1});
// ### Dimension 1 ###
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 2, dimensionLabel: 'Two'});
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'B',
dimensionInd: 1,
categoryInd: 0,
displayInd: 0});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'A',
dimensionInd: 1,
categoryInd: 1,
displayInd: 1});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
dimensionInd: 1,
categoryInd: 2,
displayInd: 2});
// ### Dimension 2 ###
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 1, dimensionLabel: 'Three'});
checkCategoryCalc(gd, 2, 0, {
categoryLabel: 11,
dimensionInd: 2,
categoryInd: 0,
displayInd: 0});
})
.catch(failTest)
.then(done);
});
it('should recover from bad display order specification', function(done) {
// Define bad display indexes [0, 2, 0]
mock.data[0].dimensions[2].displayindex = 0;
Plotly.newPlot(gd, mock)
.then(function() {
// Var check calc data
/** @type {ParcatsModel} */
var calcdata = gd.calcdata[0][0];
// Check cross dimension values
// ----------------------------
expect(calcdata.dimensions.length).toEqual(3);
expect(calcdata.maxCats).toEqual(3);
// Check dimension display order
// -----------------------------
// Display indexes should equal dimension indexes
// ### Dimension 0 ###
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dimensionLabel: 'One'});
checkCategoryCalc(gd, 0, 0, {
categoryLabel: 'One',
categoryInd: 0,
displayInd: 0});
checkCategoryCalc(gd, 0, 1, {
categoryLabel: 'Two',
categoryInd: 1,
displayInd: 1});
// ### Dimension 1 ###
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dimensionLabel: 'Two'});
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'B',
categoryInd: 0,
displayInd: 0});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'A',
categoryInd: 1,
displayInd: 1});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
categoryInd: 2,
displayInd: 2});
// ### Dimension 2 ###
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dimensionLabel: 'Three'});
checkCategoryCalc(gd, 2, 0, {
categoryLabel: 11,
categoryInd: 0,
displayInd: 0});
})
.catch(failTest)
.then(done);
});
it('should compute initial model views properly', function(done) {
Plotly.newPlot(gd, mock)
.then(function() {
checkParcatsModelView(gd);
})
.catch(failTest)
.then(done);
});
it('should compute initial svg properly', function(done) {
Plotly.newPlot(gd, mock)
.then(function() {
checkParcatsSvg(gd);
})
.catch(failTest)
.then(done);
});
});
describe('Drag to reordered dimensions', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var restyleCallback;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_basic_freeform.json'));
});
afterEach(destroyGraphDiv);
function getMousePositions(parcatsViewModel) {
// Compute Mouse positions
// -----------------------
// Start mouse in the middle of the dimension label on the
// second dimensions (dimension display index 1)
var dragDimStartX = parcatsViewModel.dimensions[1].x;
var mouseStartY = parcatsViewModel.y - 5;
var mouseStartX = parcatsViewModel.x + dragDimStartX + dimWidth / 2;
// Pause mouse half-way between the original location of
// the first and second dimensions. Also move mosue
// downward a bit to make sure drag 'sticks'
var mouseMidY = parcatsViewModel.y + 50;
var mouseMidX = mouseStartX + dimDx / 2;
// End mouse drag in the middle of the original
// position of the dimension label of the third dimension
// (dimension display index 2)
var mouseEndY = parcatsViewModel.y + 100;
var mouseEndX = parcatsViewModel.x + parcatsViewModel.dimensions[2].x + dimWidth / 2;
return {
mouseStartY: mouseStartY,
mouseStartX: mouseStartX,
mouseMidY: mouseMidY,
mouseMidX: mouseMidX,
mouseEndY: mouseEndY,
mouseEndX: mouseEndX
};
}
function checkInitialDimensions() {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dragX: null, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dragX: null, dimensionLabel: 'Three', count: 9});
}
function checkReorderedDimensions() {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 2, dragX: null, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 1, dragX: null, dimensionLabel: 'Three', count: 9});
}
function checkMidDragDimensions(dragDimStartX) {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dragX: dragDimStartX + dimDx / 2, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dragX: null, dimensionLabel: 'Three', count: 9});
}
it('should support dragging dimension label to reorder dimensions in freeform arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'freeform';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
var dragDimStartX = parcatsViewModel.dimensions[1].x;
var pos = getMousePositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY
// {buttons: 1} // Left click
);
// Make sure we're dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// Make sure dimensions haven't changed order yet, but that
// we do have a drag in progress on the middle dimension
checkMidDragDimensions(dragDimStartX);
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Make sure we've cleared drag dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Check final dimension order
// -----------------------------
checkReorderedDimensions();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that proper restyle event was emitted
// -------------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(1);
expect(restyleCallback).toHaveBeenCalledWith([
{
'dimensions[0].displayindex': 0,
'dimensions[1].displayindex': 2,
'dimensions[2].displayindex': 1
},
[0]]);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
it('should support dragging dimension label to reorder dimensions in perpendicular arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'perpendicular';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
var dragDimStartX = parcatsViewModel.dimensions[1].x;
var pos = getMousePositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY
// {buttons: 1} // Left click
);
// Make sure we're dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// Make sure dimensions haven't changed order yet, but that
// we do have a drag in progress on the middle dimension
checkMidDragDimensions(dragDimStartX);
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Make sure we've cleared drag dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Check final dimension order
// -----------------------------
checkReorderedDimensions();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that proper restyle event was emitted
// -------------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(1);
expect(restyleCallback).toHaveBeenCalledWith([
{
'dimensions[0].displayindex': 0,
'dimensions[1].displayindex': 2,
'dimensions[2].displayindex': 1
},
[0]]);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
it('should NOT support dragging dimension label to reorder dimensions in fixed arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'fixed';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
var pos = getMousePositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY
// {buttons: 1} // Left click
);
// Make sure we're not dragging any dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Make sure dimensions haven't changed order yet
checkInitialDimensions();
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still not dragging a dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Make sure dimensions haven't changed
// ------------------------------------
checkInitialDimensions();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that no restyle event was emitted
// ---------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(0);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
});
describe('Drag to reordered categories', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var restyleCallback;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_basic_freeform.json'));
});
afterEach(destroyGraphDiv);
function getDragPositions(parcatsViewModel) {
var dragDimStartX = parcatsViewModel.dimensions[1].x;
var mouseStartY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseStartX = parcatsViewModel.x + dragDimStartX + dimWidth / 2;
// Pause mouse half-way between the original location of
// the first and second dimensions. Also move mouse
// upward enough to swap position with middle category
var mouseMidY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[1].y;
var mouseMidX = mouseStartX + dimDx / 2;
// End mouse drag in the middle of the original
// position of the dimension label of the third dimension
// (dimension display index 2), and at the height of the original top category
var mouseEndY = parcatsViewModel.y;
var mouseEndX = parcatsViewModel.x + parcatsViewModel.dimensions[2].x + dimWidth / 2;
return {
dragDimStartX: dragDimStartX,
mouseStartY: mouseStartY,
mouseStartX: mouseStartX,
mouseMidY: mouseMidY,
mouseMidX: mouseMidX,
mouseEndY: mouseEndY,
mouseEndX: mouseEndX
};
}
function checkInitialDimensions() {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dragX: null, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dragX: null, dimensionLabel: 'Three', count: 9});
}
function checkMidDragDimensions(dragDimStartX) {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 1, dragX: dragDimStartX + dimDx / 2, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 2, dragX: null, dimensionLabel: 'Three', count: 9});
}
function checkInitialCategories() {
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'A',
categoryInd: 0,
displayInd: 0
});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'B',
categoryInd: 1,
displayInd: 1
});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
categoryInd: 2,
displayInd: 2
});
}
function checkMidDragCategories() {
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'A',
categoryInd: 0,
displayInd: 0
});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'B',
categoryInd: 1,
displayInd: 2
});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
categoryInd: 2,
displayInd: 1
});
}
function checkFinalDimensions() {
checkDimensionCalc(gd, 0,
{dimensionInd: 0, displayInd: 0, dragX: null, dimensionLabel: 'One', count: 9});
checkDimensionCalc(gd, 1,
{dimensionInd: 1, displayInd: 2, dragX: null, dimensionLabel: 'Two', count: 9});
checkDimensionCalc(gd, 2,
{dimensionInd: 2, displayInd: 1, dragX: null, dimensionLabel: 'Three', count: 9});
}
function checkFinalCategories() {
checkCategoryCalc(gd, 1, 0, {
categoryLabel: 'A',
categoryInd: 0,
displayInd: 1
});
checkCategoryCalc(gd, 1, 1, {
categoryLabel: 'B',
categoryInd: 1,
displayInd: 2
});
checkCategoryCalc(gd, 1, 2, {
categoryLabel: 'C',
categoryInd: 2,
displayInd: 0
});
}
it('should support dragging category to reorder categories and dimensions in freeform arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'freeform';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
// Compute Mouse positions
// -----------------------
// Start mouse in the middle of the lowest category
// second dimensions (dimension display index 1)
var pos = getDragPositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Check initial categories
// ------------------------
checkInitialCategories();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY);
// Make sure we're dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// Make sure dimensions haven't changed order yet, but that
// we do have a drag in progress on the middle dimension
checkMidDragDimensions(pos.dragDimStartX);
// Make sure categories in dimension 1 have changed already
checkMidDragCategories();
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Make sure we've cleared drag dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Check final dimension order
// -----------------------------
checkFinalDimensions();
// Make sure categories in dimension 1 have changed already
checkFinalCategories();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that proper restyle event was emitted
// -------------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(1);
expect(restyleCallback).toHaveBeenCalledWith([
{'dimensions[0].displayindex': 0,
'dimensions[1].displayindex': 2,
'dimensions[2].displayindex': 1,
'dimensions[1].categoryorder': 'array',
'dimensions[1].categoryarray': [['C', 'A', 'B' ]],
'dimensions[1].ticktext': [['C', 'A', 'B' ]]},
[0]]);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
it('should support dragging category to reorder categories only in perpendicular arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'perpendicular';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
// Compute Mouse positions
// -----------------------
var pos = getDragPositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Check initial categories
// ------------------------
checkInitialCategories();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY);
// Make sure we're dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// Make sure dimensions haven't changed order or position
checkInitialDimensions();
// Make sure categories in dimension 1 have changed already
checkMidDragCategories();
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still dragging the middle dimension
expect(parcatsViewModel.dragDimension.model.dimensionLabel).toEqual('Two');
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Make sure we've cleared drag dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Check final dimension order
// ---------------------------
// Dimension order should not have changed
checkInitialDimensions();
// Make sure categories in dimension 1 have changed already
checkFinalCategories();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that proper restyle event was emitted
// -------------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(1);
expect(restyleCallback).toHaveBeenCalledWith([
{
'dimensions[1].categoryorder': 'array',
'dimensions[1].categoryarray': [['C', 'A', 'B' ]],
'dimensions[1].ticktext': [['C', 'A', 'B' ]]},
[0]]);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
it('should NOT support dragging category to reorder categories or dimensions in fixed arrangement', function(done) {
// Set arrangement
mock.data[0].arrangement = 'fixed';
Plotly.newPlot(gd, mock)
.then(function() {
restyleCallback = jasmine.createSpy('restyleCallback');
gd.on('plotly_restyle', restyleCallback);
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
// Compute Mouse positions
// -----------------------
var pos = getDragPositions(parcatsViewModel);
// Check initial dimension order
// -----------------------------
checkInitialDimensions();
// Check initial categories
// ------------------------
checkInitialCategories();
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', pos.mouseStartX, pos.mouseStartY);
// Perform drag
// ------------
mouseEvent('mousedown', pos.mouseStartX, pos.mouseStartY);
// ### Pause at drag mid-point
mouseEvent('mousemove', pos.mouseMidX, pos.mouseMidY);
// Make sure we're not dragging a dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// Make sure dimensions and categories haven't changed order
checkInitialDimensions();
checkInitialCategories();
// ### Move to drag end-point
mouseEvent('mousemove', pos.mouseEndX, pos.mouseEndY);
// Make sure we're still not dragging a dimension
expect(parcatsViewModel.dragDimension).toEqual(null);
// End drag
// --------
mouseEvent('mouseup', pos.mouseEndX, pos.mouseEndY);
// Check final dimension order
// ---------------------------
// Dimension and category order should not have changed
checkInitialDimensions();
checkInitialCategories();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that no restyle event was emitted
// ---------------------------------------
expect(restyleCallback).toHaveBeenCalledTimes(0);
restyleCallback.calls.reset();
})
.catch(failTest)
.then(done);
});
});
describe('Click events', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_basic_freeform.json'));
});
afterEach(destroyGraphDiv);
it('should fire on category click', function(done) {
var clickData;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth / 2;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeDefined();
// Check that the right points were reported
var pts = clickData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
// Check points
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 4},
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
// Check constraints
var constraints = clickData.constraints;
expect(constraints).toEqual({1: 'C'});
})
.catch(failTest)
.then(done);
});
it('should NOT fire on category click if hoverinfo is skip', function(done) {
var clickData;
mock.data[0].hoverinfo = 'skip';
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth / 2;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeUndefined();
})
.catch(failTest)
.then(done);
});
it('should fire on path click', function(done) {
var clickData;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the top path to the right of the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth + 10;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeDefined();
// Check that the right points were reported
var pts = clickData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
// Check points
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
// Check constraints
var constraints = clickData.constraints;
expect(constraints).toEqual({0: 1, 1: 'C', 2: 11});
})
.catch(failTest)
.then(done);
});
it('should NOT fire on path click if hoverinfo is skip', function(done) {
var clickData;
mock.data[0].hoverinfo = 'skip';
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the top path to the right of the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth + 10;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeUndefined();
})
.catch(failTest)
.then(done);
});
});
describe('Click events with hoveron color', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_hoveron_color.json'));
});
afterEach(destroyGraphDiv);
it('should fire on category click', function(done) {
var clickData;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the top of the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth / 2;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeDefined();
// Check that the right points were reported
var pts = clickData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
// Check points
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
// Check constraints
var constraints = clickData.constraints;
expect(constraints).toEqual({1: 'C', color: 1});
})
.catch(failTest)
.then(done);
});
it('should fire on path click', function(done) {
var clickData;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_click', function(data) {
clickData = data;
});
// Click on the top path to the right of the lowest category in the middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
var mouseY = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
var mouseX = parcatsViewModel.x + dimStartX + dimWidth + 10;
// Position mouse for start of drag
// --------------------------------
click(mouseX, mouseY);
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that click callback was called
expect(clickData).toBeDefined();
// Check that the right points were reported
var pts = clickData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
// Check points
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
// Check constraints
var constraints = clickData.constraints;
expect(constraints).toEqual({0: 1, 1: 'C', 2: 11, color: 1});
})
.catch(failTest)
.then(done);
});
});
describe('Hover events', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_basic_freeform.json'));
});
afterEach(destroyGraphDiv);
it('hover and unhover should fire on category', function(done) {
var hoverData;
var unhoverData;
var mouseY0;
var mouseX0;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_hover', function(data) {
hoverData = data;
});
gd.on('plotly_unhover', function(data) {
unhoverData = data;
});
// Hover over top of bottom category of middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
mouseY0 = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
mouseX0 = parcatsViewModel.x + dimStartX + dimWidth / 2;
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', mouseX0, mouseY0);
mouseEvent('mouseover', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that hover callback was called
expect(hoverData).toBeDefined();
// Check that the right points were reported
var pts = hoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 4},
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
// Check that unhover is still undefined
expect(unhoverData).toBeUndefined();
})
.then(function() {
// Unhover
mouseEvent('mouseout', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(function() {
// Check that unhover callback was called
expect(unhoverData).toBeDefined();
// Check that the right points were reported
var pts = unhoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 4},
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
})
.catch(failTest)
.then(done);
});
it('hover and unhover should fire on path', function(done) {
var hoverData;
var unhoverData;
var mouseY0;
var mouseX0;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_hover', function(data) {
hoverData = data;
});
gd.on('plotly_unhover', function(data) {
unhoverData = data;
});
var dimStartX = parcatsViewModel.dimensions[1].x;
mouseY0 = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
mouseX0 = parcatsViewModel.x + dimStartX + dimWidth + 10;
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', mouseX0, mouseY0);
mouseEvent('mouseover', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that hover callback was called
expect(hoverData).toBeDefined();
// Check that the right points were reported
var pts = hoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
// Check that unhover is still undefined
expect(unhoverData).toBeUndefined();
})
.then(function() {
// Unhover
mouseEvent('mouseout', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(function() {
// Check that unhover callback was called
expect(unhoverData).toBeDefined();
// Check that the right points were reported
var pts = unhoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5},
{curveNumber: 0, pointNumber: 8}]);
})
.catch(failTest)
.then(done);
});
});
describe('Hover events with hoveron color', function() {
// Variable declarations
// ---------------------
// ### Trace level ###
var gd;
var mock;
// Fixtures
// --------
beforeEach(function() {
gd = createGraphDiv();
mock = Lib.extendDeep({}, require('@mocks/parcats_hoveron_color.json'));
});
afterEach(destroyGraphDiv);
it('hover and unhover should fire on category hoveron color', function(done) {
var hoverData;
var unhoverData;
var mouseY0;
var mouseX0;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_hover', function(data) {
hoverData = data;
});
gd.on('plotly_unhover', function(data) {
unhoverData = data;
});
// Hover over top of bottom category of middle dimension (category "C")
var dimStartX = parcatsViewModel.dimensions[1].x;
mouseY0 = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
mouseX0 = parcatsViewModel.x + dimStartX + dimWidth / 2;
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', mouseX0, mouseY0);
mouseEvent('mouseover', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that hover callback was called
expect(hoverData).toBeDefined();
// Check that the right points were reported
var pts = hoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
// Check that unhover is still undefined
expect(unhoverData).toBeUndefined();
})
.then(function() {
// Unhover
mouseEvent('mouseout', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(function() {
// Check that unhover callback was called
expect(unhoverData).toBeDefined();
// Check that the right points were reported
var pts = unhoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
})
.catch(failTest)
.then(done);
});
it('hover and unhover should fire on path hoveron color', function(done) {
var hoverData;
var unhoverData;
var mouseY0;
var mouseX0;
Plotly.newPlot(gd, mock)
.then(function() {
/** @type {ParcatsViewModel} */
var parcatsViewModel = d3.select('g.trace.parcats').datum();
gd.on('plotly_hover', function(data) {
hoverData = data;
});
gd.on('plotly_unhover', function(data) {
unhoverData = data;
});
var dimStartX = parcatsViewModel.dimensions[1].x;
mouseY0 = parcatsViewModel.y + parcatsViewModel.dimensions[1].categories[2].y + 10;
mouseX0 = parcatsViewModel.x + dimStartX + dimWidth + 10;
// Position mouse for start of drag
// --------------------------------
mouseEvent('mousemove', mouseX0, mouseY0);
mouseEvent('mouseover', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(delay(CALLBACK_DELAY))
.then(function() {
// Check that hover callback was called
expect(hoverData).toBeDefined();
// Check that the right points were reported
var pts = hoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
// Check that unhover is still undefined
expect(unhoverData).toBeUndefined();
})
.then(function() {
// Unhover
mouseEvent('mouseout', mouseX0, mouseY0);
Lib.clearThrottle();
})
.then(function() {
// Check that unhover callback was called
expect(unhoverData).toBeDefined();
// Check that the right points were reported
var pts = unhoverData.points.sort(function(a, b) {
return a.pointNumber - b.pointNumber;
});
expect(pts).toEqual([
{curveNumber: 0, pointNumber: 5}]);
})
.catch(failTest)
.then(done);
});
});
describe('Parcats hover:', function() {
var gd;
afterEach(destroyGraphDiv);
function run(s, done) {
gd = createGraphDiv();
var fig = Lib.extendDeep({},
s.mock || require('@mocks/parcats_basic.json')
);
if(s.patch) fig = s.patch(fig);
return Plotly.plot(gd, fig).then(function() {
mouseEvent('mousemove', s.pos[0], s.pos[1]);
mouseEvent('mouseover', s.pos[0], s.pos[1]);
setTimeout(function() {
assertHoverLabelContent(s);
done();
}, CALLBACK_DELAY);
})
.catch(failTest);
}
var dimPos = [320, 310];
var linePos = [272, 415];
var specs = [{
desc: 'basic - on dimension',
pos: dimPos,
nums: 'Count: 9',
name: ''
}, {
desc: 'basic - on line',
pos: linePos,
nums: 'Count: 1',
name: ''
}, {
desc: 'with hovetemplate - on dimension',
pos: dimPos,
patch: function(fig) {
fig.data[0].hovertemplate = 'probz=%{probability:.1f}<extra>LOOK</extra>';
return fig;
},
nums: 'probz=1.0',
name: 'LOOK'
}, {
desc: 'with hovertemplate - on line',
pos: linePos,
patch: function(fig) {
fig.data[0].line = {
hovertemplate: 'P=%{probability}<extra>with count=%{count}</extra>'
};
return fig;
},
nums: 'P=0.111',
name: 'with count=1'
}];
specs.forEach(function(s) {
it('should generate correct hover labels ' + s.desc, function(done) {
run(s, done);
});
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:e847cb39793f726908e51e499c618101a112c1fc489793b0b330c49fba2928c8
size 48203
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n)), v = n.toString().replace(/^[^.]*\.?/, '').length;
if (i === 1 && v === 0) return 1;
return 5;
}
root.ng.common.locales['en-na'] = [
'en-NA',
[['a', 'p'], ['am', 'pm'], u],
[['am', 'pm'], u, u],
[
['S', 'M', 'T', 'W', 'T', 'F', 'S'], ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
[
'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'
]
],
u,
[['B', 'A'], ['BC', 'AD'], ['Before Christ', 'Anno Domini']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE, d MMMM y'],
['h:mm a', 'h:mm:ss a', 'h:mm:ss a z', 'h:mm:ss a zzzz'],
['{1}, {0}', u, '{1} \'at\' {0}', u],
['.', ',', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0%', '¤#,##0.00', '#E0'],
'ZAR',
'South African Rand',
{'JPY': ['JP¥', '¥'], 'NAD': ['$'], 'USD': ['US$', '$']},
plural,
[
[
['mi', 'n', 'in the morning', 'in the afternoon', 'in the evening', 'at night'],
['midnight', 'noon', 'in the morning', 'in the afternoon', 'in the evening', 'at night'], u
],
[['midnight', 'noon', 'morning', 'afternoon', 'evening', 'night'], u, u],
[
'00:00', '12:00', ['06:00', '12:00'], ['12:00', '18:00'], ['18:00', '21:00'],
['21:00', '06:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
/*
* @Author: Picker
* @Date: 2017-05-27 11:04:54
* @Last Modified by: Picker
* @Last Modified time: 2017-05-27 15:27:33
*/
import { v4 } from 'uuid';
/**
* 基础组件模型
* 其他组件模型均需要继承自该模型
*/
export default class BaseComponent {
constructor(options) {
this.cid = v4();
this.attrs = {
'@click.native.stop': `__onFocus('${this.cid}')`
};
// this.component=options.component;
// this.attrs= options.attrs;
// this.children=options.children;
// 将配置注册到 CNode 实例中
Object.assign(this, options);
}
// 根据当前节点的信息,输出最终配置结构
transformToData() {
throw new Error('Function [ transformToData ] should be overwrited!');
}
}
|
Template.server_info.events({
'click button.stripe-button': function(e, t){
// e = event, t = template
e.preventDefault();
var params = this;
var rate = this.rate;
var serverName = this.serverName;
var serverOwner = this.serverOwner;
console.log('Client rate ' + rate);
var checkout = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://i.imgur.com/ErLyYDo.jpg',
token: function(token){
Meteor.call('stripeCheckout', token, params, function(e, r){
if(e){
console.log('client ' + e);
};
});
}
});
checkout.open({
name: 'Plex Server Portal',
description: 'Access to ' + serverName + ' owned by ' + serverOwner,
amount: rate
});
}
}); |
// import Gallery from '../index';
import expect from 'expect';
// import { shallow } from 'enzyme';
// import React from 'react';
describe('<Gallery />', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
|
const ngdocPackage = require('./');
const Dgeni = require('dgeni');
const mockLog = require('dgeni/lib/mocks/log');
describe('ngdoc package', () => {
it("should be instance of Package", () => {
expect(ngdocPackage instanceof Dgeni.Package).toBeTruthy();
});
function runDgeni(docs) {
const testPackage = new Dgeni.Package('testPackage', [ngdocPackage])
.factory('log', function log() { return mockLog(false); })
.processor('provideTestDocs', function provideTestDocs() {
return {
$runBefore: ['computePathsProcessor'],
$process() {
return docs;
}
};
})
.config(function(readFilesProcessor, writeFilesProcessor, renderDocsProcessor, unescapeCommentsProcessor) {
readFilesProcessor.$enabled = false;
writeFilesProcessor.$enabled = false;
renderDocsProcessor.$enabled = false;
unescapeCommentsProcessor.$enabled = false;
});
return new Dgeni([testPackage]).generate();
}
it("should compute the path of components from their attributes", done => {
const docTypes = ['service', 'provider', 'directive', 'input', 'function', 'filter', 'type'];
const docs = docTypes.map(docType => ({ docType: docType, area: 'AREA', module: 'MODULE', name: 'NAME' }));
runDgeni(docs).then(
docs => {
for(var i=0; i<docs.length; i++) {
expect(docs[i].path).toEqual('AREA/MODULE/' + docs[i].docType + '/NAME');
expect(docs[i].outputPath).toEqual('partials/AREA/MODULE/' + docs[i].docType + '/NAME.html');
}
done();
},
err => {
console.log(err);
throw err;
});
});
it("should compute the path of modules from their attributes", done => {
const doc = { docType: 'module', area: 'AREA', name: 'MODULE' };
runDgeni([doc]).then(
docs => {
expect(docs[0].path).toEqual('AREA/MODULE');
expect(docs[0].outputPath).toEqual('partials/AREA/MODULE/index.html');
done();
},
err => {
console.log(err);
throw err;
});
});
it("should compute the path of component groups from their attributes", done => {
const groupTypes = ['service', 'provider', 'directive', 'input', 'function', 'filter', 'type'];
const docs = groupTypes.map(groupType =>
({ docType: 'componentGroup', area: 'AREA', groupType: groupType, moduleName: 'MODULE' }));
runDgeni(docs).then(
docs => {
for(var i=0; i<docs.length; i++) {
expect(docs[i].path).toEqual('AREA/MODULE/' + docs[i].groupType);
expect(docs[i].outputPath).toEqual('partials/AREA/MODULE/' + docs[i].groupType + '/index.html');
}
done();
},
err => {
console.log(err);
throw err;
});
});
});
|
var React = require('react');
var UI = require('UI');
var View = UI.View;
var Content = UI.Content;
var List = UI.List;
var Grid = UI.Grid;
var Card = UI.Card;
var Icon = UI.Icon.Icon;
var Badge = UI.Badge.Badge;
var Button = UI.Button.Button;
var SHOW_NONE_BUTTON = 0;
var SHOW_CALLIN_BUTTON = 1;
var SHOW_CALLOUT_BUTTON = 2;
module.exports = React.createClass({
componentWillMount: function() {
var param = this.props.data.param;
this.userid = param.userid;
this.localLarge = true;
var callid = param.callid;
if (callid != null) {
this.answer = true;
this.callid = callid;
this.state.showButton = SHOW_CALLIN_BUTTON;
} else {
this.answer = false;
this.state.showButton = SHOW_CALLOUT_BUTTON;
}
},
componentDidMount: function() {
var mgr = app.callMgr;
var self = this;
this.smallView = this.refs.smallView.getDOMNode();
this.largeView = this.refs.largeView.getDOMNode();
mgr.addCallChangeListener(this._onChange);
this.updateVideoView();
if (!this.answer) {
this.callid = mgr.callOut(this.userid, mgr.VIDEO_TYPE);
}
mgr.updateTime(function(time, status) {
self.setState({time:time, status:status});
});
},
componentWillUnmount: function() {
this.hangupVideoCall();
app.callMgr.removeCallChangeListener(this._onChange);
},
_onChange: function(obj) {
var type = obj.type;
switch(type) {
case "ON_SESSION_ANSWER":
this.onSessionAnswer(obj.userid, obj.callid);
break;
case "ON_CALLOUT_ERROR":
this.onCallOutError(obj.callid);
break;
case "ON_CALLOUT_ANSWERED":
this.onCallOutAnswered(obj.callid);
break;
case "ON_CALLOUT_REFUSED":
this.onCallOutRefused(obj.callid);
break;
case "ON_PRE_CALL_HANGUP_NOTIFY":
this.onPreCallHangupNotify(obj.callid);
break;
case "ON_CALL_HANGUP_NOTIFY":
this.onCallHangupNotify(obj.callid);
break;
default:;
}
},
getInitialState: function() {
return {
status: '',
time: '',
showButton:SHOW_NONE_BUTTON
}
},
toggleVideoView: function() {
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
console.log("==================toggleVideoView");
this.localLarge = !this.localLarge;
this.updateVideoView();
},
updateVideoView: function() {
var local = this.localLarge;
navigator.phonertc.setVideoView({
localView: local?this.largeView:this.smallView,
remoteView: !local?this.largeView:this.smallView
});
},
onSessionAnswer: function(userid, callid) {
console.log('onSessionAnswer', userid, callid);
this.toggleVideoView();
},
onCallOutError: function(callid) {
console.log('onCallOutError', callid, this.callid);
if (this.callid != null) {
this.callid = null;
navigator.phonertc.removeLocalVideoView();
app.goBack();
}
},
answerVideoCall: function() {
var mgr = app.callMgr;
console.log('answerVideoCall', this.callid);
mgr.answerCallIn(this.userid, mgr.VIDEO_TYPE, this.callid);
this.setState({showButton: SHOW_CALLOUT_BUTTON});
},
onCallOutAnswered: function(callid) {
console.log('onCallOutAnswered', callid, this.callid);
},
refuseVideoCall: function() {
if (this.callid != null) {
navigator.phonertc.removeLocalVideoView();
console.log('refuseVideoCall', this.callid);
var mgr = app.callMgr;
mgr.refuseCallIn(this.userid, mgr.VIDEO_TYPE, this.callid);
this.callid = null;
app.goBack();
}
},
onCallOutRefused: function(callid) {
if (this.callid != null) {
navigator.phonertc.removeLocalVideoView();
console.log('onCallOutRefused', callid, this.callid);
this.callid = null;
app.goBack();
}
},
hangupVideoCall: function() {
if (this.callid != null) {
navigator.phonertc.removeLocalVideoView();
console.log('hangupVideoCall', this.callid);
var mgr = app.callMgr;
mgr.callHangup(this.userid, mgr.VIDEO_TYPE, this.callid);
this.callid = null;
app.goBack();
}
},
onPreCallHangupNotify: function(callid) {
this.setState({showButton: SHOW_CALLOUT_BUTTON});
},
onCallHangupNotify: function(callid) {
if (this.callid != null) {
navigator.phonertc.removeLocalVideoView();
console.log('onCallHangupNotify', callid, this.callid);
this.callid = null;
app.goBack();
}
},
render: function() {
var userid = this.userid;
var user = app.userMgr.users[userid];
var username = user.username;
return (
<View.Page title="Video Call">
<View.PageContent>
<div className="video_call_status_container">
<div className={"chat_head video_call_head default_head user_head_"+userid}></div>
<div className="video_call_status">
<div>fang</div>
<div className="call_state" style={{color:"red"}}>{this.state.status}</div>
<div className="call_time">{this.state.time}</div>
</div>
</div>
<div className="video_small_screen" ref="smallView" onclick={this.toggleVideoView}></div>
<div className="video_large_screen" ref="largeView" onclick={this.toggleVideoView}></div>
<div className="vidc_panel">
{this.state.showButton===SHOW_CALLOUT_BUTTON&&<Content.ContentBlock>
<Grid.Row>
<Grid.Col><Button big fill color="red" onTap={this.hangupVideoCall}>挂断</Button></Grid.Col>
</Grid.Row>
</Content.ContentBlock>}
{this.state.showButton===SHOW_CALLIN_BUTTON&&<Content.ContentBlock>
<Grid.Row>
<Grid.Col per={50}><Button big fill color="green" onTap={this.answerVideoCall}>接听</Button></Grid.Col>
<Grid.Col per={50}><Button big fill color="red" onTap={this.refuseVideoCall}>挂断</Button></Grid.Col>
</Grid.Row>
</Content.ContentBlock>}
</div>
</View.PageContent>
</View.Page>
);
}
});
|
$(document).ready(function () {
var enviroment = 'production';
if (enviroment == 'local') {
url = 'http://localhost/guestRegistration/settings.php';
urlajax = 'http://localhost/guestRegistration/settings/core/ajax.php';
// urlajaxlive = 'http://localhost/onaf3/settings/core/live_report.php';
// urlajaxnotification = 'http://localhost/onaf3/settings/core/notify.php';
// urlsettings = 'http://localhost/onaf3/settings.php';
} else if (enviroment == 'testing') {
// url = 'https://customers.pmilimited.com/ONAF3/index.php';
// urlajax = 'https://customers.pmilimited.com/ONAF3/settings/core/ajax.php';
// urlajaxlive = 'https://customers.pmilimited.com/ONAF3/settings/core/live_report.php';
// urlajaxnotification = 'https://customers.pmilimited.com/ONAF3/settings/core/notify.php';
// urlsettings = 'https://customers.pmilimited.com/ONAF3/settings.php';
} else if (enviroment == 'production') {
url = 'https://bohemiarealtygroup.com/guestRegistration/settings.php';
urlajax = 'https://bohemiarealtygroup.com/guestRegistration/settings/core/ajax.php';
// url = 'https://onaf.pmi.ky/index.php';
// urlajax = 'https://onaf.pmi.ky/settings/core/ajax.php';
// urlajaxlive = 'https://onaf.pmi.ky/settings/core/live_report.php';
// urlajaxnotification = 'https://onaf.pmi.ky/settings/core/notify.php';
// urlsettings = 'https://onaf.pmi.ky/settings.php';
}
});
|
import Ember from "ember";
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('file-menu', 'Integration | Component | file menu', {
integration: true,
beforeEach() {
this.addFileCalled = false;
this.renameFileCalled = false;
this.removeFileCalled = false;
this.saveGistCalled = false;
this.forkCalled = false;
this.copyCalled = false;
this.deleteGistCalled = false;
this.signInViaGithubCalled = false;
this.downloadProjectCalled = false;
this.fileType = null;
this.renamedFile = null;
this.removedFile = null;
this.gistToSave = null;
this.gistToFork = null;
this.gistToDelete = null;
this.file = Ember.Object.create({
filePath: "some.path.js"
});
this.gist = Ember.Object.create({
id: '74bae9a34142370ff5a3',
files: [this.file],
history: [],
ownerLogin: 'Gaurav0',
isNew: false
});
// Set any properties with this.set('myProperty', 'value');
this.set('model', this.gist);
this.set('session', Ember.Object.create({
isAuthenticated: true,
currentUser: {
login: 'octocat'
}
}));
this.set('activeEditorCol', 1);
this.set('activeFile', this.file);
// Handle any actions with this.on('myAction', function(val) { ... });
this.on('addFile', (type) => { this.addFileCalled = true; this.fileType = type; });
this.on('renameFile', (file) => { this.renameFileCalled = true; this.renamedFile = file; });
this.on('removeFile', (file) => { this.removeFileCalled = true; this.removedFile = file; });
this.on('saveGist', (gist) => { this.saveGistCalled = true; this.gistToSave = gist; });
this.on('fork', (gist) => { this.forkCalled = true; this.gistToFork = gist; });
this.on('copy', () => { this.copyCalled = true; });
this.on('deleteGist', (gist) => { this.deleteGistCalled = true; this.gistToDelete = gist; });
this.on('signInViaGithub', () => { this.signInViaGithubCalled = true; });
this.on('downloadProject', () => { this.downloadProjectCalled = true; });
this.render(hbs`{{file-menu model=model
session=session
activeEditorCol=activeEditorCol
activeFile=activeFile
addFile=(action "addFile")
renameFile=(action "renameFile")
removeFile=(action "removeFile")
saveGist=(action "saveGist")
fork=(action "fork")
copy=(action "copy")
deleteGist=(action "deleteGist")
signInViaGithub=(action "signInViaGithub")
downloadProject=(action "downloadProject")}}`);
}
});
test('it calls addFile on clicking an add file menu item', function(assert) {
assert.expect(2);
this.$('.test-template-action').click();
assert.ok(this.addFileCalled, 'addFile was called');
assert.equal(this.fileType, 'template', 'addFile was called with type parameter');
});
test("it calls renameFile on clicking 'Rename'", function(assert) {
assert.expect(2);
this.$('.test-rename-action').click();
assert.ok(this.renameFileCalled, 'renameFile was called');
assert.equal(this.renamedFile, this.file, 'renameFile was called with file to rename');
});
test("it calls renameFile on clicking 'Move'", function(assert) {
assert.expect(2);
this.$('.test-move-action').click();
assert.ok(this.renameFileCalled, 'renameFile was called');
assert.equal(this.renamedFile, this.file, 'renameFile was called with file to rename');
});
test("it calls removeFile on clicking 'Remove'", function(assert) {
assert.expect(2);
this.$('.test-remove-action').click();
assert.ok(this.removeFileCalled, 'removeFile was called');
assert.equal(this.removedFile, this.file, 'removeFile was called with file to remove');
});
test("it calls saveGist on clicking 'Save to Github'", function(assert) {
assert.expect(2);
this.$('.test-save-action').click();
assert.ok(this.saveGistCalled, 'saveGist was called');
assert.equal(this.gistToSave, this.gist, 'saveGist was called with gist to save');
});
test("it calls fork on clicking 'Fork Twiddle'", function(assert) {
assert.expect(2);
this.$('.test-fork-action').click();
assert.ok(this.forkCalled, 'fork was called');
assert.equal(this.gistToFork, this.gist, 'fork was called with gist to fork');
});
test("it calls copy on clicking 'Copy Twiddle'", function(assert) {
assert.expect(1);
// logged in user is the same as the owner of the gist
this.set('session.currentUser.login', 'Gaurav0');
this.$('.test-copy-action').click();
assert.ok(this.copyCalled, 'copy was called');
});
test("it calls deleteGist on clicking 'Delete Twiddle'", function(assert) {
assert.expect(2);
this.$('.test-delete-action').click();
assert.ok(this.deleteGistCalled, 'deleteGist was called');
assert.equal(this.gistToDelete, this.gist, 'deleteGist was called with gist to delete');
});
test("it calls signInViaGithub when clicking on 'Sign In To Github To Save'", function(assert) {
assert.expect(1);
this.set('session.isAuthenticated', false);
this.$('.test-sign-in-action').click();
assert.ok(this.signInViaGithubCalled, 'signInViaGithub was called');
});
test("it calls downloadProject when clicking on 'Download Project'", function(assert) {
assert.expect(1);
this.$('.test-download-project-action').click();
assert.ok(this.downloadProjectCalled, 'downloadProject was called');
});
test("it only renders 'New Twiddle' menu item, when no model is specified", function(assert) {
this.render(hbs`{{file-menu}}`);
assert.equal(this.$('.dropdown-menu li').length, 1, "only one menu item is rendered");
assert.equal(this.$('.dropdown-menu li').text().trim(), "New Twiddle");
});
|
!function(w,d){
var extras = {
_el:function (name){ return document.createElement(name); },
c_node:function(data,clb,selected,id,state){
var li = this._el('li')
,d = this._el('div')
,node_text = this._el('span')
,l = this._el('span')
,container = this._el('div')
,c = this._el('input')
,b = this._el('a');
node_text.className = ' node-text';
container.className = 'pull-right';
c.type = 'checkbox';
c.name = 'checked[]';
c.value = id;
c.onchange = selected;
c.className = ' hidden ';
b.href = 'javascript:void(0)';
b.innerHTML = '<span class="glyphicon glyphicon-chevron-down"></span><span class="glyphicon glyphicon-chevron-right"></span>';
b.setAttribute('aria-expanded',state);
b.className = state ? ' hidden expanded ':' hidden collapsed ';
b.onclick = clb;
li.className = ' dd-item ';
d.className = ' dd-handle ';
node_text.innerHTML = data.parent === undefined ? '<b>'+data.label+'</b>':data.label;
container.appendChild(c);
l.appendChild(b);
d.appendChild(l);
d.appendChild(node_text);
d.appendChild(container);
li.appendChild(d);
return {
components:container
,root: this._el('ol')
,container:li
,expander: b
,checkBox: c
,nodeText:node_text
};
},
gebi:function(id){
return d.getElementById(id);
},
log:function (){
var t = Array.prototype.slice.call(arguments);
console.info.call(console, '%c TreeJS Debug : ','background: #ff508e; color: #fff;padding:5px', t.join(' '));
},
extend:function() {
var a = arguments, target = a[0] || {}, i = 1, l = a.length, deep = false, options;
if (typeof target === 'boolean') {
deep = target;
target = a[1] || {};
i = 2;
}
if (typeof target !== 'object' && (typeof target !== "function")) target = {};
for (; i < l; ++i) {
if ((options = a[i]) != null) {
for (var name in options) {
var src = target[name], copy = options[name];
if (target === copy) continue;
if (deep && copy && typeof copy === 'object' && !copy.nodeType) {
target[name] = extend(deep, src || (copy.length != null ? [] : {}), copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
},
append_child:function(n){
var tmp = n;
while (tmp.parents.length){
tmp.parents[0].childNodes.push(n);
tmp = tmp.parents[0];
}
},
unid:function(prefix){
return prefix+'-xxx-yxxx-x'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
set_depth:function(node){
for(var i=0,ln=node.childNodes.length; i<ln; i++){
node.childNodes[i].depth++;
this.set_depth(node.childNodes[i]);
} return !0;
},
create_component:function(o){
var btn = extra._el('a')
,wrap = extra._el('div');
wrap.className = ' pull-right ';
wrap.id = extra.unid('tree-component');
btn.className = ' btn btn-small btn-xs ';
btn.innerHTML = o.html;
wrap.appendChild( btn );
return wrap;
}
};
w.extra = extras;
}(window,document); |
import React, { Component } from 'react'
import { Carousel } from 'semantic.js'
export default class Rtl extends Component {
render() {
const settings = {
dots: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 2000,
rtl: true
};
return (
<div>
<h2>Right to Left</h2>
<Carousel {...settings}>
<div><h3>1</h3></div>
<div><h3>2</h3></div>
<div><h3>3</h3></div>
<div><h3>4</h3></div>
<div><h3>5</h3></div>
<div><h3>6</h3></div>
</Carousel>
</div>
);
}
}
|
// Make sure we don't re-inject
if (!window.ssSmugmugForChromeAtStart) {
window.ssSmugmugForChromeAtStart = true;
/**
* Inject our tweak JS into the DOM, along with any information it needs from us to get started (since it can't call chrome extension APIs).
* Note that the DOM is completely empty at this point, so we can't read any info from the page.
*/
var
tweakJSData = document.createElement('script'),
tweakJS = document.createElement('script'),
parent = (document.head || document.documentElement);
var
data = {
config: {
path: chrome.extension.getURL("tweaks/")
},
settings: {}
};
tweakJSData.text = "window.sherlockPhotographySMForChrome = " + JSON.stringify(data) + ";";
var startPoint = parent.firstChild;
parent.insertBefore(tweakJSData, startPoint);
tweakJS.type = 'text/javascript';
tweakJS.src = chrome.extension.getURL('tweaks/inject.js');
parent.insertBefore(tweakJS, startPoint);
var tweakCSS = document.createElement('link');
tweakCSS.type = 'text/css';
tweakCSS.rel = 'stylesheet';
tweakCSS.href = chrome.extension.getURL('tweaks/inject.css');
parent.insertBefore(tweakCSS, startPoint);
// User storage can only be read asynchronously :(, we just have to hope that the settings are loaded before they are read, there is no better alternative.
chrome.storage.local.get('tweaks.settings', function(localData) {
// Need to pass the settings to the document by adding a DOM node (since we can't access JS properties)
var tweakJSSettings = document.createElement('script');
tweakJSSettings.text = "window.sherlockPhotographySMForChrome.settings = " + JSON.stringify(localData['tweaks.settings'] || {}) + ";";
parent.appendChild(tweakJSSettings);
});
} |
var monad = require('../monad');
var monoid = require('../monoid');
monad(Array, {
// map: already defined in Array
of: function(value) {
return [value];
},
ap: function(other) {
var ret = [];
this.forEach(function(f) {
other.forEach(function(x) {
ret.push(f(x));
});
});
return ret;
},
chain: function(f) {
return this.map(function(x) { return f(x); })
.reduce(function(list, x) { return list.concat(x); }, []);
}
});
monoid(Array, {
empty: function() { return []; }
// concat: already defined in Array
});
module.exports = Array; |
export default {
plugins : {},
/**
push ( name: String )
Return Type:
void
Description:
查看是否存在指定插件
URL doc:
http://amaple.org/######
*/
has ( name ) {
return !!this.plugins [ name ];
},
/**
push ( name: String, plugin: Object|Function )
Return Type:
void
Description:
添加插件
URL doc:
http://amaple.org/######
*/
push ( name, plugin ) {
this.plugins [ name ] = plugin;
},
/**
get ( name: String )
Return Type:
Object
插件对象
Description:
获取插件,没有找打则返回null
URL doc:
http://amaple.org/######
*/
get ( name ) {
return this.plugins [ name ] || null;
}
}; |
(function() {
angular
.module('meanApp')
.controller('homeCtrl', homeCtrl);
homeCtrl.$inject = ['authentication', '$routeParams', '$location']
function homeCtrl (authentication, $routeParams, $location) {
console.log('Home controller is running');
}
})(); |
var Config = require('./config.js');
var URL = require('url');
var Parse = require('parse').Parse;
function Api(cfg) {
if (typeof this !== 'object') {
throw new TypeError('Api must be constructed via new');
}
if (Config.keys[cfg]) {
this.parseAppID = Config.keys[cfg].parseAppID;
this.parseMasterKey = Config.keys[cfg].parseMasterKey;
} else {
throw new TypeError("Configuration '" + cfg + "' doesn't exists");
}
}
Api.prototype.prepareRequestOptions = function (f) {
var options = URL.parse("https://api.parse.com/1/" + f);
options.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'X-Parse-Application-Id': this.parseAppID,
'X-Parse-Master-Key': this.parseMasterKey,
'Content-Type': 'application/json'
};
return options;
};
module.exports = Api;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var logger = require('../util/logger');
var db = require('../util/db');
var mongodb = require("mongodb");
var Rx_1 = require("rxjs/Rx");
var util = require("util");
var SensorModel = (function () {
function SensorModel() {
this._schema_version = 1;
this.createIndex();
}
SensorModel.prototype.createIndex = function () {
logger.info("model.sensor.createIndex - called");
var options = { unique: true, background: true, w: 1 };
db.connect(function (err, dbObj) {
var collection = dbObj.collection(SensorModel._collectionName);
// delete all - remove this later...
// collection.deleteMany({}, function (e, results) {
collection.createIndex({ name: 1 }, options, function (err, indexName) {
logger.info("model.sensor.createIndex - callback");
if (err) {
logger.error("model.sensor.createIndex - error: %s", err);
}
if (indexName) {
SensorModel._indexName = indexName;
logger.info("model.sensor.createIndex - indexName: %s", util.inspect(indexName));
}
});
// });
});
logger.info("model.sensor.createIndex - return(void)");
};
SensorModel.getInstance = function () {
if (SensorModel._instance == null) {
SensorModel._instance = new SensorModel();
}
return SensorModel._instance;
};
SensorModel.prototype.get = function () {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
var sv = this._schema_version;
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
coll.find({ schema_version: sv }).toArray().then(function (docs) {
obs.next(docs);
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.getById = function (id) {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
var oid = mongodb.ObjectID.createFromHexString(id);
coll.findOne({ _id: oid }, {}, function (e, results) {
if (e) {
logger.warn("SensorModel.getById.findOne error: ", e);
obs.error(e);
}
if (results && results._id) {
if (results._id instanceof mongodb.ObjectID) {
results._id = results._id.toString();
}
}
obs.next(results);
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.post = function (data) {
var id = "error";
if (!data.name) {
data.name = data.host + "." + data.type;
logger.info("sensor.post(): name set to %s", data.name);
}
var ms = new MongoSensor(data);
var obs = new Rx_1.Subject();
var cn = SensorModel._collectionName;
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
coll.insert(ms, {}, function (e, results) {
if (e) {
return obs.error("insert error: " + e);
}
if (results) {
return obs.next(results.ops[0]._id.toString());
}
});
}
catch (ex) {
obs.error("exception: " + ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.postData = function (sensorId, host, type, val) {
var obs = new Rx_1.Subject();
var mongoSensorId;
try {
logger.info("sensor.postData() - try to convert to ObjectID: %s [%s]", sensorId, typeof (sensorId));
mongoSensorId = mongodb.ObjectID.createFromHexString(sensorId.toString());
db.connect(function (err, dbObj) {
var coll = dbObj.collection(SensorModel._dataCollectionName);
coll.insert({
sensorId: mongoSensorId,
host: host,
type: type,
val: val
}, {}, function (e, results) {
if (e) {
var msg = e.toString();
logger.warn(msg);
obs.error(msg);
}
if (results) {
obs.next(results.ops[0]._id.toString());
}
});
});
}
catch (e) {
logger.error("sensor.postData() - could not convert to ObjectID: %s, error: %s", sensorId, e.toString());
obs.error(e.toString());
}
return obs.asObservable();
};
;
SensorModel.prototype.delete = function (id) {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
var oid = mongodb.ObjectID.createFromHexString(id);
coll.deleteOne({ _id: oid }, function (e, results) {
if (e) {
obs.error(e);
}
if (results) {
obs.next(results.deletedCount);
}
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.deleteAll = function () {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
coll.deleteMany({}, function (e, results) {
if (e) {
obs.error(e);
}
if (results) {
obs.next(results.deletedCount);
}
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.getCollectionName = function () {
return SensorModel._collectionName;
};
SensorModel.prototype.getByHost = function (host) {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
coll.find({ host: host }, {}, function (e, results) {
if (e) {
obs.error(e);
}
results.toArray(function (err, docs) {
obs.next(docs);
});
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.find = function (pattern) {
var cn = SensorModel._collectionName;
var obs = new Rx_1.Subject();
var mpattern = this.mongofy(pattern);
db.connect(function (err, dbObj) {
var coll = dbObj.collection(cn);
try {
coll.find(mpattern, {}, function (e, results) {
if (e) {
obs.error(e);
}
results.toArray(function (err, docs) {
obs.next(docs);
});
});
}
catch (ex) {
obs.error(ex);
}
});
return obs.asObservable();
};
SensorModel.prototype.mongofy = function (s) {
var lrc = {};
if (s._id) {
lrc._id = new mongodb.ObjectId.createFromHexString(s._id);
}
if (s.host) {
lrc.host = s.host;
}
if (s.name) {
lrc.name = s.name;
}
if (s.type) {
lrc.type = s.type;
}
return lrc;
};
SensorModel._collectionName = db.collectionName('model.sensor');
SensorModel._dataCollectionName = db.collectionName('model.sensorData');
SensorModel._instance = null;
SensorModel._indexName = null;
return SensorModel;
}());
exports.SensorModel = SensorModel;
var Sensor = (function () {
function Sensor() {
}
return Sensor;
}());
exports.Sensor = Sensor;
var MongoSensor = (function () {
function MongoSensor(is) {
this._id = null;
this.schema_version = 1;
this.name = null;
this.host = null;
this.type = null;
if (is._id) {
this._id = new mongodb.ObjectId.createFromHexString(is._id);
}
this.name = is.name;
this.host = is.host;
this.type = is.type;
}
return MongoSensor;
}());
//# sourceMappingURL=model.sensor.js.map |
'use strict';
var router = require('koa-router')();
module.exports = function (app) {
app.use(router.routes());
};
router.get('/api', function *(next) {
this.body = 'return some documentation';
});
|
//http://www.rejoicealways.net/lcu-semesters/fall2010/mat1302/Eigenmath.pdf
//EigenMath Manual
const utils = require("../utils.js");
const Algebrite = require("./Interpreters/Algebrite.js");
const Jimp = require("jimp");
const helpMain = "```" +
`MiniAlpha Module Help
/minialpha <expression>
Examples:
integral of x^2
integral of sin(2x) from 0 to pi/2
integral of sqrt(x y) + x sin(y)
derivative of e^x
derivative of sqrt(34-x+y) with respect to y
d/dx e^x
d/dx d/dx sin(x)
d/dx d/dt t*sin(x+t)
You can also use direct commands from Eigenmath.
http://www.rejoicealways.net/lcu-semesters/fall2010/mat1302/Eigenmath.pdf
Keywords:
last, ans --Last answer obtained
` + "```";
class MathEval { //This is an module that adds some essential commands to the selfbot
constructor(debug) {
this.name = "MALP";
this.desc = "MiniAlpha Module";
this.refname = "MiniAlpha";
this.id = 770, //use an ID larger than 100 so that CommandProc processes the message before this module
this.uid = "malp1000"; //Unique ID used to save data to file
this.command = "minialpha"; //Command that activates this module
this.help = helpMain; //Help that displays when users ask
this.isDebug = debug||false;
//modules are run in order, from the smallest id to the largest id.
this.lasteval = {}; //use lasteval[userid] to get last answer
}
main(eventpacket, infopacket, data) {
if (eventpacket.type !== "message" || eventpacket.strength < 1 || eventpacket.isSelf) {
return;
}
const symbol = infopacket.command.symbol;
const command = infopacket.command.verb;
const args = infopacket.command.args;
const ev = eventpacket.event;
const userId = eventpacket.userId;
const rawmsg = eventpacket.rawmsg;
if (command !==this.command) {
return;
}
const expression = new Expression(rawmsg, command);
if (!args[0] || args[0] === "help") {
ev.author.sendMessage(helpMain);
return;
}
if (expression.contains("integral ")) {
expression.removeBefore("integral");
expression.removeAllInstance("of");
let respectToArr = expression.findDx();
//console.log(respectToArr);
if (respectToArr.length < 1) {
respectToArr = ["x"];
}
expression.removeDx();
if (expression.contains("from")) { //Definite Integral
const from = expression.removeAfter("from");
const valsArr = from.split("to");
const vals = valsArr.join(",");
const expressionTeX = Algebrite.run(expression.content, true)[1];
const finalExpressionTeX = ("\\int_{" + valsArr[0] + "}^{" + valsArr[1] + "}{" + expressionTeX + "} \\,d" + respectToArr[0]);
evalReply("defint(" + expression.content + "," + respectToArr[0] + "," + vals + ")", ev, finalExpressionTeX);
} else { //Indefinite Integral
let respectTo = respectToArr.join(",");
let intIs = "";
let intDs = "";
for (let i=0; i<respectToArr.length; i++) {
intIs = intIs + "i";
intDs = intDs + "\\,d" + respectToArr[i];
}
const expressionTeX = Algebrite.run(expression.content, true)[1];
const finalExpressionTeX = ("\\" + intIs + "nt{" + expressionTeX + "}" + intDs);
evalReply("integral(" + expression.content + "," + respectTo + ")", ev, finalExpressionTeX, false, "+C");
}
} else if (expression.contains("derivative ")) {
expression.removeBefore("derivative");
expression.removeAllInstance("of");
let vals = "x";
if (expression.contains("respect")) { //Partial derivative
expression.removeAllInstance("with");
expression.removeAllInstance("to");
vals = expression.removeAfter("respect");
}
const valsArr = vals.split(",");
const finalExpressionTeX = getDerivStr(expression.content, valsArr);
//console.log(finalExpressionTeX);
//console.log(expression.content);
evalReply("d(" + expression.content + "," + vals + ")", ev, finalExpressionTeX);
} else if (expression.contains("d/d")) {
expression.removeAllInstance("of");
let valsArr = expression.findDd();
expression.removeDd();
if (valsArr.length < 1) {
valsArr = ["x"];
}
let vals = valsArr.join(",");
const finalExpressionTeX = getDerivStr(expression.content, valsArr);
evalReply("d(" + expression.content + "," + vals + ")", ev, finalExpressionTeX);
} else {
evalReply(expression.content, ev, false);
}
}
}
const isLetter = function(char) {
return char.toLowerCase() !== char.toUpperCase();
};
const getDerivStr = function(expression, valsArr) {
const expressionTeX = Algebrite.run(expression, true)[1];
expression = " " + expression + " "; //Pad the input
//Find out the number of variables (derivative or partial derivative)
const variables = [];
for (let i=0; i<expression.length-2; i++) {
if (!isLetter(expression[i]) && isLetter(expression[i+1]) && !isLetter(expression[i+2])) {
if (variables.indexOf(expression[i+1]) === -1) {
variables.push(expression[i+1]);
}
}
}
const varnum = variables.length;
const dsymbol = (varnum > 1) ? "\\partial " : "d";
//Find out the order of the derivative
const dvariables = [];
const dvariablespow = [];
let dorder = 0;
for (let i=0; i<valsArr.length; i++) {
const currentVal = valsArr[i].replace(/ /g, "");
const index = dvariables.indexOf(currentVal);
dorder++;
if (index > -1) {
dvariablespow[index] += 1;
} else {
dvariables.push(currentVal);
dvariablespow.push(1);
}
}
//Create the LaTeX string
let derivstr = "";
for (let i=0; i<dvariables.length; i++) {
if (dvariablespow[i] === 1) {
derivstr = derivstr + dsymbol + dvariables[i] + "\\,";
} else {
derivstr = derivstr + dsymbol + dvariables[i] + "^" + dvariablespow[i] + "\\,";
}
}
if (dorder < 2) {
derivstr = "\\frac{" + dsymbol + "}{" + derivstr + "}";
} else {
derivstr = "\\frac{" + dsymbol + "^" + dorder + "}{" + derivstr + "}";
}
return derivstr + "\\bigg({" + expressionTeX + "}\\bigg)";
};
const evalReply = function(expression, ev, evaltext, anstextpre, anstextpost, isText) {
if (evaltext) {
evaltext = evaltext.replace(/ /gi, "%20");
Jimp.read("https://latex.codecogs.com/png.latex?{Evaluate:%20" + evaltext + "}", function(err, image){
image.invert();
image.getBuffer(Jimp.MIME_PNG, function(err, data) {
ev.channel.sendFile(data).then(function(message) {
evalAnsReply(expression, ev, anstextpre, anstextpost, isText);
}).catch(err => {});
});
});
} else {
evalAnsReply(expression, ev, anstextpre, anstextpost, isText);
}
};
const evalAnsReply = function(expression, ev, anstextpre, anstextpost, isText) {
//console.log(expression);
const outeval = Algebrite.run(expression, true);
let outstr = outeval[0];
let outTeX = outeval[1];
Algebrite.clearall();
//console.log(outstr);
if (outstr.indexOf("not find") > -1) {
outstr = "Sorry, could not find a solution.";
outTeX = "\\text{Sorry, could not find a solution.}";
anstextpre = anstextpre || " ";
}
anstextpre = anstextpre || "Answer:%20";
anstextpost = anstextpost || "";
const oTeX = anstextpre + outTeX + anstextpost;
const finalTeX = oTeX.replace(/ /gi, "%20");
if (isText) {
ev.reply(outstr).then().catch(err =>{});
} else {
Jimp.read("https://latex.codecogs.com/png.latex?{" + finalTeX + "}", function(err, image){
image.invert();
image.getBuffer(Jimp.MIME_PNG, function(err, data) {
ev.channel.sendFile(data);
});
});
}
};
class Expression {
constructor(msg, command) {
this.content = msg.slice(msg.indexOf(command)+command.length, msg.length);
}
contains(str) {
return this.content.indexOf(str) > -1;
}
removeFirstInstance(str) {
this.content = this.content.replace(str, "");
}
removeAllInstance(str) {
this.content = this.content.replace(new RegExp(str, 'gi'), "");
}
removeBefore(str) {
const index = this.content.indexOf(str);
if (index > -1) {
const before = this.content.slice(0, index);
this.content = this.content.slice(index + str.length, this.content.length);
return before;
} else {
return "";
}
}
removeAfter(str) {
const index = this.content.indexOf(str);
if (index > -1) {
const after = this.content.slice(index + str.length, this.content.length);
this.content = this.content.slice(0, index);
return after;
} else {
return "";
}
}
findDx() {
const d = [];
const str = this.content;
for (let i=0; i<str.length-1; i++) {
if (str[i] === "d" && str[i+1].toUpperCase() !== str[i+1].toLowerCase()) { //if we found dx, dy, dA etc...
d.push(str[i+1]);
}
}
return d;
}
removeDx() {
this.content = this.content.replace(/d[a-zA-Z]/gi, "");
}
findDd() {
const d = [];
const str = this.content;
for (let i=0; i<str.length-1; i++) {
if (str[i] === "d" && str[i+1] === "/" && str[i+2] === "d" && str[i+3].toUpperCase() !== str[i+3].toLowerCase()) { //if we found d/dx, d/dy, d/dA etc...
d.push(str[i+3]);
}
}
return d;
}
removeDd() {
this.content = this.content.replace(/d\/d[a-zA-Z]/gi, "");
}
}
module.exports = MathEval;
|
import './Index.css';
import React from 'react';
import {render} from 'react-dom';
import {deepOrange500} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Routes from './Routes.js';
import Storage from './models/Storage';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#008cba',
accent1Color: deepOrange500
}
});
console.log(`Hi. Seems that you are interested in the internals of this project.
If you have any feedback/improvement about the layout or the internals you can make an issues/pr at
https://github.com/Pouja/tudscheduler. Have a nice day :).`);
Storage.init().then(() => {
/**
* Main entry point of React and the whole application
* @type {React.element}
*/
const App = <MuiThemeProvider muiTheme={muiTheme}><Routes/></MuiThemeProvider>;
render(App, document.getElementById('react'));
});
|
c['3378']=[['3379',"Properties","topic_000000000000006C_props--.html",1]]; |
/*
* Copyright (c) 2016 airbug Inc. http://airbug.com
*
* bugcore may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@TestFile
//@Require('Class')
//@Require('Flows')
//@Require('Throwables')
//@Require('bugmeta.BugMeta')
//@Require('bugunit.TestTag')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Flows = bugpack.require('Flows');
var Throwables = bugpack.require('Throwables');
var BugMeta = bugpack.require('bugmeta.BugMeta');
var TestTag = bugpack.require('bugunit.TestTag');
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var bugmeta = BugMeta.context();
var test = TestTag.test;
//-------------------------------------------------------------------------------
// Declare Tests
//-------------------------------------------------------------------------------
/**
* This tests..
* 1) That the while parallel completes
*/
var bugflowExecuteWhileParallelTest = {
async: true,
// Setup Test
//-------------------------------------------------------------------------------
setup: function(test) {
var _this = this;
this.testIndex = -1;
this.numberTasksCompleted = 0;
this.numberTasksStarted = 0;
this.testAssertionMethod = function(flow) {
_this.testIndex++;
return (_this.testIndex < 2);
};
this.testTask = Flows.$task(function(flow) {
_this.numberTasksStarted++;
if (_this.numberTasksStarted == 2) {
test.assertEqual(_this.numberTasksCompleted, 0,
"Assert tasks are executed in parallel");
}
setTimeout(function() {
_this.numberTasksCompleted++;
flow.complete();
}, 0);
});
this.whileParallel = Flows.$whileParallel(this.testAssertionMethod, this.testTask);
test.completeSetup();
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
var _this = this;
var executeCallbackFired = false;
this.whileParallel.execute(function(throwable) {
test.assertFalse(executeCallbackFired,
"Assert that the execute callback has not already fired");
executeCallbackFired = true;
if (!throwable) {
test.assertEqual(_this.numberTasksCompleted, 2,
"Assert testTask was run twice");
test.assertEqual(_this.testIndex, 2,
"Assert that the ForEachParallel iterated 2 times");
} else {
test.error(throwable);
}
test.completeTest();
});
}
};
/**
* This tests..
* 1) That the while parallel does not execute another assertion until the previous assertion completes
*/
var bugflowExecuteWhileParallelWithAsyncAssertionTest = {
async: true,
// Setup Test
//-------------------------------------------------------------------------------
setup: function(test) {
var _this = this;
this.numberAssertionsCompleted = 0;
this.numberAssertionsStarted = 0;
this.testAsyncAssertionMethod = function(flow) {
_this.numberAssertionsStarted++;
if (_this.numberAssertionsStarted > 3) {
throw new Throwables.exception("TestException", {}, "Test assertions are running infinitely");
}
setTimeout(function() {
_this.numberAssertionsCompleted++;
test.assertEqual(_this.numberAssertionsCompleted, _this.numberAssertionsStarted,
"Assert that previous assertion completed before the next one started");
flow.assert(_this.numberAssertionsStarted < 3);
}, 0);
};
this.numberTasksCompleted = 0;
this.numberTasksStarted = 0;
this.testWhileTask = Flows.$task(function(flow) {
_this.numberTasksStarted++;
setTimeout(function() {
_this.numberTasksCompleted++;
flow.complete();
}, 0);
});
this.whileParallel = Flows.$whileParallel(this.testAsyncAssertionMethod, this.testWhileTask);
test.completeSetup();
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
var _this = this;
var executeCallbackFired = false;
this.whileParallel.execute(function(throwable) {
test.assertFalse(executeCallbackFired,
"Assert that the execute callback has not already fired");
executeCallbackFired = true;
if (!throwable) {
test.assertEqual(_this.numberAssertionsStarted, 3,
"Assert three assertions started");
test.assertEqual(_this.numberAssertionsCompleted, 3,
"Assert three assertions completed");
test.assertEqual(_this.numberTasksStarted, 2,
"Assert that the ForEachParallel started 2 tasks");
test.assertEqual(_this.numberTasksCompleted, 2,
"Assert that the ForEachParallel completed 2 tasks");
} else {
test.error(throwable);
}
test.completeTest();
});
}
};
//-------------------------------------------------------------------------------
// BugMeta
//-------------------------------------------------------------------------------
bugmeta.tag(bugflowExecuteWhileParallelTest).with(
test().name("Flows WhileParallel - execute test")
);
bugmeta.tag(bugflowExecuteWhileParallelWithAsyncAssertionTest).with(
test().name("Flows WhileParallel - execute with async assertion test")
);
});
|
$(document).ready(function() {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now).toLocaleString('en'));
}
});
});
// Add scrollspy to <body>
$('body').scrollspy({target: ".navbar", offset: 50});
// Add smooth scrolling on all links inside the navbar
$("#myNavbar a").on('click', function(event) {
// Make sure this.hash has a value before overridding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth scroll
// The optional number (800) specifies the number of milliseconds
// it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
|
(function() {
var Batman,
__slice = [].slice;
Batman = function() {
var mixins;
mixins = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Batman.Object, mixins, function(){});
};
Batman.version = '0.15.0';
Batman.config = {
pathToApp: '/',
usePushState: true,
pathToHTML: 'html',
fetchRemoteHTML: true,
cacheViews: false,
minificationErrors: true,
protectFromCSRF: false
};
(Batman.container = (function() {
return this;
})()).Batman = Batman;
if (typeof define === 'function') {
define('batman', [], function() {
return Batman;
});
}
Batman.exportHelpers = function(onto) {
var k, _i, _len, _ref;
_ref = ['mixin', 'extend', 'unmixin', 'redirect', 'typeOf', 'redirect', 'setImmediate', 'clearImmediate'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
onto["$" + k] = Batman[k];
}
return onto;
};
Batman.exportGlobals = function() {
return Batman.exportHelpers(Batman.container);
};
}).call(this);
(function() {
var _Batman;
Batman._Batman = _Batman = (function() {
function _Batman(object) {
this.object = object;
}
_Batman.prototype.check = function(object) {
if (object !== this.object) {
object._batman = new Batman._Batman(object);
return false;
}
return true;
};
_Batman.prototype.get = function(key) {
var reduction, results;
results = this.getAll(key);
switch (results.length) {
case 0:
return void 0;
case 1:
return results[0];
default:
reduction = results[0].concat != null ? function(a, b) {
return a.concat(b);
} : results[0].merge != null ? function(a, b) {
return a.merge(b);
} : results.every(function(x) {
return typeof x === 'object';
}) ? (results.unshift({}), function(a, b) {
return Batman.extend(a, b);
}) : void 0;
if (reduction) {
return results.reduceRight(reduction);
} else {
return results;
}
}
};
_Batman.prototype.getFirst = function(key) {
var results;
results = this.getAll(key);
return results[0];
};
_Batman.prototype.getAll = function(keyOrGetter) {
var getter, results, val;
if (typeof keyOrGetter === 'function') {
getter = keyOrGetter;
} else {
getter = function(ancestor) {
var _ref;
return (_ref = ancestor._batman) != null ? _ref[keyOrGetter] : void 0;
};
}
results = this.ancestors(getter);
if (val = getter(this.object)) {
results.unshift(val);
}
return results;
};
_Batman.prototype.ancestors = function(getter) {
var ancestor, results, val, _i, _len, _ref;
this._allAncestors || (this._allAncestors = this.allAncestors());
if (getter) {
results = [];
_ref = this._allAncestors;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
ancestor = _ref[_i];
val = getter(ancestor);
if (val != null) {
results.push(val);
}
}
return results;
} else {
return this._allAncestors;
}
};
_Batman.prototype.allAncestors = function() {
var isClass, parent, proto, results, _ref, _ref1;
results = [];
isClass = !!this.object.prototype;
parent = isClass ? (_ref = this.object.__super__) != null ? _ref.constructor : void 0 : (proto = Object.getPrototypeOf(this.object)) === this.object ? this.object.constructor.__super__ : proto;
if (parent != null) {
if ((_ref1 = parent._batman) != null) {
_ref1.check(parent);
}
results.push(parent);
if (parent._batman != null) {
results = results.concat(parent._batman.allAncestors());
}
}
return results;
};
_Batman.prototype.set = function(key, value) {
return this[key] = value;
};
return _Batman;
})();
}).call(this);
(function() {
var chr, _encodedChars, _encodedCharsPattern, _entityMap, _implementImmediates, _objectToString, _unsafeChars, _unsafeCharsPattern,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Batman.typeOf = function(object) {
if (typeof object === 'undefined') {
return "Undefined";
}
return _objectToString.call(object).slice(8, -1);
};
_objectToString = Object.prototype.toString;
Batman.extend = function() {
var key, object, objects, to, value, _i, _len;
to = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
for (_i = 0, _len = objects.length; _i < _len; _i++) {
object = objects[_i];
for (key in object) {
value = object[key];
to[key] = value;
}
}
return to;
};
Batman.mixin = function() {
var hasSet, key, mixin, mixins, to, value, _i, _len;
to = arguments[0], mixins = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
hasSet = typeof to.set === 'function';
for (_i = 0, _len = mixins.length; _i < _len; _i++) {
mixin = mixins[_i];
if (Batman.typeOf(mixin) !== 'Object') {
continue;
}
for (key in mixin) {
if (!__hasProp.call(mixin, key)) continue;
value = mixin[key];
if (key === 'initialize' || key === 'uninitialize' || key === 'prototype') {
continue;
}
if (hasSet) {
to.set(key, value);
} else if (to.nodeName != null) {
Batman.data(to, key, value);
} else {
to[key] = value;
}
}
if (typeof mixin.initialize === 'function') {
mixin.initialize.call(to);
}
}
return to;
};
Batman.unmixin = function() {
var from, key, mixin, mixins, _i, _len;
from = arguments[0], mixins = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
for (_i = 0, _len = mixins.length; _i < _len; _i++) {
mixin = mixins[_i];
for (key in mixin) {
if (key === 'initialize' || key === 'uninitialize') {
continue;
}
delete from[key];
}
if (typeof mixin.uninitialize === 'function') {
mixin.uninitialize.call(from);
}
}
return from;
};
Batman._functionName = Batman.functionName = function(f) {
var _ref;
if (f.__name__) {
return f.__name__;
}
if (f.name) {
return f.name;
}
return (_ref = f.toString().match(/\W*function\s+([\w\$]+)\(/)) != null ? _ref[1] : void 0;
};
Batman._isChildOf = Batman.isChildOf = function(parentNode, childNode) {
var node;
node = childNode.parentNode;
while (node) {
if (node === parentNode) {
return true;
}
node = node.parentNode;
}
return false;
};
_implementImmediates = function(container) {
var canUsePostMessage, count, functions, getHandle, handler, prefix, tasks;
canUsePostMessage = function() {
var async, oldMessage;
if (!container.postMessage) {
return false;
}
async = true;
oldMessage = container.onmessage;
container.onmessage = function() {
return async = false;
};
container.postMessage("", "*");
container.onmessage = oldMessage;
return async;
};
tasks = new Batman.SimpleHash;
count = 0;
getHandle = function() {
return "go" + (++count);
};
if (container.setImmediate && container.clearImmediate) {
Batman.setImmediate = function() {
return container.setImmediate.apply(container, arguments);
};
return Batman.clearImmediate = function() {
return container.clearImmediate.apply(container, arguments);
};
} else if (canUsePostMessage()) {
prefix = 'com.batman.';
handler = function(e) {
var handle, _base;
if (typeof e.data !== 'string' || !~e.data.search(prefix)) {
return;
}
handle = e.data.substring(prefix.length);
return typeof (_base = tasks.unset(handle)) === "function" ? _base() : void 0;
};
if (container.addEventListener) {
container.addEventListener('message', handler, false);
} else {
container.attachEvent('onmessage', handler);
}
Batman.setImmediate = function(f) {
var handle;
tasks.set(handle = getHandle(), f);
container.postMessage(prefix + handle, "*");
return handle;
};
return Batman.clearImmediate = function(handle) {
return tasks.unset(handle);
};
} else if (typeof document !== 'undefined' && __indexOf.call(document.createElement("script"), "onreadystatechange") >= 0) {
Batman.setImmediate = function(f) {
var handle, script;
handle = getHandle();
script = document.createElement("script");
script.onreadystatechange = function() {
var _base;
if (typeof (_base = tasks.get(handle)) === "function") {
_base();
}
script.onreadystatechange = null;
script.parentNode.removeChild(script);
return script = null;
};
document.documentElement.appendChild(script);
return handle;
};
return Batman.clearImmediate = function(handle) {
return tasks.unset(handle);
};
} else if (typeof process !== "undefined" && process !== null ? process.nextTick : void 0) {
functions = {};
Batman.setImmediate = function(f) {
var handle;
handle = getHandle();
functions[handle] = f;
process.nextTick(function() {
if (typeof functions[handle] === "function") {
functions[handle]();
}
return delete functions[handle];
});
return handle;
};
return Batman.clearImmediate = function(handle) {
return delete functions[handle];
};
} else {
Batman.setImmediate = function(f) {
return setTimeout(f, 0);
};
return Batman.clearImmediate = function(handle) {
return clearTimeout(handle);
};
}
};
Batman.setImmediate = function() {
_implementImmediates(Batman.container);
return Batman.setImmediate.apply(this, arguments);
};
Batman.clearImmediate = function() {
_implementImmediates(Batman.container);
return Batman.clearImmediate.apply(this, arguments);
};
Batman.forEach = function(container, iterator, ctx) {
var e, i, k, v, _i, _len;
if (container.forEach) {
container.forEach(iterator, ctx);
} else if (container.indexOf) {
for (i = _i = 0, _len = container.length; _i < _len; i = ++_i) {
e = container[i];
iterator.call(ctx, e, i, container);
}
} else {
for (k in container) {
v = container[k];
iterator.call(ctx, k, v, container);
}
}
};
Batman.objectHasKey = function(object, key) {
if (typeof object.hasKey === 'function') {
return object.hasKey(key);
} else {
return key in object;
}
};
Batman.contains = function(container, item) {
if (container.indexOf) {
return __indexOf.call(container, item) >= 0;
} else if (typeof container.has === 'function') {
return container.has(item);
} else {
return Batman.objectHasKey(container, item);
}
};
Batman.get = function(base, key) {
if (typeof base.get === 'function') {
return base.get(key);
} else {
return Batman.Property.forBaseAndKey(base, key).getValue();
}
};
Batman.getPath = function(base, segments) {
var segment, _i, _len;
for (_i = 0, _len = segments.length; _i < _len; _i++) {
segment = segments[_i];
if (base != null) {
base = Batman.get(base, segment);
if (base == null) {
return base;
}
} else {
return;
}
}
return base;
};
_entityMap = {
"&": "&",
"<": "<",
">": ">",
"\"": """,
"'": "'"
};
_unsafeChars = [];
_encodedChars = [];
for (chr in _entityMap) {
_unsafeChars.push(chr);
_encodedChars.push(_entityMap[chr]);
}
_unsafeCharsPattern = new RegExp("[" + (_unsafeChars.join('')) + "]", "g");
_encodedCharsPattern = new RegExp("(" + (_encodedChars.join('|')) + ")", "g");
Batman.escapeHTML = (function() {
return function(s) {
return ("" + s).replace(_unsafeCharsPattern, function(c) {
return _entityMap[c];
});
};
})();
Batman.unescapeHTML = (function() {
return function(s) {
var node;
if (s == null) {
return;
}
node = Batman._unescapeHTMLNode || (Batman._unescapeHTMLNode = document.createElement('DIV'));
node.innerHTML = s;
return Batman.DOM.textContent(node);
};
})();
Batman.translate = function(x, values) {
if (values == null) {
values = {};
}
return Batman.helpers.interpolate(Batman.get(Batman.translate.messages, x), values);
};
Batman.translate.messages = {};
Batman.t = function() {
return Batman.translate.apply(Batman, arguments);
};
Batman.redirect = function(url, replaceState) {
var _ref;
if (replaceState == null) {
replaceState = false;
}
return (_ref = Batman.navigator) != null ? _ref.redirect(url, replaceState) : void 0;
};
Batman.initializeObject = function(object) {
if (object._batman != null) {
return object._batman.check(object);
} else {
return object._batman = new Batman._Batman(object);
}
};
}).call(this);
(function() {
var __slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Batman.Inflector = (function() {
Inflector.prototype.plural = function(regex, replacement) {
return this._plural.unshift([regex, replacement]);
};
Inflector.prototype.singular = function(regex, replacement) {
return this._singular.unshift([regex, replacement]);
};
Inflector.prototype.human = function(regex, replacement) {
return this._human.unshift([regex, replacement]);
};
Inflector.prototype.uncountable = function() {
var strings;
strings = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return this._uncountable = this._uncountable.concat(strings.map(function(x) {
return new RegExp("" + x + "$", 'i');
}));
};
Inflector.prototype.irregular = function(singular, plural) {
if (singular.charAt(0) === plural.charAt(0)) {
this.plural(new RegExp("(" + (singular.charAt(0)) + ")" + (singular.slice(1)) + "$", "i"), "$1" + plural.slice(1));
this.plural(new RegExp("(" + (singular.charAt(0)) + ")" + (plural.slice(1)) + "$", "i"), "$1" + plural.slice(1));
return this.singular(new RegExp("(" + (plural.charAt(0)) + ")" + (plural.slice(1)) + "$", "i"), "$1" + singular.slice(1));
} else {
this.plural(new RegExp("" + singular + "$", 'i'), plural);
this.plural(new RegExp("" + plural + "$", 'i'), plural);
return this.singular(new RegExp("" + plural + "$", 'i'), singular);
}
};
function Inflector() {
this._plural = [];
this._singular = [];
this._uncountable = [];
this._human = [];
}
Inflector.prototype.ordinalize = function(number, radix) {
var absNumber, _ref;
if (radix == null) {
radix = 10;
}
number = parseInt(number, radix);
absNumber = Math.abs(number);
if (_ref = absNumber % 100, __indexOf.call([11, 12, 13], _ref) >= 0) {
return number + "th";
} else {
switch (absNumber % 10) {
case 1:
return number + "st";
case 2:
return number + "nd";
case 3:
return number + "rd";
default:
return number + "th";
}
}
};
Inflector.prototype.pluralize = function(word) {
var regex, replace_string, uncountableRegex, _i, _j, _len, _len1, _ref, _ref1, _ref2;
_ref = this._uncountable;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
uncountableRegex = _ref[_i];
if (uncountableRegex.test(word)) {
return word;
}
}
_ref1 = this._plural;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
_ref2 = _ref1[_j], regex = _ref2[0], replace_string = _ref2[1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
return word;
};
Inflector.prototype.singularize = function(word) {
var regex, replace_string, uncountableRegex, _i, _j, _len, _len1, _ref, _ref1, _ref2;
_ref = this._uncountable;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
uncountableRegex = _ref[_i];
if (uncountableRegex.test(word)) {
return word;
}
}
_ref1 = this._singular;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
_ref2 = _ref1[_j], regex = _ref2[0], replace_string = _ref2[1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
return word;
};
Inflector.prototype.humanize = function(word) {
var regex, replace_string, _i, _len, _ref, _ref1;
_ref = this._human;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
_ref1 = _ref[_i], regex = _ref1[0], replace_string = _ref1[1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
return word;
};
return Inflector;
})();
}).call(this);
(function() {
var Inflector, camelize_rx, capitalize_rx, humanize_rx1, humanize_rx2, humanize_rx3, underscore_rx1, underscore_rx2;
camelize_rx = /(?:^|_|\-)(.)/g;
capitalize_rx = /(^|\s)([a-z])/g;
underscore_rx1 = /([A-Z]+)([A-Z][a-z])/g;
underscore_rx2 = /([a-z\d])([A-Z])/g;
humanize_rx1 = /_id$/;
humanize_rx2 = /_|-/g;
humanize_rx3 = /^\w/g;
Batman.helpers = {
ordinalize: function() {
return Batman.helpers.inflector.ordinalize.apply(Batman.helpers.inflector, arguments);
},
singularize: function() {
return Batman.helpers.inflector.singularize.apply(Batman.helpers.inflector, arguments);
},
pluralize: function(count, singular, plural, includeCount) {
var result;
if (includeCount == null) {
includeCount = true;
}
if (arguments.length < 2) {
return Batman.helpers.inflector.pluralize(count);
} else {
result = +count === 1 ? singular : plural || Batman.helpers.inflector.pluralize(singular);
if (includeCount) {
result = ("" + (count || 0) + " ") + result;
}
return result;
}
},
camelize: function(string, firstLetterLower) {
string = string.replace(camelize_rx, function(str, p1) {
return p1.toUpperCase();
});
if (firstLetterLower) {
return string.substr(0, 1).toLowerCase() + string.substr(1);
} else {
return string;
}
},
underscore: function(string) {
return string.replace(underscore_rx1, '$1_$2').replace(underscore_rx2, '$1_$2').replace('-', '_').toLowerCase();
},
capitalize: function(string) {
return string.replace(capitalize_rx, function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
},
trim: function(string) {
if (string) {
return string.trim();
} else {
return "";
}
},
interpolate: function(stringOrObject, keys) {
var key, string, value;
if (typeof stringOrObject === 'object') {
string = stringOrObject[keys.count];
if (!string) {
string = stringOrObject['other'];
}
} else {
string = stringOrObject;
}
for (key in keys) {
value = keys[key];
string = string.replace(new RegExp("%\\{" + key + "\\}", "g"), value);
}
return string;
},
humanize: function(string) {
string = Batman.helpers.underscore(string);
string = Batman.helpers.inflector.humanize(string);
return string.replace(humanize_rx1, '').replace(humanize_rx2, ' ').replace(humanize_rx3, function(match) {
return match.toUpperCase();
});
}
};
Inflector = new Batman.Inflector;
Batman.helpers.inflector = Inflector;
Inflector.plural(/$/, 's');
Inflector.plural(/s$/i, 's');
Inflector.plural(/(ax|test)is$/i, '$1es');
Inflector.plural(/(octop|vir)us$/i, '$1i');
Inflector.plural(/(octop|vir)i$/i, '$1i');
Inflector.plural(/(alias|status)$/i, '$1es');
Inflector.plural(/(bu)s$/i, '$1ses');
Inflector.plural(/(buffal|tomat)o$/i, '$1oes');
Inflector.plural(/([ti])um$/i, '$1a');
Inflector.plural(/([ti])a$/i, '$1a');
Inflector.plural(/sis$/i, 'ses');
Inflector.plural(/(?:([^f])fe|([lr])f)$/i, '$1$2ves');
Inflector.plural(/(hive)$/i, '$1s');
Inflector.plural(/([^aeiouy]|qu)y$/i, '$1ies');
Inflector.plural(/(x|ch|ss|sh)$/i, '$1es');
Inflector.plural(/(matr|vert|ind)(?:ix|ex)$/i, '$1ices');
Inflector.plural(/([m|l])ouse$/i, '$1ice');
Inflector.plural(/([m|l])ice$/i, '$1ice');
Inflector.plural(/^(ox)$/i, '$1en');
Inflector.plural(/^(oxen)$/i, '$1');
Inflector.plural(/(quiz)$/i, '$1zes');
Inflector.singular(/s$/i, '');
Inflector.singular(/(n)ews$/i, '$1ews');
Inflector.singular(/([ti])a$/i, '$1um');
Inflector.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, '$1$2sis');
Inflector.singular(/(^analy)ses$/i, '$1sis');
Inflector.singular(/([^f])ves$/i, '$1fe');
Inflector.singular(/(hive)s$/i, '$1');
Inflector.singular(/(tive)s$/i, '$1');
Inflector.singular(/([lr])ves$/i, '$1f');
Inflector.singular(/([^aeiouy]|qu)ies$/i, '$1y');
Inflector.singular(/(s)eries$/i, '$1eries');
Inflector.singular(/(m)ovies$/i, '$1ovie');
Inflector.singular(/(x|ch|ss|sh)es$/i, '$1');
Inflector.singular(/([m|l])ice$/i, '$1ouse');
Inflector.singular(/(bus)es$/i, '$1');
Inflector.singular(/(o)es$/i, '$1');
Inflector.singular(/(shoe)s$/i, '$1');
Inflector.singular(/(cris|ax|test)es$/i, '$1is');
Inflector.singular(/(octop|vir)i$/i, '$1us');
Inflector.singular(/(alias|status)es$/i, '$1');
Inflector.singular(/^(ox)en/i, '$1');
Inflector.singular(/(vert|ind)ices$/i, '$1ex');
Inflector.singular(/(matr)ices$/i, '$1ix');
Inflector.singular(/(quiz)zes$/i, '$1');
Inflector.singular(/(database)s$/i, '$1');
Inflector.irregular('person', 'people');
Inflector.irregular('man', 'men');
Inflector.irregular('child', 'children');
Inflector.irregular('sex', 'sexes');
Inflector.irregular('move', 'moves');
Inflector.irregular('cow', 'kine');
Inflector.irregular('zombie', 'zombies');
Inflector.uncountable('equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans');
}).call(this);
(function() {
var developer;
Batman.developer = {
suppressed: false,
DevelopmentError: (function() {
var DevelopmentError;
DevelopmentError = function(message) {
this.message = message;
return this.name = "DevelopmentError";
};
DevelopmentError.prototype = Error.prototype;
return DevelopmentError;
})(),
_ie_console: function(f, args) {
var arg, _i, _len, _results;
if (args.length !== 1) {
if (typeof console !== "undefined" && console !== null) {
console[f]("..." + f + " of " + args.length + " items...");
}
}
_results = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
_results.push(typeof console !== "undefined" && console !== null ? console[f](arg) : void 0);
}
return _results;
},
suppress: function(f) {
developer.suppressed = true;
if (f) {
f();
return developer.suppressed = false;
}
},
unsuppress: function() {
return developer.suppressed = false;
},
log: function() {
if (developer.suppressed || !((typeof console !== "undefined" && console !== null ? console.log : void 0) != null)) {
return;
}
if (console.log.apply) {
return console.log.apply(console, arguments);
} else {
return developer._ie_console("log", arguments);
}
},
warn: function() {
if (developer.suppressed || !((typeof console !== "undefined" && console !== null ? console.warn : void 0) != null)) {
return;
}
if (console.warn.apply) {
return console.warn.apply(console, arguments);
} else {
return developer._ie_console("warn", arguments);
}
},
error: function(message) {
throw new developer.DevelopmentError(message);
},
assert: function(result, message) {
if (!result) {
return developer.error(message);
}
},
"do": function(f) {
if (!developer.suppressed) {
return f();
}
},
addFilters: function() {
return Batman.extend(Batman.Filters, {
log: function(value, key) {
if (typeof console !== "undefined" && console !== null) {
if (typeof console.log === "function") {
console.log(arguments);
}
}
return value;
},
logStack: function(value) {
if (typeof console !== "undefined" && console !== null) {
if (typeof console.log === "function") {
console.log(developer.currentFilterStack);
}
}
return value;
}
});
},
deprecated: function(deprecatedName, upgradeString) {
return Batman.developer.warn("" + deprecatedName + " has been deprecated.", upgradeString || '');
}
};
developer = Batman.developer;
Batman.developer.assert((function() {}).bind, "Error! Batman needs Function.bind to work! Please shim it using something like es5-shim or augmentjs!");
}).call(this);
(function() {
Batman.Event = (function() {
Event.forBaseAndKey = function(base, key) {
if (base.isEventEmitter) {
return base.event(key);
} else {
return new Batman.Event(base, key);
}
};
function Event(base, key) {
this.base = base;
this.key = key;
this._preventCount = 0;
}
Event.prototype.isEvent = true;
Event.prototype.isEqual = function(other) {
return this.constructor === other.constructor && this.base === other.base && this.key === other.key;
};
Event.prototype.hashKey = function() {
var key;
this.hashKey = function() {
return key;
};
return key = "<Batman.Event base: " + (Batman.Hash.prototype.hashKeyFor(this.base)) + ", key: \"" + (Batman.Hash.prototype.hashKeyFor(this.key)) + "\">";
};
Event.prototype.addHandler = function(handler) {
this.handlers || (this.handlers = []);
if (this.handlers.indexOf(handler) === -1) {
this.handlers.push(handler);
}
if (this.oneShot) {
this.autofireHandler(handler);
}
return this;
};
Event.prototype.removeHandler = function(handler) {
var index;
if (this.handlers && (index = this.handlers.indexOf(handler)) !== -1) {
this.handlers.splice(index, 1);
}
return this;
};
Event.prototype.eachHandler = function(iterator) {
var ancestor, key, _i, _len, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if ((_ref = this.handlers) != null) {
_ref.slice().forEach(iterator);
}
if ((_ref1 = this.base) != null ? _ref1.isEventEmitter : void 0) {
key = this.key;
_ref3 = (_ref2 = this.base._batman) != null ? _ref2.ancestors() : void 0;
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
ancestor = _ref3[_i];
if (ancestor.isEventEmitter && ((_ref4 = ancestor._batman) != null ? (_ref5 = _ref4.events) != null ? _ref5.hasOwnProperty(key) : void 0 : void 0)) {
if ((_ref6 = ancestor.event(key, false)) != null) {
if ((_ref7 = _ref6.handlers) != null) {
_ref7.slice().forEach(iterator);
}
}
}
}
}
};
Event.prototype.clearHandlers = function() {
return this.handlers = void 0;
};
Event.prototype.handlerContext = function() {
return this.base;
};
Event.prototype.prevent = function() {
return ++this._preventCount;
};
Event.prototype.allow = function() {
if (this._preventCount) {
--this._preventCount;
}
return this._preventCount;
};
Event.prototype.isPrevented = function() {
return this._preventCount > 0;
};
Event.prototype.autofireHandler = function(handler) {
if (this._oneShotFired && (this._oneShotArgs != null)) {
return handler.apply(this.handlerContext(), this._oneShotArgs);
}
};
Event.prototype.resetOneShot = function() {
this._oneShotFired = false;
return this._oneShotArgs = null;
};
Event.prototype.fire = function() {
return this.fireWithContext(this.handlerContext(), arguments);
};
Event.prototype.fireWithContext = function(context, args) {
if (this.isPrevented() || this._oneShotFired) {
return false;
}
if (this.oneShot) {
this._oneShotFired = true;
this._oneShotArgs = args;
}
return this.eachHandler(function(handler) {
return handler.apply(context, args);
});
};
Event.prototype.allowAndFire = function() {
return this.allowAndFireWithContext(this.handlerContext, arguments);
};
Event.prototype.allowAndFireWithContext = function(context, args) {
this.allow();
return this.fireWithContext(context, args);
};
return Event;
})();
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PropertyEvent = (function(_super) {
__extends(PropertyEvent, _super);
function PropertyEvent() {
_ref = PropertyEvent.__super__.constructor.apply(this, arguments);
return _ref;
}
PropertyEvent.prototype.eachHandler = function(iterator) {
return this.eachObserver(iterator);
};
PropertyEvent.prototype.handlerContext = function() {
return this.base;
};
return PropertyEvent;
})(Batman.Event);
}).call(this);
(function() {
var __slice = [].slice;
Batman.EventEmitter = {
isEventEmitter: true,
hasEvent: function(key) {
var _ref, _ref1;
return (_ref = this._batman) != null ? typeof _ref.get === "function" ? (_ref1 = _ref.get('events')) != null ? _ref1.hasOwnProperty(key) : void 0 : void 0 : void 0;
},
event: function(key, createEvent) {
var ancestor, eventClass, events, existingEvent, newEvent, _base, _i, _len, _ref, _ref1, _ref2, _ref3;
if (createEvent == null) {
createEvent = true;
}
Batman.initializeObject(this);
eventClass = this.eventClass || Batman.Event;
if ((_ref = this._batman.events) != null ? _ref.hasOwnProperty(key) : void 0) {
return existingEvent = this._batman.events[key];
} else {
_ref1 = this._batman.ancestors();
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
ancestor = _ref1[_i];
existingEvent = (_ref2 = ancestor._batman) != null ? (_ref3 = _ref2.events) != null ? _ref3[key] : void 0 : void 0;
if (existingEvent) {
break;
}
}
if (createEvent || (existingEvent != null ? existingEvent.oneShot : void 0)) {
events = (_base = this._batman).events || (_base.events = {});
newEvent = events[key] = new eventClass(this, key);
newEvent.oneShot = existingEvent != null ? existingEvent.oneShot : void 0;
return newEvent;
} else {
return existingEvent;
}
}
},
on: function() {
var handler, key, keys, _i, _j, _len;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), handler = arguments[_i++];
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
this.event(key).addHandler(handler);
}
return true;
},
off: function() {
var handler, key, keys, _i, _j, _len;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), handler = arguments[_i++];
if (!keys.length) {
key = handler;
this.event(key).clearHandlers();
}
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
this.event(key).removeHandler(handler);
}
return true;
},
once: function(key, handler) {
var event, handlerWrapper;
event = this.event(key);
handlerWrapper = function() {
handler.apply(this, arguments);
return event.removeHandler(handlerWrapper);
};
return event.addHandler(handlerWrapper);
},
registerAsMutableSource: function() {
return Batman.Property.registerSource(this);
},
mutate: function(wrappedFunction) {
var result;
this.prevent('change');
result = wrappedFunction.call(this);
this.allowAndFire('change', this, this);
return result;
},
mutation: function(wrappedFunction) {
return function() {
var result, _ref;
result = wrappedFunction.apply(this, arguments);
if ((_ref = this.event('change', false)) != null) {
_ref.fire(this, this);
}
return result;
};
},
prevent: function(key) {
this.event(key).prevent();
return this;
},
allow: function(key) {
this.event(key).allow();
return this;
},
fire: function() {
var args, key, _ref;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return (_ref = this.event(key, false)) != null ? _ref.fireWithContext(this, args) : void 0;
},
allowAndFire: function() {
var args, key, _ref;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
return (_ref = this.event(key, false)) != null ? _ref.allowAndFireWithContext(this, args) : void 0;
},
isPrevented: function(key) {
var _ref;
return (_ref = this.event(key, false)) != null ? _ref.isPrevented() : void 0;
}
};
}).call(this);
(function() {
var fire,
__slice = [].slice;
Batman.LifecycleEvents = {
initialize: function() {
return this.prototype.fireLifecycleEvent = fire;
},
lifecycleEvent: function(eventName, normalizeFunction) {
var addCallback, afterName, beforeName;
beforeName = "before" + (Batman.helpers.camelize(eventName));
afterName = "after" + (Batman.helpers.camelize(eventName));
addCallback = function(lifecycleEventName) {
return function(callbackName, options) {
var callback, handlers, target, _base, _ref;
if (Batman.typeOf(callbackName) === 'Object') {
_ref = [options, callbackName], callbackName = _ref[0], options = _ref[1];
}
if (Batman.typeOf(callbackName) === 'String') {
callback = function() {
return this[callbackName].apply(this, arguments);
};
} else {
callback = callbackName;
}
options = (typeof normalizeFunction === "function" ? normalizeFunction(options) : void 0) || options;
target = this.prototype || this;
Batman.initializeObject(target);
handlers = (_base = target._batman)[lifecycleEventName] || (_base[lifecycleEventName] = []);
return handlers.push({
options: options,
callback: callback
});
};
};
this[beforeName] = addCallback(beforeName);
this.prototype[beforeName] = addCallback(beforeName);
this[afterName] = addCallback(afterName);
return this.prototype[afterName] = addCallback(afterName);
}
};
fire = function() {
var args, callback, handlers, lifecycleEventName, options, _i, _len, _ref;
lifecycleEventName = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (!(handlers = this._batman.get(lifecycleEventName))) {
return;
}
for (_i = 0, _len = handlers.length; _i < _len; _i++) {
_ref = handlers[_i], options = _ref.options, callback = _ref.callback;
if ((options != null ? options["if"] : void 0) && !options["if"].apply(this, args)) {
continue;
}
if ((options != null ? options.unless : void 0) && options.unless.apply(this, args)) {
continue;
}
if (callback.apply(this, args) === false) {
return false;
}
}
};
}).call(this);
(function() {
Batman.Enumerable = {
isEnumerable: true,
map: function(f, ctx) {
var result;
if (ctx == null) {
ctx = Batman.container;
}
result = [];
this.forEach(function() {
return result.push(f.apply(ctx, arguments));
});
return result;
},
mapToProperty: function(key) {
var result;
result = [];
this.forEach(function(item) {
return result.push(Batman.get(item, key));
});
return result;
},
every: function(f, ctx) {
var result;
if (ctx == null) {
ctx = Batman.container;
}
result = true;
this.forEach(function() {
return result = result && f.apply(ctx, arguments);
});
return result;
},
some: function(f, ctx) {
var result;
if (ctx == null) {
ctx = Batman.container;
}
result = false;
this.forEach(function() {
return result = result || f.apply(ctx, arguments);
});
return result;
},
reduce: function(f, accumulator) {
var index, initialValuePassed,
_this = this;
index = 0;
initialValuePassed = accumulator != null;
this.forEach(function(element, value) {
if (!initialValuePassed) {
accumulator = element;
initialValuePassed = true;
return;
}
accumulator = f(accumulator, element, value, index, self);
return index++;
});
return accumulator;
},
filter: function(f) {
var result, wrap,
_this = this;
result = new this.constructor;
if (result.add) {
wrap = function(result, element, value) {
if (f(element, value, _this)) {
result.add(element);
}
return result;
};
} else if (result.set) {
wrap = function(result, element, value) {
if (f(element, value, _this)) {
result.set(element, value);
}
return result;
};
} else {
if (!result.push) {
result = [];
}
wrap = function(result, element, value) {
if (f(element, value, _this)) {
result.push(element);
}
return result;
};
}
return this.reduce(wrap, result);
},
count: function(f, ctx) {
var count,
_this = this;
if (ctx == null) {
ctx = Batman.container;
}
if (!f) {
return this.length;
}
count = 0;
this.forEach(function(element, value) {
if (f.call(ctx, element, value, _this)) {
return count++;
}
});
return count;
},
inGroupsOf: function(groupSize) {
var current, i, result;
result = [];
current = false;
i = 0;
this.forEach(function(element) {
if (i++ % groupSize === 0) {
current = [];
result.push(current);
}
return current.push(element);
});
return result;
}
};
}).call(this);
(function() {
var _objectToString,
__slice = [].slice;
_objectToString = Object.prototype.toString;
Batman.SimpleHash = (function() {
function SimpleHash(obj) {
this._storage = {};
this.length = 0;
if (obj != null) {
this.update(obj);
}
}
Batman.extend(SimpleHash.prototype, Batman.Enumerable);
SimpleHash.prototype.hasKey = function(key) {
var pair, pairs, _i, _len;
if (this.objectKey(key)) {
if (!this._objectStorage) {
return false;
}
if (pairs = this._objectStorage[this.hashKeyFor(key)]) {
for (_i = 0, _len = pairs.length; _i < _len; _i++) {
pair = pairs[_i];
if (this.equality(pair[0], key)) {
return true;
}
}
}
return false;
} else {
key = this.prefixedKey(key);
return this._storage.hasOwnProperty(key);
}
};
SimpleHash.prototype.getObject = function(key) {
var pair, pairs, _i, _len;
if (!this._objectStorage) {
return;
}
if (pairs = this._objectStorage[this.hashKeyFor(key)]) {
for (_i = 0, _len = pairs.length; _i < _len; _i++) {
pair = pairs[_i];
if (this.equality(pair[0], key)) {
return pair[1];
}
}
}
};
SimpleHash.prototype.getString = function(key) {
return this._storage["_" + key];
};
SimpleHash.prototype.setObject = function(key, val) {
var pair, pairs, _base, _i, _len, _name;
this._objectStorage || (this._objectStorage = {});
pairs = (_base = this._objectStorage)[_name = this.hashKeyFor(key)] || (_base[_name] = []);
for (_i = 0, _len = pairs.length; _i < _len; _i++) {
pair = pairs[_i];
if (this.equality(pair[0], key)) {
return pair[1] = val;
}
}
this.length++;
pairs.push([key, val]);
return val;
};
SimpleHash.prototype.setString = function(key, val) {
key = "_" + key;
if (this._storage[key] == null) {
this.length++;
}
return this._storage[key] = val;
};
SimpleHash.prototype.get = function(key) {
var pair, pairs, _i, _len;
if (this.objectKey(key)) {
if (!this._objectStorage) {
return;
}
if (pairs = this._objectStorage[this.hashKeyFor(key)]) {
for (_i = 0, _len = pairs.length; _i < _len; _i++) {
pair = pairs[_i];
if (this.equality(pair[0], key)) {
return pair[1];
}
}
}
} else {
return this._storage[this.prefixedKey(key)];
}
};
SimpleHash.prototype.set = function(key, val) {
var pair, pairs, _base, _i, _len, _name;
if (this.objectKey(key)) {
this._objectStorage || (this._objectStorage = {});
pairs = (_base = this._objectStorage)[_name = this.hashKeyFor(key)] || (_base[_name] = []);
for (_i = 0, _len = pairs.length; _i < _len; _i++) {
pair = pairs[_i];
if (this.equality(pair[0], key)) {
return pair[1] = val;
}
}
this.length++;
pairs.push([key, val]);
return val;
} else {
key = this.prefixedKey(key);
if (this._storage[key] == null) {
this.length++;
}
return this._storage[key] = val;
}
};
SimpleHash.prototype.unset = function(key) {
var hashKey, index, obj, pair, pairs, val, value, _i, _len, _ref;
if (this.objectKey(key)) {
if (!this._objectStorage) {
return;
}
hashKey = this.hashKeyFor(key);
if (pairs = this._objectStorage[hashKey]) {
for (index = _i = 0, _len = pairs.length; _i < _len; index = ++_i) {
_ref = pairs[index], obj = _ref[0], value = _ref[1];
if (this.equality(obj, key)) {
pair = pairs.splice(index, 1);
if (!pairs.length) {
delete this._objectStorage[hashKey];
}
this.length--;
return pair[0][1];
}
}
}
} else {
key = this.prefixedKey(key);
val = this._storage[key];
if (this._storage[key] != null) {
this.length--;
delete this._storage[key];
}
return val;
}
};
SimpleHash.prototype.getOrSet = function(key, valueFunction) {
var currentValue;
currentValue = this.get(key);
if (!currentValue) {
currentValue = valueFunction();
this.set(key, currentValue);
}
return currentValue;
};
SimpleHash.prototype.prefixedKey = function(key) {
return "_" + key;
};
SimpleHash.prototype.unprefixedKey = function(key) {
return key.slice(1);
};
SimpleHash.prototype.hashKeyFor = function(obj) {
var hashKey, typeString;
if (hashKey = obj != null ? typeof obj.hashKey === "function" ? obj.hashKey() : void 0 : void 0) {
return hashKey;
} else {
typeString = _objectToString.call(obj);
if (typeString === "[object Array]") {
return typeString;
} else {
return obj;
}
}
};
SimpleHash.prototype.equality = function(lhs, rhs) {
if (lhs === rhs) {
return true;
}
if (lhs !== lhs && rhs !== rhs) {
return true;
}
if ((lhs != null ? typeof lhs.isEqual === "function" ? lhs.isEqual(rhs) : void 0 : void 0) && (rhs != null ? typeof rhs.isEqual === "function" ? rhs.isEqual(lhs) : void 0 : void 0)) {
return true;
}
return false;
};
SimpleHash.prototype.objectKey = function(key) {
return typeof key !== 'string';
};
SimpleHash.prototype.forEach = function(iterator, ctx) {
var key, obj, results, value, values, _i, _len, _ref, _ref1, _ref2, _ref3;
results = [];
if (this._objectStorage) {
_ref = this._objectStorage;
for (key in _ref) {
values = _ref[key];
_ref1 = values.slice();
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
_ref2 = _ref1[_i], obj = _ref2[0], value = _ref2[1];
results.push(iterator.call(ctx, obj, value, this));
}
}
}
_ref3 = this._storage;
for (key in _ref3) {
value = _ref3[key];
results.push(iterator.call(ctx, this.unprefixedKey(key), value, this));
}
return results;
};
SimpleHash.prototype.keys = function() {
var result;
result = [];
Batman.SimpleHash.prototype.forEach.call(this, function(key) {
return result.push(key);
});
return result;
};
SimpleHash.prototype.toArray = SimpleHash.prototype.keys;
SimpleHash.prototype.clear = function() {
this._storage = {};
delete this._objectStorage;
return this.length = 0;
};
SimpleHash.prototype.isEmpty = function() {
return this.length === 0;
};
SimpleHash.prototype.merge = function() {
var hash, merged, others, _i, _len;
others = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
merged = new this.constructor;
others.unshift(this);
for (_i = 0, _len = others.length; _i < _len; _i++) {
hash = others[_i];
hash.forEach(function(obj, value) {
return merged.set(obj, value);
});
}
return merged;
};
SimpleHash.prototype.update = function(object) {
var k, v;
for (k in object) {
v = object[k];
this.set(k, v);
}
};
SimpleHash.prototype.replace = function(object) {
var _this = this;
this.forEach(function(key, value) {
if (!(key in object)) {
return _this.unset(key);
}
});
return this.update(object);
};
SimpleHash.prototype.toObject = function() {
var key, obj, pair, value, _ref, _ref1;
obj = {};
_ref = this._storage;
for (key in _ref) {
value = _ref[key];
obj[this.unprefixedKey(key)] = value;
}
if (this._objectStorage) {
_ref1 = this._objectStorage;
for (key in _ref1) {
pair = _ref1[key];
obj[key] = pair[0][1];
}
}
return obj;
};
SimpleHash.prototype.toJSON = SimpleHash.prototype.toObject;
return SimpleHash;
})();
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.AssociationCurator = (function(_super) {
__extends(AssociationCurator, _super);
AssociationCurator.availableAssociations = ['belongsTo', 'hasOne', 'hasMany'];
function AssociationCurator(model) {
this.model = model;
AssociationCurator.__super__.constructor.call(this);
this._byTypeStorage = new Batman.SimpleHash;
}
AssociationCurator.prototype.add = function(association) {
var associationTypeSet;
this.set(association.label, association);
if (!(associationTypeSet = this._byTypeStorage.get(association.associationType))) {
associationTypeSet = new Batman.SimpleSet;
this._byTypeStorage.set(association.associationType, associationTypeSet);
}
return associationTypeSet.add(association);
};
AssociationCurator.prototype.getByType = function(type) {
return this._byTypeStorage.get(type);
};
AssociationCurator.prototype.getByLabel = function(label) {
return this.get(label);
};
AssociationCurator.prototype.reset = function() {
this.forEach(function(label, association) {
return association.reset();
});
return true;
};
AssociationCurator.prototype.merge = function() {
var others, result;
others = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
result = AssociationCurator.__super__.merge.apply(this, arguments);
result._byTypeStorage = this._byTypeStorage.merge(others.map(function(other) {
return other._byTypeStorage;
}));
return result;
};
AssociationCurator.prototype._markDirtyAttribute = function(key, oldValue) {
var _ref;
if ((_ref = this.lifecycle.get('state')) !== 'loading' && _ref !== 'creating' && _ref !== 'saving' && _ref !== 'saved') {
if (this.lifecycle.startTransition('set')) {
return this.dirtyKeys.set(key, oldValue);
} else {
throw new Batman.StateMachine.InvalidTransitionError("Can't set while in state " + (this.lifecycle.get('state')));
}
}
};
return AssociationCurator;
})(Batman.SimpleHash);
}).call(this);
(function() {
var __slice = [].slice;
Batman.SimpleSet = (function() {
function SimpleSet() {
var item, itemsToAdd;
this._storage = [];
this.length = 0;
itemsToAdd = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = arguments.length; _i < _len; _i++) {
item = arguments[_i];
if (item != null) {
_results.push(item);
}
}
return _results;
}).apply(this, arguments);
if (itemsToAdd.length > 0) {
this.add.apply(this, itemsToAdd);
}
}
Batman.extend(SimpleSet.prototype, Batman.Enumerable);
SimpleSet.prototype.at = function(index) {
return this._storage[index];
};
SimpleSet.prototype.add = function() {
var addedItems, item, items, _i, _len;
items = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
addedItems = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (!(this._indexOfItem(item) === -1)) {
continue;
}
this._storage.push(item);
addedItems.push(item);
}
this.length = this._storage.length;
return addedItems;
};
SimpleSet.prototype.insert = function() {
return this.insertWithIndexes.apply(this, arguments).addedItems;
};
SimpleSet.prototype.insertWithIndexes = function(items, indexes) {
var addedIndexes, addedItems, i, index, item, _i, _len;
addedIndexes = [];
addedItems = [];
for (i = _i = 0, _len = items.length; _i < _len; i = ++_i) {
item = items[i];
if (!(this._indexOfItem(item) === -1)) {
continue;
}
index = indexes[i];
this._storage.splice(index, 0, item);
addedItems.push(item);
addedIndexes.push(index);
}
this.length = this._storage.length;
return {
addedItems: addedItems,
addedIndexes: addedIndexes
};
};
SimpleSet.prototype.remove = function() {
return this.removeWithIndexes.apply(this, arguments).removedItems;
};
SimpleSet.prototype.removeWithIndexes = function() {
var index, item, items, removedIndexes, removedItems, _i, _len;
items = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
removedIndexes = [];
removedItems = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (!((index = this._indexOfItem(item)) !== -1)) {
continue;
}
this._storage.splice(index, 1);
removedItems.push(item);
removedIndexes.push(index);
}
this.length = this._storage.length;
return {
removedItems: removedItems,
removedIndexes: removedIndexes
};
};
SimpleSet.prototype.clear = function() {
var items;
items = this._storage;
this._storage = [];
this.length = 0;
return items;
};
SimpleSet.prototype.replace = function(other) {
this.clear();
return this.add.apply(this, other.toArray());
};
SimpleSet.prototype.has = function(item) {
return this._indexOfItem(item) !== -1;
};
SimpleSet.prototype.find = function(fn) {
var item, _i, _len, _ref;
_ref = this._storage;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
item = _ref[_i];
if (fn(item)) {
return item;
}
}
};
SimpleSet.prototype.forEach = function(iterator, ctx) {
var key, _i, _len, _ref;
_ref = this._storage;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
iterator.call(ctx, key, null, this);
}
};
SimpleSet.prototype.isEmpty = function() {
return this.length === 0;
};
SimpleSet.prototype.toArray = function() {
return this._storage.slice();
};
SimpleSet.prototype.merge = function() {
var merged, others, set, _i, _len;
others = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
merged = new this.constructor;
others.unshift(this);
for (_i = 0, _len = others.length; _i < _len; _i++) {
set = others[_i];
set.forEach(function(v) {
return merged.add(v);
});
}
return merged;
};
SimpleSet.prototype.indexedBy = function(key) {
this._indexes || (this._indexes = new Batman.SimpleHash);
return this._indexes.get(key) || this._indexes.set(key, new Batman.SetIndex(this, key));
};
SimpleSet.prototype.indexedByUnique = function(key) {
this._uniqueIndexes || (this._uniqueIndexes = new Batman.SimpleHash);
return this._uniqueIndexes.get(key) || this._uniqueIndexes.set(key, new Batman.UniqueSetIndex(this, key));
};
SimpleSet.prototype.sortedBy = function(key, order) {
var sortsForKey;
if (order == null) {
order = "asc";
}
order = order.toLowerCase() === "desc" ? "desc" : "asc";
this._sorts || (this._sorts = new Batman.SimpleHash);
sortsForKey = this._sorts.get(key) || this._sorts.set(key, new Batman.Object);
return sortsForKey.get(order) || sortsForKey.set(order, new Batman.SetSort(this, key, order));
};
SimpleSet.prototype.equality = Batman.SimpleHash.prototype.equality;
SimpleSet.prototype._indexOfItem = function(givenItem) {
var index, item, _i, _len, _ref;
_ref = this._storage;
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
item = _ref[index];
if (this.equality(givenItem, item)) {
return index;
}
}
return -1;
};
return SimpleSet;
})();
}).call(this);
(function() {
var SOURCE_TRACKER_STACK, SOURCE_TRACKER_STACK_VALID,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
SOURCE_TRACKER_STACK = [];
SOURCE_TRACKER_STACK_VALID = true;
Batman.Property = (function(_super) {
__extends(Property, _super);
Property._sourceTrackerStack = SOURCE_TRACKER_STACK;
Property._sourceTrackerStackValid = SOURCE_TRACKER_STACK_VALID;
Property.defaultAccessor = {
get: function(key) {
return this[key];
},
set: function(key, val) {
return this[key] = val;
},
unset: function(key) {
var x;
x = this[key];
delete this[key];
return x;
},
cache: false
};
Property.defaultAccessorForBase = function(base) {
var _ref;
return ((_ref = base._batman) != null ? _ref.getFirst('defaultAccessor') : void 0) || Batman.Property.defaultAccessor;
};
Property.accessorForBaseAndKey = function(base, key) {
var accessor, ancestor, _bm, _i, _len, _ref, _ref1, _ref2, _ref3;
if ((_bm = base._batman) != null) {
accessor = (_ref = _bm.keyAccessors) != null ? _ref.get(key) : void 0;
if (!accessor) {
_ref1 = _bm.ancestors();
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
ancestor = _ref1[_i];
accessor = (_ref2 = ancestor._batman) != null ? (_ref3 = _ref2.keyAccessors) != null ? _ref3.get(key) : void 0 : void 0;
if (accessor) {
break;
}
}
}
}
return accessor || this.defaultAccessorForBase(base);
};
Property.forBaseAndKey = function(base, key) {
if (base.isObservable) {
return base.property(key);
} else {
return new Batman.Keypath(base, key);
}
};
Property.withoutTracking = function(block) {
return this.wrapTrackingPrevention(block)();
};
Property.wrapTrackingPrevention = function(block) {
return function() {
Batman.Property.pushDummySourceTracker();
try {
return block.apply(this, arguments);
} finally {
Batman.Property.popSourceTracker();
}
};
};
Property.registerSource = function(obj) {
var set;
if (!(obj.isEventEmitter || obj instanceof Batman.Property)) {
return;
}
if (SOURCE_TRACKER_STACK_VALID) {
set = SOURCE_TRACKER_STACK[SOURCE_TRACKER_STACK.length - 1];
} else {
set = [];
SOURCE_TRACKER_STACK.push(set);
SOURCE_TRACKER_STACK_VALID = true;
}
if (set != null) {
set.push(obj);
}
return void 0;
};
Property.pushSourceTracker = function() {
if (SOURCE_TRACKER_STACK_VALID) {
return SOURCE_TRACKER_STACK_VALID = false;
} else {
return SOURCE_TRACKER_STACK.push([]);
}
};
Property.popSourceTracker = function() {
if (SOURCE_TRACKER_STACK_VALID) {
return SOURCE_TRACKER_STACK.pop();
} else {
SOURCE_TRACKER_STACK_VALID = true;
return void 0;
}
};
Property.pushDummySourceTracker = function() {
if (!SOURCE_TRACKER_STACK_VALID) {
SOURCE_TRACKER_STACK.push([]);
SOURCE_TRACKER_STACK_VALID = true;
}
return SOURCE_TRACKER_STACK.push(null);
};
function Property(base, key) {
this.base = base;
this.key = key;
}
Property.prototype._isolationCount = 0;
Property.prototype.cached = false;
Property.prototype.value = null;
Property.prototype.sources = null;
Property.prototype.isProperty = true;
Property.prototype.isDead = false;
Property.prototype.isBatchingChanges = false;
Property.prototype.registerAsMutableSource = function() {
return Batman.Property.registerSource(this);
};
Property.prototype.isEqual = function(other) {
return this.constructor === other.constructor && this.base === other.base && this.key === other.key;
};
Property.prototype.hashKey = function() {
return this._hashKey || (this._hashKey = "<Batman.Property base: " + (Batman.Hash.prototype.hashKeyFor(this.base)) + ", key: \"" + (Batman.Hash.prototype.hashKeyFor(this.key)) + "\">");
};
Property.prototype.accessor = function() {
return this._accessor || (this._accessor = this.constructor.accessorForBaseAndKey(this.base, this.key));
};
Property.prototype.eachObserver = function(iterator) {
var ancestor, handlers, key, object, property, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2;
key = this.key;
handlers = (_ref = this.handlers) != null ? _ref.slice() : void 0;
if (handlers) {
for (_i = 0, _len = handlers.length; _i < _len; _i++) {
object = handlers[_i];
iterator(object);
}
}
if (this.base.isObservable) {
_ref1 = this.base._batman.ancestors();
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
ancestor = _ref1[_j];
if (ancestor.isObservable && ancestor.hasProperty(key)) {
property = ancestor.property(key);
handlers = (_ref2 = property.handlers) != null ? _ref2.slice() : void 0;
if (handlers) {
for (_k = 0, _len2 = handlers.length; _k < _len2; _k++) {
object = handlers[_k];
iterator(object);
}
}
}
}
}
};
Property.prototype.observers = function() {
var results;
results = [];
this.eachObserver(function(observer) {
return results.push(observer);
});
return results;
};
Property.prototype.hasObservers = function() {
return this.observers().length > 0;
};
Property.prototype.updateSourcesFromTracker = function() {
var handler, newSources, source, _i, _j, _len, _len1, _ref, _ref1;
newSources = this.constructor.popSourceTracker();
handler = this.sourceChangeHandler();
if (this.sources) {
_ref = this.sources;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
source = _ref[_i];
if (source != null) {
if (source.on) {
source.off('change', handler);
} else {
source.removeHandler(handler);
}
}
}
}
this.sources = newSources;
if (this.sources) {
_ref1 = this.sources;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
source = _ref1[_j];
if (source != null) {
if (source.on) {
source.on('change', handler);
} else {
source.addHandler(handler);
}
}
}
}
return null;
};
Property.prototype.getValue = function() {
this.registerAsMutableSource();
if (!this.isCached()) {
this.constructor.pushSourceTracker();
try {
this.value = this.valueFromAccessor();
this.cached = true;
} finally {
this.updateSourcesFromTracker();
}
}
return this.value;
};
Property.prototype.isCachable = function() {
var cacheable;
if (this.isFinal()) {
return true;
}
cacheable = this.accessor().cache;
if (cacheable != null) {
return !!cacheable;
} else {
return true;
}
};
Property.prototype.isCached = function() {
return this.isCachable() && this.cached;
};
Property.prototype.isFinal = function() {
return this.final || (this.final = !!this.accessor()['final']);
};
Property.prototype.refresh = function() {
var previousValue, value;
this.cached = false;
previousValue = this.value;
value = this.getValue();
if (value !== previousValue && !this.isIsolated()) {
this.fire(value, previousValue, this.key);
}
if (this.value !== void 0 && this.isFinal()) {
return this.lockValue();
}
};
Property.prototype.sourceChangeHandler = function() {
var _this = this;
this._sourceChangeHandler || (this._sourceChangeHandler = this._handleSourceChange.bind(this));
Batman.developer["do"](function() {
return _this._sourceChangeHandler.property = _this;
});
return this._sourceChangeHandler;
};
Property.prototype._handleSourceChange = function() {
if (this.isIsolated()) {
return this._needsRefresh = true;
} else if (this.isDead) {
return this._removeHandlers();
} else if (!this.isFinal() && !this.hasObservers()) {
this.cached = false;
return this._removeHandlers();
} else if (!this.isBatchingChanges) {
return this.refresh();
}
};
Property.prototype.valueFromAccessor = function() {
var _ref;
return (_ref = this.accessor().get) != null ? _ref.call(this.base, this.key) : void 0;
};
Property.prototype.setValue = function(val) {
var set;
if (!(set = this.accessor().set)) {
return;
}
return this._changeValue(function() {
return set.call(this.base, this.key, val);
});
};
Property.prototype.unsetValue = function() {
var unset;
if (!(unset = this.accessor().unset)) {
return;
}
return this._changeValue(function() {
return unset.call(this.base, this.key);
});
};
Property.prototype._changeValue = function(block) {
var result;
this.cached = false;
this.constructor.pushDummySourceTracker();
try {
result = block.apply(this);
this.refresh();
} finally {
this.constructor.popSourceTracker();
}
if (!(this.isCached() || this.hasObservers())) {
this.die();
}
return result;
};
Property.prototype.forget = function(handler) {
if (handler != null) {
return this.removeHandler(handler);
} else {
return this.clearHandlers();
}
};
Property.prototype.observeAndFire = function(handler) {
this.observe(handler);
return handler.call(this.base, this.value, this.value, this.key);
};
Property.prototype.observe = function(handler) {
this.addHandler(handler);
if (this.sources == null) {
this.getValue();
}
return this;
};
Property.prototype.observeOnce = function(originalHandler) {
var handler, self;
self = this;
handler = function() {
originalHandler.apply(this, arguments);
return self.removeHandler(handler);
};
this.addHandler(handler);
if (this.sources == null) {
this.getValue();
}
return this;
};
Property.prototype._removeHandlers = function() {
var handler, source, _i, _len, _ref;
handler = this.sourceChangeHandler();
if (this.sources) {
_ref = this.sources;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
source = _ref[_i];
if (source.on) {
source.off('change', handler);
} else {
source.removeHandler(handler);
}
}
}
delete this.sources;
return this.clearHandlers();
};
Property.prototype.lockValue = function() {
this._removeHandlers();
this.getValue = function() {
return this.value;
};
return this.setValue = this.unsetValue = this.refresh = this.observe = function() {};
};
Property.prototype.die = function() {
var _ref, _ref1;
this._removeHandlers();
if ((_ref = this.base._batman) != null) {
if ((_ref1 = _ref.properties) != null) {
_ref1.unset(this.key);
}
}
this.base = null;
return this.isDead = true;
};
Property.prototype.isolate = function() {
if (this._isolationCount === 0) {
this._preIsolationValue = this.getValue();
}
return this._isolationCount++;
};
Property.prototype.expose = function() {
if (this._isolationCount === 1) {
this._isolationCount--;
if (this._needsRefresh) {
this.value = this._preIsolationValue;
this.refresh();
} else if (this.value !== this._preIsolationValue) {
this.fire(this.value, this._preIsolationValue, this.key);
}
return this._preIsolationValue = null;
} else if (this._isolationCount > 0) {
return this._isolationCount--;
}
};
Property.prototype.isIsolated = function() {
return this._isolationCount > 0;
};
return Property;
})(Batman.PropertyEvent);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Keypath = (function(_super) {
__extends(Keypath, _super);
function Keypath(base, key) {
if (typeof key === 'string') {
this.segments = key.split('.');
this.depth = this.segments.length;
} else {
this.segments = [key];
this.depth = 1;
}
Keypath.__super__.constructor.apply(this, arguments);
}
Keypath.prototype.isCachable = function() {
if (this.depth === 1) {
return Keypath.__super__.isCachable.apply(this, arguments);
} else {
return true;
}
};
Keypath.prototype.terminalProperty = function() {
var base;
base = Batman.getPath(this.base, this.segments.slice(0, -1));
if (base == null) {
return;
}
return Batman.Keypath.forBaseAndKey(base, this.segments[this.depth - 1]);
};
Keypath.prototype.valueFromAccessor = function() {
if (this.depth === 1) {
return Keypath.__super__.valueFromAccessor.apply(this, arguments);
} else {
return Batman.getPath(this.base, this.segments);
}
};
Keypath.prototype.setValue = function(val) {
var _ref;
if (this.depth === 1) {
return Keypath.__super__.setValue.apply(this, arguments);
} else {
return (_ref = this.terminalProperty()) != null ? _ref.setValue(val) : void 0;
}
};
Keypath.prototype.unsetValue = function() {
var _ref;
if (this.depth === 1) {
return Keypath.__super__.unsetValue.apply(this, arguments);
} else {
return (_ref = this.terminalProperty()) != null ? _ref.unsetValue() : void 0;
}
};
return Keypath;
})(Batman.Property);
}).call(this);
(function() {
var __slice = [].slice;
Batman.Observable = {
isObservable: true,
hasProperty: function(key) {
var _ref, _ref1;
return (_ref = this._batman) != null ? (_ref1 = _ref.properties) != null ? typeof _ref1.hasKey === "function" ? _ref1.hasKey(key) : void 0 : void 0 : void 0;
},
property: function(key) {
var properties, propertyClass, _base;
Batman.initializeObject(this);
propertyClass = this.propertyClass || Batman.Keypath;
properties = (_base = this._batman).properties || (_base.properties = new Batman.SimpleHash);
if (properties.objectKey(key)) {
return properties.getObject(key) || properties.setObject(key, new propertyClass(this, key));
} else {
return properties.getString(key) || properties.setString(key, new propertyClass(this, key));
}
},
get: function(key) {
return this.property(key).getValue();
},
set: function(key, val) {
return this.property(key).setValue(val);
},
unset: function(key) {
return this.property(key).unsetValue();
},
getOrSet: Batman.SimpleHash.prototype.getOrSet,
forget: function(key, observer) {
var _ref;
if (key) {
this.property(key).forget(observer);
} else {
if ((_ref = this._batman.properties) != null) {
_ref.forEach(function(key, property) {
return property.forget();
});
}
}
return this;
},
observe: function() {
var args, key, _ref;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
(_ref = this.property(key)).observe.apply(_ref, args);
return this;
},
observeAndFire: function() {
var args, key, _ref;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
(_ref = this.property(key)).observeAndFire.apply(_ref, args);
return this;
},
observeOnce: function() {
var args, key, _ref;
key = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
(_ref = this.property(key)).observeOnce.apply(_ref, args);
return this;
}
};
}).call(this);
(function() {
var methodName, platformMethods, _i, _len;
Batman.DOM = {
textInputTypes: ['text', 'search', 'tel', 'url', 'email', 'password'],
scrollIntoView: function(elementID) {
var _ref;
return (_ref = document.getElementById(elementID)) != null ? typeof _ref.scrollIntoView === "function" ? _ref.scrollIntoView() : void 0 : void 0;
},
setStyleProperty: function(node, property, value, importance) {
if (node.style.setProperty) {
return node.style.setProperty(property, value, importance);
} else {
return node.style.setAttribute(property, value, importance);
}
},
valueForNode: function(node, value, escapeValue) {
var child, isSetting, nodeName, _i, _len, _ref, _results;
if (value == null) {
value = '';
}
if (escapeValue == null) {
escapeValue = true;
}
isSetting = arguments.length > 1;
nodeName = node.nodeName.toUpperCase();
switch (nodeName) {
case 'INPUT':
case 'TEXTAREA':
if (isSetting) {
return node.value = value;
} else {
return node.value;
}
break;
case 'SELECT':
if (isSetting) {
return node.value = value;
} else if (node.multiple) {
_ref = node.children;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
if (child.selected) {
_results.push(child.value);
}
}
return _results;
} else {
return node.value;
}
break;
default:
if (isSetting) {
if (nodeName === 'OPTION') {
node.text = value;
}
return Batman.DOM.setInnerHTML(node, escapeValue ? Batman.escapeHTML(value) : value);
} else {
return node.innerHTML;
}
}
},
nodeIsEditable: function(node) {
var _ref;
return (_ref = node.nodeName.toUpperCase()) === 'INPUT' || _ref === 'TEXTAREA' || _ref === 'SELECT';
},
addEventListener: function(node, eventName, callback) {
var listeners;
if (!(listeners = Batman._data(node, 'listeners'))) {
listeners = Batman._data(node, 'listeners', {});
}
if (!listeners[eventName]) {
listeners[eventName] = [];
}
listeners[eventName].push(callback);
if (Batman.DOM.hasAddEventListener) {
return node.addEventListener(eventName, callback, false);
} else {
return node.attachEvent("on" + eventName, callback);
}
},
removeEventListener: function(node, eventName, callback) {
var eventListeners, index, listeners;
if (listeners = Batman._data(node, 'listeners')) {
if (eventListeners = listeners[eventName]) {
index = eventListeners.indexOf(callback);
if (index !== -1) {
eventListeners.splice(index, 1);
}
}
}
if (Batman.DOM.hasAddEventListener) {
return node.removeEventListener(eventName, callback, false);
} else {
return node.detachEvent('on' + eventName, callback);
}
},
cleanupNode: function(node) {
var child, eventListeners, eventName, listeners, _i, _len, _ref;
if (listeners = Batman._data(node, 'listeners')) {
for (eventName in listeners) {
eventListeners = listeners[eventName];
eventListeners.forEach(function(listener) {
return Batman.DOM.removeEventListener(node, eventName, listener);
});
}
}
Batman.removeData(node, null, null, true);
_ref = node.childNodes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
child = _ref[_i];
Batman.DOM.cleanupNode(child);
}
},
hasAddEventListener: !!(typeof window !== "undefined" && window !== null ? window.addEventListener : void 0),
preventDefault: function(e) {
if (typeof e.preventDefault === "function") {
return e.preventDefault();
} else {
return e.returnValue = false;
}
},
stopPropagation: function(e) {
if (e.stopPropagation) {
return e.stopPropagation();
} else {
return e.cancelBubble = true;
}
}
};
platformMethods = ['querySelector', 'querySelectorAll', 'setInnerHTML', 'containsNode', 'destroyNode', 'textContent'];
for (_i = 0, _len = platformMethods.length; _i < _len; _i++) {
methodName = platformMethods[_i];
Batman.DOM[methodName] = function() {
return Batman.developer.error("Please include a platform adapter to define " + methodName + ".");
};
}
}).call(this);
(function() {
Batman.DOM.ReaderBindingDefinition = (function() {
function ReaderBindingDefinition(node, keyPath, view) {
this.node = node;
this.keyPath = keyPath;
this.view = view;
}
return ReaderBindingDefinition;
})();
Batman.BindingDefinitionOnlyObserve = {
Data: 'data',
Node: 'node',
All: 'all',
None: 'none'
};
Batman.DOM.readers = {
target: function(definition) {
definition.onlyObserve = Batman.BindingDefinitionOnlyObserve.Node;
return Batman.DOM.readers.bind(definition);
},
source: function(definition) {
definition.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
return Batman.DOM.readers.bind(definition);
},
bind: function(definition) {
var bindingClass, node;
node = definition.node;
switch (node.nodeName.toLowerCase()) {
case 'input':
switch (node.getAttribute('type')) {
case 'checkbox':
definition.attr = 'checked';
Batman.DOM.attrReaders.bind(definition);
return true;
case 'radio':
bindingClass = Batman.DOM.RadioBinding;
break;
case 'file':
bindingClass = Batman.DOM.FileBinding;
}
break;
case 'select':
bindingClass = Batman.DOM.SelectBinding;
}
bindingClass || (bindingClass = Batman.DOM.ValueBinding);
return new bindingClass(definition);
},
context: function(definition) {
return new Batman.DOM.ContextBinding(definition);
},
showif: function(definition) {
return new Batman.DOM.ShowHideBinding(definition);
},
hideif: function(definition) {
definition.invert = true;
return new Batman.DOM.ShowHideBinding(definition);
},
insertif: function(definition) {
return new Batman.DOM.InsertionBinding(definition);
},
removeif: function(definition) {
definition.invert = true;
return new Batman.DOM.InsertionBinding(definition);
},
renderif: function(definition) {
return new Batman.DOM.DeferredRenderBinding(definition);
},
route: function(definition) {
return new Batman.DOM.RouteBinding(definition);
},
view: function(definition) {
return new Batman.DOM.ViewBinding(definition);
},
partial: function(definition) {
var keyPath, node, partialView, view;
node = definition.node, keyPath = definition.keyPath, view = definition.view;
node.removeAttribute('data-partial');
partialView = new Batman.View({
source: keyPath,
parentNode: node,
node: node
});
return {
skipChildren: true,
initialized: function() {
partialView.loadView(node);
return view.subviews.add(partialView);
}
};
},
defineview: function(definition) {
var keyPath, node, view;
node = definition.node, view = definition.view, keyPath = definition.keyPath;
Batman.View.store.set(Batman.Navigator.normalizePath(keyPath), node.innerHTML);
return {
skipChildren: true,
initialized: function() {
if (node.parentNode) {
return node.parentNode.removeChild(node);
}
}
};
},
contentfor: function(definition) {
var contentView, keyPath, node, view;
node = definition.node, keyPath = definition.keyPath, view = definition.view;
contentView = new Batman.View({
html: node.innerHTML,
contentFor: keyPath
});
contentView.addToParentNode = function(parentNode) {
parentNode.innerHTML = '';
return parentNode.appendChild(this.get('node'));
};
view.subviews.add(contentView);
return {
skipChildren: true,
initialized: function() {
if (node.parentNode) {
return node.parentNode.removeChild(node);
}
}
};
},
"yield": function(definition) {
var yieldObject;
yieldObject = Batman.DOM.Yield.withName(definition.keyPath);
yieldObject.set('containerNode', definition.node);
return {
skipChildren: true
};
}
};
}).call(this);
(function() {
var __slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Batman.DOM.events = {
click: function(node, callback, view, eventName, preventDefault) {
if (eventName == null) {
eventName = 'click';
}
if (preventDefault == null) {
preventDefault = true;
}
Batman.DOM.addEventListener(node, eventName, function() {
var args, event;
event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
if (event.metaKey || event.ctrlKey || event.button === 1) {
return;
}
if (preventDefault) {
Batman.DOM.preventDefault(event);
}
if (!Batman.DOM.eventIsAllowed(eventName, event)) {
return;
}
return callback.apply(null, [node, event].concat(__slice.call(args), [view]));
});
if (node.nodeName.toUpperCase() === 'A' && !node.href) {
node.href = '#';
}
return node;
},
doubleclick: function(node, callback, view) {
return Batman.DOM.events.click(node, callback, view, 'dblclick');
},
change: function(node, callback, view) {
var eventName, eventNames, oldCallback, _i, _len;
eventNames = (function() {
var _ref;
switch (node.nodeName.toUpperCase()) {
case 'TEXTAREA':
return ['input', 'keyup', 'change'];
case 'INPUT':
if (_ref = node.type.toLowerCase(), __indexOf.call(Batman.DOM.textInputTypes, _ref) >= 0) {
oldCallback = callback;
callback = function(node, event, view) {
if (event.type === 'keyup' && Batman.DOM.events.isEnter(event)) {
return;
}
return oldCallback(node, event, view);
};
return ['input', 'keyup', 'change'];
} else {
return ['input', 'change'];
}
break;
default:
return ['change'];
}
})();
for (_i = 0, _len = eventNames.length; _i < _len; _i++) {
eventName = eventNames[_i];
Batman.DOM.addEventListener(node, eventName, function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return callback.apply(null, [node].concat(__slice.call(args), [view]));
});
}
},
isEnter: function(ev) {
var _ref, _ref1;
return ((13 <= (_ref = ev.keyCode) && _ref <= 14)) || ((13 <= (_ref1 = ev.which) && _ref1 <= 14)) || ev.keyIdentifier === 'Enter' || ev.key === 'Enter';
},
submit: function(node, callback, view) {
if (Batman.DOM.nodeIsEditable(node)) {
Batman.DOM.addEventListener(node, 'keydown', function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (Batman.DOM.events.isEnter(args[0])) {
return Batman.DOM._keyCapturingNode = node;
}
});
Batman.DOM.addEventListener(node, 'keyup', function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (Batman.DOM.events.isEnter(args[0])) {
if (Batman.DOM._keyCapturingNode === node) {
Batman.DOM.preventDefault(args[0]);
callback.apply(null, [node].concat(__slice.call(args), [view]));
}
return Batman.DOM._keyCapturingNode = null;
}
});
} else {
Batman.DOM.addEventListener(node, 'submit', function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
Batman.DOM.preventDefault(args[0]);
return callback.apply(null, [node].concat(__slice.call(args), [view]));
});
}
return node;
},
other: function(node, eventName, callback, view) {
return Batman.DOM.addEventListener(node, eventName, function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return callback.apply(null, [node].concat(__slice.call(args), [view]));
});
}
};
Batman.DOM.eventIsAllowed = function(eventName, event) {
var delegate, _ref, _ref1;
if (delegate = (_ref = Batman.currentApp) != null ? (_ref1 = _ref.shouldAllowEvent) != null ? _ref1[eventName] : void 0 : void 0) {
if (delegate(event) === false) {
return false;
}
}
return true;
};
}).call(this);
(function() {
Batman.DOM.AttrReaderBindingDefinition = (function() {
function AttrReaderBindingDefinition(node, attr, keyPath, view) {
this.node = node;
this.attr = attr;
this.keyPath = keyPath;
this.view = view;
}
return AttrReaderBindingDefinition;
})();
Batman.DOM.attrReaders = {
_parseAttribute: function(value) {
if (value === 'false') {
value = false;
}
if (value === 'true') {
value = true;
}
return value;
},
source: function(definition) {
definition.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
return Batman.DOM.attrReaders.bind(definition);
},
bind: function(definition) {
var bindingClass;
bindingClass = (function() {
switch (definition.attr) {
case 'checked':
case 'disabled':
case 'selected':
return Batman.DOM.CheckedBinding;
case 'value':
case 'href':
case 'src':
case 'size':
return Batman.DOM.NodeAttributeBinding;
case 'class':
return Batman.DOM.ClassBinding;
case 'style':
return Batman.DOM.StyleBinding;
default:
return Batman.DOM.AttributeBinding;
}
})();
return new bindingClass(definition);
},
context: function(definition) {
return new Batman.DOM.ContextBinding(definition);
},
event: function(definition) {
return new Batman.DOM.EventBinding(definition);
},
track: function(definition) {
if (definition.attr === 'view') {
return new Batman.DOM.ViewTrackingBinding(definition);
} else if (definition.attr === 'click') {
return new Batman.DOM.ClickTrackingBinding(definition);
}
},
addclass: function(definition) {
return new Batman.DOM.AddClassBinding(definition);
},
removeclass: function(definition) {
definition.invert = true;
return new Batman.DOM.AddClassBinding(definition);
},
foreach: function(definition) {
return new Batman.DOM.IteratorBinding(definition);
},
formfor: function(definition) {
return new Batman.DOM.FormBinding(definition);
},
style: function(definition) {
return new Batman.DOM.StyleAttributeBinding(definition);
}
};
}).call(this);
(function() {
var BatmanObject, ObjectFunctions, getAccessorObject, promiseWrapper, wrapSingleAccessor,
__slice = [].slice,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
getAccessorObject = function(base, accessor) {
var deprecated, _i, _len, _ref;
if (typeof accessor === 'function') {
accessor = {
get: accessor
};
}
_ref = ['cachable', 'cacheable'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
deprecated = _ref[_i];
if (deprecated in accessor) {
Batman.developer.warn("Property accessor option \"" + deprecated + "\" is deprecated. Use \"cache\" instead.");
if (!('cache' in accessor)) {
accessor.cache = accessor[deprecated];
}
}
}
return accessor;
};
promiseWrapper = function(fetcher) {
return function(defaultAccessor) {
return {
get: function(key) {
var asyncDeliver, existingValue, newValue, _base, _base1,
_this = this;
if ((existingValue = defaultAccessor.get.apply(this, arguments)) != null) {
return existingValue;
}
asyncDeliver = false;
newValue = void 0;
if ((_base = this._batman).promises == null) {
_base.promises = {};
}
if ((_base1 = this._batman.promises)[key] == null) {
_base1[key] = (function() {
var deliver, returnValue;
deliver = function(err, result) {
if (asyncDeliver) {
_this.set(key, result);
}
return newValue = result;
};
returnValue = fetcher.call(_this, deliver, key);
if (newValue == null) {
newValue = returnValue;
}
return true;
})();
}
asyncDeliver = true;
return newValue;
},
cache: true
};
};
};
wrapSingleAccessor = function(core, wrapper) {
var k, v;
wrapper = (typeof wrapper === "function" ? wrapper(core) : void 0) || wrapper;
for (k in core) {
v = core[k];
if (!(k in wrapper)) {
wrapper[k] = v;
}
}
return wrapper;
};
ObjectFunctions = {
_defineAccessor: function() {
var accessor, key, keys, _base, _i, _j, _len, _ref;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), accessor = arguments[_i++];
if (accessor == null) {
return Batman.Property.defaultAccessorForBase(this);
} else if (keys.length === 0 && ((_ref = Batman.typeOf(accessor)) !== 'Object' && _ref !== 'Function')) {
return Batman.Property.accessorForBaseAndKey(this, accessor);
} else if (typeof accessor.promise === 'function') {
return this._defineWrapAccessor.apply(this, __slice.call(keys).concat([promiseWrapper(accessor.promise)]));
}
Batman.initializeObject(this);
if (keys.length === 0) {
this._batman.defaultAccessor = getAccessorObject(this, accessor);
} else {
(_base = this._batman).keyAccessors || (_base.keyAccessors = new Batman.SimpleHash);
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
this._batman.keyAccessors.set(key, getAccessorObject(this, accessor));
}
}
return true;
},
_defineWrapAccessor: function() {
var key, keys, wrapper, _i, _j, _len;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), wrapper = arguments[_i++];
Batman.initializeObject(this);
if (keys.length === 0) {
this._defineAccessor(wrapSingleAccessor(this._defineAccessor(), wrapper));
} else {
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
this._defineAccessor(key, wrapSingleAccessor(this._defineAccessor(key), wrapper));
}
}
return true;
},
_resetPromises: function() {
var key;
if (this._batman.promises == null) {
return;
}
for (key in this._batman.promises) {
this._resetPromise(key);
}
},
_resetPromise: function(key) {
this.unset(key);
this.property(key).cached = false;
delete this._batman.promises[key];
}
};
BatmanObject = (function(_super) {
var counter;
__extends(BatmanObject, _super);
Batman.initializeObject(BatmanObject);
Batman.initializeObject(BatmanObject.prototype);
Batman.mixin(BatmanObject.prototype, ObjectFunctions, Batman.EventEmitter, Batman.Observable);
Batman.mixin(BatmanObject, ObjectFunctions, Batman.EventEmitter, Batman.Observable);
BatmanObject.classMixin = function() {
return Batman.mixin.apply(Batman, [this].concat(__slice.call(arguments)));
};
BatmanObject.mixin = function() {
return this.classMixin.apply(this.prototype, arguments);
};
BatmanObject.prototype.mixin = BatmanObject.classMixin;
BatmanObject.classAccessor = BatmanObject._defineAccessor;
BatmanObject.accessor = function() {
var _ref;
return (_ref = this.prototype)._defineAccessor.apply(_ref, arguments);
};
BatmanObject.prototype.accessor = BatmanObject._defineAccessor;
BatmanObject.wrapClassAccessor = BatmanObject._defineWrapAccessor;
BatmanObject.wrapAccessor = function() {
var _ref;
return (_ref = this.prototype)._defineWrapAccessor.apply(_ref, arguments);
};
BatmanObject.prototype.wrapAccessor = BatmanObject._defineWrapAccessor;
BatmanObject.observeAll = function() {
return this.prototype.observe.apply(this.prototype, arguments);
};
BatmanObject.singleton = function(singletonMethodName) {
if (singletonMethodName == null) {
singletonMethodName = "sharedInstance";
}
return this.classAccessor(singletonMethodName, {
get: function() {
var _name;
return this[_name = "_" + singletonMethodName] || (this[_name] = new this);
}
});
};
BatmanObject.accessor('_batmanID', function() {
return this._batmanID();
});
BatmanObject.delegate = function() {
var options, properties, _i,
_this = this;
properties = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), options = arguments[_i++];
if (options == null) {
options = {};
}
if (!options.to) {
Batman.developer.warn('delegate must include to option', this, properties);
}
return properties.forEach(function(property) {
return _this.accessor(property, function() {
var _ref;
return (_ref = this.get(options.to)) != null ? _ref.get(property) : void 0;
});
});
};
function BatmanObject() {
var mixins;
mixins = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
this._batman = new Batman._Batman(this);
this.mixin.apply(this, mixins);
}
counter = 0;
BatmanObject.prototype._batmanID = function() {
var _base;
this._batman.check(this);
if ((_base = this._batman).id == null) {
_base.id = counter++;
}
return this._batman.id;
};
BatmanObject.prototype.hashKey = function() {
var _base;
if (typeof this.isEqual === 'function') {
return;
}
return (_base = this._batman).hashKey || (_base.hashKey = "<Batman.Object " + (this._batmanID()) + ">");
};
BatmanObject.prototype.toJSON = function() {
var key, obj, value;
obj = {};
for (key in this) {
if (!__hasProp.call(this, key)) continue;
value = this[key];
if (key !== "_batman" && key !== "hashKey" && key !== "_batmanID") {
obj[key] = (value != null ? value.toJSON : void 0) ? value.toJSON() : value;
}
}
return obj;
};
BatmanObject.prototype.batchAccessorChanges = function() {
var i, key, properties, property, result, wrappedFunction, _i, _j, _k, _len, _len1;
properties = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), wrappedFunction = arguments[_i++];
for (i = _j = 0, _len = properties.length; _j < _len; i = ++_j) {
key = properties[i];
property = properties[i] = this.property(key);
property.isBatchingChanges = true;
}
result = wrappedFunction.call(this);
for (_k = 0, _len1 = properties.length; _k < _len1; _k++) {
property = properties[_k];
property.isBatchingChanges = false;
property.refresh();
}
return result;
};
return BatmanObject;
})(Object);
Batman.Object = BatmanObject;
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.BindingParser = (function(_super) {
var bindingSortOrder, bindingSortPositions, name, pos, viewBackedBindings, _i, _len;
__extends(BindingParser, _super);
function BindingParser(view) {
this.view = view;
BindingParser.__super__.constructor.call(this);
this.node = this.view.node;
this.parseTree(this.node);
}
bindingSortOrder = ["defineview", "foreach", "renderif", "view", "formfor", "context", "bind", "source", "target", "track", "event"];
viewBackedBindings = ["foreach", "renderif", "formfor", "context"];
bindingSortPositions = {};
for (pos = _i = 0, _len = bindingSortOrder.length; _i < _len; pos = ++_i) {
name = bindingSortOrder[pos];
bindingSortPositions[name] = pos;
}
BindingParser.prototype._sortBindings = function(a, b) {
var aindex, bindex;
aindex = bindingSortPositions[a[0]];
bindex = bindingSortPositions[b[0]];
if (aindex == null) {
aindex = bindingSortOrder.length;
}
if (bindex == null) {
bindex = bindingSortOrder.length;
}
if (aindex > bindex) {
return 1;
} else if (bindex > aindex) {
return -1;
} else if (a[0] > b[0]) {
return 1;
} else if (b[0] > a[0]) {
return -1;
} else {
return 0;
}
};
BindingParser.prototype.parseTree = function(root) {
var skipChildren;
while (root) {
skipChildren = this.parseNode(root);
root = this.nextNode(root, skipChildren);
}
this.fire('bindingsInitialized');
};
BindingParser.prototype.parseNode = function(node) {
var attr, attrIndex, attribute, backingView, binding, bindingDefinition, bindings, isViewBacked, reader, value, _j, _k, _len1, _len2, _ref, _ref1, _ref2, _ref3;
isViewBacked = false;
if (node.getAttribute && node.attributes) {
bindings = [];
_ref = node.attributes;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
attribute = _ref[_j];
if (((_ref1 = attribute.nodeName) != null ? _ref1.substr(0, 5) : void 0) !== "data-") {
continue;
}
name = attribute.nodeName.substr(5);
attrIndex = name.indexOf('-');
bindings.push(attrIndex !== -1 ? [name.substr(0, attrIndex), name.substr(attrIndex + 1), attribute.value] : [name, void 0, attribute.value]);
}
_ref2 = bindings.sort(this._sortBindings);
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
_ref3 = _ref2[_k], name = _ref3[0], attr = _ref3[1], value = _ref3[2];
if (isViewBacked && viewBackedBindings.indexOf(name) === -1) {
continue;
}
binding = attr ? (reader = Batman.DOM.attrReaders[name]) ? (bindingDefinition = new Batman.DOM.AttrReaderBindingDefinition(node, attr, value, this.view), reader(bindingDefinition)) : void 0 : (reader = Batman.DOM.readers[name]) ? (bindingDefinition = new Batman.DOM.ReaderBindingDefinition(node, value, this.view), reader(bindingDefinition)) : void 0;
if (binding != null ? binding.initialized : void 0) {
this.once('bindingsInitialized', (function(binding) {
return function() {
return binding.initialized.call(binding);
};
})(binding));
}
if (binding != null ? binding.skipChildren : void 0) {
return true;
}
if (binding != null ? binding.backWithView : void 0) {
isViewBacked = true;
}
}
}
if (isViewBacked && (backingView = Batman._data(node, 'view'))) {
backingView.initializeBindings();
}
return isViewBacked;
};
BindingParser.prototype.nextNode = function(node, skipChildren) {
var children, nextParent, parentSibling, sibling;
if (!skipChildren) {
children = node.childNodes;
if (children != null ? children.length : void 0) {
return children[0];
}
}
sibling = node.nextSibling;
if (this.node === node) {
return;
}
if (sibling) {
return sibling;
}
nextParent = node;
while (nextParent = nextParent.parentNode) {
parentSibling = nextParent.nextSibling;
if (this.node === nextParent) {
return;
}
if (parentSibling) {
return parentSibling;
}
}
};
return BindingParser;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ValidationError = (function(_super) {
__extends(ValidationError, _super);
ValidationError.accessor('fullMessage', function() {
if (this.attribute === 'base') {
return Batman.t('errors.base.format', {
message: this.message
});
} else {
return Batman.t('errors.format', {
attribute: Batman.helpers.humanize(this.attribute),
message: this.message
});
}
});
function ValidationError(attribute, message) {
ValidationError.__super__.constructor.call(this, {
attribute: attribute,
message: message
});
}
return ValidationError;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.StorageAdapter = (function(_super) {
__extends(StorageAdapter, _super);
StorageAdapter.StorageError = (function(_super1) {
__extends(StorageError, _super1);
StorageError.prototype.name = "StorageError";
function StorageError(message) {
StorageError.__super__.constructor.apply(this, arguments);
this.message = message;
}
return StorageError;
})(Error);
StorageAdapter.RecordExistsError = (function(_super1) {
__extends(RecordExistsError, _super1);
RecordExistsError.prototype.name = 'RecordExistsError';
function RecordExistsError(message) {
RecordExistsError.__super__.constructor.call(this, message || "Can't create this record because it already exists in the store!");
}
return RecordExistsError;
})(StorageAdapter.StorageError);
StorageAdapter.NotFoundError = (function(_super1) {
__extends(NotFoundError, _super1);
NotFoundError.prototype.name = 'NotFoundError';
function NotFoundError(message) {
NotFoundError.__super__.constructor.call(this, message || "Record couldn't be found in storage!");
}
return NotFoundError;
})(StorageAdapter.StorageError);
StorageAdapter.UnauthorizedError = (function(_super1) {
__extends(UnauthorizedError, _super1);
UnauthorizedError.prototype.name = 'UnauthorizedError';
function UnauthorizedError(message) {
UnauthorizedError.__super__.constructor.call(this, message || "Storage operation denied due to invalid credentials!");
}
return UnauthorizedError;
})(StorageAdapter.StorageError);
StorageAdapter.NotAllowedError = (function(_super1) {
__extends(NotAllowedError, _super1);
NotAllowedError.prototype.name = "NotAllowedError";
function NotAllowedError(message) {
NotAllowedError.__super__.constructor.call(this, message || "Storage operation denied access to the operation!");
}
return NotAllowedError;
})(StorageAdapter.StorageError);
StorageAdapter.NotAcceptableError = (function(_super1) {
__extends(NotAcceptableError, _super1);
NotAcceptableError.prototype.name = "NotAcceptableError";
function NotAcceptableError(message) {
NotAcceptableError.__super__.constructor.call(this, message || "Storage operation permitted but the request was malformed!");
}
return NotAcceptableError;
})(StorageAdapter.StorageError);
StorageAdapter.UnprocessableRecordError = (function(_super1) {
__extends(UnprocessableRecordError, _super1);
UnprocessableRecordError.prototype.name = "UnprocessableRecordError";
function UnprocessableRecordError(message) {
UnprocessableRecordError.__super__.constructor.call(this, message || "Storage adapter could not process the record!");
}
return UnprocessableRecordError;
})(StorageAdapter.StorageError);
StorageAdapter.InternalStorageError = (function(_super1) {
__extends(InternalStorageError, _super1);
InternalStorageError.prototype.name = "InternalStorageError";
function InternalStorageError(message) {
InternalStorageError.__super__.constructor.call(this, message || "An error occurred during the storage operation!");
}
return InternalStorageError;
})(StorageAdapter.StorageError);
StorageAdapter.NotImplementedError = (function(_super1) {
__extends(NotImplementedError, _super1);
NotImplementedError.prototype.name = "NotImplementedError";
function NotImplementedError(message) {
NotImplementedError.__super__.constructor.call(this, message || "This operation is not implemented by the storage adapter!");
}
return NotImplementedError;
})(StorageAdapter.StorageError);
function StorageAdapter(model) {
var constructor;
StorageAdapter.__super__.constructor.call(this, {
model: model
});
constructor = this.constructor;
if (constructor.ModelMixin) {
Batman.extend(model, constructor.ModelMixin);
}
if (constructor.RecordMixin) {
Batman.extend(model.prototype, constructor.RecordMixin);
}
}
StorageAdapter.prototype.isStorageAdapter = true;
StorageAdapter.prototype.storageKey = function(record) {
var model;
model = (record != null ? record.constructor : void 0) || this.model;
return model.get('storageKey') || Batman.helpers.pluralize(Batman.helpers.underscore(model.get('resourceName')));
};
StorageAdapter.prototype.getRecordFromData = function(attributes, constructor) {
if (constructor == null) {
constructor = this.model;
}
return constructor._makeOrFindRecordFromData(attributes);
};
StorageAdapter.prototype.getRecordsFromData = function(attributeSet, constructor) {
if (constructor == null) {
constructor = this.model;
}
return constructor._makeOrFindRecordsFromData(attributeSet);
};
StorageAdapter.skipIfError = function(f) {
return function(env, next) {
if (env.error != null) {
return next();
} else {
return f.call(this, env, next);
}
};
};
StorageAdapter.prototype.before = function() {
return this._addFilter.apply(this, ['before'].concat(__slice.call(arguments)));
};
StorageAdapter.prototype.after = function() {
return this._addFilter.apply(this, ['after'].concat(__slice.call(arguments)));
};
StorageAdapter.prototype._inheritFilters = function() {
var filtersByKey, filtersList, key, oldFilters, position;
if (!this._batman.check(this) || !this._batman.filters) {
oldFilters = this._batman.getFirst('filters');
this._batman.filters = {
before: {},
after: {}
};
if (oldFilters != null) {
for (position in oldFilters) {
filtersByKey = oldFilters[position];
for (key in filtersByKey) {
filtersList = filtersByKey[key];
this._batman.filters[position][key] = filtersList.slice(0);
}
}
}
}
return true;
};
StorageAdapter.prototype._addFilter = function() {
var filter, key, keys, position, _base, _i, _j, _len;
position = arguments[0], keys = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), filter = arguments[_i++];
this._inheritFilters();
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
(_base = this._batman.filters[position])[key] || (_base[key] = []);
this._batman.filters[position][key].push(filter);
}
return true;
};
StorageAdapter.prototype.runFilter = function(position, action, env, callback) {
var actionFilters, allFilters, filters, next,
_this = this;
this._inheritFilters();
allFilters = this._batman.filters[position].all || [];
actionFilters = this._batman.filters[position][action] || [];
env.action = action;
filters = position === 'before' ? actionFilters.concat(allFilters) : allFilters.concat(actionFilters);
next = function(newEnv) {
var nextFilter;
if (newEnv != null) {
env = newEnv;
}
if ((nextFilter = filters.shift()) != null) {
return nextFilter.call(_this, env, next);
} else {
return callback.call(_this, env);
}
};
return next();
};
StorageAdapter.prototype.runBeforeFilter = function() {
return this.runFilter.apply(this, ['before'].concat(__slice.call(arguments)));
};
StorageAdapter.prototype.runAfterFilter = function(action, env, callback) {
return this.runFilter('after', action, env, this.exportResult(callback));
};
StorageAdapter.prototype.exportResult = function(callback) {
return function(env) {
return callback(env.error, env.result, env);
};
};
StorageAdapter.prototype._jsonToAttributes = function(json) {
return JSON.parse(json);
};
StorageAdapter.prototype.perform = function(key, subject, options, callback) {
var env, next,
_this = this;
options || (options = {});
env = {
options: options,
subject: subject
};
next = function(newEnv) {
if (newEnv != null) {
env = newEnv;
}
return _this.runAfterFilter(key, env, callback);
};
this.runBeforeFilter(key, env, function(env) {
return this[key](env, next);
});
return void 0;
};
return StorageAdapter;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Batman.RestStorage = (function(_super) {
var key, _fn, _i, _len, _ref,
_this = this;
__extends(RestStorage, _super);
RestStorage.CommunicationError = (function(_super1) {
__extends(CommunicationError, _super1);
CommunicationError.prototype.name = 'CommunicationError';
function CommunicationError(message) {
CommunicationError.__super__.constructor.call(this, message || "A communication error has occurred!");
}
return CommunicationError;
})(RestStorage.StorageError);
RestStorage.JSONContentType = 'application/json';
RestStorage.PostBodyContentType = 'application/x-www-form-urlencoded';
RestStorage.BaseMixin = {
request: function(action, options, callback) {
if (!callback) {
callback = options;
options = {};
}
options.method || (options.method = 'GET');
options.action = action;
return this._doStorageOperation(options.method.toLowerCase(), options, callback);
}
};
RestStorage.ModelMixin = Batman.extend({}, RestStorage.BaseMixin, {
urlNestsUnder: function() {
var key, keys, parents, _i, _len;
keys = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
parents = {};
for (_i = 0, _len = keys.length; _i < _len; _i++) {
key = keys[_i];
parents[key + '_id'] = Batman.helpers.pluralize(key);
}
this.url = function(options) {
var childSegment, parentID, plural;
childSegment = Batman.helpers.pluralize(this.get('resourceName').toLowerCase());
for (key in parents) {
plural = parents[key];
parentID = options.data[key];
if (parentID) {
delete options.data[key];
return "" + plural + "/" + parentID + "/" + childSegment;
}
}
return childSegment;
};
return this.prototype.url = function() {
var childSegment, id, parentID, plural, url;
childSegment = Batman.helpers.pluralize(this.constructor.get('resourceName').toLowerCase());
for (key in parents) {
plural = parents[key];
parentID = this.get('dirtyKeys').get(key);
if (parentID === void 0) {
parentID = this.get(key);
}
if (parentID) {
url = "" + plural + "/" + parentID + "/" + childSegment;
break;
}
}
url || (url = childSegment);
if (id = this.get('id')) {
url += '/' + id;
}
return url;
};
}
});
RestStorage.RecordMixin = Batman.extend({}, RestStorage.BaseMixin);
RestStorage.prototype.defaultRequestOptions = {
type: 'json'
};
RestStorage.prototype._implicitActionNames = ['create', 'read', 'update', 'destroy', 'readAll'];
RestStorage.prototype.serializeAsForm = true;
function RestStorage() {
RestStorage.__super__.constructor.apply(this, arguments);
this.defaultRequestOptions = Batman.extend({}, this.defaultRequestOptions);
}
RestStorage.prototype.recordJsonNamespace = function(record) {
return Batman.helpers.singularize(this.storageKey(record));
};
RestStorage.prototype.collectionJsonNamespace = function(constructor) {
return Batman.helpers.pluralize(this.storageKey(constructor.prototype));
};
RestStorage.prototype._execWithOptions = function(object, key, options, context) {
if (context == null) {
context = object;
}
if (typeof object[key] === 'function') {
return object[key].call(context, options);
} else {
return object[key];
}
};
RestStorage.prototype._defaultCollectionUrl = function(model) {
return "" + (this.storageKey(model.prototype));
};
RestStorage.prototype._addParams = function(url, options) {
var _ref;
if (options && options.action && !(_ref = options.action, __indexOf.call(this._implicitActionNames, _ref) >= 0)) {
url += '/' + options.action.toLowerCase();
}
return url;
};
RestStorage.prototype._addUrlAffixes = function(url, subject, env) {
var prefix, segments;
segments = [url, this.urlSuffix(subject, env)];
if (url.charAt(0) !== '/') {
prefix = this.urlPrefix(subject, env);
if (prefix.charAt(prefix.length - 1) !== '/') {
segments.unshift('/');
}
segments.unshift(prefix);
}
return segments.join('');
};
RestStorage.prototype.urlPrefix = function(object, env) {
return this._execWithOptions(object, 'urlPrefix', env.options) || '';
};
RestStorage.prototype.urlSuffix = function(object, env) {
return this._execWithOptions(object, 'urlSuffix', env.options) || '';
};
RestStorage.prototype.urlForRecord = function(record, env) {
var id, url, _ref;
if ((_ref = env.options) != null ? _ref.recordUrl : void 0) {
url = this._execWithOptions(env.options, 'recordUrl', env.options, record);
} else if (record.url) {
url = this._execWithOptions(record, 'url', env.options);
} else {
url = record.constructor.url ? this._execWithOptions(record.constructor, 'url', env.options) : this._defaultCollectionUrl(record.constructor);
if (env.action !== 'create') {
if ((id = record.get('id')) != null) {
url = url + "/" + id;
} else {
throw new this.constructor.StorageError("Couldn't get/set record primary key on " + env.action + "!");
}
}
}
return this._addUrlAffixes(this._addParams(url, env.options), record, env);
};
RestStorage.prototype.urlForCollection = function(model, env) {
var url, _ref;
url = ((_ref = env.options) != null ? _ref.collectionUrl : void 0) ? this._execWithOptions(env.options, 'collectionUrl', env.options, env.options.urlContext) : model.url ? this._execWithOptions(model, 'url', env.options) : this._defaultCollectionUrl(model, env.options);
return this._addUrlAffixes(this._addParams(url, env.options), model, env);
};
RestStorage.prototype.request = function(env, next) {
var options;
options = Batman.extend(env.options, {
autosend: false,
success: function(data) {
return env.data = data;
},
error: function(error) {
return env.error = error;
},
loaded: function() {
env.response = env.request.get('response');
return next();
}
});
env.request = new Batman.Request(options);
return env.request.send();
};
RestStorage.prototype.perform = function(key, record, options, callback) {
options || (options = {});
Batman.extend(options, this.defaultRequestOptions);
return RestStorage.__super__.perform.call(this, key, record, options, callback);
};
RestStorage.prototype.before('all', RestStorage.skipIfError(function(env, next) {
var error;
if (!env.options.url) {
try {
env.options.url = env.subject.prototype ? this.urlForCollection(env.subject, env) : this.urlForRecord(env.subject, env);
} catch (_error) {
error = _error;
env.error = error;
}
}
return next();
}));
RestStorage.prototype.before('get', 'put', 'post', 'delete', RestStorage.skipIfError(function(env, next) {
env.options.method = env.action.toUpperCase();
return next();
}));
RestStorage.prototype.before('create', 'update', RestStorage.skipIfError(function(env, next) {
var data, json, namespace;
json = env.subject.toJSON();
if (namespace = this.recordJsonNamespace(env.subject)) {
data = {};
data[namespace] = json;
} else {
data = json;
}
env.options.data = data;
return next();
}));
RestStorage.prototype.before('create', 'update', 'put', 'post', RestStorage.skipIfError(function(env, next) {
if (this.serializeAsForm) {
env.options.contentType = this.constructor.PostBodyContentType;
} else {
if (env.options.data != null) {
env.options.data = JSON.stringify(env.options.data);
env.options.contentType = this.constructor.JSONContentType;
}
}
return next();
}));
RestStorage.prototype.after('all', RestStorage.skipIfError(function(env, next) {
var error, json;
if (env.data == null) {
return next();
}
if (typeof env.data === 'string') {
if (env.data.length > 0) {
try {
json = this._jsonToAttributes(env.data);
} catch (_error) {
error = _error;
env.error = error;
return next();
}
}
} else if (typeof env.data === 'object') {
json = env.data;
}
if (json != null) {
env.json = json;
}
return next();
}));
RestStorage.prototype.extractFromNamespace = function(data, namespace) {
if (namespace && (data[namespace] != null)) {
return data[namespace];
} else {
return data;
}
};
RestStorage.prototype.after('create', 'read', 'update', RestStorage.skipIfError(function(env, next) {
var json;
if (env.json != null) {
json = this.extractFromNamespace(env.json, this.recordJsonNamespace(env.subject));
env.subject._withoutDirtyTracking(function() {
return this.fromJSON(json);
});
}
env.result = env.subject;
return next();
}));
RestStorage.prototype.after('readAll', RestStorage.skipIfError(function(env, next) {
var namespace;
namespace = this.collectionJsonNamespace(env.subject);
env.recordsAttributes = this.extractFromNamespace(env.json, namespace);
if (Batman.typeOf(env.recordsAttributes) !== 'Array') {
namespace = this.recordJsonNamespace(env.subject.prototype);
env.recordsAttributes = [this.extractFromNamespace(env.json, namespace)];
}
env.result = env.records = this.getRecordsFromData(env.recordsAttributes, env.subject);
return next();
}));
RestStorage.prototype.after('get', 'put', 'post', 'delete', RestStorage.skipIfError(function(env, next) {
var namespace;
if (env.json != null) {
namespace = env.subject.prototype ? this.collectionJsonNamespace(env.subject) : this.recordJsonNamespace(env.subject);
env.result = this.extractFromNamespace(env.json, namespace);
}
return next();
}));
RestStorage.HTTPMethods = {
create: 'POST',
update: 'PUT',
read: 'GET',
readAll: 'GET',
destroy: 'DELETE'
};
_ref = ['create', 'read', 'update', 'destroy', 'readAll', 'get', 'post', 'put', 'delete'];
_fn = function(key) {
return RestStorage.prototype[key] = RestStorage.skipIfError(function(env, next) {
var _base;
(_base = env.options).method || (_base.method = this.constructor.HTTPMethods[key]);
return this.request(env, next);
});
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
_fn(key);
}
RestStorage.prototype.after('all', function(env, next) {
if (env.error) {
env.error = this._errorFor(env.error, env);
}
return next();
});
RestStorage._statusCodeErrors = {
'0': RestStorage.CommunicationError,
'401': RestStorage.UnauthorizedError,
'403': RestStorage.NotAllowedError,
'404': RestStorage.NotFoundError,
'406': RestStorage.NotAcceptableError,
'409': RestStorage.RecordExistsError,
'422': RestStorage.UnprocessableRecordError,
'500': RestStorage.InternalStorageError,
'501': RestStorage.NotImplementedError
};
RestStorage.prototype._errorFor = function(error, env) {
var errorClass, request;
if (error instanceof Error || (error.request == null)) {
return error;
}
if (errorClass = this.constructor._statusCodeErrors[error.request.status]) {
request = error.request;
error = new errorClass;
error.request = request;
error.env = env;
}
return error;
};
return RestStorage;
}).call(this, Batman.StorageAdapter);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.LocalStorage = (function(_super) {
__extends(LocalStorage, _super);
function LocalStorage() {
if (typeof window.localStorage === 'undefined') {
return null;
}
LocalStorage.__super__.constructor.apply(this, arguments);
this.storage = localStorage;
}
LocalStorage.prototype.storageRegExpForRecord = function(record) {
return new RegExp("^" + (this.storageKey(record)) + "(\\d+)$");
};
LocalStorage.prototype.nextIdForRecord = function(record) {
var nextId, re;
re = this.storageRegExpForRecord(record);
nextId = 1;
this._forAllStorageEntries(function(k, v) {
var matches;
if (matches = re.exec(k)) {
return nextId = Math.max(nextId, parseInt(matches[1], 10) + 1);
}
});
return nextId;
};
LocalStorage.prototype._forAllStorageEntries = function(iterator) {
var i, key, _i, _ref;
for (i = _i = 0, _ref = this.storage.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
key = this.storage.key(i);
iterator.call(this, key, this.storage.getItem(key));
}
return true;
};
LocalStorage.prototype._storageEntriesMatching = function(constructor, options) {
var re, records;
re = this.storageRegExpForRecord(constructor.prototype);
records = [];
this._forAllStorageEntries(function(storageKey, storageString) {
var data, keyMatches;
if (keyMatches = re.exec(storageKey)) {
data = this._jsonToAttributes(storageString);
data[constructor.primaryKey] = keyMatches[1];
if (this._dataMatches(options, data)) {
return records.push(data);
}
}
});
return records;
};
LocalStorage.prototype._dataMatches = function(conditions, data) {
var k, match, v;
match = true;
for (k in conditions) {
v = conditions[k];
if (data[k] !== v) {
match = false;
break;
}
}
return match;
};
LocalStorage.prototype.before('read', 'create', 'update', 'destroy', LocalStorage.skipIfError(function(env, next) {
var _this = this;
if (env.action === 'create') {
env.id = env.subject.get('id') || env.subject._withoutDirtyTracking(function() {
return env.subject.set('id', _this.nextIdForRecord(env.subject));
});
} else {
env.id = env.subject.get('id');
}
if (env.id == null) {
env.error = new this.constructor.StorageError("Couldn't get/set record primary key on " + env.action + "!");
} else {
env.key = this.storageKey(env.subject) + env.id;
}
return next();
}));
LocalStorage.prototype.before('create', 'update', LocalStorage.skipIfError(function(env, next) {
env.recordAttributes = JSON.stringify(env.subject);
return next();
}));
LocalStorage.prototype.after('read', LocalStorage.skipIfError(function(env, next) {
var error;
if (typeof env.recordAttributes === 'string') {
try {
env.recordAttributes = this._jsonToAttributes(env.recordAttributes);
} catch (_error) {
error = _error;
env.error = error;
return next();
}
}
env.subject._withoutDirtyTracking(function() {
return this.fromJSON(env.recordAttributes);
});
return next();
}));
LocalStorage.prototype.after('read', 'create', 'update', 'destroy', LocalStorage.skipIfError(function(env, next) {
env.result = env.subject;
return next();
}));
LocalStorage.prototype.after('readAll', LocalStorage.skipIfError(function(env, next) {
env.result = env.records = this.getRecordsFromData(env.recordsAttributes, env.subject);
return next();
}));
LocalStorage.prototype.read = LocalStorage.skipIfError(function(env, next) {
env.recordAttributes = this.storage.getItem(env.key);
if (!env.recordAttributes) {
env.error = new this.constructor.NotFoundError();
}
return next();
});
LocalStorage.prototype.create = LocalStorage.skipIfError(function(_arg, next) {
var key, recordAttributes;
key = _arg.key, recordAttributes = _arg.recordAttributes;
if (this.storage.getItem(key)) {
arguments[0].error = new this.constructor.RecordExistsError;
} else {
this.storage.setItem(key, recordAttributes);
}
return next();
});
LocalStorage.prototype.update = LocalStorage.skipIfError(function(_arg, next) {
var key, recordAttributes;
key = _arg.key, recordAttributes = _arg.recordAttributes;
this.storage.setItem(key, recordAttributes);
return next();
});
LocalStorage.prototype.destroy = LocalStorage.skipIfError(function(_arg, next) {
var key;
key = _arg.key;
this.storage.removeItem(key);
return next();
});
LocalStorage.prototype.readAll = LocalStorage.skipIfError(function(env, next) {
var error;
try {
arguments[0].recordsAttributes = this._storageEntriesMatching(env.subject, env.options.data);
} catch (_error) {
error = _error;
arguments[0].error = error;
}
return next();
});
return LocalStorage;
})(Batman.StorageAdapter);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.SessionStorage = (function(_super) {
__extends(SessionStorage, _super);
function SessionStorage() {
if (typeof window.sessionStorage === 'undefined') {
return null;
}
SessionStorage.__super__.constructor.apply(this, arguments);
this.storage = sessionStorage;
}
return SessionStorage;
})(Batman.LocalStorage);
}).call(this);
(function() {
Batman.Encoders = new Batman.Object;
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ParamsReplacer = (function(_super) {
__extends(ParamsReplacer, _super);
function ParamsReplacer(navigator, params) {
this.navigator = navigator;
this.params = params;
}
ParamsReplacer.prototype.redirect = function() {
return this.navigator.redirect(this.toObject(), true);
};
ParamsReplacer.prototype.replace = function(params) {
this.params.replace(params);
return this.redirect();
};
ParamsReplacer.prototype.update = function(params) {
this.params.update(params);
return this.redirect();
};
ParamsReplacer.prototype.clear = function() {
this.params.clear();
return this.redirect();
};
ParamsReplacer.prototype.toObject = function() {
return this.params.toObject();
};
ParamsReplacer.accessor({
get: function(k) {
return this.params.get(k);
},
set: function(k, v) {
var oldValue, result;
oldValue = this.params.get(k);
result = this.params.set(k, v);
if (oldValue !== v) {
this.redirect();
}
return result;
},
unset: function(k) {
var hadKey, result;
hadKey = this.params.hasKey(k);
result = this.params.unset(k);
if (hadKey) {
this.redirect();
}
return result;
}
});
return ParamsReplacer;
})(Batman.Object);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ParamsPusher = (function(_super) {
__extends(ParamsPusher, _super);
function ParamsPusher() {
_ref = ParamsPusher.__super__.constructor.apply(this, arguments);
return _ref;
}
ParamsPusher.prototype.redirect = function() {
return this.navigator.redirect(this.toObject());
};
return ParamsPusher;
})(Batman.ParamsReplacer);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.NamedRouteQuery = (function(_super) {
__extends(NamedRouteQuery, _super);
NamedRouteQuery.prototype.isNamedRouteQuery = true;
function NamedRouteQuery(routeMap, args) {
var key;
if (args == null) {
args = [];
}
NamedRouteQuery.__super__.constructor.call(this, {
routeMap: routeMap,
args: args
});
for (key in this.get('routeMap').childrenByName) {
this[key] = this._queryAccess.bind(this, key);
}
}
NamedRouteQuery.accessor('route', function() {
var collectionRoute, memberRoute, route, _i, _len, _ref, _ref1;
_ref = this.get('routeMap'), memberRoute = _ref.memberRoute, collectionRoute = _ref.collectionRoute;
_ref1 = [memberRoute, collectionRoute];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
route = _ref1[_i];
if (route != null) {
if (route.namedArguments.length === this.get('args').length) {
return route;
}
}
}
return collectionRoute || memberRoute;
});
NamedRouteQuery.accessor('path', function() {
return this.path();
});
NamedRouteQuery.accessor('routeMap', 'args', 'cardinality', 'hashValue', Batman.Property.defaultAccessor);
NamedRouteQuery.accessor({
get: function(key) {
if (key == null) {
return;
}
if (typeof key === 'string') {
return this.nextQueryForName(key);
} else {
return this.nextQueryWithArgument(key);
}
},
cache: false
});
NamedRouteQuery.accessor('withHash', function() {
var _this = this;
return new Batman.Accessible(function(hashValue) {
return _this.withHash(hashValue);
});
});
NamedRouteQuery.prototype.withHash = function(hashValue) {
var clone;
clone = this.clone();
clone.set('hashValue', hashValue);
return clone;
};
NamedRouteQuery.prototype.nextQueryForName = function(key) {
var map;
if (map = this.get('routeMap').childrenByName[key]) {
return new Batman.NamedRouteQuery(map, this.args);
} else {
return Batman.developer.error("Couldn't find a route for the name " + key + "!");
}
};
NamedRouteQuery.prototype.nextQueryWithArgument = function(arg) {
var args;
args = this.args.slice(0);
args.push(arg);
return this.clone(args);
};
NamedRouteQuery.prototype.path = function() {
var argumentName, argumentValue, index, namedArguments, params, _i, _len;
params = {};
namedArguments = this.get('route.namedArguments');
for (index = _i = 0, _len = namedArguments.length; _i < _len; index = ++_i) {
argumentName = namedArguments[index];
if ((argumentValue = this.get('args')[index]) != null) {
params[argumentName] = this._toParam(argumentValue);
}
}
if (this.get('hashValue') != null) {
params['#'] = this.get('hashValue');
}
return this.get('route').pathFromParams(params);
};
NamedRouteQuery.prototype.toString = function() {
return this.path();
};
NamedRouteQuery.prototype.clone = function(args) {
if (args == null) {
args = this.args;
}
return new Batman.NamedRouteQuery(this.routeMap, args);
};
NamedRouteQuery.prototype._toParam = function(arg) {
if (arg instanceof Batman.AssociationProxy) {
arg = arg.get('target');
}
if ((arg != null ? arg.toParam : void 0) != null) {
return arg.toParam();
} else {
return arg;
}
};
NamedRouteQuery.prototype._queryAccess = function(key, arg) {
var query;
query = this.nextQueryForName(key);
if (arg != null) {
query = query.nextQueryWithArgument(arg);
}
return query;
};
return NamedRouteQuery;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Dispatcher = (function(_super) {
var ControllerDirectory, _ref;
__extends(Dispatcher, _super);
Dispatcher.canInferRoute = function(argument) {
return argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy || argument.prototype instanceof Batman.Model;
};
Dispatcher.paramsFromArgument = function(argument) {
var resourceNameFromModel;
resourceNameFromModel = function(model) {
return Batman.helpers.camelize(Batman.helpers.pluralize(model.get('resourceName')), true);
};
if (!this.canInferRoute(argument)) {
return argument;
}
if (argument instanceof Batman.Model || argument instanceof Batman.AssociationProxy) {
if (argument.isProxy) {
argument = argument.get('target');
}
if (argument != null) {
return {
controller: resourceNameFromModel(argument.constructor),
action: 'show',
id: argument.get('id')
};
} else {
return {};
}
} else if (argument.prototype instanceof Batman.Model) {
return {
controller: resourceNameFromModel(argument),
action: 'index'
};
} else {
return argument;
}
};
ControllerDirectory = (function(_super1) {
__extends(ControllerDirectory, _super1);
function ControllerDirectory() {
_ref = ControllerDirectory.__super__.constructor.apply(this, arguments);
return _ref;
}
ControllerDirectory.accessor('__app', Batman.Property.defaultAccessor);
ControllerDirectory.accessor(function(key) {
return this.get("__app." + (Batman.helpers.capitalize(key)) + "Controller.sharedController");
});
return ControllerDirectory;
})(Batman.Object);
Dispatcher.accessor('controllers', function() {
return new ControllerDirectory({
__app: this.get('app')
});
});
function Dispatcher(app, routeMap) {
Dispatcher.__super__.constructor.call(this, {
app: app,
routeMap: routeMap
});
}
Dispatcher.prototype.routeForParams = function(params) {
params = this.constructor.paramsFromArgument(params);
return this.get('routeMap').routeForParams(params);
};
Dispatcher.prototype.pathFromParams = function(params) {
var _ref1;
if (typeof params === 'string') {
return params;
}
params = this.constructor.paramsFromArgument(params);
return (_ref1 = this.routeForParams(params)) != null ? _ref1.pathFromParams(params) : void 0;
};
Dispatcher.prototype.dispatch = function(params, paramsMixin) {
var error, inferredParams, path, route, _ref1, _ref2;
inferredParams = this.constructor.paramsFromArgument(params);
route = this.routeForParams(inferredParams);
if (route) {
_ref1 = route.pathAndParamsFromArgument(inferredParams), path = _ref1[0], params = _ref1[1];
if (paramsMixin) {
Batman.mixin(params, paramsMixin);
}
this.set('app.currentRoute', route);
this.set('app.currentURL', path);
this.get('app.currentParams').replace(params || {});
route.dispatch(params);
} else {
if (Batman.typeOf(params) === 'Object' && !this.constructor.canInferRoute(params)) {
return this.get('app.currentParams').replace(params);
} else {
this.get('app.currentParams').clear();
}
error = {
type: '404',
isPrevented: false,
preventDefault: function() {
return this.isPrevented = true;
}
};
if ((_ref2 = Batman.currentApp) != null) {
_ref2.fire('error', error);
}
if (error.isPrevented) {
return params;
}
if (params !== '/404') {
return Batman.redirect('/404');
}
}
return path;
};
return Dispatcher;
}).call(this, Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Route = (function(_super) {
__extends(Route, _super);
Route.regexps = {
namedParam: /:([\w\d]+)/g,
splatParam: /\*([\w\d]+)/g,
queryParam: '(?:\\?.+)?',
namedOrSplat: /[:|\*]([\w\d]+)/g,
namePrefix: '[:|\*]',
escapeRegExp: /[-[\]{}+?.,\\^$|#\s]/g,
openOptParam: /\(/g,
closeOptParam: /\)/g
};
Route.prototype.optionKeys = ['member', 'collection'];
Route.prototype.testKeys = ['controller', 'action'];
Route.prototype.isRoute = true;
function Route(templatePath, baseParams) {
var k, matches, namedArguments, pattern, properties, regexp, regexps, _i, _len, _ref;
regexps = this.constructor.regexps;
if (templatePath.indexOf('/') !== 0) {
templatePath = "/" + templatePath;
}
pattern = templatePath.replace(regexps.escapeRegExp, '\\$&');
regexp = RegExp("^" + (pattern.replace(regexps.openOptParam, '(?:').replace(regexps.closeOptParam, ')?').replace(regexps.namedParam, '([^\/]+)').replace(regexps.splatParam, '(.*?)')) + regexps.queryParam + "$");
regexps.namedOrSplat.lastIndex = 0;
namedArguments = ((function() {
var _results;
_results = [];
while (matches = regexps.namedOrSplat.exec(pattern)) {
_results.push(matches[1]);
}
return _results;
})());
properties = {
templatePath: templatePath,
pattern: pattern,
regexp: regexp,
namedArguments: namedArguments,
baseParams: baseParams
};
_ref = this.optionKeys;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
properties[k] = baseParams[k];
delete baseParams[k];
}
Route.__super__.constructor.call(this, properties);
}
Route.prototype.paramsFromPath = function(pathAndQuery) {
var index, match, matches, name, namedArguments, params, uri, _i, _len;
uri = new Batman.URI(pathAndQuery);
namedArguments = this.get('namedArguments');
params = Batman.extend({
path: uri.path
}, this.get('baseParams'));
matches = this.get('regexp').exec(uri.path).slice(1);
for (index = _i = 0, _len = matches.length; _i < _len; index = ++_i) {
match = matches[index];
name = namedArguments[index];
if (match != null) {
params[name] = decodeURIComponent(match);
}
}
return Batman.extend(params, uri.queryParams);
};
Route.prototype.pathFromParams = function(argumentParams) {
var hash, key, name, newPath, params, path, query, regexp, regexps, _i, _j, _len, _len1, _ref, _ref1;
params = Batman.extend({}, argumentParams);
path = this.get('templatePath');
regexps = this.constructor.regexps;
_ref = this.get('namedArguments');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
regexp = RegExp("" + regexps.namePrefix + name);
newPath = path.replace(regexp, (params[name] != null ? params[name] : ''));
if (newPath !== path) {
delete params[name];
path = newPath;
}
}
path = path.replace(regexps.openOptParam, '').replace(regexps.closeOptParam, '').replace(/([^\/])\/+$/, '$1');
_ref1 = this.testKeys;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
key = _ref1[_j];
delete params[key];
}
if (params['#']) {
hash = params['#'];
delete params['#'];
}
query = Batman.URI.queryFromParams(params);
if (query) {
path += "?" + query;
}
if (hash) {
path += "#" + hash;
}
return path;
};
Route.prototype.test = function(pathOrParams) {
var key, path, value, _i, _len, _ref;
if (typeof pathOrParams === 'string') {
path = pathOrParams;
} else if (pathOrParams.path != null) {
path = pathOrParams.path;
} else {
path = this.pathFromParams(pathOrParams);
_ref = this.testKeys;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
if ((value = this.get(key)) != null) {
if (pathOrParams[key] !== value) {
return false;
}
}
}
}
return this.get('regexp').test(path);
};
Route.prototype.pathAndParamsFromArgument = function(pathOrParams) {
var params, path;
if (typeof pathOrParams === 'string') {
params = this.paramsFromPath(pathOrParams);
path = pathOrParams;
} else {
params = pathOrParams;
path = this.pathFromParams(pathOrParams);
}
return [path, params];
};
Route.prototype.dispatch = function(params) {
if (!this.test(params)) {
return false;
}
return this.get('callback')(params);
};
Route.prototype.callback = function() {
throw new Batman.DevelopmentError("Override callback in a Route subclass");
};
return Route;
})(Batman.Object);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ControllerActionRoute = (function(_super) {
__extends(ControllerActionRoute, _super);
ControllerActionRoute.prototype.optionKeys = ['member', 'collection', 'app', 'controller', 'action'];
function ControllerActionRoute(templatePath, options) {
this.callback = __bind(this.callback, this);
var action, controller, _ref;
if (options.signature) {
_ref = options.signature.split('#'), controller = _ref[0], action = _ref[1];
action || (action = 'index');
options.controller = controller;
options.action = action;
delete options.signature;
}
ControllerActionRoute.__super__.constructor.call(this, templatePath, options);
}
ControllerActionRoute.prototype.callback = function(params) {
var controller;
controller = this.get("app.dispatcher.controllers." + (this.get('controller')));
return controller.dispatch(this.get('action'), params);
};
return ControllerActionRoute;
})(Batman.Route);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.CallbackActionRoute = (function(_super) {
__extends(CallbackActionRoute, _super);
function CallbackActionRoute() {
_ref = CallbackActionRoute.__super__.constructor.apply(this, arguments);
return _ref;
}
CallbackActionRoute.prototype.optionKeys = ['member', 'collection', 'callback', 'app'];
CallbackActionRoute.prototype.controller = false;
CallbackActionRoute.prototype.action = false;
return CallbackActionRoute;
})(Batman.Route);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Hash = (function(_super) {
var k, _fn, _i, _j, _len, _len1, _ref, _ref1,
_this = this;
__extends(Hash, _super);
Hash.Metadata = (function(_super1) {
__extends(Metadata, _super1);
Batman.extend(Metadata.prototype, Batman.Enumerable);
function Metadata(hash) {
this.hash = hash;
}
Metadata.accessor('length', function() {
this.hash.registerAsMutableSource();
return this.hash.length;
});
Metadata.accessor('isEmpty', 'keys', 'toArray', function(key) {
this.hash.registerAsMutableSource();
return this.hash[key]();
});
Metadata.prototype.forEach = function() {
var _ref;
return (_ref = this.hash).forEach.apply(_ref, arguments);
};
return Metadata;
})(Batman.Object);
function Hash() {
this.meta = new this.constructor.Metadata(this);
Batman.SimpleHash.apply(this, arguments);
Hash.__super__.constructor.apply(this, arguments);
}
Batman.extend(Hash.prototype, Batman.Enumerable);
Hash.prototype.propertyClass = Batman.Property;
Hash.defaultAccessor = {
cache: false,
get: Batman.SimpleHash.prototype.get,
set: Hash.mutation(function(key, value) {
var oldResult, result;
oldResult = Batman.SimpleHash.prototype.get.call(this, key);
result = Batman.SimpleHash.prototype.set.call(this, key, value);
if ((oldResult != null) && oldResult !== result) {
this.fire('itemsWereChanged', [key], [result], [oldResult]);
} else {
this.fire('itemsWereAdded', [key], [result]);
}
return result;
}),
unset: Hash.mutation(function(key) {
var result;
result = Batman.SimpleHash.prototype.unset.call(this, key);
if (result != null) {
this.fire('itemsWereRemoved', [key], [result]);
}
return result;
})
};
Hash.accessor(Hash.defaultAccessor);
Hash.prototype._preventMutationEvents = function(block) {
this.prevent('change');
this.prevent('itemsWereAdded');
this.prevent('itemsWereChanged');
this.prevent('itemsWereRemoved');
try {
return block.call(this);
} finally {
this.allow('change');
this.allow('itemsWereAdded');
this.allow('itemsWereChanged');
this.allow('itemsWereRemoved');
}
};
Hash.prototype.clear = Hash.mutation(function() {
var key, keys, values;
keys = this.keys();
values = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = keys.length; _i < _len; _i++) {
key = keys[_i];
_results.push(this.get(key));
}
return _results;
}).call(this);
this._preventMutationEvents(function() {
var _this = this;
return this.forEach(function(k) {
return _this.unset(k);
});
});
Batman.SimpleHash.prototype.clear.call(this);
this.fire('itemsWereRemoved', keys, values);
return values;
});
Hash.prototype.update = Hash.mutation(function(object) {
var addedKeys, addedValues, changedKeys, changedNewValues, changedOldValues;
addedKeys = [];
addedValues = [];
changedKeys = [];
changedNewValues = [];
changedOldValues = [];
this._preventMutationEvents(function() {
var _this = this;
return Batman.forEach(object, function(k, v) {
if (_this.hasKey(k)) {
changedKeys.push(k);
changedOldValues.push(_this.get(k));
return changedNewValues.push(_this.set(k, v));
} else {
addedKeys.push(k);
return addedValues.push(_this.set(k, v));
}
});
});
if (addedKeys.length > 0) {
this.fire('itemsWereAdded', addedKeys, addedValues);
}
if (changedKeys.length > 0) {
return this.fire('itemsWereChanged', changedKeys, changedNewValues, changedOldValues);
}
});
Hash.prototype.replace = Hash.mutation(function(object) {
var addedKeys, addedValues, changedKeys, changedNewValues, changedOldValues, removedKeys, removedValues;
addedKeys = [];
addedValues = [];
removedKeys = [];
removedValues = [];
changedKeys = [];
changedOldValues = [];
changedNewValues = [];
this._preventMutationEvents(function() {
var _this = this;
this.forEach(function(k) {
if (!Batman.objectHasKey(object, k)) {
removedKeys.push(k);
return removedValues.push(_this.unset(k));
}
});
return Batman.forEach(object, function(k, v) {
if (_this.hasKey(k)) {
changedKeys.push(k);
changedOldValues.push(_this.get(k));
return changedNewValues.push(_this.set(k, v));
} else {
addedKeys.push(k);
return addedValues.push(_this.set(k, v));
}
});
});
if (addedKeys.length > 0) {
this.fire('itemsWereAdded', addedKeys, addedValues);
}
if (changedKeys.length > 0) {
this.fire('itemsWereChanged', changedKeys, changedNewValues, changedOldValues);
}
if (removedKeys.length > 0) {
return this.fire('itemsWereRemoved', removedKeys, removedValues);
}
});
_ref = ['equality', 'hashKeyFor', 'objectKey', 'prefixedKey', 'unprefixedKey'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
Hash.prototype[k] = Batman.SimpleHash.prototype[k];
}
_ref1 = ['hasKey', 'forEach', 'isEmpty', 'keys', 'toArray', 'merge', 'toJSON', 'toObject'];
_fn = function(k) {
return Hash.prototype[k] = function() {
this.registerAsMutableSource();
return Batman.SimpleHash.prototype[k].apply(this, arguments);
};
};
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
k = _ref1[_j];
_fn(k);
}
return Hash;
}).call(this, Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.RenderCache = (function(_super) {
__extends(RenderCache, _super);
RenderCache.prototype.maximumLength = 4;
function RenderCache() {
RenderCache.__super__.constructor.apply(this, arguments);
this.keyQueue = [];
}
RenderCache.prototype.viewForOptions = function(options) {
var _this = this;
if (Batman.config.cacheViews || options.cache || options.viewClass.prototype.cache) {
return this.getOrSet(options, function() {
return _this._newViewFromOptions(Batman.extend({}, options));
});
} else {
return this._newViewFromOptions(options);
}
};
RenderCache.prototype._newViewFromOptions = function(options) {
return new options.viewClass(options);
};
RenderCache.wrapAccessor(function(core) {
return {
cache: false,
get: function(key) {
var result;
result = core.get.call(this, key);
if (result) {
this._addOrBubbleKey(key);
}
return result;
},
set: function(key, value) {
var result;
result = core.set.apply(this, arguments);
result.set('cached', true);
this._addOrBubbleKey(key);
this._evictExpiredKeys();
return result;
},
unset: function(key) {
var result;
result = core.unset.apply(this, arguments);
result.set('cached', false);
this._removeKeyFromQueue(key);
return result;
}
};
});
RenderCache.prototype.equality = function(incomingOptions, storageOptions) {
var key;
if (Object.keys(incomingOptions).length !== Object.keys(storageOptions).length) {
return false;
}
for (key in incomingOptions) {
if (!(key === 'view')) {
if (incomingOptions[key] !== storageOptions[key]) {
return false;
}
}
}
return true;
};
RenderCache.prototype.reset = function() {
var key, _i, _len, _ref;
_ref = this.keyQueue.slice(0);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
this.unset(key);
}
};
RenderCache.prototype._addOrBubbleKey = function(key) {
this._removeKeyFromQueue(key);
return this.keyQueue.unshift(key);
};
RenderCache.prototype._removeKeyFromQueue = function(key) {
var index, queuedKey, _i, _len, _ref;
_ref = this.keyQueue;
for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) {
queuedKey = _ref[index];
if (this.equality(queuedKey, key)) {
this.keyQueue.splice(index, 1);
break;
}
}
return key;
};
RenderCache.prototype._evictExpiredKeys = function() {
var currentKeys, i, key, _i, _ref, _ref1;
if (this.length > this.maximumLength) {
currentKeys = this.keyQueue.slice(0);
for (i = _i = _ref = this.maximumLength, _ref1 = currentKeys.length; _ref <= _ref1 ? _i < _ref1 : _i > _ref1; i = _ref <= _ref1 ? ++_i : --_i) {
key = currentKeys[i];
if (!this.get(key).isInDOM()) {
this.unset(key);
}
}
}
};
return RenderCache;
})(Batman.Hash);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
Batman.Controller = (function(_super) {
__extends(Controller, _super);
Controller.singleton('sharedController');
Controller.wrapAccessor('routingKey', function(core) {
return {
get: function() {
if (this.routingKey != null) {
return this.routingKey;
} else {
if (Batman.config.minificationErrors) {
Batman.developer.error("Please define `routingKey` on the prototype of " + (Batman.functionName(this.constructor)) + " in order for your controller to be minification safe.");
}
return Batman.functionName(this.constructor).replace(/Controller$/, '');
}
}
};
});
Controller.classMixin(Batman.LifecycleEvents);
Controller.lifecycleEvent('action', function(options) {
var except, normalized, only;
if (options == null) {
options = {};
}
normalized = {};
only = Batman.typeOf(options.only) === 'String' ? [options.only] : options.only;
except = Batman.typeOf(options.except) === 'String' ? [options.except] : options.except;
normalized["if"] = function(params, frame) {
var _ref, _ref1;
if (this._afterFilterRedirect) {
return false;
}
if (only && (_ref = frame.action, __indexOf.call(only, _ref) < 0)) {
return false;
}
if (except && (_ref1 = frame.action, __indexOf.call(except, _ref1) >= 0)) {
return false;
}
return true;
};
return normalized;
});
Controller.beforeFilter = function() {
Batman.developer.deprecated("Batman.Controller::beforeFilter", "Please use beforeAction instead.");
return this.beforeAction.apply(this, arguments);
};
Controller.afterFilter = function() {
Batman.developer.deprecated("Batman.Controller::afterFilter", "Please use afterAction instead.");
return this.afterAction.apply(this, arguments);
};
Controller.afterAction(function(params) {
if (this.autoScrollToHash && (params['#'] != null)) {
return this.scrollToHash(params['#']);
}
});
Controller.catchError = function() {
var currentHandlers, error, errors, handlers, options, _base, _i, _j, _len, _results;
errors = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), options = arguments[_i++];
Batman.initializeObject(this);
(_base = this._batman).errorHandlers || (_base.errorHandlers = new Batman.SimpleHash);
handlers = Batman.typeOf(options["with"]) === 'Array' ? options["with"] : [options["with"]];
_results = [];
for (_j = 0, _len = errors.length; _j < _len; _j++) {
error = errors[_j];
currentHandlers = this._batman.errorHandlers.get(error) || [];
_results.push(this._batman.errorHandlers.set(error, currentHandlers.concat(handlers)));
}
return _results;
};
Controller.prototype.errorHandler = function(callback) {
var errorFrame, _ref,
_this = this;
errorFrame = (_ref = this._actionFrames) != null ? _ref[this._actionFrames.length - 1] : void 0;
return function(err, result, env) {
if (err) {
if (errorFrame != null ? errorFrame.error : void 0) {
return;
}
if (errorFrame != null) {
errorFrame.error = err;
}
if (!_this.handleError(err)) {
throw err;
}
} else {
return typeof callback === "function" ? callback(result, env) : void 0;
}
};
};
Controller.prototype.handleError = function(error) {
var handled, _ref,
_this = this;
handled = false;
if ((_ref = this.constructor._batman.getAll('errorHandlers')) != null) {
_ref.forEach(function(hash) {
return hash.forEach(function(key, value) {
var handler, _i, _len, _results;
if (error instanceof key) {
handled = true;
_results = [];
for (_i = 0, _len = value.length; _i < _len; _i++) {
handler = value[_i];
_results.push(handler.call(_this, error));
}
return _results;
}
});
});
}
return handled;
};
function Controller() {
this.redirect = __bind(this.redirect, this);
this.handleError = __bind(this.handleError, this);
this.errorHandler = __bind(this.errorHandler, this);
Controller.__super__.constructor.apply(this, arguments);
this._resetActionFrames();
}
Controller.prototype.renderCache = new Batman.RenderCache;
Controller.prototype.defaultRenderYield = 'main';
Controller.prototype.autoScrollToHash = true;
Controller.prototype.dispatch = function(action, params) {
var redirectTo;
if (params == null) {
params = {};
}
params.controller || (params.controller = this.get('routingKey'));
params.action || (params.action = action);
params.target || (params.target = this);
this._resetActionFrames();
this.set('action', action);
this.set('params', params);
this.executeAction(action, params);
redirectTo = this._afterFilterRedirect;
this._afterFilterRedirect = null;
delete this._afterFilterRedirect;
if (redirectTo) {
return Batman.redirect(redirectTo);
}
};
Controller.prototype.executeAction = function(action, params) {
var frame, oldRedirect, parentFrame, result, _ref, _ref1,
_this = this;
if (params == null) {
params = this.get('params');
}
Batman.developer.assert(this[action], "Error! Controller action " + (this.get('routingKey')) + "." + action + " couldn't be found!");
parentFrame = this._actionFrames[this._actionFrames.length - 1];
frame = new Batman.ControllerActionFrame({
parentFrame: parentFrame,
action: action,
params: params
}, function() {
var _ref;
if (!_this._afterFilterRedirect) {
_this.fireLifecycleEvent('afterAction', frame.params, frame);
}
_this._resetActionFrames();
return (_ref = Batman.navigator) != null ? _ref.redirect = oldRedirect : void 0;
});
this._actionFrames.push(frame);
frame.startOperation({
internal: true
});
oldRedirect = (_ref = Batman.navigator) != null ? _ref.redirect : void 0;
if ((_ref1 = Batman.navigator) != null) {
_ref1.redirect = this.redirect;
}
if (this.fireLifecycleEvent('beforeAction', frame.params, frame) !== false) {
if (!this._afterFilterRedirect) {
result = this[action](params);
}
if (!frame.operationOccurred) {
this.render();
}
}
frame.finishOperation();
return result;
};
Controller.prototype.redirect = function(url) {
var frame;
frame = this._actionFrames[this._actionFrames.length - 1];
if (frame) {
if (frame.operationOccurred) {
Batman.developer.warn("Warning! Trying to redirect but an action has already been taken during " + (this.get('routingKey')) + "." + (frame.action || this.get('action')));
return;
}
frame.startAndFinishOperation();
if (this._afterFilterRedirect != null) {
return Batman.developer.warn("Warning! Multiple actions trying to redirect!");
} else {
return this._afterFilterRedirect = url;
}
} else {
if (Batman.typeOf(url) === 'Object') {
if (!url.controller) {
url.controller = this;
}
}
return Batman.redirect(url);
}
};
Controller.prototype.render = function(options) {
var action, frame, view, yieldContentView, yieldName, _ref, _ref1, _ref2, _ref3;
if (options == null) {
options = {};
}
if (frame = (_ref = this._actionFrames) != null ? _ref[this._actionFrames.length - 1] : void 0) {
frame.startOperation();
}
if (options === false) {
frame.finishOperation();
return;
}
action = (frame != null ? frame.action : void 0) || this.get('action');
if (view = options.view) {
options.view = null;
} else {
options.viewClass || (options.viewClass = this._viewClassForAction(action));
options.source || (options.source = Batman.helpers.underscore(this.get('routingKey') + '/' + action));
view = this.renderCache.viewForOptions(options);
}
if (view) {
view.once('viewDidAppear', function() {
return frame != null ? frame.finishOperation() : void 0;
});
yieldName = options.into || this.defaultRenderYield;
if (yieldContentView = Batman.DOM.Yield.withName(yieldName).contentView) {
if (yieldContentView !== view && !yieldContentView.isDead) {
yieldContentView.die();
}
}
if (!view.contentFor && !view.parentNode) {
view.set('contentFor', yieldName);
}
view.set('controller', this);
if ((_ref1 = Batman.currentApp) != null) {
if ((_ref2 = _ref1.layout) != null) {
if ((_ref3 = _ref2.subviews) != null) {
_ref3.add(view);
}
}
}
this.set('currentView', view);
}
return view;
};
Controller.prototype.scrollToHash = function(hash) {
if (hash == null) {
hash = this.get('params')['#'];
}
return Batman.DOM.scrollIntoView(hash);
};
Controller.prototype._resetActionFrames = function() {
return this._actionFrames = [];
};
Controller.prototype._viewClassForAction = function(action) {
var classPrefix, _ref;
classPrefix = this.get('routingKey').replace('/', '_');
return ((_ref = Batman.currentApp) != null ? _ref[Batman.helpers.camelize("" + classPrefix + "_" + action + "_view")] : void 0) || Batman.View;
};
return Controller;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Set = (function(_super) {
var k, _fn, _i, _j, _len, _len1, _ref, _ref1,
_this = this;
__extends(Set, _super);
Set.prototype.isCollectionEventEmitter = true;
function Set() {
Batman.SimpleSet.apply(this, arguments);
}
Batman.extend(Set.prototype, Batman.Enumerable);
Set._applySetAccessors = function(klass) {
var accessor, accessors, key;
accessors = {
first: function() {
return this.toArray()[0];
},
last: function() {
return this.toArray()[this.length - 1];
},
isEmpty: function() {
return this.isEmpty();
},
toArray: function() {
return this.toArray();
},
length: function() {
this.registerAsMutableSource();
return this.length;
},
indexedBy: function() {
var _this = this;
return new Batman.TerminalAccessible(function(key) {
return _this.indexedBy(key);
});
},
indexedByUnique: function() {
var _this = this;
return new Batman.TerminalAccessible(function(key) {
return _this.indexedByUnique(key);
});
},
sortedBy: function() {
var _this = this;
return new Batman.TerminalAccessible(function(key) {
return _this.sortedBy(key);
});
},
sortedByDescending: function() {
var _this = this;
return new Batman.TerminalAccessible(function(key) {
return _this.sortedBy(key, 'desc');
});
}
};
for (key in accessors) {
accessor = accessors[key];
klass.accessor(key, accessor);
}
};
Set._applySetAccessors(Set);
_ref = ['indexedBy', 'indexedByUnique', 'sortedBy', 'equality', '_indexOfItem'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
Set.prototype[k] = Batman.SimpleSet.prototype[k];
}
_ref1 = ['at', 'find', 'merge', 'forEach', 'toArray', 'isEmpty', 'has'];
_fn = function(k) {
return Set.prototype[k] = function() {
this.registerAsMutableSource();
return Batman.SimpleSet.prototype[k].apply(this, arguments);
};
};
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
k = _ref1[_j];
_fn(k);
}
Set.prototype.toJSON = Set.prototype.toArray;
Set.prototype.add = Set.mutation(function() {
var addedItems;
addedItems = Batman.SimpleSet.prototype.add.apply(this, arguments);
if (addedItems.length) {
this.fire('itemsWereAdded', addedItems);
}
return addedItems;
});
Set.prototype.insert = function() {
return this.insertWithIndexes.apply(this, arguments).addedItems;
};
Set.prototype.insertWithIndexes = Set.mutation(function() {
var addedIndexes, addedItems, _ref2;
_ref2 = Batman.SimpleSet.prototype.insertWithIndexes.apply(this, arguments), addedItems = _ref2.addedItems, addedIndexes = _ref2.addedIndexes;
if (addedItems.length) {
this.fire('itemsWereAdded', addedItems, addedIndexes);
}
return {
addedItems: addedItems,
addedIndexes: addedIndexes
};
});
Set.prototype.remove = function() {
return this.removeWithIndexes.apply(this, arguments).removedItems;
};
Set.prototype.removeWithIndexes = Set.mutation(function() {
var removedIndexes, removedItems, _ref2;
_ref2 = Batman.SimpleSet.prototype.removeWithIndexes.apply(this, arguments), removedItems = _ref2.removedItems, removedIndexes = _ref2.removedIndexes;
if (removedItems.length) {
this.fire('itemsWereRemoved', removedItems, removedIndexes);
}
return {
removedItems: removedItems,
removedIndexes: removedIndexes
};
});
Set.prototype.clear = Set.mutation(function() {
var removedItems;
removedItems = Batman.SimpleSet.prototype.clear.call(this);
if (removedItems.length) {
this.fire('itemsWereRemoved', removedItems);
}
return removedItems;
});
Set.prototype.replace = Set.mutation(function(other) {
var addedItems, removedItems;
removedItems = Batman.SimpleSet.prototype.clear.call(this);
addedItems = Batman.SimpleSet.prototype.add.apply(this, other.toArray());
if (removedItems.length) {
this.fire('itemsWereRemoved', removedItems);
}
if (addedItems.length) {
return this.fire('itemsWereAdded', addedItems);
}
});
return Set;
}).call(this, Batman.Object);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ErrorsSet = (function(_super) {
__extends(ErrorsSet, _super);
function ErrorsSet() {
_ref = ErrorsSet.__super__.constructor.apply(this, arguments);
return _ref;
}
ErrorsSet.accessor(function(key) {
return this.indexedBy('attribute').get(key);
});
ErrorsSet.prototype.add = function(key, error) {
return ErrorsSet.__super__.add.call(this, new Batman.ValidationError(key, error));
};
return ErrorsSet;
})(Batman.Set);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.SetProxy = (function(_super) {
var k, _fn, _i, _len, _ref,
_this = this;
__extends(SetProxy, _super);
function SetProxy(base) {
this.base = base;
SetProxy.__super__.constructor.call(this);
this.length = this.base.length;
if (this.base.isCollectionEventEmitter) {
this.isCollectionEventEmitter = true;
this._setObserver = new Batman.SetObserver(this.base);
this._setObserver.on('itemsWereAdded', this._handleItemsAdded.bind(this));
this._setObserver.on('itemsWereRemoved', this._handleItemsRemoved.bind(this));
this.startObserving();
}
}
Batman.extend(SetProxy.prototype, Batman.Enumerable);
SetProxy.prototype.startObserving = function() {
var _ref;
return (_ref = this._setObserver) != null ? _ref.startObserving() : void 0;
};
SetProxy.prototype.stopObserving = function() {
var _ref;
return (_ref = this._setObserver) != null ? _ref.stopObserving() : void 0;
};
SetProxy.prototype._handleItemsAdded = function(items, indexes) {
this.set('length', this.base.length);
return this.fire('itemsWereAdded', items, indexes);
};
SetProxy.prototype._handleItemsRemoved = function(items, indexes) {
this.set('length', this.base.length);
return this.fire('itemsWereRemoved', items, indexes);
};
SetProxy.prototype.filter = function(f) {
return this.reduce(function(accumulator, element) {
if (f(element)) {
accumulator.add(element);
}
return accumulator;
}, new Batman.Set());
};
SetProxy.prototype.replace = function() {
var length, result;
length = this.property('length');
length.isolate();
result = this.base.replace.apply(this.base, arguments);
length.expose();
return result;
};
Batman.Set._applySetAccessors(SetProxy);
_ref = ['add', 'insert', 'insertWithIndexes', 'remove', 'removeWithIndexes', 'at', 'find', 'clear', 'has', 'merge', 'toArray', 'isEmpty', 'indexedBy', 'indexedByUnique', 'sortedBy'];
_fn = function(k) {
return SetProxy.prototype[k] = function() {
return this.base[k].apply(this.base, arguments);
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
_fn(k);
}
SetProxy.accessor('length', {
get: function() {
this.registerAsMutableSource();
return this.length;
},
set: function(_, v) {
return this.length = v;
}
});
return SetProxy;
}).call(this, Batman.Object);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.BinarySetOperation = (function(_super) {
__extends(BinarySetOperation, _super);
function BinarySetOperation(left, right) {
this.left = left;
this.right = right;
this._setup = __bind(this._setup, this);
BinarySetOperation.__super__.constructor.call(this);
this._setup(this.left, this.right);
this._setup(this.right, this.left);
}
BinarySetOperation.prototype._setup = function(set, opposite) {
var _this = this;
set.on('itemsWereAdded', function(items) {
return _this._itemsWereAddedToSource.apply(_this, [set, opposite].concat(__slice.call(items)));
});
set.on('itemsWereRemoved', function(items) {
return _this._itemsWereRemovedFromSource.apply(_this, [set, opposite].concat(__slice.call(items)));
});
return this._itemsWereAddedToSource.apply(this, [set, opposite].concat(__slice.call(set.toArray())));
};
BinarySetOperation.prototype.merge = function() {
var merged, others, set, _i, _len;
others = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
merged = new Batman.Set;
others.unshift(this);
for (_i = 0, _len = others.length; _i < _len; _i++) {
set = others[_i];
set.forEach(function(v) {
return merged.add(v);
});
}
return merged;
};
BinarySetOperation.prototype.filter = Batman.SetProxy.prototype.filter;
return BinarySetOperation;
})(Batman.Set);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.SetUnion = (function(_super) {
__extends(SetUnion, _super);
function SetUnion() {
_ref = SetUnion.__super__.constructor.apply(this, arguments);
return _ref;
}
SetUnion.prototype._itemsWereAddedToSource = function() {
var items, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
return this.add.apply(this, items);
};
SetUnion.prototype._itemsWereRemovedFromSource = function() {
var item, items, itemsToRemove, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
itemsToRemove = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (!opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
return this.remove.apply(this, itemsToRemove);
};
return SetUnion;
})(Batman.BinarySetOperation);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.SetIntersection = (function(_super) {
__extends(SetIntersection, _super);
function SetIntersection() {
_ref = SetIntersection.__super__.constructor.apply(this, arguments);
return _ref;
}
SetIntersection.prototype._itemsWereAddedToSource = function() {
var item, items, itemsToAdd, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
itemsToAdd = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
if (itemsToAdd.length > 0) {
return this.add.apply(this, itemsToAdd);
}
};
SetIntersection.prototype._itemsWereRemovedFromSource = function() {
var items, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
return this.remove.apply(this, items);
};
return SetIntersection;
})(Batman.BinarySetOperation);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.SetComplement = (function(_super) {
__extends(SetComplement, _super);
function SetComplement() {
_ref = SetComplement.__super__.constructor.apply(this, arguments);
return _ref;
}
SetComplement.prototype._itemsWereAddedToSource = function() {
var item, items, itemsToAdd, itemsToRemove, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if (source === this.left) {
itemsToAdd = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (!opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
if (itemsToAdd.length > 0) {
return this.add.apply(this, itemsToAdd);
}
} else {
itemsToRemove = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
if (itemsToRemove.length > 0) {
return this.remove.apply(this, itemsToRemove);
}
}
};
SetComplement.prototype._itemsWereRemovedFromSource = function() {
var item, items, itemsToAdd, opposite, source;
source = arguments[0], opposite = arguments[1], items = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
if (source === this.left) {
return this.remove.apply(this, items);
} else {
itemsToAdd = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
if (itemsToAdd.length > 0) {
return this.add.apply(this, itemsToAdd);
}
}
};
SetComplement.prototype._addComplement = function(items, opposite) {
var item, itemsToAdd;
itemsToAdd = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (opposite.has(item)) {
_results.push(item);
}
}
return _results;
})();
if (itemsToAdd.length > 0) {
return this.add.apply(this, itemsToAdd);
}
};
return SetComplement;
})(Batman.BinarySetOperation);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.StateMachine = (function(_super) {
__extends(StateMachine, _super);
StateMachine.InvalidTransitionError = function(message) {
this.message = message != null ? message : "";
};
StateMachine.InvalidTransitionError.prototype = new Error;
StateMachine.transitions = function(table) {
var definePredicate, fromState, k, object, predicateKeys, toState, transitions, v, _fn, _ref,
_this = this;
for (k in table) {
v = table[k];
if (!(v.from && v.to)) {
continue;
}
object = {};
if (v.from.forEach) {
v.from.forEach(function(fromKey) {
return object[fromKey] = v.to;
});
} else {
object[v.from] = v.to;
}
table[k] = object;
}
this.prototype.transitionTable = Batman.extend({}, this.prototype.transitionTable, table);
predicateKeys = [];
definePredicate = function(state) {
var key;
key = "is" + (Batman.helpers.capitalize(state));
if (_this.prototype[key] != null) {
return;
}
predicateKeys.push(key);
return _this.prototype[key] = function() {
return this.get('state') === state;
};
};
_ref = this.prototype.transitionTable;
_fn = function(k) {
return _this.prototype[k] = function() {
return this.startTransition(k);
};
};
for (k in _ref) {
transitions = _ref[k];
if (!(!this.prototype[k])) {
continue;
}
_fn(k);
for (fromState in transitions) {
toState = transitions[fromState];
definePredicate(fromState);
definePredicate(toState);
}
}
if (predicateKeys.length) {
this.accessor.apply(this, __slice.call(predicateKeys).concat([function(key) {
return this[key]();
}]));
}
return this;
};
function StateMachine(startState) {
this.nextEvents = [];
this.set('_state', startState);
}
StateMachine.accessor('state', function() {
return this.get('_state');
});
StateMachine.prototype.isTransitioning = false;
StateMachine.prototype.transitionTable = {};
StateMachine.prototype._transitionEvent = function(from, into) {
return "" + from + "->" + into;
};
StateMachine.prototype._enterEvent = function(into) {
return "enter " + into;
};
StateMachine.prototype._exitEvent = function(from) {
return "exit " + from;
};
StateMachine.prototype._beforeEvent = function(into) {
return "before " + into;
};
StateMachine.prototype.onTransition = function(from, into, callback) {
return this.on(this._transitionEvent(from, into), callback);
};
StateMachine.prototype.onEnter = function(into, callback) {
return this.on(this._enterEvent(into), callback);
};
StateMachine.prototype.onExit = function(from, callback) {
return this.on(this._exitEvent(from), callback);
};
StateMachine.prototype.onBefore = function(into, callback) {
return this.on(this._beforeEvent(into), callback);
};
StateMachine.prototype.offTransition = function(from, into, callback) {
return this.off(this._transitionEvent(from, into), callback);
};
StateMachine.prototype.offEnter = function(into, callback) {
return this.off(this._enterEvent(into), callback);
};
StateMachine.prototype.offExit = function(from, callback) {
return this.off(this._exitEvent(from), callback);
};
StateMachine.prototype.offBefore = function(into, callback) {
return this.off(this._beforeEvent(into), callback);
};
StateMachine.prototype.startTransition = Batman.Property.wrapTrackingPrevention(function(event) {
var nextState, previousState;
if (this.isTransitioning) {
this.nextEvents.push(event);
return;
}
previousState = this.get('state');
nextState = this.nextStateForEvent(event);
if (!nextState) {
return false;
}
this.fire(this._beforeEvent(nextState));
this.isTransitioning = true;
this.fire(this._exitEvent(previousState));
this.set('_state', nextState);
this.fire(this._transitionEvent(previousState, nextState));
this.fire(this._enterEvent(nextState));
this.fire(event);
this.isTransitioning = false;
if (this.nextEvents.length > 0) {
this.startTransition(this.nextEvents.shift());
}
return true;
});
StateMachine.prototype.canStartTransition = function(event, fromState) {
if (fromState == null) {
fromState = this.get('state');
}
return !!this.nextStateForEvent(event, fromState);
};
StateMachine.prototype.nextStateForEvent = function(event, fromState) {
var _ref;
if (fromState == null) {
fromState = this.get('state');
}
return (_ref = this.transitionTable[event]) != null ? _ref[fromState] : void 0;
};
return StateMachine;
})(Batman.Object);
Batman.DelegatingStateMachine = (function(_super) {
__extends(DelegatingStateMachine, _super);
function DelegatingStateMachine(startState, base) {
this.base = base;
DelegatingStateMachine.__super__.constructor.call(this, startState);
}
DelegatingStateMachine.prototype.fire = function() {
var result, _ref;
result = DelegatingStateMachine.__super__.fire.apply(this, arguments);
(_ref = this.base).fire.apply(_ref, arguments);
return result;
};
return DelegatingStateMachine;
})(Batman.StateMachine);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.Model = (function(_super) {
var functionName, _i, _j, _len, _len1, _ref, _ref1, _ref2;
__extends(Model, _super);
Model.storageKey = null;
Model.primaryKey = 'id';
Model.persist = function() {
var mechanism, options;
mechanism = arguments[0], options = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
Batman.initializeObject(this.prototype);
mechanism = mechanism.isStorageAdapter ? mechanism : new mechanism(this);
if (options.length > 0) {
Batman.mixin.apply(Batman, [mechanism].concat(__slice.call(options)));
}
this.prototype._batman.storage = mechanism;
return mechanism;
};
Model.storageAdapter = function() {
Batman.initializeObject(this.prototype);
return this.prototype._batman.storage;
};
Model.encode = function() {
var encoder, encoderForKey, encoderOrLastKey, key, keys, _base, _i, _j, _len;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), encoderOrLastKey = arguments[_i++];
Batman.initializeObject(this.prototype);
(_base = this.prototype._batman).encoders || (_base.encoders = new Batman.SimpleHash);
encoder = {};
switch (Batman.typeOf(encoderOrLastKey)) {
case 'String':
keys.push(encoderOrLastKey);
break;
case 'Function':
encoder.encode = encoderOrLastKey;
break;
default:
encoder = encoderOrLastKey;
}
for (_j = 0, _len = keys.length; _j < _len; _j++) {
key = keys[_j];
encoderForKey = Batman.extend({
as: key
}, this.defaultEncoder, encoder);
this.prototype._batman.encoders.set(key, encoderForKey);
}
};
Model.defaultEncoder = {
encode: function(x) {
return x;
},
decode: function(x) {
return x;
}
};
Model.observeAndFire('primaryKey', function(newPrimaryKey, oldPrimaryKey) {
this.encode(oldPrimaryKey, {
encode: false,
decode: false
});
return this.encode(newPrimaryKey, {
encode: false,
decode: this.defaultEncoder.decode
});
});
Model.validate = function() {
var keys, matches, optionsOrFunction, validatorClass, validators, _base, _i, _j, _len, _ref;
keys = 2 <= arguments.length ? __slice.call(arguments, 0, _i = arguments.length - 1) : (_i = 0, []), optionsOrFunction = arguments[_i++];
Batman.initializeObject(this.prototype);
validators = (_base = this.prototype._batman).validators || (_base.validators = []);
if (typeof optionsOrFunction === 'function') {
validators.push({
keys: keys,
callback: optionsOrFunction
});
} else {
_ref = Batman.Validators;
for (_j = 0, _len = _ref.length; _j < _len; _j++) {
validatorClass = _ref[_j];
if ((matches = validatorClass.matches(optionsOrFunction))) {
validators.push({
keys: keys,
validator: new validatorClass(matches)
});
}
}
}
};
Model.classAccessor('resourceName', {
get: function() {
if (this.resourceName != null) {
return this.resourceName;
} else if (this.prototype.resourceName != null) {
if (Batman.config.minificationErrors) {
Batman.developer.error("Please define the resourceName property of the " + (Batman.functionName(this)) + " on the constructor and not the prototype.");
}
return this.prototype.resourceName;
} else {
if (Batman.config.minificationErrors) {
Batman.developer.error("Please define " + (Batman.functionName(this)) + ".resourceName in order for your model to be minification safe.");
}
return Batman.helpers.underscore(Batman.functionName(this));
}
}
});
Model.classAccessor('all', {
get: function() {
this._batman.check(this);
if (this.prototype.hasStorage() && !this._batman.allLoadTriggered) {
this.load();
this._batman.allLoadTriggered = true;
}
return this.get('loaded');
},
set: function(k, v) {
return this.set('loaded', v);
}
});
Model.classAccessor('loaded', {
get: function() {
return this._loaded || (this._loaded = new Batman.Set);
},
set: function(k, v) {
return this._loaded = v;
}
});
Model.classAccessor('first', function() {
return this.get('all').toArray()[0];
});
Model.classAccessor('last', function() {
var x;
x = this.get('all').toArray();
return x[x.length - 1];
});
Model.clear = function() {
var result, _ref;
Batman.initializeObject(this);
result = this.get('loaded').clear();
if ((_ref = this._batman.get('associations')) != null) {
_ref.reset();
}
this._resetPromises();
return result;
};
Model.find = function(id, callback) {
return this.findWithOptions(id, void 0, callback);
};
Model.findWithOptions = function(id, options, callback) {
var record;
if (options == null) {
options = {};
}
Batman.developer.assert(callback, "Must call find with a callback!");
record = new this;
record._withoutDirtyTracking(function() {
return this.set('id', id);
});
record.loadWithOptions(options, callback);
return record;
};
Model.load = function(options, callback) {
var _ref;
if ((_ref = typeof options) === 'function' || _ref === 'undefined') {
callback = options;
options = {};
} else {
options = {
data: options
};
}
return this.loadWithOptions(options, callback);
};
Model.loadWithOptions = function(options, callback) {
var _this = this;
this.fire('loading', options);
return this._doStorageOperation('readAll', options, function(err, records, env) {
if (err != null) {
_this.fire('error', err);
return typeof callback === "function" ? callback(err, []) : void 0;
} else {
_this.fire('loaded', records, env);
return typeof callback === "function" ? callback(err, records, env) : void 0;
}
});
};
Model.create = function(attrs, callback) {
var record, _ref;
if (!callback) {
_ref = [{}, attrs], attrs = _ref[0], callback = _ref[1];
}
record = new this(attrs);
record.save(callback);
return record;
};
Model.findOrCreate = function(attrs, callback) {
var record;
record = this._loadIdentity(attrs[this.primaryKey]);
if (record) {
record.mixin(attrs);
callback(void 0, record);
} else {
record = new this(attrs);
record.save(callback);
}
return record;
};
Model.createFromJSON = function(json) {
return this._makeOrFindRecordFromData(json);
};
Model._loadIdentity = function(id) {
return this.get('loaded.indexedByUnique.id').get(id);
};
Model._loadRecord = function(attributes) {
var id, record;
if (id = attributes[this.primaryKey]) {
record = this._loadIdentity(id);
}
record || (record = new this);
record._withoutDirtyTracking(function() {
return this.fromJSON(attributes);
});
return record;
};
Model._makeOrFindRecordFromData = function(attributes) {
var record;
record = this._loadRecord(attributes);
return this._mapIdentity(record);
};
Model._makeOrFindRecordsFromData = function(attributeSet) {
var attributes, newRecords;
newRecords = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = attributeSet.length; _i < _len; _i++) {
attributes = attributeSet[_i];
_results.push(this._loadRecord(attributes));
}
return _results;
}).call(this);
this._mapIdentities(newRecords);
return newRecords;
};
Model._mapIdentity = function(record) {
var existing, id, lifecycle;
if ((id = record.get('id')) != null) {
if (existing = this._loadIdentity(id)) {
lifecycle = existing.get('lifecycle');
lifecycle.load();
existing._withoutDirtyTracking(function() {
var attributes, _ref;
attributes = (_ref = record.get('attributes')) != null ? _ref.toObject() : void 0;
if (attributes) {
return this.mixin(attributes);
}
});
lifecycle.loaded();
record = existing;
} else {
this.get('loaded').add(record);
}
}
return record;
};
Model._mapIdentities = function(records) {
var existing, id, index, lifecycle, newRecords, record, _i, _len, _ref;
newRecords = [];
for (index = _i = 0, _len = records.length; _i < _len; index = ++_i) {
record = records[index];
if ((id = record.get('id')) == null) {
continue;
} else if (existing = this._loadIdentity(id)) {
lifecycle = existing.get('lifecycle');
lifecycle.load();
existing._withoutDirtyTracking(function() {
var attributes, _ref;
attributes = (_ref = record.get('attributes')) != null ? _ref.toObject() : void 0;
if (attributes) {
return this.mixin(attributes);
}
});
lifecycle.loaded();
records[index] = existing;
} else {
newRecords.push(record);
}
}
if (newRecords.length) {
(_ref = this.get('loaded')).add.apply(_ref, newRecords);
}
return records;
};
Model._doStorageOperation = function(operation, options, callback) {
var adapter;
Batman.developer.assert(this.prototype.hasStorage(), "Can't " + operation + " model " + (Batman.functionName(this.constructor)) + " without any storage adapters!");
adapter = this.prototype._batman.get('storage');
return adapter.perform(operation, this, options, callback);
};
_ref = ['find', 'load', 'create'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
functionName = _ref[_i];
Model[functionName] = Batman.Property.wrapTrackingPrevention(Model[functionName]);
}
Model.InstanceLifecycleStateMachine = (function(_super1) {
__extends(InstanceLifecycleStateMachine, _super1);
function InstanceLifecycleStateMachine() {
_ref1 = InstanceLifecycleStateMachine.__super__.constructor.apply(this, arguments);
return _ref1;
}
InstanceLifecycleStateMachine.transitions({
load: {
from: ['dirty', 'clean'],
to: 'loading'
},
create: {
from: ['dirty', 'clean'],
to: 'creating'
},
save: {
from: ['dirty', 'clean'],
to: 'saving'
},
destroy: {
from: ['dirty', 'clean'],
to: 'destroying'
},
failedValidation: {
from: ['saving', 'creating'],
to: 'dirty'
},
loaded: {
loading: 'clean'
},
created: {
creating: 'clean'
},
saved: {
saving: 'clean'
},
destroyed: {
destroying: 'destroyed'
},
set: {
from: ['dirty', 'clean'],
to: 'dirty'
},
error: {
from: ['saving', 'creating', 'loading', 'destroying'],
to: 'error'
}
});
return InstanceLifecycleStateMachine;
})(Batman.DelegatingStateMachine);
function Model(idOrAttributes) {
if (idOrAttributes == null) {
idOrAttributes = {};
}
Batman.developer.assert(this instanceof Batman.Object, "constructors must be called with new");
if (Batman.typeOf(idOrAttributes) === 'Object') {
Model.__super__.constructor.call(this, idOrAttributes);
} else {
Model.__super__.constructor.call(this);
this.set('id', idOrAttributes);
}
}
Model.accessor('lifecycle', function() {
return this.lifecycle || (this.lifecycle = new Batman.Model.InstanceLifecycleStateMachine('clean', this));
});
Model.accessor('attributes', function() {
return this.attributes || (this.attributes = new Batman.Hash);
});
Model.accessor('dirtyKeys', function() {
return this.dirtyKeys || (this.dirtyKeys = new Batman.Hash);
});
Model.accessor('_dirtiedKeys', function() {
return this._dirtiedKeys || (this._dirtiedKeys = new Batman.SimpleSet);
});
Model.accessor('errors', function() {
return this.errors || (this.errors = new Batman.ErrorsSet);
});
Model.accessor('isNew', function() {
return this.isNew();
});
Model.accessor('isDirty', function() {
return this.isDirty();
});
Model.accessor(Model.defaultAccessor = {
get: function(k) {
return Batman.getPath(this, ['attributes', k]);
},
set: function(k, v) {
if (this._willSet(k)) {
return this.get('attributes').set(k, v);
} else {
return this.get(k);
}
},
unset: function(k) {
return this.get('attributes').unset(k);
}
});
Model.wrapAccessor('id', function(core) {
return {
get: function() {
var primaryKey;
primaryKey = this.constructor.primaryKey;
if (primaryKey === 'id') {
return core.get.apply(this, arguments);
} else {
return this.get(primaryKey);
}
},
set: function(key, value) {
var parsedValue, primaryKey;
if ((typeof value === "string") && (value.match(/[^0-9]/) === null) && (("" + (parsedValue = parseInt(value, 10))) === value)) {
value = parsedValue;
}
primaryKey = this.constructor.primaryKey;
if (primaryKey === 'id') {
this._willSet(key);
return core.set.apply(this, arguments);
} else {
return this.set(primaryKey, value);
}
}
};
});
Model.prototype.isNew = function() {
return typeof this.get('id') === 'undefined';
};
Model.prototype.isDirty = function() {
return this.get('lifecycle.state') === 'dirty';
};
Model.prototype.updateAttributes = function(attrs) {
this.mixin(attrs);
return this;
};
Model.prototype.toString = function() {
return "" + (this.constructor.get('resourceName')) + ": " + (this.get('id'));
};
Model.prototype.toParam = function() {
return this.get('id');
};
Model.prototype.toJSON = function() {
var encoders, obj,
_this = this;
obj = {};
encoders = this._batman.get('encoders');
if (!(!encoders || encoders.isEmpty())) {
encoders.forEach(function(key, encoder) {
var encodedVal, val;
if (encoder.encode) {
val = _this.get(key);
if (typeof val !== 'undefined') {
encodedVal = encoder.encode(val, key, obj, _this);
if (typeof encodedVal !== 'undefined') {
return obj[encoder.as] = encodedVal;
}
}
}
});
}
return obj;
};
Model.prototype.fromJSON = function(data) {
var encoders, key, obj, value,
_this = this;
obj = {};
encoders = this._batman.get('encoders');
if (!encoders || encoders.isEmpty() || !encoders.some(function(key, encoder) {
return encoder.decode != null;
})) {
for (key in data) {
value = data[key];
obj[key] = value;
}
} else {
encoders.forEach(function(key, encoder) {
if (encoder.decode && typeof data[encoder.as] !== 'undefined') {
return obj[key] = encoder.decode(data[encoder.as], encoder.as, data, obj, _this);
}
});
}
if (this.constructor.primaryKey !== 'id') {
obj.id = data[this.constructor.primaryKey];
}
Batman.developer["do"](function() {
if ((!encoders) || encoders.length <= 1) {
return Batman.developer.warn("Warning: Model " + (Batman.functionName(_this.constructor)) + " has suspiciously few decoders!");
}
});
return this.mixin(obj);
};
Model.prototype.hasStorage = function() {
return this._batman.get('storage') != null;
};
Model.prototype.load = function(options, callback) {
var _ref2;
if (!callback) {
_ref2 = [{}, options], options = _ref2[0], callback = _ref2[1];
} else {
options = {
data: options
};
}
return this.loadWithOptions(options, callback);
};
Model.prototype.loadWithOptions = function(options, callback) {
var callbackQueue, hasOptions, _ref2,
_this = this;
hasOptions = Object.keys(options).length !== 0;
if ((_ref2 = this.get('lifecycle.state')) === 'destroying' || _ref2 === 'destroyed') {
if (typeof callback === "function") {
callback(new Error("Can't load a destroyed record!"));
}
return;
}
if (this.get('lifecycle').load()) {
callbackQueue = [];
if (callback != null) {
callbackQueue.push(callback);
}
if (!hasOptions) {
this._currentLoad = callbackQueue;
}
return this._doStorageOperation('read', options, function(err, record, env) {
var _j, _len1;
if (!err) {
_this.get('lifecycle').loaded();
record = _this.constructor._mapIdentity(record);
record.get('errors').clear();
} else {
_this.get('lifecycle').error();
}
if (!hasOptions) {
_this._currentLoad = null;
}
for (_j = 0, _len1 = callbackQueue.length; _j < _len1; _j++) {
callback = callbackQueue[_j];
callback(err, record, env);
}
});
} else {
if (this.get('lifecycle.state') === 'loading' && !hasOptions) {
if (callback != null) {
return this._currentLoad.push(callback);
}
} else {
return typeof callback === "function" ? callback(new Batman.StateMachine.InvalidTransitionError("Can't load while in state " + (this.get('lifecycle.state')))) : void 0;
}
}
};
Model.prototype.save = function(options, callback) {
var endState, isNew, startState, storageOperation, _ref2, _ref3,
_this = this;
if (!callback) {
_ref2 = [{}, options], options = _ref2[0], callback = _ref2[1];
}
isNew = this.isNew();
_ref3 = isNew ? ['create', 'create', 'created'] : ['save', 'update', 'saved'], startState = _ref3[0], storageOperation = _ref3[1], endState = _ref3[2];
if (this.get('lifecycle').startTransition(startState)) {
return this.validate(function(error, errors) {
var associations;
if (error || errors.length) {
_this.get('lifecycle').failedValidation();
return typeof callback === "function" ? callback(error || errors, _this) : void 0;
}
associations = _this.constructor._batman.get('associations');
_this._withoutDirtyTracking(function() {
var _ref4,
_this = this;
return associations != null ? (_ref4 = associations.getByType('belongsTo')) != null ? _ref4.forEach(function(association, label) {
return association.apply(_this);
}) : void 0 : void 0;
});
return _this._doStorageOperation(storageOperation, {
data: options
}, function(err, record, env) {
if (!err) {
_this.get('dirtyKeys').clear();
_this.get('_dirtiedKeys').clear();
if (associations) {
record._withoutDirtyTracking(function() {
var _ref4, _ref5;
if ((_ref4 = associations.getByType('hasOne')) != null) {
_ref4.forEach(function(association, label) {
return association.apply(err, record);
});
}
return (_ref5 = associations.getByType('hasMany')) != null ? _ref5.forEach(function(association, label) {
return association.apply(err, record);
}) : void 0;
});
}
record = _this.constructor._mapIdentity(record);
_this.get('lifecycle').startTransition(endState);
} else {
if (err instanceof Batman.ErrorsSet) {
_this.get('lifecycle').failedValidation();
} else {
_this.get('lifecycle').error();
}
}
return typeof callback === "function" ? callback(err, record || _this, env) : void 0;
});
});
} else {
return typeof callback === "function" ? callback(new Batman.StateMachine.InvalidTransitionError("Can't save while in state " + (this.get('lifecycle.state')))) : void 0;
}
};
Model.prototype.destroy = function(options, callback) {
var _ref2,
_this = this;
if (!callback) {
_ref2 = [{}, options], options = _ref2[0], callback = _ref2[1];
}
if (this.get('lifecycle').destroy()) {
return this._doStorageOperation('destroy', {
data: options
}, function(err, record, env) {
if (!err) {
_this.constructor.get('loaded').remove(_this);
_this.get('lifecycle').destroyed();
} else {
_this.get('lifecycle').error();
}
return typeof callback === "function" ? callback(err, record, env) : void 0;
});
} else {
return typeof callback === "function" ? callback(new Batman.StateMachine.InvalidTransitionError("Can't destroy while in state " + (this.get('lifecycle.state')))) : void 0;
}
};
Model.prototype.validate = function(callback) {
var args, count, e, errors, finishedValidation, key, validator, validators, _j, _k, _len1, _len2, _ref2;
errors = this.get('errors');
errors.clear();
validators = this._batman.get('validators') || [];
if (!validators || validators.length === 0) {
if (typeof callback === "function") {
callback(void 0, errors);
}
return true;
}
count = validators.reduce((function(acc, validator) {
return acc + validator.keys.length;
}), 0);
finishedValidation = function() {
if (--count === 0) {
return typeof callback === "function" ? callback(void 0, errors) : void 0;
}
};
for (_j = 0, _len1 = validators.length; _j < _len1; _j++) {
validator = validators[_j];
_ref2 = validator.keys;
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
key = _ref2[_k];
args = [errors, this, key, finishedValidation];
try {
if (validator.validator) {
validator.validator.validateEach.apply(validator.validator, args);
} else {
validator.callback.apply(validator, args);
}
} catch (_error) {
e = _error;
if (typeof callback === "function") {
callback(e, errors);
}
}
}
}
};
Model.prototype.associationProxy = function(association) {
var proxies, _base, _name;
Batman.initializeObject(this);
proxies = (_base = this._batman).associationProxies || (_base.associationProxies = {});
proxies[_name = association.label] || (proxies[_name] = new association.proxyClass(association, this));
return proxies[association.label];
};
Model.prototype._willSet = function(key) {
if (this._pauseDirtyTracking) {
return true;
}
if (this.get('lifecycle').startTransition('set')) {
if (!this.get('_dirtiedKeys').has(key)) {
this.set("dirtyKeys." + key, this.get(key));
this.get('_dirtiedKeys').add(key);
}
return true;
} else {
return false;
}
};
Model.prototype._doStorageOperation = function(operation, options, callback) {
var adapter,
_this = this;
Batman.developer.assert(this.hasStorage(), "Can't " + operation + " model " + (Batman.functionName(this.constructor)) + " without any storage adapters!");
adapter = this._batman.get('storage');
return adapter.perform(operation, this, options, function() {
return callback.apply(null, arguments);
});
};
Model.prototype._withoutDirtyTracking = function(block) {
var result;
if (this._pauseDirtyTracking) {
return block.call(this);
}
this._pauseDirtyTracking = true;
result = block.call(this);
this._pauseDirtyTracking = false;
return result;
};
_ref2 = ['load', 'save', 'validate', 'destroy'];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
functionName = _ref2[_j];
Model.prototype[functionName] = Batman.Property.wrapTrackingPrevention(Model.prototype[functionName]);
}
return Model;
}).call(this, Batman.Object);
}).call(this);
(function() {
var k, _fn, _i, _len, _ref,
_this = this;
_ref = Batman.AssociationCurator.availableAssociations;
_fn = function(k) {
return Batman.Model[k] = function(label, scope) {
var collection, _base;
Batman.initializeObject(this);
collection = (_base = this._batman).associations || (_base.associations = new Batman.AssociationCurator(this));
return collection.add(new Batman["" + (Batman.helpers.capitalize(k)) + "Association"](this, label, scope));
};
};
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
_fn(k);
}
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Proxy = (function(_super) {
__extends(Proxy, _super);
Proxy.prototype.isProxy = true;
function Proxy(target) {
Proxy.__super__.constructor.call(this);
if (target != null) {
this.set('target', target);
}
}
Proxy.accessor('target', Batman.Property.defaultAccessor);
Proxy.accessor({
get: function(key) {
var _ref;
return (_ref = this.get('target')) != null ? _ref.get(key) : void 0;
},
set: function(key, value) {
var _ref;
return (_ref = this.get('target')) != null ? _ref.set(key, value) : void 0;
},
unset: function(key) {
var _ref;
return (_ref = this.get('target')) != null ? _ref.unset(key) : void 0;
}
});
return Proxy;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.AssociationProxy = (function(_super) {
__extends(AssociationProxy, _super);
AssociationProxy.prototype.loaded = false;
function AssociationProxy(association, model) {
this.association = association;
this.model = model;
AssociationProxy.__super__.constructor.call(this);
}
AssociationProxy.prototype.toJSON = function() {
var target;
target = this.get('target');
if (target != null) {
return this.get('target').toJSON();
}
};
AssociationProxy.prototype.load = function(callback) {
var _this = this;
this.fetch(function(err, proxiedRecord) {
if (!err) {
_this._setTarget(proxiedRecord);
}
return typeof callback === "function" ? callback(err, proxiedRecord) : void 0;
});
return this.get('target');
};
AssociationProxy.prototype.loadFromLocal = function() {
var target;
if (!this._canLoad()) {
return;
}
if (target = this.fetchFromLocal()) {
this._setTarget(target);
}
return target;
};
AssociationProxy.prototype.fetch = function(callback) {
var record;
if (!this._canLoad()) {
return callback(void 0, void 0);
}
record = this.fetchFromLocal();
if (record) {
return callback(void 0, record);
} else {
return this.fetchFromRemote(callback);
}
};
AssociationProxy.accessor('loaded', Batman.Property.defaultAccessor);
AssociationProxy.accessor('target', {
get: function() {
return this.fetchFromLocal();
},
set: function(_, v) {
return v;
}
});
AssociationProxy.prototype._canLoad = function() {
return (this.get('foreignValue') || this.get('primaryValue')) != null;
};
AssociationProxy.prototype._setTarget = function(target) {
this.set('target', target);
this.set('loaded', true);
return this.fire('loaded', target);
};
return AssociationProxy;
})(Batman.Proxy);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.HasOneProxy = (function(_super) {
__extends(HasOneProxy, _super);
function HasOneProxy() {
_ref = HasOneProxy.__super__.constructor.apply(this, arguments);
return _ref;
}
HasOneProxy.accessor('primaryValue', function() {
return this.model.get(this.association.primaryKey);
});
HasOneProxy.prototype.fetchFromLocal = function() {
return this.association.setIndex().get(this.get('primaryValue'));
};
HasOneProxy.prototype.fetchFromRemote = function(callback) {
var loadOptions,
_this = this;
loadOptions = {
data: {}
};
loadOptions.data[this.association.foreignKey] = this.get('primaryValue');
if (this.association.options.url) {
loadOptions.collectionUrl = this.association.options.url;
loadOptions.urlContext = this.model;
}
return this.association.getRelatedModel().loadWithOptions(loadOptions, function(error, loadedRecords) {
if (error) {
throw error;
}
if (!loadedRecords || loadedRecords.length <= 0) {
return callback(new Error("Couldn't find related record!"), void 0);
} else {
return callback(void 0, loadedRecords[0]);
}
});
};
return HasOneProxy;
})(Batman.AssociationProxy);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.BelongsToProxy = (function(_super) {
__extends(BelongsToProxy, _super);
function BelongsToProxy() {
_ref = BelongsToProxy.__super__.constructor.apply(this, arguments);
return _ref;
}
BelongsToProxy.accessor('foreignValue', function() {
return this.model.get(this.association.foreignKey);
});
BelongsToProxy.prototype.fetchFromLocal = function() {
return this.association.setIndex().get(this.get('foreignValue'));
};
BelongsToProxy.prototype.fetchFromRemote = function(callback) {
var loadOptions,
_this = this;
loadOptions = {};
if (this.association.options.url) {
loadOptions.recordUrl = this.association.options.url;
}
return this.association.getRelatedModel().findWithOptions(this.get('foreignValue'), loadOptions, function(error, loadedRecord) {
if (error) {
throw error;
}
return callback(void 0, loadedRecord);
});
};
return BelongsToProxy;
})(Batman.AssociationProxy);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicBelongsToProxy = (function(_super) {
__extends(PolymorphicBelongsToProxy, _super);
function PolymorphicBelongsToProxy() {
_ref = PolymorphicBelongsToProxy.__super__.constructor.apply(this, arguments);
return _ref;
}
PolymorphicBelongsToProxy.accessor('foreignTypeValue', function() {
return this.model.get(this.association.foreignTypeKey);
});
PolymorphicBelongsToProxy.prototype.fetchFromLocal = function() {
return this.association.setIndexForType(this.get('foreignTypeValue')).get(this.get('foreignValue'));
};
PolymorphicBelongsToProxy.prototype.fetchFromRemote = function(callback) {
var loadOptions,
_this = this;
loadOptions = {};
if (this.association.options.url) {
loadOptions.recordUrl = this.association.options.url;
}
return this.association.getRelatedModelForType(this.get('foreignTypeValue')).findWithOptions(this.get('foreignValue'), loadOptions, function(error, loadedRecord) {
if (error) {
throw error;
}
return callback(void 0, loadedRecord);
});
};
return PolymorphicBelongsToProxy;
})(Batman.BelongsToProxy);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Accessible = (function(_super) {
__extends(Accessible, _super);
function Accessible() {
this.accessor.apply(this, arguments);
}
return Accessible;
})(Batman.Object);
Batman.TerminalAccessible = (function(_super) {
__extends(TerminalAccessible, _super);
function TerminalAccessible() {
_ref = TerminalAccessible.__super__.constructor.apply(this, arguments);
return _ref;
}
TerminalAccessible.prototype.propertyClass = Batman.Property;
return TerminalAccessible;
})(Batman.Accessible);
}).call(this);
(function() {
Batman.URI = (function() {
/*
# URI parsing
*/
var attributes, childKeyMatchers, decodeQueryComponent, encodeComponent, encodeQueryComponent, keyVal, nameParser, normalizeParams, plus, queryFromParams, r20, strictParser;
strictParser = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/;
attributes = ["source", "protocol", "authority", "userInfo", "user", "password", "hostname", "port", "relative", "path", "directory", "file", "query", "hash"];
function URI(str) {
var i, matches;
matches = strictParser.exec(str);
i = 14;
while (i--) {
this[attributes[i]] = matches[i] || '';
}
this.queryParams = this.constructor.paramsFromQuery(this.query);
delete this.authority;
delete this.userInfo;
delete this.relative;
delete this.directory;
delete this.file;
delete this.query;
}
URI.prototype.queryString = function() {
return this.constructor.queryFromParams(this.queryParams);
};
URI.prototype.toString = function() {
return [this.protocol ? "" + this.protocol + ":" : void 0, this.authority() ? "//" : void 0, this.authority(), this.relative()].join("");
};
URI.prototype.userInfo = function() {
return [this.user, this.password ? ":" + this.password : void 0].join("");
};
URI.prototype.authority = function() {
return [this.userInfo(), this.user || this.password ? "@" : void 0, this.hostname, this.port ? ":" + this.port : void 0].join("");
};
URI.prototype.relative = function() {
var query;
query = this.queryString();
return [this.path, query ? "?" + query : void 0, this.hash ? "#" + this.hash : void 0].join("");
};
URI.prototype.directory = function() {
var splitPath;
splitPath = this.path.split('/');
if (splitPath.length > 1) {
return splitPath.slice(0, splitPath.length - 1).join('/') + "/";
} else {
return "";
}
};
URI.prototype.file = function() {
var splitPath;
splitPath = this.path.split("/");
return splitPath[splitPath.length - 1];
};
/*
# query parsing
*/
URI.paramsFromQuery = function(query) {
var matches, params, segment, _i, _len, _ref;
params = {};
_ref = query.split('&');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
segment = _ref[_i];
if (matches = segment.match(keyVal)) {
normalizeParams(params, decodeQueryComponent(matches[1]), decodeQueryComponent(matches[2]));
} else {
normalizeParams(params, decodeQueryComponent(segment), null);
}
}
return params;
};
URI.decodeQueryComponent = decodeQueryComponent = function(str) {
return decodeURIComponent(str.replace(plus, '%20'));
};
nameParser = /^[\[\]]*([^\[\]]+)\]*(.*)/;
childKeyMatchers = [/^\[\]\[([^\[\]]+)\]$/, /^\[\](.+)$/];
plus = /\+/g;
r20 = /%20/g;
keyVal = /^([^=]*)=(.*)/;
normalizeParams = function(params, name, v) {
var after, childKey, k, last, matches;
if (matches = name.match(nameParser)) {
k = matches[1];
after = matches[2];
} else {
return;
}
if (after === '') {
params[k] = v;
} else if (after === '[]') {
if (params[k] == null) {
params[k] = [];
}
if (Batman.typeOf(params[k]) !== 'Array') {
throw new Error("expected Array (got " + (Batman.typeOf(params[k])) + ") for param \"" + k + "\"");
}
params[k].push(v);
} else if (matches = after.match(childKeyMatchers[0]) || after.match(childKeyMatchers[1])) {
childKey = matches[1];
if (params[k] == null) {
params[k] = [];
}
if (Batman.typeOf(params[k]) !== 'Array') {
throw new Error("expected Array (got " + (Batman.typeOf(params[k])) + ") for param \"" + k + "\"");
}
last = params[k][params[k].length - 1];
if (Batman.typeOf(last) === 'Object' && !(childKey in last)) {
normalizeParams(last, childKey, v);
} else {
params[k].push(normalizeParams({}, childKey, v));
}
} else {
if (params[k] == null) {
params[k] = {};
}
if (Batman.typeOf(params[k]) !== 'Object') {
throw new Error("expected Object (got " + (Batman.typeOf(params[k])) + ") for param \"" + k + "\"");
}
params[k] = normalizeParams(params[k], after, v);
}
return params;
};
/*
# query building
*/
URI.queryFromParams = queryFromParams = function(value, prefix) {
var arrayResults, k, v, valueType;
if (value == null) {
return prefix;
}
valueType = Batman.typeOf(value);
if (!((prefix != null) || valueType === 'Object')) {
throw new Error("value must be an Object");
}
switch (valueType) {
case 'Array':
return ((function() {
var _i, _len;
arrayResults = [];
if (value.length === 0) {
arrayResults.push(queryFromParams(null, "" + prefix + "[]"));
} else {
for (_i = 0, _len = value.length; _i < _len; _i++) {
v = value[_i];
arrayResults.push(queryFromParams(v, "" + prefix + "[]"));
}
}
return arrayResults;
})()).join("&");
case 'Object':
return ((function() {
var _results;
_results = [];
for (k in value) {
v = value[k];
_results.push(queryFromParams(v, prefix ? "" + prefix + "[" + (encodeQueryComponent(k)) + "]" : encodeQueryComponent(k)));
}
return _results;
})()).join("&");
default:
if (prefix != null) {
return "" + prefix + "=" + (encodeQueryComponent(value));
} else {
return encodeQueryComponent(value);
}
}
};
URI.encodeComponent = encodeComponent = function(str) {
if (str != null) {
return encodeURIComponent(str);
} else {
return '';
}
};
URI.encodeQueryComponent = encodeQueryComponent = function(str) {
return encodeComponent(str).replace(r20, '+');
};
return URI;
})();
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Request = (function(_super) {
var dataHasFileUploads;
__extends(Request, _super);
Request.objectToFormData = function(data) {
var formData, key, pairForList, val, _i, _len, _ref, _ref1;
pairForList = function(key, object, first) {
var k, list, v;
if (first == null) {
first = false;
}
if (object instanceof Batman.container.File) {
return [[key, object]];
}
return list = (function() {
switch (Batman.typeOf(object)) {
case 'Object':
list = (function() {
var _results;
_results = [];
for (k in object) {
v = object[k];
_results.push(pairForList((first ? k : "" + key + "[" + k + "]"), v));
}
return _results;
})();
return list.reduce(function(acc, list) {
return acc.concat(list);
}, []);
case 'Array':
return object.reduce(function(acc, element) {
return acc.concat(pairForList("" + key + "[]", element));
}, []);
default:
return [[key, object != null ? object : ""]];
}
})();
};
formData = new Batman.container.FormData();
_ref = pairForList("", data, true);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
_ref1 = _ref[_i], key = _ref1[0], val = _ref1[1];
formData.append(key, val);
}
return formData;
};
Request.dataHasFileUploads = dataHasFileUploads = function(data) {
var k, type, v, _i, _len;
if ((typeof File !== "undefined" && File !== null) && data instanceof File) {
return true;
}
type = Batman.typeOf(data);
switch (type) {
case 'Object':
for (k in data) {
v = data[k];
if (dataHasFileUploads(v)) {
return true;
}
}
break;
case 'Array':
for (_i = 0, _len = data.length; _i < _len; _i++) {
v = data[_i];
if (dataHasFileUploads(v)) {
return true;
}
}
}
return false;
};
Request.wrapAccessor('method', function(core) {
return {
set: function(k, val) {
return core.set.call(this, k, val != null ? typeof val.toUpperCase === "function" ? val.toUpperCase() : void 0 : void 0);
}
};
});
Request.prototype.method = 'GET';
Request.prototype.hasFileUploads = function() {
return dataHasFileUploads(this.data);
};
Request.prototype.contentType = 'application/x-www-form-urlencoded';
Request.prototype.autosend = true;
function Request(options) {
var handler, handlers, k, _ref;
handlers = {};
for (k in options) {
handler = options[k];
if (!(k === 'success' || k === 'error' || k === 'loading' || k === 'loaded')) {
continue;
}
handlers[k] = handler;
delete options[k];
}
Request.__super__.constructor.call(this, options);
for (k in handlers) {
handler = handlers[k];
this.on(k, handler);
}
if (((_ref = this.get('url')) != null ? _ref.length : void 0) > 0) {
if (this.autosend) {
this.send();
}
} else {
this.observe('url', function(url) {
if (url != null) {
return this.send();
}
});
}
}
Request.prototype.send = function() {
return Batman.developer.error("Please source a dependency file for a request implementation");
};
return Request;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.SetObserver = (function(_super) {
__extends(SetObserver, _super);
function SetObserver(base) {
var _this = this;
this.base = base;
this._itemObservers = new Batman.SimpleHash;
this._setObservers = new Batman.SimpleHash;
this._setObservers.set("itemsWereAdded", function() {
return _this.fire.apply(_this, ['itemsWereAdded'].concat(__slice.call(arguments)));
});
this._setObservers.set("itemsWereRemoved", function() {
return _this.fire.apply(_this, ['itemsWereRemoved'].concat(__slice.call(arguments)));
});
this.on('itemsWereAdded', this.startObservingItems.bind(this));
this.on('itemsWereRemoved', this.stopObservingItems.bind(this));
}
SetObserver.prototype.observedItemKeys = [];
SetObserver.prototype.observerForItemAndKey = function(item, key) {};
SetObserver.prototype._getOrSetObserverForItemAndKey = function(item, key) {
var _this = this;
return this._itemObservers.getOrSet(item, function() {
var observersByKey;
observersByKey = new Batman.SimpleHash;
return observersByKey.getOrSet(key, function() {
return _this.observerForItemAndKey(item, key);
});
});
};
SetObserver.prototype.startObserving = function() {
this._manageItemObservers("observe");
return this._manageSetObservers("addHandler");
};
SetObserver.prototype.stopObserving = function() {
this._manageItemObservers("forget");
return this._manageSetObservers("removeHandler");
};
SetObserver.prototype.startObservingItems = function(items) {
var item, _i, _len;
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
this._manageObserversForItem(item, "observe");
}
};
SetObserver.prototype.stopObservingItems = function(items) {
var item, _i, _len;
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
this._manageObserversForItem(item, "forget");
}
};
SetObserver.prototype._manageObserversForItem = function(item, method) {
var key, _i, _len, _ref;
if (item.isObservable) {
_ref = this.observedItemKeys;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
key = _ref[_i];
item[method](key, this._getOrSetObserverForItemAndKey(item, key));
}
if (method === "forget") {
return this._itemObservers.unset(item);
}
}
};
SetObserver.prototype._manageItemObservers = function(method) {
var _this = this;
return this.base.forEach(function(item) {
return _this._manageObserversForItem(item, method);
});
};
SetObserver.prototype._manageSetObservers = function(method) {
var _this = this;
if (this.base.isObservable) {
return this._setObservers.forEach(function(key, observer) {
return _this.base.event(key)[method](observer);
});
}
};
return SetObserver;
})(Batman.Object);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.SetSort = (function(_super) {
__extends(SetSort, _super);
function SetSort(base, key, order) {
var _this = this;
this.key = key;
if (order == null) {
order = "asc";
}
this.compareElements = __bind(this.compareElements, this);
SetSort.__super__.constructor.call(this, base);
this.descending = order.toLowerCase() === "desc";
this.isSorted = true;
if (this.isCollectionEventEmitter) {
this._setObserver.observedItemKeys = [this.key];
this._setObserver.observerForItemAndKey = function(item) {
return function(newValue, oldValue) {
return _this._handleItemsModified(item, newValue, oldValue);
};
};
}
this._reIndex();
}
SetSort.prototype._handleItemsModified = function(item, newValue, oldValue) {
var match, newIndex, newStorage, oldIndex, proxyItem, wrappedCompare, _ref, _ref1,
_this = this;
proxyItem = {};
proxyItem[this.key] = oldValue;
wrappedCompare = function(a, b) {
if (a === item) {
a = proxyItem;
}
if (b === item) {
b = proxyItem;
}
return _this.compareElements(a, b);
};
newStorage = this._storage.slice();
_ref = this.constructor._binarySearch(newStorage, item, wrappedCompare), match = _ref.match, oldIndex = _ref.index;
if (!match) {
return;
}
newStorage.splice(oldIndex, 1);
_ref1 = this.constructor._binarySearch(newStorage, item, this.compareElements), match = _ref1.match, newIndex = _ref1.index;
if (oldIndex === newIndex) {
return;
}
newStorage.splice(newIndex, 0, item);
this.set('_storage', newStorage);
return this.fire('itemWasMoved', item, newIndex, oldIndex);
};
SetSort.prototype._handleItemsAdded = function(items) {
var addedIndexes, addedItems, index, item, match, newStorage, _i, _len, _ref;
newStorage = this._storage.slice();
addedItems = [];
addedIndexes = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
_ref = this.constructor._binarySearch(newStorage, item, this.compareElements), match = _ref.match, index = _ref.index;
if (!match) {
newStorage.splice(index, 0, item);
addedItems.push(item);
addedIndexes.push(index);
}
}
this.set('_storage', newStorage);
this.set('length', this._storage.length);
return this.fire('itemsWereAdded', addedItems, addedIndexes);
};
SetSort.prototype._handleItemsRemoved = function(items) {
var index, item, match, newStorage, removedIndexes, removedItems, _i, _len, _ref;
newStorage = this._storage.slice();
removedItems = [];
removedIndexes = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
_ref = this.constructor._binarySearch(newStorage, item, this.compareElements), match = _ref.match, index = _ref.index;
if (match) {
newStorage.splice(index, 1);
removedItems.push(item);
removedIndexes.push(index);
}
}
this.set('_storage', newStorage);
this.set('length', this._storage.length);
return this.fire('itemsWereRemoved', removedItems, removedIndexes);
};
SetSort.prototype.toArray = function() {
var _base;
if (typeof (_base = this.base).registerAsMutableSource === "function") {
_base.registerAsMutableSource();
}
return this._storage.slice();
};
SetSort.prototype.forEach = function(iterator, ctx) {
var e, i, _base, _i, _len, _ref;
if (typeof (_base = this.base).registerAsMutableSource === "function") {
_base.registerAsMutableSource();
}
_ref = this._storage;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
e = _ref[i];
iterator.call(ctx, e, i, this);
}
};
SetSort.prototype.find = function(block) {
var item, _i, _len, _ref;
this.base.registerAsMutableSource();
_ref = this._storage;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
item = _ref[_i];
if (block(item)) {
return item;
}
}
};
SetSort.prototype.merge = function(other) {
this.base.registerAsMutableSource();
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Batman.Set, this._storage, function(){}).merge(other).sortedBy(this.key, this.order);
};
SetSort.prototype.compare = function(a, b) {
if (a === b) {
return 0;
}
if (a === void 0) {
return 1;
}
if (b === void 0) {
return -1;
}
if (a === null) {
return 1;
}
if (b === null) {
return -1;
}
if (a === false) {
return 1;
}
if (b === false) {
return -1;
}
if (a === true) {
return 1;
}
if (b === true) {
return -1;
}
if (a !== a) {
if (b !== b) {
return 0;
} else {
return 1;
}
}
if (b !== b) {
return -1;
}
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
};
SetSort.prototype.compareElements = function(a, b) {
var multiple, valueA, valueB;
valueA = this.key && (a != null) ? Batman.get(a, this.key) : a;
if (typeof valueA === 'function') {
valueA = valueA.call(a);
}
if (valueA != null) {
valueA = valueA.valueOf();
}
valueB = this.key && (b != null) ? Batman.get(b, this.key) : b;
if (typeof valueB === 'function') {
valueB = valueB.call(b);
}
if (valueB != null) {
valueB = valueB.valueOf();
}
multiple = this.descending ? -1 : 1;
return this.compare(valueA, valueB) * multiple;
};
SetSort.prototype._reIndex = function() {
var newOrder, _ref;
newOrder = this.base.toArray().sort(this.compareElements);
if ((_ref = this._setObserver) != null) {
_ref.startObservingItems(newOrder);
}
return this.set('_storage', newOrder);
};
SetSort.prototype._indexOfItem = function(target) {
var index, match, _ref;
_ref = this.constructor._binarySearch(this._storage, target, this.compareElements), match = _ref.match, index = _ref.index;
if (match) {
return index;
} else {
return -1;
}
};
SetSort._binarySearch = function(arr, target, compare) {
var direction, end, i, index, matched, result, start;
start = 0;
end = arr.length - 1;
result = {};
while (end >= start) {
index = ((end - start) >> 1) + start;
direction = compare(target, arr[index]);
if (direction > 0) {
start = index + 1;
} else if (direction < 0) {
end = index - 1;
} else {
matched = false;
i = index;
while (i >= 0 && compare(target, arr[i]) === 0) {
if (target === arr[i]) {
index = i;
matched = true;
break;
}
i--;
}
if (!matched) {
i = index + 1;
while (i < arr.length && compare(target, arr[i]) === 0) {
if (target === arr[i]) {
index = i;
matched = true;
break;
}
i++;
}
}
return {
match: matched,
index: index
};
}
}
return {
match: false,
index: start
};
};
return SetSort;
})(Batman.SetProxy);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.AssociationSet = (function(_super) {
__extends(AssociationSet, _super);
function AssociationSet(foreignKeyValue, association) {
var base;
this.foreignKeyValue = foreignKeyValue;
this.association = association;
base = new Batman.Set;
AssociationSet.__super__.constructor.call(this, base, '_batmanID');
}
AssociationSet.prototype.loaded = false;
AssociationSet.accessor('loaded', Batman.Property.defaultAccessor);
AssociationSet.prototype.load = function(options, callback) {
var loadOptions,
_this = this;
loadOptions = this._getLoadOptions();
if (!callback) {
callback = options;
} else {
loadOptions.data = Batman.extend(loadOptions.data, options);
}
if (this.foreignKeyValue == null) {
return callback(void 0, this);
}
return this.association.getRelatedModel().loadWithOptions(loadOptions, function(err, records, env) {
if (!err) {
_this.markAsLoaded();
}
return callback(err, _this, env);
});
};
AssociationSet.prototype._getLoadOptions = function() {
var loadOptions;
loadOptions = {
data: {}
};
loadOptions.data[this.association.foreignKey] = this.foreignKeyValue;
if (this.association.options.url) {
loadOptions.collectionUrl = this.association.options.url;
loadOptions.urlContext = this.association.parentSetIndex().get(this.foreignKeyValue);
}
return loadOptions;
};
AssociationSet.prototype.markAsLoaded = function() {
this.set('loaded', true);
return this.fire('loaded');
};
return AssociationSet;
})(Batman.SetSort);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicAssociationSet = (function(_super) {
__extends(PolymorphicAssociationSet, _super);
function PolymorphicAssociationSet(foreignKeyValue, foreignTypeKeyValue, association) {
this.foreignKeyValue = foreignKeyValue;
this.foreignTypeKeyValue = foreignTypeKeyValue;
this.association = association;
PolymorphicAssociationSet.__super__.constructor.call(this, this.foreignKeyValue, this.association);
}
PolymorphicAssociationSet.prototype._getLoadOptions = function() {
var loadOptions;
loadOptions = {
data: {}
};
loadOptions.data[this.association.foreignKey] = this.foreignKeyValue;
loadOptions.data[this.association.foreignTypeKey] = this.foreignTypeKeyValue;
if (this.association.options.url) {
loadOptions.collectionUrl = this.association.options.url;
loadOptions.urlContext = this.association.parentSetIndex().get(this.foreignKeyValue);
}
return loadOptions;
};
return PolymorphicAssociationSet;
})(Batman.AssociationSet);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.SetIndex = (function(_super) {
__extends(SetIndex, _super);
SetIndex.accessor('toArray', function() {
return this.toArray();
});
Batman.extend(SetIndex.prototype, Batman.Enumerable);
SetIndex.prototype.propertyClass = Batman.Property;
function SetIndex(base, key) {
var _this = this;
this.base = base;
this.key = key;
SetIndex.__super__.constructor.call(this);
this._storage = new Batman.Hash;
if (this.base.isEventEmitter) {
this._setObserver = new Batman.SetObserver(this.base);
this._setObserver.observedItemKeys = [this.key];
this._setObserver.observerForItemAndKey = this.observerForItemAndKey.bind(this);
this._setObserver.on('itemsWereAdded', function(items) {
return _this._addItems(items);
});
this._setObserver.on('itemsWereRemoved', function(items) {
return _this._removeItems(items);
});
}
this._addItems(this.base._storage);
this.startObserving();
}
SetIndex.accessor(function(key) {
return this._resultSetForKey(key);
});
SetIndex.prototype.startObserving = function() {
var _ref;
return (_ref = this._setObserver) != null ? _ref.startObserving() : void 0;
};
SetIndex.prototype.stopObserving = function() {
var _ref;
return (_ref = this._setObserver) != null ? _ref.stopObserving() : void 0;
};
SetIndex.prototype.observerForItemAndKey = function(item, key) {
var _this = this;
return function(newKey, oldKey) {
_this._removeItemsFromKey(oldKey, [item]);
return _this._addItemsToKey(newKey, [item]);
};
};
SetIndex.prototype.forEach = function(iterator, ctx) {
var _this = this;
return this._storage.forEach(function(key, set) {
if (set.get('length') > 0) {
return iterator.call(ctx, key, set, _this);
}
});
};
SetIndex.prototype.toArray = function() {
var results;
results = [];
this._storage.forEach(function(key, set) {
if (set.get('length') > 0) {
return results.push(key);
}
});
return results;
};
SetIndex.prototype._addItems = function(items) {
var index, item, itemsForKey, key, lastKey, _i, _len;
if (!(items != null ? items.length : void 0)) {
return;
}
lastKey = this._keyForItem(items[0]);
itemsForKey = [];
for (index = _i = 0, _len = items.length; _i < _len; index = ++_i) {
item = items[index];
if (Batman.SimpleHash.prototype.equality(lastKey, (key = this._keyForItem(item)))) {
itemsForKey.push(item);
} else {
this._addItemsToKey(lastKey, itemsForKey);
itemsForKey = [item];
lastKey = key;
}
}
if (itemsForKey.length) {
return this._addItemsToKey(lastKey, itemsForKey);
}
};
SetIndex.prototype._removeItems = function(items) {
var index, item, itemsForKey, key, lastKey, _i, _len;
if (!(items != null ? items.length : void 0)) {
return;
}
lastKey = this._keyForItem(items[0]);
itemsForKey = [];
for (index = _i = 0, _len = items.length; _i < _len; index = ++_i) {
item = items[index];
if (Batman.SimpleHash.prototype.equality(lastKey, (key = this._keyForItem(item)))) {
itemsForKey.push(item);
} else {
this._removeItemsFromKey(lastKey, itemsForKey);
itemsForKey = [item];
lastKey = key;
}
}
if (itemsForKey.length) {
return this._removeItemsFromKey(lastKey, itemsForKey);
}
};
SetIndex.prototype._addItemsToKey = function(key, items) {
var resultSet;
resultSet = this._resultSetForKey(key);
resultSet.add.apply(resultSet, items);
return resultSet;
};
SetIndex.prototype._removeItemsFromKey = function(key, items) {
var resultSet;
resultSet = this._resultSetForKey(key);
resultSet.remove.apply(resultSet, items);
return resultSet;
};
SetIndex.prototype._resultSetForKey = function(key) {
return this._storage.getOrSet(key, function() {
return new Batman.Set;
});
};
SetIndex.prototype._keyForItem = function(item) {
return Batman.Keypath.forBaseAndKey(item, this.key).getValue();
};
return SetIndex;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicAssociationSetIndex = (function(_super) {
__extends(PolymorphicAssociationSetIndex, _super);
function PolymorphicAssociationSetIndex(association, type, key) {
this.association = association;
this.type = type;
PolymorphicAssociationSetIndex.__super__.constructor.call(this, this.association.getRelatedModel().get('loaded'), key);
}
PolymorphicAssociationSetIndex.prototype._resultSetForKey = function(key) {
return this.association.setForKey(key);
};
PolymorphicAssociationSetIndex.prototype._addItemsToKey = function(key, items) {
var filteredItems, item;
filteredItems = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (this.association.modelType() === item.get(this.association.foreignTypeKey)) {
_results.push(item);
}
}
return _results;
}).call(this);
return PolymorphicAssociationSetIndex.__super__._addItemsToKey.call(this, key, filteredItems);
};
PolymorphicAssociationSetIndex.prototype._removeItemsFromKey = function(key, items) {
var filteredItems, item;
filteredItems = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (this.association.modelType() === item.get(this.association.foreignTypeKey)) {
_results.push(item);
}
}
return _results;
}).call(this);
return PolymorphicAssociationSetIndex.__super__._removeItemsFromKey.call(this, key, filteredItems);
};
return PolymorphicAssociationSetIndex;
})(Batman.SetIndex);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.AssociationSetIndex = (function(_super) {
__extends(AssociationSetIndex, _super);
function AssociationSetIndex(association, key) {
this.association = association;
AssociationSetIndex.__super__.constructor.call(this, this.association.getRelatedModel().get('loaded'), key);
}
AssociationSetIndex.prototype._resultSetForKey = function(key) {
return this.association.setForKey(key);
};
AssociationSetIndex.prototype.forEach = function(iterator, ctx) {
var _this = this;
return this.association.proxies.forEach(function(record, set) {
var key;
key = _this.association.indexValueForRecord(record);
if (set.get('length') > 0) {
return iterator.call(ctx, key, set, _this);
}
});
};
AssociationSetIndex.prototype.toArray = function() {
var results;
results = [];
this.forEach(function(key) {
return results.push(key);
});
return results;
};
return AssociationSetIndex;
})(Batman.SetIndex);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.UniqueSetIndex = (function(_super) {
__extends(UniqueSetIndex, _super);
function UniqueSetIndex() {
this._uniqueIndex = new Batman.Hash;
UniqueSetIndex.__super__.constructor.apply(this, arguments);
}
UniqueSetIndex.accessor(function(key) {
return this._uniqueIndex.get(key);
});
UniqueSetIndex.prototype._addItemsToKey = function(key, items) {
UniqueSetIndex.__super__._addItemsToKey.apply(this, arguments);
if (!this._uniqueIndex.hasKey(key)) {
return this._uniqueIndex.set(key, items[0]);
}
};
UniqueSetIndex.prototype._removeItemsFromKey = function(key, items) {
var resultSet;
resultSet = UniqueSetIndex.__super__._removeItemsFromKey.apply(this, arguments);
if (resultSet.isEmpty()) {
return this._uniqueIndex.unset(key);
} else {
return this._uniqueIndex.set(key, resultSet._storage[0]);
}
};
return UniqueSetIndex;
})(Batman.SetIndex);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.UniqueAssociationSetIndex = (function(_super) {
__extends(UniqueAssociationSetIndex, _super);
function UniqueAssociationSetIndex(association, key) {
this.association = association;
UniqueAssociationSetIndex.__super__.constructor.call(this, this.association.getRelatedModel().get('loaded'), key);
}
return UniqueAssociationSetIndex;
})(Batman.UniqueSetIndex);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicUniqueAssociationSetIndex = (function(_super) {
__extends(PolymorphicUniqueAssociationSetIndex, _super);
function PolymorphicUniqueAssociationSetIndex(association, type, key) {
this.association = association;
this.type = type;
PolymorphicUniqueAssociationSetIndex.__super__.constructor.call(this, this.association.getRelatedModelForType(type).get('loaded'), key);
}
return PolymorphicUniqueAssociationSetIndex;
})(Batman.UniqueSetIndex);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice;
Batman.Navigator = (function() {
Navigator.forApp = function(app) {
return new (this.defaultClass())(app);
};
Navigator.defaultClass = function() {
if (Batman.config.usePushState && Batman.PushStateNavigator.isSupported()) {
return Batman.PushStateNavigator;
} else {
return Batman.HashbangNavigator;
}
};
function Navigator(app) {
this.app = app;
this.handleCurrentLocation = __bind(this.handleCurrentLocation, this);
}
Navigator.prototype.start = function() {
var _this = this;
if (typeof window === 'undefined') {
return;
}
if (this.started) {
return;
}
this.started = true;
this.startWatching();
Batman.currentApp.prevent('ready');
return Batman.setImmediate(function() {
if (_this.started && Batman.currentApp) {
_this.checkInitialHash();
_this.handleCurrentLocation();
return Batman.currentApp.allowAndFire('ready');
}
});
};
Navigator.prototype.stop = function() {
this.stopWatching();
return this.started = false;
};
Navigator.prototype.checkInitialHash = function(location) {
var hash, index, prefix;
if (location == null) {
location = window.location;
}
prefix = Batman.HashbangNavigator.prototype.hashPrefix;
hash = location.hash;
if (hash.length > prefix.length && hash.substr(0, prefix.length) !== prefix) {
return this.initialHash = hash.substr(prefix.length - 1);
} else if ((index = hash.indexOf("##BATMAN##")) !== -1) {
this.initialHash = hash.substr(index + 10);
return this.replaceState(null, '', hash.substr(prefix.length, index - prefix.length), location);
}
};
Navigator.prototype.handleCurrentLocation = function() {
return this.handleLocation(window.location);
};
Navigator.prototype.handleLocation = function(location) {
var path;
path = this.pathFromLocation(location);
if (path === this.cachedPath) {
return;
}
return this.dispatch(path);
};
Navigator.prototype.dispatch = function(params) {
var dispatcher, paramsMixin;
dispatcher = this.app.get('dispatcher');
this.cachedPath = this.initialHash ? (paramsMixin = {
initialHash: this.initialHash
}, delete this.initialHash, dispatcher.dispatch(params, paramsMixin)) : dispatcher.dispatch(params);
return this.cachedPath;
};
Navigator.prototype.redirect = function(params, replaceState) {
var path, pathFromParams, _base;
if (replaceState == null) {
replaceState = false;
}
pathFromParams = typeof (_base = this.app.get('dispatcher')).pathFromParams === "function" ? _base.pathFromParams(params) : void 0;
if (pathFromParams) {
this._lastRedirect = pathFromParams;
}
path = this.dispatch(params);
if (this._lastRedirect) {
this.cachedPath = this._lastRedirect;
}
if (!this._lastRedirect || this._lastRedirect === path) {
this[replaceState ? 'replaceState' : 'pushState'](null, '', path);
}
return path;
};
Navigator.prototype.push = function(params) {
Batman.developer.deprecated("Navigator::push", "Please use Batman.redirect({}) instead.");
return this.redirect(params);
};
Navigator.prototype.replace = function(params) {
Batman.developer.deprecated("Navigator::replace", "Please use Batman.redirect({}, true) instead.");
return this.redirect(params, true);
};
Navigator.prototype.normalizePath = function() {
var i, seg, segments;
segments = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
segments = (function() {
var _i, _len, _results;
_results = [];
for (i = _i = 0, _len = segments.length; _i < _len; i = ++_i) {
seg = segments[i];
_results.push(("" + seg).replace(/^(?!\/)/, '/').replace(/\/+$/, ''));
}
return _results;
})();
return segments.join('') || '/';
};
Navigator.normalizePath = Navigator.prototype.normalizePath;
return Navigator;
})();
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PushStateNavigator = (function(_super) {
__extends(PushStateNavigator, _super);
function PushStateNavigator() {
_ref = PushStateNavigator.__super__.constructor.apply(this, arguments);
return _ref;
}
PushStateNavigator.isSupported = function() {
var _ref1;
return (typeof window !== "undefined" && window !== null ? (_ref1 = window.history) != null ? _ref1.pushState : void 0 : void 0) != null;
};
PushStateNavigator.prototype.startWatching = function() {
return Batman.DOM.addEventListener(window, 'popstate', this.handleCurrentLocation);
};
PushStateNavigator.prototype.stopWatching = function() {
return Batman.DOM.removeEventListener(window, 'popstate', this.handleCurrentLocation);
};
PushStateNavigator.prototype.pushState = function(stateObject, title, path) {
if (path !== this.pathFromLocation(window.location)) {
return window.history.pushState(stateObject, title, this.linkTo(path));
}
};
PushStateNavigator.prototype.replaceState = function(stateObject, title, path) {
if (path !== this.pathFromLocation(window.location)) {
return window.history.replaceState(stateObject, title, this.linkTo(path));
}
};
PushStateNavigator.prototype.linkTo = function(url) {
return this.normalizePath(Batman.config.pathToApp, url);
};
PushStateNavigator.prototype.pathFromLocation = function(location) {
var fullPath, prefixPattern;
fullPath = "" + (location.pathname || '') + (location.search || '');
prefixPattern = new RegExp("^" + (this.normalizePath(Batman.config.pathToApp)));
return this.normalizePath(fullPath.replace(prefixPattern, ''));
};
PushStateNavigator.prototype.handleLocation = function(location) {
var hashbangPath, pushStatePath;
pushStatePath = this.pathFromLocation(location);
hashbangPath = Batman.HashbangNavigator.prototype.pathFromLocation(location);
if (pushStatePath === '/' && hashbangPath !== '/') {
return this.redirect(hashbangPath, true);
} else {
return PushStateNavigator.__super__.handleLocation.apply(this, arguments);
}
};
return PushStateNavigator;
})(Batman.Navigator);
}).call(this);
(function() {
var _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.HashbangNavigator = (function(_super) {
__extends(HashbangNavigator, _super);
function HashbangNavigator() {
this.detectHashChange = __bind(this.detectHashChange, this);
this.handleHashChange = __bind(this.handleHashChange, this);
_ref = HashbangNavigator.__super__.constructor.apply(this, arguments);
return _ref;
}
HashbangNavigator.prototype.hashPrefix = '#!';
if ((typeof window !== "undefined" && window !== null) && 'onhashchange' in window) {
HashbangNavigator.prototype.startWatching = function() {
return Batman.DOM.addEventListener(window, 'hashchange', this.handleHashChange);
};
HashbangNavigator.prototype.stopWatching = function() {
return Batman.DOM.removeEventListener(window, 'hashchange', this.handleHashChange);
};
} else {
HashbangNavigator.prototype.startWatching = function() {
return this.interval = setInterval(this.detectHashChange, 100);
};
HashbangNavigator.prototype.stopWatching = function() {
return this.interval = clearInterval(this.interval);
};
}
HashbangNavigator.prototype.handleHashChange = function() {
if (this.ignoreHashChange) {
return this.ignoreHashChange = false;
}
return this.handleCurrentLocation();
};
HashbangNavigator.prototype.detectHashChange = function() {
if (this.previousHash === window.location.hash) {
return;
}
this.previousHash = window.location.hash;
return this.handleHashChange();
};
HashbangNavigator.prototype.pushState = function(stateObject, title, path) {
var link;
link = this.linkTo(path);
if (link === window.location.hash) {
return;
}
this.ignoreHashChange = true;
return window.location.hash = link;
};
HashbangNavigator.prototype.replaceState = function(stateObject, title, path, loc) {
var link;
if (loc == null) {
loc = window.location;
}
link = this.linkTo(path);
if (link === loc.hash) {
return;
}
this.ignoreHashChange = true;
return loc.replace("" + (loc.pathname || '') + (loc.search || '') + (link || ''));
};
HashbangNavigator.prototype.linkTo = function(url) {
return this.hashPrefix + url;
};
HashbangNavigator.prototype.pathFromLocation = function(location) {
var hash, length;
hash = location.hash;
length = this.hashPrefix.length;
if ((hash != null ? hash.substr(0, length) : void 0) === this.hashPrefix) {
return this.normalizePath(hash.substr(length));
} else {
return '/';
}
};
HashbangNavigator.prototype.handleLocation = function(location) {
var pushStatePath;
if (!Batman.config.usePushState) {
return HashbangNavigator.__super__.handleLocation.apply(this, arguments);
}
pushStatePath = Batman.PushStateNavigator.prototype.pathFromLocation(location);
if (pushStatePath !== '/') {
return location.replace(this.normalizePath("" + Batman.config.pathToApp + (this.linkTo(pushStatePath)) + (this.initialHash ? '##BATMAN##' + this.initialHash : '')));
} else {
return HashbangNavigator.__super__.handleLocation.apply(this, arguments);
}
};
return HashbangNavigator;
})(Batman.Navigator);
}).call(this);
(function() {
Batman.RouteMap = (function() {
RouteMap.prototype.memberRoute = null;
RouteMap.prototype.collectionRoute = null;
function RouteMap() {
this.childrenByOrder = [];
this.childrenByName = {};
}
RouteMap.prototype.routeForParams = function(params) {
var key, route, _i, _len, _ref;
this._cachedRoutes || (this._cachedRoutes = {});
key = this.cacheKey(params);
if (this._cachedRoutes[key]) {
return this._cachedRoutes[key];
} else {
_ref = this.childrenByOrder;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
route = _ref[_i];
if (route.test(params)) {
return (this._cachedRoutes[key] = route);
}
}
}
};
RouteMap.prototype.addRoute = function(name, route) {
var base, names,
_this = this;
this.childrenByOrder.push(route);
if (name.length > 0 && (names = name.split('.')).length > 0) {
base = names.shift();
if (!this.childrenByName[base]) {
this.childrenByName[base] = new Batman.RouteMap;
}
this.childrenByName[base].addRoute(names.join('.'), route);
} else {
if (route.get('member')) {
Batman.developer["do"](function() {
if (_this.memberRoute) {
return Batman.developer.error("Member route with name " + name + " already exists!");
}
});
this.memberRoute = route;
} else {
Batman.developer["do"](function() {
if (_this.collectionRoute) {
return Batman.developer.error("Collection route with name " + name + " already exists!");
}
});
this.collectionRoute = route;
}
}
return true;
};
RouteMap.prototype.cacheKey = function(params) {
if (typeof params === 'string') {
return params;
} else if (params.path != null) {
return params.path;
} else {
return "" + params.controller + "#" + params.action;
}
};
return RouteMap;
})();
}).call(this);
(function() {
var __slice = [].slice;
Batman.RouteMapBuilder = (function() {
RouteMapBuilder.BUILDER_FUNCTIONS = ['resources', 'member', 'collection', 'route', 'root'];
RouteMapBuilder.ROUTES = {
index: {
cardinality: 'collection',
path: function(resource) {
return resource;
},
name: function(resource) {
return resource;
}
},
"new": {
cardinality: 'collection',
path: function(resource) {
return "" + resource + "/new";
},
name: function(resource) {
return "" + resource + ".new";
}
},
show: {
cardinality: 'member',
path: function(resource) {
return "" + resource + "/:id";
},
name: function(resource) {
return resource;
}
},
edit: {
cardinality: 'member',
path: function(resource) {
return "" + resource + "/:id/edit";
},
name: function(resource) {
return "" + resource + ".edit";
}
},
collection: {
cardinality: 'collection',
path: function(resource, name) {
return "" + resource + "/" + name;
},
name: function(resource, name) {
return "" + resource + "." + name;
}
},
member: {
cardinality: 'member',
path: function(resource, name) {
return "" + resource + "/:id/" + name;
},
name: function(resource, name) {
return "" + resource + "." + name;
}
}
};
function RouteMapBuilder(app, routeMap, parent, baseOptions) {
this.app = app;
this.routeMap = routeMap;
this.parent = parent;
this.baseOptions = baseOptions != null ? baseOptions : {};
if (this.parent) {
this.rootPath = this.parent._nestingPath();
this.rootName = this.parent._nestingName();
} else {
this.rootPath = '';
this.rootName = '';
}
}
RouteMapBuilder.prototype.resources = function() {
var action, actions, arg, args, as, callback, childBuilder, controller, included, k, options, path, resourceName, resourceNames, resourceRoot, routeOptions, routeTemplate, v, _i, _j, _k, _len, _len1, _len2, _ref, _ref1;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
resourceNames = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
if (typeof arg === 'string') {
_results.push(arg);
}
}
return _results;
})();
if (typeof args[args.length - 1] === 'function') {
callback = args.pop();
}
if (typeof args[args.length - 1] === 'object') {
options = args.pop();
} else {
options = {};
}
actions = {
index: true,
"new": true,
show: true,
edit: true
};
if (options.except) {
_ref = options.except;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
actions[k] = false;
}
delete options.except;
} else if (options.only) {
for (k in actions) {
v = actions[k];
actions[k] = false;
}
_ref1 = options.only;
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
k = _ref1[_j];
actions[k] = true;
}
delete options.only;
}
for (_k = 0, _len2 = resourceNames.length; _k < _len2; _k++) {
resourceName = resourceNames[_k];
resourceRoot = Batman.helpers.pluralize(resourceName);
controller = Batman.helpers.camelize(resourceRoot, true);
childBuilder = this._childBuilder({
controller: controller
});
if (callback != null) {
callback.call(childBuilder);
}
for (action in actions) {
included = actions[action];
if (!(included)) {
continue;
}
routeTemplate = this.constructor.ROUTES[action];
as = routeTemplate.name(resourceRoot);
path = routeTemplate.path(resourceRoot);
routeOptions = Batman.extend({
controller: controller,
action: action,
path: path,
as: as
}, options);
childBuilder[routeTemplate.cardinality](action, routeOptions);
}
}
return true;
};
RouteMapBuilder.prototype.member = function() {
return this._addRoutesWithCardinality.apply(this, ['member'].concat(__slice.call(arguments)));
};
RouteMapBuilder.prototype.collection = function() {
return this._addRoutesWithCardinality.apply(this, ['collection'].concat(__slice.call(arguments)));
};
RouteMapBuilder.prototype.root = function(signature, options) {
return this.route('/', signature, options);
};
RouteMapBuilder.prototype.route = function(path, signature, options, callback) {
if (!callback) {
if (typeof options === 'function') {
callback = options;
options = void 0;
} else if (typeof signature === 'function') {
callback = signature;
signature = void 0;
}
}
if (!options) {
if (typeof signature === 'string') {
options = {
signature: signature
};
} else {
options = signature;
}
options || (options = {});
} else {
if (signature) {
options.signature = signature;
}
}
if (callback) {
options.callback = callback;
}
options.as || (options.as = this._nameFromPath(path));
options.path = path;
return this._addRoute(options);
};
RouteMapBuilder.prototype._addRoutesWithCardinality = function() {
var cardinality, name, names, options, resourceRoot, routeOptions, routeTemplate, _i, _j, _len;
cardinality = arguments[0], names = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), options = arguments[_i++];
if (typeof options === 'string') {
names.push(options);
options = {};
}
options = Batman.extend({}, this.baseOptions, options);
options[cardinality] = true;
routeTemplate = this.constructor.ROUTES[cardinality];
resourceRoot = Batman.helpers.underscore(options.controller);
for (_j = 0, _len = names.length; _j < _len; _j++) {
name = names[_j];
routeOptions = Batman.extend({
action: name
}, options);
if (routeOptions.path == null) {
routeOptions.path = routeTemplate.path(resourceRoot, name);
}
if (routeOptions.as == null) {
routeOptions.as = routeTemplate.name(resourceRoot, name);
}
this._addRoute(routeOptions);
}
return true;
};
RouteMapBuilder.prototype._addRoute = function(options) {
var klass, name, path, route;
if (options == null) {
options = {};
}
path = this.rootPath + options.path;
name = this.rootName + Batman.helpers.camelize(options.as, true);
delete options.as;
delete options.path;
klass = options.callback ? Batman.CallbackActionRoute : Batman.ControllerActionRoute;
options.app = this.app;
route = new klass(path, options);
return this.routeMap.addRoute(name, route);
};
RouteMapBuilder.prototype._nameFromPath = function(path) {
path = path.replace(Batman.Route.regexps.namedOrSplat, '').replace(/\/+/g, '.').replace(/(^\.)|(\.$)/g, '');
return path;
};
RouteMapBuilder.prototype._nestingPath = function() {
var nestingParam, nestingSegment;
if (!this.parent) {
return "";
} else {
nestingParam = ":" + Batman.helpers.singularize(this.baseOptions.controller) + "Id";
nestingSegment = Batman.helpers.underscore(this.baseOptions.controller);
return "" + (this.parent._nestingPath()) + nestingSegment + "/" + nestingParam + "/";
}
};
RouteMapBuilder.prototype._nestingName = function() {
if (!this.parent) {
return "";
} else {
return this.parent._nestingName() + this.baseOptions.controller + ".";
}
};
RouteMapBuilder.prototype._childBuilder = function(baseOptions) {
if (baseOptions == null) {
baseOptions = {};
}
return new Batman.RouteMapBuilder(this.app, this.routeMap, this, baseOptions);
};
return RouteMapBuilder;
})();
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.App = (function(_super) {
var name, _fn, _i, _len, _ref1,
_this = this;
__extends(App, _super);
function App() {
_ref = App.__super__.constructor.apply(this, arguments);
return _ref;
}
App.classAccessor('currentParams', {
get: function() {
return new Batman.Hash;
},
'final': true
});
App.classAccessor('paramsManager', {
get: function() {
var nav, params;
if (!(nav = this.get('navigator'))) {
return;
}
params = this.get('currentParams');
return params.replacer = new Batman.ParamsReplacer(nav, params);
},
'final': true
});
App.classAccessor('paramsPusher', {
get: function() {
var nav, params;
if (!(nav = this.get('navigator'))) {
return;
}
params = this.get('currentParams');
return params.pusher = new Batman.ParamsPusher(nav, params);
},
'final': true
});
App.classAccessor('routes', function() {
return new Batman.NamedRouteQuery(this.get('routeMap'));
});
App.classAccessor('routeMap', function() {
return new Batman.RouteMap;
});
App.classAccessor('routeMapBuilder', function() {
return new Batman.RouteMapBuilder(this, this.get('routeMap'));
});
App.classAccessor('dispatcher', function() {
return new Batman.Dispatcher(this, this.get('routeMap'));
});
App.classAccessor('controllers', function() {
return this.get('dispatcher.controllers');
});
App.layout = void 0;
App.shouldAllowEvent = {};
_ref1 = Batman.RouteMapBuilder.BUILDER_FUNCTIONS;
_fn = function(name) {
return App[name] = function() {
var _ref2;
return (_ref2 = this.get('routeMapBuilder'))[name].apply(_ref2, arguments);
};
};
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
name = _ref1[_i];
_fn(name);
}
App.event('ready').oneShot = true;
App.event('run').oneShot = true;
App.run = function() {
var LayoutView, layout, layoutClass, _ref2,
_this = this;
if (Batman.currentApp) {
if (Batman.currentApp === this) {
return;
}
Batman.currentApp.stop();
}
if (this.hasRun) {
return false;
}
if (this.isPrevented('run')) {
this.wantsToRun = true;
return false;
} else {
delete this.wantsToRun;
}
Batman.currentApp = this;
Batman.App.set('current', this);
if (this.get('dispatcher') == null) {
this.set('dispatcher', new Batman.Dispatcher(this, this.get('routeMap')));
this.set('controllers', this.get('dispatcher.controllers'));
}
if (this.get('navigator') == null) {
this.set('navigator', Batman.Navigator.forApp(this));
Batman.navigator = this.get('navigator');
this.on('run', function() {
if (Object.keys(_this.get('dispatcher').routeMap).length > 0) {
return Batman.navigator.start();
}
});
}
this.observe('layout', function(layout) {
return layout != null ? layout.on('ready', function() {
return _this.fire('ready');
}) : void 0;
});
layout = this.get('layout');
if (layout) {
if (typeof layout === 'string') {
layoutClass = this[Batman.helpers.camelize(layout) + 'View'];
}
} else {
if (layout !== null) {
layoutClass = (LayoutView = (function(_super1) {
__extends(LayoutView, _super1);
function LayoutView() {
_ref2 = LayoutView.__super__.constructor.apply(this, arguments);
return _ref2;
}
return LayoutView;
})(Batman.View));
}
}
if (layoutClass) {
layout = this.set('layout', new layoutClass({
node: document.documentElement
}));
layout.propagateToSubviews('viewWillAppear');
layout.initializeBindings();
layout.propagateToSubviews('isInDOM', true);
layout.propagateToSubviews('viewDidAppear');
}
if (Batman.config.translations) {
this.set('t', Batman.I18N.get('translations'));
}
this.hasRun = true;
this.fire('run');
return this;
};
App.event('ready').oneShot = true;
App.event('stop').oneShot = true;
App.stop = function() {
var _ref2;
if ((_ref2 = this.navigator) != null) {
_ref2.stop();
}
Batman.navigator = null;
this.hasRun = false;
this.fire('stop');
return this;
};
return App;
}).call(this, Batman.Object);
}).call(this);
(function() {
Batman.Association = (function() {
Association.prototype.associationType = '';
Association.prototype.isPolymorphic = false;
Association.prototype.defaultOptions = {
saveInline: true,
autoload: true,
nestUrl: false
};
function Association(model, label, options) {
var association, defaultOptions, encoder, encoderKey, getAccessor;
this.model = model;
this.label = label;
if (options == null) {
options = {};
}
defaultOptions = {
namespace: Batman.currentApp,
name: Batman.helpers.camelize(Batman.helpers.singularize(this.label))
};
this.options = Batman.extend(defaultOptions, this.defaultOptions, options);
if (this.options.nestUrl) {
if (this.model.urlNestsUnder == null) {
Batman.developer.error("You must persist the the model " + this.model.constructor.name + " to use the url helpers on an association");
}
this.model.urlNestsUnder(Batman.helpers.underscore(this.getRelatedModel().get('resourceName')));
}
if (this.options.extend != null) {
Batman.extend(this, this.options.extend);
}
encoder = {
encode: this.options.saveInline ? this.encoder() : false,
decode: this.decoder()
};
encoderKey = options.encoderKey || this.label;
this.model.encode(encoderKey, encoder);
association = this;
getAccessor = function() {
return association.getAccessor.call(this, association, this.model, this.label);
};
this.model.accessor(this.label, {
get: getAccessor,
set: model.defaultAccessor.set,
unset: model.defaultAccessor.unset
});
}
Association.prototype.getRelatedModel = function() {
var className, relatedModel, scope;
scope = this.options.namespace || Batman.currentApp;
className = this.options.name;
relatedModel = scope != null ? scope[className] : void 0;
Batman.developer["do"](function() {
if ((Batman.currentApp != null) && !relatedModel) {
return Batman.developer.warn("Related model " + className + " hasn't loaded yet.");
}
});
return relatedModel;
};
Association.prototype.getFromAttributes = function(record) {
return record.get("attributes." + this.label);
};
Association.prototype.setIntoAttributes = function(record, value) {
return record.get('attributes').set(this.label, value);
};
Association.prototype.inverse = function() {
var inverse, relatedAssocs,
_this = this;
if (relatedAssocs = this.getRelatedModel()._batman.get('associations')) {
if (this.options.inverseOf) {
return relatedAssocs.getByLabel(this.options.inverseOf);
}
inverse = null;
relatedAssocs.forEach(function(label, assoc) {
if (assoc.getRelatedModel() === _this.model) {
return inverse = assoc;
}
});
return inverse;
}
};
Association.prototype.reset = function() {
delete this.index;
return true;
};
return Association;
})();
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PluralAssociation = (function(_super) {
__extends(PluralAssociation, _super);
PluralAssociation.prototype.proxyClass = Batman.AssociationSet;
PluralAssociation.prototype.isSingular = false;
function PluralAssociation() {
PluralAssociation.__super__.constructor.apply(this, arguments);
this._resetSetHashes();
}
PluralAssociation.prototype.setForRecord = function(record) {
var childModelSetIndex, indexValue,
_this = this;
indexValue = this.indexValueForRecord(record);
childModelSetIndex = this.setIndex();
Batman.Property.withoutTracking(function() {
return _this._setsByRecord.getOrSet(record, function() {
var existingValueSet, newSet;
if (indexValue != null) {
existingValueSet = _this._setsByValue.get(indexValue);
if (existingValueSet != null) {
return existingValueSet;
}
}
newSet = _this.proxyClassInstanceForKey(indexValue);
if (indexValue != null) {
_this._setsByValue.set(indexValue, newSet);
}
return newSet;
});
});
if (indexValue != null) {
return childModelSetIndex.get(indexValue);
} else {
return this._setsByRecord.get(record);
}
};
PluralAssociation.prototype.setForKey = Batman.Property.wrapTrackingPrevention(function(indexValue) {
var foundSet,
_this = this;
foundSet = void 0;
this._setsByRecord.forEach(function(record, set) {
if (foundSet != null) {
return;
}
if (_this.indexValueForRecord(record) === indexValue) {
return foundSet = set;
}
});
if (foundSet != null) {
foundSet.foreignKeyValue = indexValue;
return foundSet;
}
return this._setsByValue.getOrSet(indexValue, function() {
return _this.proxyClassInstanceForKey(indexValue);
});
});
PluralAssociation.prototype.proxyClassInstanceForKey = function(indexValue) {
return new this.proxyClass(indexValue, this);
};
PluralAssociation.prototype.getAccessor = function(self, model, label) {
var relatedRecords, setInAttributes,
_this = this;
if (!self.getRelatedModel()) {
return;
}
if (setInAttributes = self.getFromAttributes(this)) {
return setInAttributes;
} else {
relatedRecords = self.setForRecord(this);
self.setIntoAttributes(this, relatedRecords);
Batman.Property.withoutTracking(function() {
if (self.options.autoload && !_this.isNew() && !relatedRecords.loaded) {
return relatedRecords.load(function(error, records) {
if (error) {
throw error;
}
});
}
});
return relatedRecords;
}
};
PluralAssociation.prototype.parentSetIndex = function() {
this.parentIndex || (this.parentIndex = this.model.get('loaded').indexedByUnique(this.primaryKey));
return this.parentIndex;
};
PluralAssociation.prototype.setIndex = function() {
this.index || (this.index = new Batman.AssociationSetIndex(this, this[this.indexRelatedModelOn]));
return this.index;
};
PluralAssociation.prototype.indexValueForRecord = function(record) {
return record.get(this.primaryKey);
};
PluralAssociation.prototype.reset = function() {
PluralAssociation.__super__.reset.apply(this, arguments);
return this._resetSetHashes();
};
PluralAssociation.prototype._resetSetHashes = function() {
this._setsByRecord = new Batman.SimpleHash;
return this._setsByValue = new Batman.SimpleHash;
};
return PluralAssociation;
})(Batman.Association);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.HasManyAssociation = (function(_super) {
__extends(HasManyAssociation, _super);
HasManyAssociation.prototype.associationType = 'hasMany';
HasManyAssociation.prototype.indexRelatedModelOn = 'foreignKey';
function HasManyAssociation(model, label, options) {
if (options != null ? options.as : void 0) {
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Batman.PolymorphicHasManyAssociation, arguments, function(){});
}
HasManyAssociation.__super__.constructor.apply(this, arguments);
this.primaryKey = this.options.primaryKey || "id";
this.foreignKey = this.options.foreignKey || ("" + (Batman.helpers.underscore(model.get('resourceName'))) + "_id");
}
HasManyAssociation.prototype.apply = function(baseSaveError, base) {
var relations, set,
_this = this;
if (!baseSaveError) {
if (relations = this.getFromAttributes(base)) {
relations.forEach(function(model) {
return model.set(_this.foreignKey, base.get(_this.primaryKey));
});
}
base.set(this.label, set = this.setForRecord(base));
if (base.lifecycle.get('state') === 'creating') {
return set.markAsLoaded();
}
}
};
HasManyAssociation.prototype.encoder = function() {
var association;
association = this;
return function(relationSet, _, __, record) {
var jsonArray;
if (relationSet != null) {
jsonArray = [];
relationSet.forEach(function(relation) {
var relationJSON;
relationJSON = relation.toJSON();
if (!association.inverse() || association.inverse().options.encodeForeignKey) {
relationJSON[association.foreignKey] = record.get(association.primaryKey);
}
return jsonArray.push(relationJSON);
});
}
return jsonArray;
};
};
HasManyAssociation.prototype.decoder = function() {
var association;
association = this;
return function(data, key, _, __, parentRecord) {
var children, id, jsonObject, newChildren, record, recordsToAdd, recordsToMap, relatedModel, _i, _len, _ref;
if (!(relatedModel = association.getRelatedModel())) {
Batman.developer.error("Can't decode model " + association.options.name + " because it hasn't been loaded yet!");
return;
}
children = association.setForRecord(parentRecord);
newChildren = children.filter(function(relation) {
return relation.isNew();
}).toArray();
recordsToMap = [];
recordsToAdd = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
jsonObject = data[_i];
id = jsonObject[relatedModel.primaryKey];
record = relatedModel._loadIdentity(id);
if (record != null) {
recordsToAdd.push(record);
} else {
if (newChildren.length > 0) {
record = newChildren.shift();
if (id != null) {
recordsToMap.push(record);
}
} else {
record = new relatedModel;
if (id != null) {
recordsToMap.push(record);
}
recordsToAdd.push(record);
}
}
record._withoutDirtyTracking(function() {
this.fromJSON(jsonObject);
if (association.options.inverseOf) {
return record.set(association.options.inverseOf, parentRecord);
}
});
}
(_ref = relatedModel.get('loaded')).add.apply(_ref, recordsToMap);
children.add.apply(children, recordsToAdd);
children.markAsLoaded();
return children;
};
};
return HasManyAssociation;
})(Batman.PluralAssociation);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicHasManyAssociation = (function(_super) {
__extends(PolymorphicHasManyAssociation, _super);
PolymorphicHasManyAssociation.prototype.proxyClass = Batman.PolymorphicAssociationSet;
PolymorphicHasManyAssociation.prototype.isPolymorphic = true;
function PolymorphicHasManyAssociation(model, label, options) {
options.inverseOf = this.foreignLabel = options.as;
delete options.as;
options.foreignKey || (options.foreignKey = "" + this.foreignLabel + "_id");
PolymorphicHasManyAssociation.__super__.constructor.call(this, model, label, options);
this.foreignTypeKey = options.foreignTypeKey || ("" + this.foreignLabel + "_type");
this.model.encode(this.foreignTypeKey);
}
PolymorphicHasManyAssociation.prototype.apply = function(baseSaveError, base) {
var relations,
_this = this;
if (!baseSaveError) {
if (relations = this.getFromAttributes(base)) {
PolymorphicHasManyAssociation.__super__.apply.apply(this, arguments);
relations.forEach(function(model) {
return model.set(_this.foreignTypeKey, _this.modelType());
});
}
}
};
PolymorphicHasManyAssociation.prototype.proxyClassInstanceForKey = function(indexValue) {
return new this.proxyClass(indexValue, this.modelType(), this);
};
PolymorphicHasManyAssociation.prototype.getRelatedModelForType = function(type) {
var relatedModel, scope;
scope = this.options.namespace || Batman.currentApp;
if (type) {
relatedModel = scope != null ? scope[type] : void 0;
relatedModel || (relatedModel = scope != null ? scope[Batman.helpers.camelize(type)] : void 0);
} else {
relatedModel = this.getRelatedModel();
}
Batman.developer["do"](function() {
if ((Batman.currentApp != null) && !relatedModel) {
return Batman.developer.warn("Related model " + type + " for polymorphic association not found.");
}
});
return relatedModel;
};
PolymorphicHasManyAssociation.prototype.modelType = function() {
return this.model.get('resourceName');
};
PolymorphicHasManyAssociation.prototype.setIndex = function() {
return this.typeIndex || (this.typeIndex = new Batman.PolymorphicAssociationSetIndex(this, this.modelType(), this[this.indexRelatedModelOn]));
};
PolymorphicHasManyAssociation.prototype.encoder = function() {
var association;
association = this;
return function(relationSet, _, __, record) {
var jsonArray;
if (relationSet != null) {
jsonArray = [];
relationSet.forEach(function(relation) {
var relationJSON;
relationJSON = relation.toJSON();
relationJSON[association.foreignKey] = record.get(association.primaryKey);
relationJSON[association.foreignTypeKey] = association.modelType();
return jsonArray.push(relationJSON);
});
}
return jsonArray;
};
};
PolymorphicHasManyAssociation.prototype.decoder = function() {
var association;
association = this;
return function(data, key, _, __, parentRecord) {
var children, id, jsonObject, newChildren, record, recordsToAdd, relatedModel, type, _i, _len;
children = association.getFromAttributes(parentRecord) || association.setForRecord(parentRecord);
newChildren = children.filter(function(relation) {
return relation.isNew();
}).toArray();
recordsToAdd = [];
for (_i = 0, _len = data.length; _i < _len; _i++) {
jsonObject = data[_i];
type = jsonObject[association.options.foreignTypeKey];
if (!(relatedModel = association.getRelatedModelForType(type))) {
Batman.developer.error("Can't decode model " + association.options.name + " because it hasn't been loaded yet!");
return;
}
id = jsonObject[relatedModel.primaryKey];
record = relatedModel._loadIdentity(id);
if (record != null) {
record._withoutDirtyTracking(function() {
return this.fromJSON(jsonObject);
});
recordsToAdd.push(record);
} else {
if (newChildren.length > 0) {
record = newChildren.shift();
record._withoutDirtyTracking(function() {
return this.fromJSON(jsonObject);
});
record = relatedModel._mapIdentity(record);
} else {
record = relatedModel._makeOrFindRecordFromData(jsonObject);
recordsToAdd.push(record);
}
}
if (association.options.inverseOf) {
record._withoutDirtyTracking(function() {
return record.set(association.options.inverseOf, parentRecord);
});
}
}
children.add.apply(children, recordsToAdd);
children.markAsLoaded();
return children;
};
};
return PolymorphicHasManyAssociation;
})(Batman.HasManyAssociation);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.SingularAssociation = (function(_super) {
__extends(SingularAssociation, _super);
function SingularAssociation() {
_ref = SingularAssociation.__super__.constructor.apply(this, arguments);
return _ref;
}
SingularAssociation.prototype.isSingular = true;
SingularAssociation.prototype.getAccessor = function(association, model, label) {
var proxy, record, recordInAttributes,
_this = this;
if (recordInAttributes = association.getFromAttributes(this)) {
return recordInAttributes;
}
if (association.getRelatedModel()) {
proxy = this.associationProxy(association);
record = false;
if (proxy._loadSetter == null) {
proxy._loadSetter = proxy.once('loaded', function(child) {
return _this._withoutDirtyTracking(function() {
return this.set(association.label, child);
});
});
}
if (!Batman.Property.withoutTracking(function() {
return proxy.get('loaded');
})) {
if (association.options.autoload) {
Batman.Property.withoutTracking(function() {
return proxy.load();
});
} else {
record = proxy.loadFromLocal();
}
}
return record || proxy;
}
};
SingularAssociation.prototype.setIndex = function() {
return this.index || (this.index = new Batman.UniqueAssociationSetIndex(this, this[this.indexRelatedModelOn]));
};
return SingularAssociation;
})(Batman.Association);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.HasOneAssociation = (function(_super) {
__extends(HasOneAssociation, _super);
HasOneAssociation.prototype.associationType = 'hasOne';
HasOneAssociation.prototype.proxyClass = Batman.HasOneProxy;
HasOneAssociation.prototype.indexRelatedModelOn = 'foreignKey';
function HasOneAssociation() {
HasOneAssociation.__super__.constructor.apply(this, arguments);
this.primaryKey = this.options.primaryKey || "id";
this.foreignKey = this.options.foreignKey || ("" + (Batman.helpers.underscore(this.model.get('resourceName'))) + "_id");
}
HasOneAssociation.prototype.apply = function(baseSaveError, base) {
var relation;
if (!baseSaveError) {
if (relation = this.getFromAttributes(base)) {
return relation.set(this.foreignKey, base.get(this.primaryKey));
}
}
};
HasOneAssociation.prototype.encoder = function() {
var association;
association = this;
return function(val, key, object, record) {
var json;
if (!association.options.saveInline) {
return;
}
if (json = val.toJSON()) {
json[association.foreignKey] = record.get(association.primaryKey);
}
return json;
};
};
HasOneAssociation.prototype.decoder = function() {
var association;
association = this;
return function(data, _, __, ___, parentRecord) {
var record, relatedModel;
if (!data) {
return;
}
relatedModel = association.getRelatedModel();
record = relatedModel.createFromJSON(data);
if (association.options.inverseOf) {
record.set(association.options.inverseOf, parentRecord);
}
return record;
};
};
return HasOneAssociation;
})(Batman.SingularAssociation);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.BelongsToAssociation = (function(_super) {
__extends(BelongsToAssociation, _super);
BelongsToAssociation.prototype.associationType = 'belongsTo';
BelongsToAssociation.prototype.proxyClass = Batman.BelongsToProxy;
BelongsToAssociation.prototype.indexRelatedModelOn = 'primaryKey';
BelongsToAssociation.prototype.defaultOptions = {
saveInline: false,
autoload: true,
encodeForeignKey: true
};
function BelongsToAssociation(model, label, options) {
if (options != null ? options.polymorphic : void 0) {
delete options.polymorphic;
return (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Batman.PolymorphicBelongsToAssociation, arguments, function(){});
}
BelongsToAssociation.__super__.constructor.apply(this, arguments);
this.foreignKey = this.options.foreignKey || ("" + this.label + "_id");
this.primaryKey = this.options.primaryKey || "id";
if (this.options.encodeForeignKey) {
this.model.encode(this.foreignKey);
}
}
BelongsToAssociation.prototype.encoder = function() {
return function(val) {
return val.toJSON();
};
};
BelongsToAssociation.prototype.decoder = function() {
var association;
association = this;
return function(data, _, __, ___, childRecord) {
var inverse, record, relatedModel;
relatedModel = association.getRelatedModel();
record = relatedModel.createFromJSON(data);
if (association.options.inverseOf) {
if (inverse = association.inverse()) {
if (inverse instanceof Batman.HasManyAssociation) {
childRecord.set(association.foreignKey, record.get(association.primaryKey));
} else {
record.set(inverse.label, childRecord);
}
}
}
childRecord.set(association.label, record);
return record;
};
};
BelongsToAssociation.prototype.apply = function(base) {
var foreignValue, model;
if (model = base.get(this.label)) {
foreignValue = model.get(this.primaryKey);
if (foreignValue !== void 0) {
return base.set(this.foreignKey, foreignValue);
}
}
};
return BelongsToAssociation;
})(Batman.SingularAssociation);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PolymorphicBelongsToAssociation = (function(_super) {
__extends(PolymorphicBelongsToAssociation, _super);
PolymorphicBelongsToAssociation.prototype.isPolymorphic = true;
PolymorphicBelongsToAssociation.prototype.proxyClass = Batman.PolymorphicBelongsToProxy;
PolymorphicBelongsToAssociation.prototype.defaultOptions = Batman.mixin({}, Batman.BelongsToAssociation.prototype.defaultOptions, {
encodeForeignTypeKey: true
});
function PolymorphicBelongsToAssociation() {
PolymorphicBelongsToAssociation.__super__.constructor.apply(this, arguments);
this.foreignTypeKey = this.options.foreignTypeKey || ("" + this.label + "_type");
if (this.options.encodeForeignTypeKey) {
this.model.encode(this.foreignTypeKey);
}
this.typeIndicies = {};
}
PolymorphicBelongsToAssociation.prototype.getRelatedModel = false;
PolymorphicBelongsToAssociation.prototype.setIndex = false;
PolymorphicBelongsToAssociation.prototype.inverse = false;
PolymorphicBelongsToAssociation.prototype.apply = function(base) {
var foreignTypeValue, instanceOrProxy;
PolymorphicBelongsToAssociation.__super__.apply.apply(this, arguments);
if (instanceOrProxy = base.get(this.label)) {
foreignTypeValue = instanceOrProxy instanceof Batman.PolymorphicBelongsToProxy ? instanceOrProxy.get('foreignTypeValue') : instanceOrProxy.constructor.get('resourceName');
return base.set(this.foreignTypeKey, foreignTypeValue);
}
};
PolymorphicBelongsToAssociation.prototype.getAccessor = function(self, model, label) {
var proxy, recordInAttributes;
if (recordInAttributes = self.getFromAttributes(this)) {
return recordInAttributes;
}
if (self.getRelatedModelForType(this.get(self.foreignTypeKey))) {
proxy = this.associationProxy(self);
Batman.Property.withoutTracking(function() {
if (!proxy.get('loaded') && self.options.autoload) {
return proxy.load();
}
});
return proxy;
}
};
PolymorphicBelongsToAssociation.prototype.url = function(recordOptions) {
var ending, helper, id, inverse, root, type, _ref, _ref1;
type = (_ref = recordOptions.data) != null ? _ref[this.foreignTypeKey] : void 0;
if (type && (inverse = this.inverseForType(type))) {
root = Batman.helpers.pluralize(type).toLowerCase();
id = (_ref1 = recordOptions.data) != null ? _ref1[this.foreignKey] : void 0;
helper = inverse.isSingular ? "singularize" : "pluralize";
ending = Batman.helpers[helper](inverse.label);
return "/" + root + "/" + id + "/" + ending;
}
};
PolymorphicBelongsToAssociation.prototype.getRelatedModelForType = function(type) {
var relatedModel, scope;
scope = this.options.namespace || Batman.currentApp;
if (type) {
relatedModel = scope != null ? scope[type] : void 0;
relatedModel || (relatedModel = scope != null ? scope[Batman.helpers.camelize(type)] : void 0);
}
Batman.developer["do"](function() {
if ((Batman.currentApp != null) && !relatedModel) {
return Batman.developer.warn("Related model " + type + " for polymorphic association not found.");
}
});
return relatedModel;
};
PolymorphicBelongsToAssociation.prototype.setIndexForType = function(type) {
var _base;
(_base = this.typeIndicies)[type] || (_base[type] = new Batman.PolymorphicUniqueAssociationSetIndex(this, type, this.primaryKey));
return this.typeIndicies[type];
};
PolymorphicBelongsToAssociation.prototype.inverseForType = function(type) {
var inverse, relatedAssocs, _ref,
_this = this;
if (relatedAssocs = (_ref = this.getRelatedModelForType(type)) != null ? _ref._batman.get('associations') : void 0) {
if (this.options.inverseOf) {
return relatedAssocs.getByLabel(this.options.inverseOf);
}
inverse = null;
relatedAssocs.forEach(function(label, assoc) {
if (assoc.getRelatedModel() === _this.model) {
return inverse = assoc;
}
});
return inverse;
}
};
PolymorphicBelongsToAssociation.prototype.decoder = function() {
var association;
association = this;
return function(data, key, response, ___, childRecord) {
var foreignTypeValue, inverse, record, relatedModel;
foreignTypeValue = response[association.foreignTypeKey] || childRecord.get(association.foreignTypeKey);
relatedModel = association.getRelatedModelForType(foreignTypeValue);
record = relatedModel.createFromJSON(data);
if (association.options.inverseOf) {
if (inverse = association.inverseForType(foreignTypeValue)) {
if (inverse instanceof Batman.PolymorphicHasManyAssociation) {
childRecord.set(association.foreignKey, record.get(association.primaryKey));
childRecord.set(association.foreignTypeKey, foreignTypeValue);
} else {
record.set(inverse.label, childRecord);
}
}
}
childRecord.set(association.label, record);
return record;
};
};
return PolymorphicBelongsToAssociation;
})(Batman.BelongsToAssociation);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.Validator = (function(_super) {
__extends(Validator, _super);
Validator.triggers = function() {
var triggers;
triggers = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (this._triggers != null) {
return this._triggers.concat(triggers);
} else {
return this._triggers = triggers;
}
};
Validator.options = function() {
var options;
options = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (this._options != null) {
return this._options.concat(options);
} else {
return this._options = options;
}
};
Validator.matches = function(options) {
var key, results, shouldReturn, value, _ref, _ref1;
results = {};
shouldReturn = false;
for (key in options) {
value = options[key];
if (~((_ref = this._options) != null ? _ref.indexOf(key) : void 0)) {
results[key] = value;
}
if (~((_ref1 = this._triggers) != null ? _ref1.indexOf(key) : void 0)) {
results[key] = value;
shouldReturn = true;
}
}
if (shouldReturn) {
return results;
}
};
function Validator() {
var mixins, options;
options = arguments[0], mixins = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
this.options = options;
Validator.__super__.constructor.apply(this, mixins);
}
Validator.prototype.validate = function(record) {
return Batman.developer.error("You must override validate in Batman.Validator subclasses.");
};
Validator.prototype.format = function(key, messageKey, interpolations) {
return Batman.t("errors.messages." + messageKey, interpolations);
};
Validator.prototype.handleBlank = function(value) {
if (this.options.allowBlank && !Batman.PresenceValidator.prototype.isPresent(value)) {
return true;
}
};
return Validator;
})(Batman.Object);
}).call(this);
(function() {
Batman.Validators = [];
Batman.extend(Batman.translate.messages, {
errors: {
base: {
format: "%{message}"
},
format: "%{attribute} %{message}",
messages: {
too_short: "must be at least %{count} characters",
too_long: "must be less than %{count} characters",
wrong_length: "must be %{count} characters",
blank: "can't be blank",
not_numeric: "must be a number",
greater_than: "must be greater than %{count}",
greater_than_or_equal_to: "must be greater than or equal to %{count}",
equal_to: "must be equal to %{count}",
less_than: "must be less than %{count}",
less_than_or_equal_to: "must be less than or equal to %{count}",
not_matching: "is not valid",
invalid_association: "is not valid",
not_included_in_list: "is not included in the list",
included_in_list: "is included in the list"
}
}
});
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.RegExpValidator = (function(_super) {
__extends(RegExpValidator, _super);
RegExpValidator.triggers('regexp', 'pattern');
RegExpValidator.options('allowBlank');
function RegExpValidator(options) {
var _ref;
this.regexp = (_ref = options.regexp) != null ? _ref : options.pattern;
RegExpValidator.__super__.constructor.apply(this, arguments);
}
RegExpValidator.prototype.validateEach = function(errors, record, key, callback) {
var value;
value = record.get(key);
if (this.handleBlank(value)) {
return callback();
}
if ((value == null) || value === '' || !this.regexp.test(value)) {
errors.add(key, this.format(key, 'not_matching'));
}
return callback();
};
return RegExpValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.RegExpValidator);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.PresenceValidator = (function(_super) {
__extends(PresenceValidator, _super);
function PresenceValidator() {
_ref = PresenceValidator.__super__.constructor.apply(this, arguments);
return _ref;
}
PresenceValidator.triggers('presence');
PresenceValidator.prototype.validateEach = function(errors, record, key, callback) {
var value;
value = record.get(key);
if (!this.isPresent(value)) {
errors.add(key, this.format(key, 'blank'));
}
return callback();
};
PresenceValidator.prototype.isPresent = function(value) {
return (value != null) && value !== '';
};
return PresenceValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.PresenceValidator);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.NumericValidator = (function(_super) {
__extends(NumericValidator, _super);
function NumericValidator() {
_ref = NumericValidator.__super__.constructor.apply(this, arguments);
return _ref;
}
NumericValidator.triggers('numeric', 'greaterThan', 'greaterThanOrEqualTo', 'equalTo', 'lessThan', 'lessThanOrEqualTo');
NumericValidator.options('allowBlank');
NumericValidator.prototype.validateEach = function(errors, record, key, callback) {
var options, value;
options = this.options;
value = record.get(key);
if (this.handleBlank(value)) {
return callback();
}
if ((value == null) || !(this.isNumeric(value) || this.canCoerceToNumeric(value))) {
errors.add(key, this.format(key, 'not_numeric'));
} else {
if ((options.greaterThan != null) && value <= options.greaterThan) {
errors.add(key, this.format(key, 'greater_than', {
count: options.greaterThan
}));
}
if ((options.greaterThanOrEqualTo != null) && value < options.greaterThanOrEqualTo) {
errors.add(key, this.format(key, 'greater_than_or_equal_to', {
count: options.greaterThanOrEqualTo
}));
}
if ((options.equalTo != null) && value !== options.equalTo) {
errors.add(key, this.format(key, 'equal_to', {
count: options.equalTo
}));
}
if ((options.lessThan != null) && value >= options.lessThan) {
errors.add(key, this.format(key, 'less_than', {
count: options.lessThan
}));
}
if ((options.lessThanOrEqualTo != null) && value > options.lessThanOrEqualTo) {
errors.add(key, this.format(key, 'less_than_or_equal_to', {
count: options.lessThanOrEqualTo
}));
}
}
return callback();
};
NumericValidator.prototype.isNumeric = function(value) {
return !isNaN(parseFloat(value)) && isFinite(value);
};
NumericValidator.prototype.canCoerceToNumeric = function(value) {
return (value - 0) == value && value.length > 0;
};
return NumericValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.NumericValidator);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.LengthValidator = (function(_super) {
__extends(LengthValidator, _super);
LengthValidator.triggers('minLength', 'maxLength', 'length', 'lengthWithin', 'lengthIn');
LengthValidator.options('allowBlank');
function LengthValidator(options) {
var range;
if (range = options.lengthIn || options.lengthWithin) {
options.minLength = range[0];
options.maxLength = range[1] || -1;
delete options.lengthWithin;
delete options.lengthIn;
}
LengthValidator.__super__.constructor.apply(this, arguments);
}
LengthValidator.prototype.validateEach = function(errors, record, key, callback) {
var options, value;
options = this.options;
value = record.get(key);
if (value !== '' && this.handleBlank(value)) {
return callback();
}
if (value == null) {
value = [];
}
if (options.minLength && value.length < options.minLength) {
errors.add(key, this.format(key, 'too_short', {
count: options.minLength
}));
}
if (options.maxLength && value.length > options.maxLength) {
errors.add(key, this.format(key, 'too_long', {
count: options.maxLength
}));
}
if (options.length && value.length !== options.length) {
errors.add(key, this.format(key, 'wrong_length', {
count: options.length
}));
}
return callback();
};
return LengthValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.LengthValidator);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.InclusionValidator = (function(_super) {
__extends(InclusionValidator, _super);
InclusionValidator.triggers('inclusion');
function InclusionValidator(options) {
this.acceptableValues = options.inclusion["in"];
InclusionValidator.__super__.constructor.apply(this, arguments);
}
InclusionValidator.prototype.validateEach = function(errors, record, key, callback) {
if (this.acceptableValues.indexOf(record.get(key)) === -1) {
errors.add(key, this.format(key, 'not_included_in_list'));
}
return callback();
};
return InclusionValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.InclusionValidator);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ExclusionValidator = (function(_super) {
__extends(ExclusionValidator, _super);
ExclusionValidator.triggers('exclusion');
function ExclusionValidator(options) {
this.unacceptableValues = options.exclusion["in"];
ExclusionValidator.__super__.constructor.apply(this, arguments);
}
ExclusionValidator.prototype.validateEach = function(errors, record, key, callback) {
if (this.unacceptableValues.indexOf(record.get(key)) >= 0) {
errors.add(key, this.format(key, 'included_in_list'));
}
return callback();
};
return ExclusionValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.ExclusionValidator);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.AssociatedValidator = (function(_super) {
__extends(AssociatedValidator, _super);
function AssociatedValidator() {
_ref = AssociatedValidator.__super__.constructor.apply(this, arguments);
return _ref;
}
AssociatedValidator.triggers('associated');
AssociatedValidator.prototype.validateEach = function(errors, record, key, callback) {
var childFinished, count, value,
_this = this;
value = record.get(key);
if (value != null) {
if (value instanceof Batman.AssociationProxy) {
value = typeof value.get === "function" ? value.get('target') : void 0;
}
count = 1;
childFinished = function(err, childErrors) {
if (childErrors.length > 0) {
errors.add(key, _this.format(key, 'invalid_association'));
}
if (--count === 0) {
return callback();
}
};
if ((value != null ? value.forEach : void 0) != null) {
value.forEach(function(record) {
count += 1;
return record.validate(childFinished);
});
} else if ((value != null ? value.validate : void 0) != null) {
count += 1;
value.validate(childFinished);
}
return childFinished(null, []);
} else {
return callback();
}
};
return AssociatedValidator;
})(Batman.Validator);
Batman.Validators.push(Batman.AssociatedValidator);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.ControllerActionFrame = (function(_super) {
__extends(ControllerActionFrame, _super);
ControllerActionFrame.prototype.operationOccurred = false;
ControllerActionFrame.prototype.remainingOperations = 0;
ControllerActionFrame.prototype.event('complete').oneShot = true;
function ControllerActionFrame(options, onComplete) {
ControllerActionFrame.__super__.constructor.call(this, options);
this.once('complete', onComplete);
}
ControllerActionFrame.prototype.startOperation = function(options) {
if (options == null) {
options = {};
}
if (!options.internal) {
this.operationOccurred = true;
}
this._changeOperationsCounter(1);
return true;
};
ControllerActionFrame.prototype.finishOperation = function() {
this._changeOperationsCounter(-1);
return true;
};
ControllerActionFrame.prototype.startAndFinishOperation = function(options) {
this.startOperation(options);
this.finishOperation(options);
return true;
};
ControllerActionFrame.prototype._changeOperationsCounter = function(delta) {
var _ref;
this.remainingOperations += delta;
if (this.remainingOperations === 0) {
this.fire('complete');
}
if ((_ref = this.parentFrame) != null) {
_ref._changeOperationsCounter(delta);
}
};
return ControllerActionFrame;
})(Batman.Object);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.HTMLStore = (function(_super) {
__extends(HTMLStore, _super);
function HTMLStore() {
HTMLStore.__super__.constructor.apply(this, arguments);
this._htmlContents = {};
this._requestedPaths = new Batman.SimpleSet;
}
HTMLStore.prototype.propertyClass = Batman.Property;
HTMLStore.prototype.fetchHTML = function(path) {
var _this = this;
return new Batman.Request({
url: Batman.Navigator.normalizePath(Batman.config.pathToHTML, "" + path + ".html"),
type: 'html',
success: function(response) {
return _this.set(path, response);
},
error: function(response) {
throw new Error("Could not load html from " + path);
}
});
};
HTMLStore.accessor({
'final': true,
get: function(path) {
var contents;
if (path.charAt(0) !== '/') {
return this.get("/" + path);
}
if (this._htmlContents[path]) {
return this._htmlContents[path];
}
if (this._requestedPaths.has(path)) {
return;
}
if (contents = this._sourceFromDOM(path)) {
return contents;
}
if (Batman.config.fetchRemoteHTML) {
this.fetchHTML(path);
} else {
throw new Error("Couldn't find html source for \'" + path + "\'!");
}
},
set: function(path, content) {
if (path.charAt(0) !== '/') {
return this.set("/" + path, content);
}
this._requestedPaths.add(path);
return this._htmlContents[path] = content;
}
});
HTMLStore.prototype.prefetch = function(path) {
this.get(path);
return true;
};
HTMLStore.prototype._sourceFromDOM = function(path) {
var node, relativePath;
relativePath = path.slice(1);
if (node = Batman.DOM.querySelector(document, "[data-defineview*='" + relativePath + "']")) {
Batman.setImmediate(function() {
var _ref;
return (_ref = node.parentNode) != null ? _ref.removeChild(node) : void 0;
});
return Batman.View.store.set(Batman.Navigator.normalizePath(path), node.innerHTML);
}
};
return HTMLStore;
})(Batman.Object);
}).call(this);
(function() {
var _base, _base1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.View = (function(_super) {
__extends(View, _super);
View.store = new Batman.HTMLStore;
View.option = function() {
var keys, options;
keys = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
Batman.initializeObject(this);
if (options = this._batman.options) {
keys = options.concat(keys);
}
return this._batman.set('options', keys);
};
View.filter = function(key, filter) {
var filters;
Batman.initializeObject(this.prototype);
filters = this.prototype._batman.filters || {};
filters[key] = filter;
return this.prototype._batman.set('filters', filters);
};
View.viewForNode = function(node, climbTree) {
var view;
if (climbTree == null) {
climbTree = true;
}
while (node) {
if (view = Batman._data(node, 'view')) {
return view;
}
if (!climbTree) {
return;
}
node = node.parentNode;
}
};
View.prototype.bindings = [];
View.prototype.subviews = [];
View.prototype.superview = null;
View.prototype.controller = null;
View.prototype.source = null;
View.prototype.html = null;
View.prototype.node = null;
View.prototype.bindImmediately = true;
View.prototype.isBound = false;
View.prototype.isInDOM = false;
View.prototype.isView = true;
View.prototype.isDead = false;
View.prototype.isBackingView = false;
function View() {
var superview,
_this = this;
this.bindings = [];
this.subviews = new Batman.Set;
this.subviews.on('itemsWereAdded', function(newSubviews) {
var subview, _i, _len;
for (_i = 0, _len = newSubviews.length; _i < _len; _i++) {
subview = newSubviews[_i];
_this._addSubview(subview);
}
});
this.subviews.on('itemsWereRemoved', function(oldSubviews) {
var subview, _i, _len;
for (_i = 0, _len = oldSubviews.length; _i < _len; _i++) {
subview = oldSubviews[_i];
subview._removeFromSuperview();
}
});
View.__super__.constructor.apply(this, arguments);
if (superview = this.superview) {
this.superview = null;
superview.subviews.add(this);
}
}
View.prototype._addChildBinding = function(binding) {
return this.bindings.push(binding);
};
View.prototype._addSubview = function(subview) {
var subviewController, yieldName, yieldObject;
subviewController = subview.controller;
subview.removeFromSuperview();
subview.set('controller', subviewController || this.controller);
subview.set('superview', this);
subview.fire('viewDidMoveToSuperview');
if ((yieldName = subview.contentFor) && !subview.parentNode) {
yieldObject = Batman.DOM.Yield.withName(yieldName);
yieldObject.set('contentView', subview);
}
this.get('node');
subview.get('node');
this.observe('node', subview._nodesChanged);
subview.observe('node', subview._nodesChanged);
subview.observe('parentNode', subview._nodesChanged);
return subview._nodesChanged();
};
View.prototype._removeFromSuperview = function() {
var superview;
if (!this.superview) {
return;
}
this.fire('viewWillRemoveFromSuperview');
this.forget('node', this._nodesChanged);
this.forget('parentNode', this._nodesChanged);
this.superview.forget('node', this._nodesChanged);
superview = this.get('superview');
this.removeFromParentNode();
this.set('superview', null);
return this.set('controller', null);
};
View.prototype.removeFromSuperview = function() {
var _ref;
return (_ref = this.superview) != null ? _ref.subviews.remove(this) : void 0;
};
View.prototype._nodesChanged = function() {
var parentNode, superviewNode;
if (!this.node) {
return;
}
if (this.bindImmediately) {
this.initializeBindings();
}
superviewNode = this.superview.get('node');
parentNode = this.parentNode;
if (typeof parentNode === 'string') {
parentNode = Batman.DOM.querySelector(superviewNode, parentNode);
}
if (!parentNode) {
parentNode = superviewNode;
}
if (parentNode) {
return this.addToParentNode(parentNode);
}
};
View.prototype.addToParentNode = function(parentNode) {
var isInDOM;
if (!this.get('node')) {
return;
}
isInDOM = Batman.DOM.containsNode(parentNode);
if (isInDOM) {
this.propagateToSubviews('viewWillAppear');
}
this.insertIntoDOM(parentNode);
this.propagateToSubviews('isInDOM', isInDOM);
if (isInDOM) {
return this.propagateToSubviews('viewDidAppear');
}
};
View.prototype.insertIntoDOM = function(parentNode) {
if (parentNode !== this.node) {
return parentNode.appendChild(this.node);
}
};
View.prototype.removeFromParentNode = function() {
var isInDOM, node, _ref, _ref1, _ref2;
node = this.get('node');
isInDOM = (_ref = this.wasInDOM) != null ? _ref : Batman.DOM.containsNode(node);
if (isInDOM) {
this.propagateToSubviews('viewWillDisappear');
}
if ((_ref1 = this.node) != null) {
if ((_ref2 = _ref1.parentNode) != null) {
_ref2.removeChild(this.node);
}
}
this.propagateToSubviews('isInDOM', false);
if (isInDOM) {
return this.propagateToSubviews('viewDidDisappear');
}
};
View.prototype.propagateToSubviews = function(eventName, value) {
var subview, _i, _len, _ref, _results;
if (value != null) {
this.set(eventName, value);
} else {
this.fire(eventName);
if (typeof this[eventName] === "function") {
this[eventName]();
}
}
_ref = this.subviews._storage;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
subview = _ref[_i];
_results.push(subview.propagateToSubviews(eventName, value));
}
return _results;
};
View.prototype.loadView = function(_node) {
var html, node;
if ((html = this.get('html')) != null) {
node = _node || document.createElement('div');
Batman.DOM.setInnerHTML(node, html);
return node;
}
};
View.accessor('html', {
get: function() {
var handler, property, source,
_this = this;
if (this.html != null) {
return this.html;
}
if (!(source = this.get('source'))) {
return;
}
source = Batman.Navigator.normalizePath(source);
this.html = this.constructor.store.get(source);
if (this.html == null) {
property = this.property('html');
handler = function(html) {
if (html != null) {
_this.set('html', html);
}
return property.removeHandler(handler);
};
property.addHandler(handler);
}
return this.html;
},
set: function(key, html) {
this.destroyBindings();
this.destroySubviews();
this.html = html;
if (this.node && (html != null)) {
this.loadView(this.node);
}
if (this.bindImmediately) {
return this.initializeBindings();
}
}
});
View.accessor('node', {
get: function() {
var node;
if ((this.node == null) && !this.isDead) {
node = this.loadView();
if (node) {
this.set('node', node);
}
this.fire('viewDidLoad');
}
return this.node;
},
set: function(key, node, oldNode) {
var _this = this;
if (oldNode) {
Batman.removeData(oldNode, 'view', true);
}
if (node === this.node) {
return;
}
this.destroyBindings();
this.destroySubviews();
this.node = node;
if (!node) {
return;
}
Batman._data(node, 'view', this);
Batman.developer["do"](function() {
var extraInfo, _base;
extraInfo = _this.get('displayName') || _this.get('source');
return typeof (_base = (node === document ? document.body : node)).setAttribute === "function" ? _base.setAttribute('batman-view', _this.constructor.name + (extraInfo ? ": " + extraInfo : '')) : void 0;
});
return node;
}
});
View.prototype.event('ready').oneShot = true;
View.prototype.initializeBindings = function() {
if (this.isBound || !this.node) {
return;
}
new Batman.BindingParser(this);
this.set('isBound', true);
this.fire('ready');
return typeof this.ready === "function" ? this.ready() : void 0;
};
View.prototype.destroyBindings = function() {
var binding, _i, _len, _ref;
_ref = this.bindings;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
binding = _ref[_i];
binding.die();
}
this.bindings = [];
return this.isBound = false;
};
View.prototype.destroySubviews = function() {
var subview, _i, _len, _ref;
if (this.isDead) {
Batman.developer.warn("Tried to destroy the subviews of a dead view.");
return;
}
_ref = this.subviews.toArray();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
subview = _ref[_i];
subview.die();
}
return this.subviews.clear();
};
View.prototype.die = function() {
var event, _, _ref, _ref1;
if (this.isDead) {
Batman.developer.warn("Tried to die() a view more than once.");
return;
}
this.fire('destroy');
if (this.node) {
this.wasInDOM = Batman.DOM.containsNode(this.node);
Batman.DOM.destroyNode(this.node);
}
this.forget();
if ((_ref = this._batman.properties) != null) {
_ref.forEach(function(key, property) {
return property.die();
});
}
if (this._batman.events) {
_ref1 = this._batman.events;
for (_ in _ref1) {
event = _ref1[_];
event.clearHandlers();
}
}
this.destroyBindings();
this.destroySubviews();
this.removeFromSuperview();
this.node = null;
this.parentNode = null;
this.subviews = null;
return this.isDead = true;
};
View.prototype.baseForKeypath = function(keypath) {
return keypath.split('.')[0].split('|')[0].trim();
};
View.prototype.prefixForKeypath = function(keypath) {
var index;
index = keypath.lastIndexOf('.');
if (index !== -1) {
return keypath.substr(0, index);
} else {
return keypath;
}
};
View.prototype.targetForKeypath = function(keypath, forceTarget) {
var controller, lookupNode, nearestNonBackingView, target;
lookupNode = this;
while (lookupNode) {
if (target = this._testTargetForKeypath(lookupNode, keypath)) {
return target;
}
if (forceTarget && !nearestNonBackingView && !lookupNode.isBackingView) {
nearestNonBackingView = Batman.get(lookupNode, 'proxiedObject') || lookupNode;
}
if (!controller && lookupNode.isView && lookupNode.controller) {
controller = lookupNode.controller;
}
if (lookupNode.isView && lookupNode.superview) {
lookupNode = lookupNode.superview;
} else if (controller) {
lookupNode = controller;
controller = null;
} else if (!lookupNode.window) {
if (Batman.currentApp && lookupNode !== Batman.currentApp) {
lookupNode = Batman.currentApp;
} else {
lookupNode = {
window: Batman.container
};
}
} else {
break;
}
}
return nearestNonBackingView;
};
View.prototype._testTargetForKeypath = function(object, keypath) {
var proxiedObject;
if (proxiedObject = Batman.get(object, 'proxiedObject')) {
if (typeof Batman.get(proxiedObject, keypath) !== 'undefined') {
return proxiedObject;
}
}
if (typeof Batman.get(object, keypath) !== 'undefined') {
return object;
}
};
View.prototype.lookupKeypath = function(keypath) {
var base, target;
base = this.baseForKeypath(keypath);
target = this.targetForKeypath(base);
if (target) {
return Batman.get(target, keypath);
}
};
View.prototype.setKeypath = function(keypath, value) {
var prefix, target, _ref;
prefix = this.prefixForKeypath(keypath);
target = this.targetForKeypath(prefix, true);
if (!target || target === Batman.container) {
return;
}
return (_ref = Batman.Property.forBaseAndKey(target, keypath)) != null ? _ref.setValue(value) : void 0;
};
return View;
})(Batman.Object);
if ((_base = Batman.container).$context == null) {
_base.$context = function(node) {
var view;
while (node) {
if (view = Batman._data(node, 'backingView') || Batman._data(node, 'view')) {
return view;
}
node = node.parentNode;
}
};
}
if ((_base1 = Batman.container).$subviews == null) {
_base1.$subviews = function(view) {
var subviews;
if (view == null) {
view = Batman.currentApp.layout;
}
subviews = [];
view.subviews.forEach(function(subview) {
var obj, _ref;
obj = Batman.mixin({}, subview);
obj.constructor = subview.constructor;
obj.subviews = ((_ref = subview.subviews) != null ? _ref.length : void 0) ? $subviews(subview) : null;
Batman.unmixin(obj, {
'_batman': true
});
return subviews.push(obj);
});
return subviews;
};
}
}).call(this);
(function() {
var _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.AbstractBinding = (function(_super) {
var get_dot_rx, get_rx, keypath_rx, onlyAll, onlyData, onlyNode;
__extends(AbstractBinding, _super);
keypath_rx = /(^|,)\s*(?:(true|false)|("[^"]*")|(\{[^\}]*\})|(([0-9\_\-]+[a-zA-Z\_\-]|[a-zA-Z])[\w\-\.\?\!\+]*))\s*(?=$|,)/g;
get_dot_rx = /(?:\]\.)(.+?)(?=[\[\.]|\s*\||$)/;
get_rx = /(?!^\s*)\[(.*?)\]/g;
AbstractBinding.accessor('filteredValue', {
get: function() {
var result, self, unfilteredValue;
unfilteredValue = this.get('unfilteredValue');
self = this;
if (this.filterFunctions.length > 0) {
result = this.filterFunctions.reduce(function(value, fn, i) {
var args;
args = self.filterArguments[i].map(function(argument) {
if (argument._keypath) {
return self.view.lookupKeypath(argument._keypath);
} else {
return argument;
}
});
args.unshift(value);
while (args.length < (fn.length - 1)) {
args.push(void 0);
}
args.push(self);
return fn.apply(self.view, args);
}, unfilteredValue);
return result;
} else {
return unfilteredValue;
}
},
set: function(_, newValue) {
return this.set('unfilteredValue', newValue);
}
});
AbstractBinding.accessor('unfilteredValue', {
get: function() {
return this._unfilteredValue(this.get('key'));
},
set: function(_, value) {
var k;
if (k = this.get('key')) {
return this.view.setKeypath(k, value);
} else {
return this.set('value', value);
}
}
});
AbstractBinding.prototype._unfilteredValue = function(key) {
if (key) {
return this.view.lookupKeypath(key);
} else {
return this.get('value');
}
};
onlyAll = Batman.BindingDefinitionOnlyObserve.All;
onlyData = Batman.BindingDefinitionOnlyObserve.Data;
onlyNode = Batman.BindingDefinitionOnlyObserve.Node;
AbstractBinding.prototype.bindImmediately = true;
AbstractBinding.prototype.shouldSet = true;
AbstractBinding.prototype.isInputBinding = false;
AbstractBinding.prototype.escapeValue = true;
AbstractBinding.prototype.onlyObserve = onlyAll;
AbstractBinding.prototype.skipParseFilter = false;
function AbstractBinding(definition) {
this._fireDataChange = __bind(this._fireDataChange, this);
var viewClass;
this.node = definition.node, this.keyPath = definition.keyPath, this.view = definition.view;
if (definition.onlyObserve) {
this.onlyObserve = definition.onlyObserve;
}
if (definition.skipParseFilter != null) {
this.skipParseFilter = definition.skipParseFilter;
}
if (!this.skipParseFilter) {
this.parseFilter();
}
if (typeof this.backWithView === 'function') {
viewClass = this.backWithView;
}
if (this.backWithView) {
this.setupBackingView(viewClass, definition.viewOptions);
}
if (this.bindImmediately) {
this.bind();
}
}
AbstractBinding.prototype.isTwoWay = function() {
return (this.key != null) && this.filterFunctions.length === 0;
};
AbstractBinding.prototype.bind = function() {
var _ref, _ref1;
if (this.node && ((_ref = this.onlyObserve) === onlyAll || _ref === onlyNode) && Batman.DOM.nodeIsEditable(this.node)) {
Batman.DOM.events.change(this.node, this._fireNodeChange.bind(this));
if (this.onlyObserve === onlyNode) {
this._fireNodeChange();
}
}
if ((_ref1 = this.onlyObserve) === onlyAll || _ref1 === onlyData) {
this.observeAndFire('filteredValue', this._fireDataChange);
}
return this.view._addChildBinding(this);
};
AbstractBinding.prototype._fireNodeChange = function(event) {
var val;
this.shouldSet = false;
val = this.value || this.get('keyContext');
if (typeof this.nodeChange === "function") {
this.nodeChange(this.node, val, event);
}
this.fire('nodeChange', this.node, val);
return this.shouldSet = true;
};
AbstractBinding.prototype._fireDataChange = function(value) {
if (this.shouldSet) {
if (typeof this.dataChange === "function") {
this.dataChange(value, this.node);
}
return this.fire('dataChange', value, this.node);
}
};
AbstractBinding.prototype.die = function() {
var _ref;
this.forget();
if ((_ref = this._batman.properties) != null) {
_ref.forEach(function(key, property) {
return property.die();
});
}
this.node = null;
this.keyPath = null;
this.view = null;
this.backingView = null;
return this.superview = null;
};
AbstractBinding.prototype.parseFilter = function() {
var args, e, filter, filterName, filterString, filters, key, keyPath, orig, split, _ref, _ref1;
this.filterFunctions = [];
this.filterArguments = [];
keyPath = this.keyPath;
while (get_dot_rx.test(keyPath)) {
keyPath = keyPath.replace(get_dot_rx, "]['$1']");
}
filters = keyPath.replace(get_rx, " | get $1 ").replace(/'/g, '"').split(/(?!")\s+\|\s+(?!")/);
try {
key = this.parseSegment(orig = filters.shift())[0];
} catch (_error) {
e = _error;
Batman.developer.warn(e);
Batman.developer.error("Error! Couldn't parse keypath in \"" + orig + "\". Parsing error above.");
}
if (key && key._keypath) {
this.key = key._keypath;
} else {
this.value = key;
}
if (filters.length) {
while (filterString = filters.shift()) {
split = filterString.indexOf(' ');
if (split === -1) {
split = filterString.length;
}
filterName = filterString.substr(0, split);
args = filterString.substr(split);
if (!(filter = ((_ref = this.view) != null ? (_ref1 = _ref._batman.get('filters')) != null ? _ref1[filterName] : void 0 : void 0) || Batman.Filters[filterName])) {
return Batman.developer.error("Unrecognized filter '" + filterName + "' in key \"" + this.keyPath + "\"!");
}
this.filterFunctions.push(filter);
try {
this.filterArguments.push(this.parseSegment(args));
} catch (_error) {
e = _error;
Batman.developer.error("Bad filter arguments \"" + args + "\"!");
}
}
return true;
}
};
AbstractBinding.prototype.parseSegment = function(segment) {
segment = segment.replace(keypath_rx, function(match, start, bool, string, object, keypath, offset) {
var replacement;
if (start == null) {
start = '';
}
replacement = keypath ? '{"_keypath": "' + keypath + '"}' : bool || string || object;
return start + replacement;
});
return JSON.parse("[" + segment + "]");
};
AbstractBinding.prototype.setupBackingView = function(viewClass, viewOptions) {
if (this.backingView) {
return this.backingView;
}
if (this.node && (this.backingView = Batman._data(this.node, 'view'))) {
return this.backingView;
}
this.superview = this.view;
viewOptions || (viewOptions = {});
if (viewOptions.node == null) {
viewOptions.node = this.node;
}
if (viewOptions.parentNode == null) {
viewOptions.parentNode = this.node;
}
viewOptions.isBackingView = true;
this.backingView = new (viewClass || Batman.BackingView)(viewOptions);
this.superview.subviews.add(this.backingView);
if (this.node) {
Batman._data(this.node, 'view', this.backingView);
}
return this.backingView;
};
return AbstractBinding;
})(Batman.Object);
Batman.BackingView = (function(_super) {
__extends(BackingView, _super);
function BackingView() {
_ref = BackingView.__super__.constructor.apply(this, arguments);
return _ref;
}
BackingView.prototype.isBackingView = true;
BackingView.prototype.bindImmediately = false;
return BackingView;
})(Batman.View);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.ViewBinding = (function(_super) {
__extends(ViewBinding, _super);
ViewBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
ViewBinding.prototype.skipChildren = true;
ViewBinding.prototype.bindImmediately = false;
function ViewBinding(definition) {
this.superview = definition.view;
ViewBinding.__super__.constructor.apply(this, arguments);
}
ViewBinding.prototype.initialized = function() {
return this.bind();
};
ViewBinding.prototype.dataChange = function(viewClassOrInstance) {
var attributeName, definition, keyPath, option, options, _i, _len, _ref;
if ((_ref = this.viewInstance) != null) {
_ref.removeFromSuperview();
}
if (!viewClassOrInstance) {
return;
}
if (viewClassOrInstance.isView) {
this.fromViewClass = false;
this.viewInstance = viewClassOrInstance;
this.viewInstance.removeFromSuperview();
} else {
this.fromViewClass = true;
this.viewInstance = new viewClassOrInstance;
}
this.node.removeAttribute('data-view');
if (options = this.viewInstance.constructor._batman.get('options')) {
for (_i = 0, _len = options.length; _i < _len; _i++) {
option = options[_i];
attributeName = "data-view-" + (option.toLowerCase());
if (keyPath = this.node.getAttribute(attributeName)) {
this.node.removeAttribute(attributeName);
definition = new Batman.DOM.ReaderBindingDefinition(this.node, keyPath, this.superview);
new Batman.DOM.ViewArgumentBinding(definition, option, this.viewInstance);
}
}
}
this.viewInstance.set('parentNode', this.node);
this.viewInstance.set('node', this.node);
this.viewInstance.loadView(this.node);
return this.superview.subviews.add(this.viewInstance);
};
ViewBinding.prototype.die = function() {
if (this.fromViewClass) {
this.viewInstance.die();
} else {
this.viewInstance.removeFromSuperview();
}
this.superview = null;
this.viewInstance = null;
return ViewBinding.__super__.die.apply(this, arguments);
};
return ViewBinding;
})(Batman.DOM.AbstractBinding);
Batman.DOM.ViewArgumentBinding = (function(_super) {
__extends(ViewArgumentBinding, _super);
ViewArgumentBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
function ViewArgumentBinding(definition, option, targetView) {
var _this = this;
this.option = option;
this.targetView = targetView;
ViewArgumentBinding.__super__.constructor.call(this, definition);
this.targetView.observe(this.option, this._updateValue = function(value) {
if (_this.isDataChanging) {
return;
}
return _this.view.set(_this.keyPath, value);
});
}
ViewArgumentBinding.prototype.dataChange = function(value) {
this.isDataChanging = true;
this.targetView.set(this.option, value);
return this.isDataChanging = false;
};
ViewArgumentBinding.prototype.die = function() {
this.targetView.forget(this.option, this._updateValue);
this.targetView = null;
return ViewArgumentBinding.__super__.die.apply(this, arguments);
};
return ViewArgumentBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.ValueBinding = (function(_super) {
__extends(ValueBinding, _super);
function ValueBinding(definition) {
var _ref;
this.isInputBinding = (_ref = definition.node.nodeName.toLowerCase()) === 'input' || _ref === 'textarea';
ValueBinding.__super__.constructor.apply(this, arguments);
}
ValueBinding.prototype.nodeChange = function(node, context) {
if (this.isTwoWay()) {
return this.set('filteredValue', this.node.value);
}
};
ValueBinding.prototype.dataChange = function(value, node) {
return Batman.DOM.valueForNode(this.node, value, this.escapeValue);
};
return ValueBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.ShowHideBinding = (function(_super) {
__extends(ShowHideBinding, _super);
ShowHideBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
function ShowHideBinding(definition) {
var display;
display = definition.node.style.display;
if (!display || display === 'none') {
display = '';
}
this.originalDisplay = display;
this.invert = definition.invert;
ShowHideBinding.__super__.constructor.apply(this, arguments);
}
ShowHideBinding.prototype.dataChange = function(value) {
var view;
view = Batman.View.viewForNode(this.node, false);
if (!!value === !this.invert) {
if (view != null) {
view.fire('viewWillShow');
}
this.node.style.display = this.originalDisplay;
return view != null ? view.fire('viewDidShow') : void 0;
} else {
if (view != null) {
view.fire('viewWillHide');
}
Batman.DOM.setStyleProperty(this.node, 'display', 'none', 'important');
return view != null ? view.fire('viewDidHide') : void 0;
}
};
return ShowHideBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
Batman.SelectView = (function(_super) {
__extends(SelectView, _super);
function SelectView() {
_ref = SelectView.__super__.constructor.apply(this, arguments);
return _ref;
}
SelectView.prototype._addChildBinding = function(binding) {
SelectView.__super__._addChildBinding.apply(this, arguments);
return this.fire('childBindingAdded', binding);
};
return SelectView;
})(Batman.BackingView);
Batman.DOM.SelectBinding = (function(_super) {
__extends(SelectBinding, _super);
SelectBinding.prototype.backWithView = Batman.SelectView;
SelectBinding.prototype.isInputBinding = true;
SelectBinding.prototype.canSetImplicitly = true;
SelectBinding.prototype.skipChildren = true;
function SelectBinding(definition) {
this.updateOptionBindings = __bind(this.updateOptionBindings, this);
this.nodeChange = __bind(this.nodeChange, this);
this.dataChange = __bind(this.dataChange, this);
this.childBindingAdded = __bind(this.childBindingAdded, this);
SelectBinding.__super__.constructor.apply(this, arguments);
this.node.removeAttribute('data-bind');
this.node.removeAttribute('data-source');
this.node.removeAttribute('data-target');
this.backingView.on('childBindingAdded', this.childBindingAdded);
this.backingView.initializeBindings();
}
SelectBinding.prototype.die = function() {
this.backingView.off('childBindingAdded', this.childBindingAdded);
return SelectBinding.__super__.die.apply(this, arguments);
};
SelectBinding.prototype.childBindingAdded = function(binding) {
var _this = this;
if (binding instanceof Batman.DOM.CheckedBinding) {
binding.on('dataChange', this.nodeChange);
} else if (binding instanceof Batman.DOM.IteratorBinding) {
binding.backingView.on('itemsWereRendered', function() {
return _this._fireDataChange(_this.get('filteredValue'));
});
} else {
return;
}
return this._fireDataChange(this.get('filteredValue'));
};
SelectBinding.prototype.lastKeyContext = null;
SelectBinding.prototype.dataChange = function(newValue) {
var child, matches, valueToChild, _i, _len, _name, _ref1,
_this = this;
this.lastKeyContext || (this.lastKeyContext = this.get('keyContext'));
if (this.lastKeyContext !== this.get('keyContext')) {
this.canSetImplicitly = true;
this.lastKeyContext = this.get('keyContext');
}
if (newValue != null ? newValue.forEach : void 0) {
valueToChild = {};
_ref1 = this.node.children;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
child = _ref1[_i];
child.selected = false;
matches = valueToChild[_name = child.value] || (valueToChild[_name] = []);
matches.push(child);
}
newValue.forEach(function(value) {
var children, node, _j, _len1;
if (children = valueToChild[value]) {
for (_j = 0, _len1 = children.length; _j < _len1; _j++) {
node = children[_j];
node.selected = true;
}
}
});
} else {
if ((newValue == null) && this.canSetImplicitly) {
if (this.node.value) {
this.canSetImplicitly = false;
this.set('unfilteredValue', this.node.value);
}
} else {
this.canSetImplicitly = false;
Batman.DOM.valueForNode(this.node, newValue, this.escapeValue);
}
}
this.updateOptionBindings();
this.fixSelectElementWidth();
};
SelectBinding.prototype.nodeChange = function() {
var selections;
if (this.isTwoWay()) {
selections = Batman.DOM.valueForNode(this.node);
if (typeof selections === Array && selections.length === 1) {
selections = selections[0];
}
this.set('unfilteredValue', selections);
this.updateOptionBindings();
}
};
SelectBinding.prototype.updateOptionBindings = function() {
var binding, _i, _len, _ref1;
_ref1 = this.backingView.bindings;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
binding = _ref1[_i];
if (binding instanceof Batman.DOM.CheckedBinding) {
binding._fireNodeChange();
}
}
};
SelectBinding.prototype.fixSelectElementWidth = function() {
var _this = this;
if (window.navigator.userAgent.toLowerCase().indexOf('msie') === -1) {
return;
}
if (this._fixWidthTimeout) {
clearTimeout(this._fixWidthTimeout);
}
return this._fixWidthTimeout = setTimeout(function() {
_this._fixWidthTimeout = null;
return _this._fixSelectElementWidth();
}, 100);
};
SelectBinding.prototype._fixSelectElementWidth = function() {
var previousWidth, style, _ref1;
style = (_ref1 = this.get('node')) != null ? _ref1.style : void 0;
if (!style) {
return;
}
previousWidth = this.get('node').currentStyle.width;
style.width = '100%';
return style.width = previousWidth != null ? previousWidth : '';
};
return SelectBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.RouteBinding = (function(_super) {
__extends(RouteBinding, _super);
function RouteBinding() {
this.routeClick = __bind(this.routeClick, this);
_ref = RouteBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
RouteBinding.prototype.onAnchorTag = false;
RouteBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
RouteBinding.accessor('dispatcher', function() {
return this.view.lookupKeypath('dispatcher') || Batman.App.get('current.dispatcher');
});
RouteBinding.prototype.bind = function() {
var _ref1;
if ((_ref1 = this.node.nodeName) === 'a' || _ref1 === 'A') {
this.onAnchorTag = true;
}
RouteBinding.__super__.bind.apply(this, arguments);
if (this.onAnchorTag && this.node.getAttribute('target')) {
return;
}
return Batman.DOM.events.click(this.node, this.routeClick);
};
RouteBinding.prototype.routeClick = function(node, event) {
var params;
if (event.__batmanActionTaken) {
return;
}
event.__batmanActionTaken = true;
params = this.pathFromValue(this.get('filteredValue'));
if (params != null) {
return Batman.redirect(params);
}
};
RouteBinding.prototype.dataChange = function(value) {
var path;
if (value) {
path = this.pathFromValue(value);
}
if (this.onAnchorTag) {
if (path && Batman.navigator) {
path = Batman.navigator.linkTo(path);
} else {
path = "#";
}
return this.node.href = path;
}
};
RouteBinding.prototype.pathFromValue = function(value) {
var _ref1;
if (value) {
if (value.isNamedRouteQuery) {
return value.get('path');
} else {
return (_ref1 = this.get('dispatcher')) != null ? _ref1.pathFromParams(value) : void 0;
}
}
};
return RouteBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.RadioBinding = (function(_super) {
__extends(RadioBinding, _super);
function RadioBinding() {
_ref = RadioBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
RadioBinding.accessor('parsedNodeValue', function() {
return Batman.DOM.attrReaders._parseAttribute(this.node.value);
});
RadioBinding.prototype.firstBind = true;
RadioBinding.prototype.dataChange = function(value) {
var boundValue;
boundValue = this.get('filteredValue');
if (boundValue != null) {
this.node.checked = boundValue === Batman.DOM.attrReaders._parseAttribute(this.node.value);
} else {
if (this.firstBind && this.node.checked) {
this.set('filteredValue', this.get('parsedNodeValue'));
}
}
return this.firstBind = false;
};
RadioBinding.prototype.nodeChange = function(node) {
if (this.isTwoWay()) {
return this.set('filteredValue', this.get('parsedNodeValue'));
}
};
return RadioBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.FileBinding = (function(_super) {
__extends(FileBinding, _super);
FileBinding.prototype.isInputBinding = true;
function FileBinding() {
FileBinding.__super__.constructor.apply(this, arguments);
this.view.set('fileAttributes', null);
}
FileBinding.prototype.nodeChange = function(node, subContext) {
if (!this.isTwoWay()) {
return;
}
if (node.hasAttribute('multiple')) {
return this.set('filteredValue', Array.prototype.slice.call(node.files));
} else {
return this.set('filteredValue', node.files[0] || null);
}
};
return FileBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var _ref, _ref1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DeferredRenderView = (function(_super) {
__extends(DeferredRenderView, _super);
function DeferredRenderView() {
_ref = DeferredRenderView.__super__.constructor.apply(this, arguments);
return _ref;
}
DeferredRenderView.prototype.bindImmediately = false;
return DeferredRenderView;
})(Batman.View);
Batman.DOM.DeferredRenderBinding = (function(_super) {
__extends(DeferredRenderBinding, _super);
function DeferredRenderBinding() {
_ref1 = DeferredRenderBinding.__super__.constructor.apply(this, arguments);
return _ref1;
}
DeferredRenderBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
DeferredRenderBinding.prototype.backWithView = Batman.DeferredRenderView;
DeferredRenderBinding.prototype.skipChildren = true;
DeferredRenderBinding.prototype.dataChange = function(value) {
if (value && !this.backingView.isBound) {
this.node.removeAttribute('data-renderif');
return this.backingView.initializeBindings();
}
};
return DeferredRenderBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.developer["do"](function() {
var DebuggerBinding;
DebuggerBinding = (function(_super) {
__extends(DebuggerBinding, _super);
function DebuggerBinding() {
DebuggerBinding.__super__.constructor.apply(this, arguments);
debugger;
}
return DebuggerBinding;
})(Batman.DOM.AbstractBinding);
return Batman.DOM.readers.debug = function(definition) {
return new DebuggerBinding(definition);
};
});
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.AbstractAttributeBinding = (function(_super) {
__extends(AbstractAttributeBinding, _super);
function AbstractAttributeBinding(definition) {
this.attributeName = definition.attr;
AbstractAttributeBinding.__super__.constructor.apply(this, arguments);
}
return AbstractAttributeBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.Tracking = {
loadTracker: function() {
if (Batman.Tracking.tracker) {
return Batman.Tracking.tracker;
}
Batman.Tracking.tracker = Batman.currentApp.EventTracker ? new Batman.currentApp.EventTracker : (Batman.developer.warn("Define " + Batman.currentApp.name + ".EventTracker to use data-track"), {
track: function() {}
});
return Batman.Tracking.tracker;
},
trackEvent: function(type, data, node) {
return Batman.Tracking.loadTracker().track(type, data, node);
}
};
Batman.DOM.ClickTrackingBinding = (function(_super) {
__extends(ClickTrackingBinding, _super);
ClickTrackingBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.None;
ClickTrackingBinding.prototype.bindImmediately = false;
function ClickTrackingBinding() {
var callback,
_this = this;
ClickTrackingBinding.__super__.constructor.apply(this, arguments);
callback = function() {
return Batman.Tracking.trackEvent('click', _this.get('filteredValue'), _this.node);
};
Batman.DOM.events.click(this.node, callback, this.view, 'click', false);
this.bind();
}
return ClickTrackingBinding;
})(Batman.DOM.AbstractAttributeBinding);
Batman.DOM.ViewTrackingBinding = (function(_super) {
__extends(ViewTrackingBinding, _super);
ViewTrackingBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.None;
function ViewTrackingBinding() {
ViewTrackingBinding.__super__.constructor.apply(this, arguments);
Batman.Tracking.trackEvent('view', this.get('filteredValue'), this.node);
}
return ViewTrackingBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.EventBinding = (function(_super) {
__extends(EventBinding, _super);
EventBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.None;
EventBinding.prototype.bindImmediately = false;
function EventBinding() {
var attacher, callback,
_this = this;
EventBinding.__super__.constructor.apply(this, arguments);
callback = function() {
var func, target;
func = _this.get('filteredValue');
target = _this.view.targetForKeypath(_this.functionPath || _this.unfilteredKey);
if (target && _this.functionPath) {
target = Batman.get(target, _this.functionPath);
}
return func != null ? func.apply(target, arguments) : void 0;
};
if (attacher = Batman.DOM.events[this.attributeName]) {
attacher(this.node, callback, this.view);
} else {
Batman.DOM.events.other(this.node, this.attributeName, callback, this.view);
}
this.bind();
}
EventBinding.prototype._unfilteredValue = function(key) {
var index, value;
this.unfilteredKey = key;
if (!this.functionName && (index = key.lastIndexOf('.')) !== -1) {
this.functionPath = key.substr(0, index);
this.functionName = key.substr(index + 1);
}
value = EventBinding.__super__._unfilteredValue.call(this, this.functionPath || key);
if (this.functionName) {
return value != null ? value[this.functionName] : void 0;
} else {
return value;
}
};
return EventBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.ContextBinding = (function(_super) {
__extends(ContextBinding, _super);
ContextBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
ContextBinding.prototype.backWithView = true;
ContextBinding.prototype.bindingName = 'context';
function ContextBinding() {
var contextAttribute;
ContextBinding.__super__.constructor.apply(this, arguments);
contextAttribute = this.attributeName ? "data-" + this.bindingName + "-" + this.attributeName : "data-" + this.bindingName;
this.node.removeAttribute(contextAttribute);
this.node.insertBefore(document.createComment("batman-" + contextAttribute + "=\"" + this.keyPath + "\""), this.node.firstChild);
}
ContextBinding.prototype.dataChange = function(proxiedObject) {
return this.backingView.set(this.attributeName || 'proxiedObject', proxiedObject);
};
ContextBinding.prototype.die = function() {
this.backingView.unset(this.attributeName || 'proxiedObject');
return ContextBinding.__super__.die.apply(this, arguments);
};
return ContextBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.FormBinding = (function(_super) {
__extends(FormBinding, _super);
FormBinding.prototype.bindingName = 'formfor';
FormBinding.prototype.errorClass = 'error';
FormBinding.prototype.defaultErrorsListSelector = 'div.errors';
function FormBinding(definition) {
FormBinding.__super__.constructor.apply(this, arguments);
this.initializeErrorsList();
this.initializeChildBindings();
Batman.DOM.events.submit(this.node, function(node, e) {
return Batman.DOM.preventDefault(e);
});
}
FormBinding.prototype.initializeChildBindings = function() {
var attribute, attributeName, binding, errorsNode, field, index, keyPath, selectedNode, selectedNodes, selectors, _i, _len;
keyPath = this.keyPath;
attribute = this.attributeName;
selectors = ['input', 'textarea', 'select'].map(function(nodeName) {
return "" + nodeName + "[data-bind^=\"" + attribute + "\"]";
});
selectedNodes = Batman.DOM.querySelectorAll(this.node, selectors.join(', '));
attributeName = "data-addclass-" + this.errorClass;
for (_i = 0, _len = selectedNodes.length; _i < _len; _i++) {
selectedNode = selectedNodes[_i];
if (!(!selectedNode.getAttribute(attributeName))) {
continue;
}
binding = selectedNode.getAttribute('data-bind');
field = binding.substr(binding.indexOf(attribute) + attribute.length + 1);
index = field.indexOf('|');
if (index !== -1) {
field = field.substr(0, index);
}
field = field.trim();
selectedNode.setAttribute(attributeName, "" + attribute + ".errors." + field + ".length");
}
errorsNode = Batman.DOM.querySelector(this.node, '.errors');
if (errorsNode && !errorsNode.getAttribute('data-showif')) {
errorsNode.setAttribute('data-showif', "" + attribute + ".errors.length");
}
};
FormBinding.prototype.initializeErrorsList = function() {
var errorsNode, selector;
selector = this.node.getAttribute('data-errors-list') || this.defaultErrorsListSelector;
if (errorsNode = Batman.DOM.querySelector(this.node, selector)) {
return Batman.DOM.setInnerHTML(errorsNode, this.errorsListHTML());
}
};
FormBinding.prototype.errorsListHTML = function() {
return "<ul>\n <li data-foreach-error=\"" + this.attributeName + ".errors\" data-bind=\"error.fullMessage\"></li>\n</ul>";
};
return FormBinding;
})(Batman.DOM.ContextBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.NodeAttributeBinding = (function(_super) {
__extends(NodeAttributeBinding, _super);
function NodeAttributeBinding() {
_ref = NodeAttributeBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
NodeAttributeBinding.prototype.dataChange = function(value) {
if (value == null) {
value = "";
}
return this.node[this.attributeName] = value;
};
NodeAttributeBinding.prototype.nodeChange = function(node) {
if (this.isTwoWay()) {
return this.set('filteredValue', Batman.DOM.attrReaders._parseAttribute(node[this.attributeName]));
}
};
return NodeAttributeBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.CheckedBinding = (function(_super) {
__extends(CheckedBinding, _super);
function CheckedBinding() {
_ref = CheckedBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
CheckedBinding.prototype.isInputBinding = true;
CheckedBinding.prototype.dataChange = function(value) {
return this.node[this.attributeName] = !!value;
};
return CheckedBinding;
})(Batman.DOM.NodeAttributeBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.AttributeBinding = (function(_super) {
__extends(AttributeBinding, _super);
function AttributeBinding() {
_ref = AttributeBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
AttributeBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
AttributeBinding.prototype.dataChange = function(value) {
return this.node.setAttribute(this.attributeName, value);
};
AttributeBinding.prototype.nodeChange = function(node) {
if (this.isTwoWay()) {
return this.set('filteredValue', Batman.DOM.attrReaders._parseAttribute(node.getAttribute(this.attributeName)));
}
};
return AttributeBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var redundantWhitespaceRegex,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
redundantWhitespaceRegex = /[ \t]{2,}/g;
Batman.DOM.AddClassBinding = (function(_super) {
__extends(AddClassBinding, _super);
AddClassBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
function AddClassBinding(definition) {
var name;
this.invert = definition.invert;
this.classes = (function() {
var _i, _len, _ref, _results;
_ref = definition.attr.split('|');
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
_results.push({
name: name,
pattern: new RegExp("(?:^|\\s)" + name + "(?:$|\\s)", 'i')
});
}
return _results;
})();
AddClassBinding.__super__.constructor.apply(this, arguments);
}
AddClassBinding.prototype.dataChange = function(value) {
var currentName, includesClassName, name, pattern, _i, _len, _ref, _ref1;
currentName = this.node.className;
_ref = this.classes;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
_ref1 = _ref[_i], name = _ref1.name, pattern = _ref1.pattern;
includesClassName = pattern.test(currentName);
if (!!value === !this.invert) {
if (!includesClassName) {
currentName = "" + currentName + " " + name;
}
} else {
if (includesClassName) {
currentName = currentName.replace(pattern, ' ');
}
}
}
this.node.className = currentName.trim().replace(redundantWhitespaceRegex, ' ');
return true;
};
return AddClassBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.AbstractCollectionBinding = (function(_super) {
__extends(AbstractCollectionBinding, _super);
function AbstractCollectionBinding() {
_ref = AbstractCollectionBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
AbstractCollectionBinding.prototype.bindCollection = function(newCollection) {
var _ref1;
if (newCollection instanceof Batman.Hash) {
newCollection = newCollection.meta;
}
if (newCollection === this.collection) {
return true;
} else {
this.unbindCollection();
this.collection = newCollection;
if (!((_ref1 = this.collection) != null ? _ref1.isObservable : void 0)) {
return false;
}
if (this.collection.isCollectionEventEmitter && this.handleItemsAdded && this.handleItemsRemoved && this.handleItemMoved) {
this.collection.on('itemsWereAdded', this.handleItemsAdded);
this.collection.on('itemsWereRemoved', this.handleItemsRemoved);
this.collection.on('itemWasMoved', this.handleItemMoved);
this.handleArrayChanged(this.collection.toArray());
} else {
this.collection.observeAndFire('toArray', this.handleArrayChanged);
}
return true;
}
};
AbstractCollectionBinding.prototype.unbindCollection = function() {
var _ref1;
if (!((_ref1 = this.collection) != null ? _ref1.isObservable : void 0)) {
return;
}
if (this.collection.isCollectionEventEmitter && this.handleItemsAdded && this.handleItemsRemoved && this.handleItemMoved) {
this.collection.off('itemsWereAdded', this.handleItemsAdded);
this.collection.off('itemsWereRemoved', this.handleItemsRemoved);
return this.collection.off('itemWasMoved', this.handleItemMoved);
} else {
return this.collection.forget('toArray', this.handleArrayChanged);
}
};
AbstractCollectionBinding.prototype.handleArrayChanged = function() {};
AbstractCollectionBinding.prototype.die = function() {
this.unbindCollection();
this.collection = null;
return AbstractCollectionBinding.__super__.die.apply(this, arguments);
};
return AbstractCollectionBinding;
})(Batman.DOM.AbstractAttributeBinding);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__slice = [].slice;
Batman.DOM.StyleBinding = (function(_super) {
__extends(StyleBinding, _super);
StyleBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
function StyleBinding() {
this.setStyle = __bind(this.setStyle, this);
this.handleArrayChanged = __bind(this.handleArrayChanged, this);
this.oldStyles = {};
this.styleBindings = {};
StyleBinding.__super__.constructor.apply(this, arguments);
}
StyleBinding.prototype.dataChange = function(value) {
var colonSplitCSSValues, cssName, key, style, _i, _len, _ref, _ref1;
if (!value) {
this.resetStyles();
return;
}
this.unbindCollection();
if (typeof value === 'string') {
this.resetStyles();
_ref = value.split(';');
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
style = _ref[_i];
_ref1 = style.split(":"), cssName = _ref1[0], colonSplitCSSValues = 2 <= _ref1.length ? __slice.call(_ref1, 1) : [];
this.setStyle(cssName, colonSplitCSSValues.join(":"));
}
return;
}
if (value instanceof Batman.Hash) {
this.bindCollection(value);
} else {
if (value instanceof Batman.Object) {
value = value.toJSON();
}
this.resetStyles();
for (key in value) {
if (!__hasProp.call(value, key)) continue;
this.bindSingleAttribute(key, "" + this.keyPath + "." + key);
}
}
};
StyleBinding.prototype.handleArrayChanged = function(array) {
var _this = this;
return this.collection.forEach(function(key, value) {
return _this.bindSingleAttribute(key, "" + _this.keyPath + "." + key);
});
};
StyleBinding.prototype.bindSingleAttribute = function(attr, keyPath) {
var definition;
definition = new Batman.DOM.AttrReaderBindingDefinition(this.node, attr, keyPath, this.view);
return this.styleBindings[attr] = new Batman.DOM.StyleBinding.SingleStyleBinding(definition, this);
};
StyleBinding.prototype.setStyle = function(key, value) {
key = Batman.helpers.camelize(key.trim(), true);
if (this.oldStyles[key] == null) {
this.oldStyles[key] = this.node.style[key] || "";
}
if (value != null ? value.trim : void 0) {
value = value.trim();
}
if (value == null) {
value = "";
}
return this.node.style[key] = value;
};
StyleBinding.prototype.resetStyles = function() {
var cssName, cssValue, _ref;
_ref = this.oldStyles;
for (cssName in _ref) {
if (!__hasProp.call(_ref, cssName)) continue;
cssValue = _ref[cssName];
this.setStyle(cssName, cssValue);
}
};
StyleBinding.prototype.resetBindings = function() {
var attribute, binding, _ref;
_ref = this.styleBindings;
for (attribute in _ref) {
binding = _ref[attribute];
binding._fireDataChange('');
binding.die();
}
return this.styleBindings = {};
};
StyleBinding.prototype.unbindCollection = function() {
this.resetBindings();
return StyleBinding.__super__.unbindCollection.apply(this, arguments);
};
StyleBinding.SingleStyleBinding = (function(_super1) {
__extends(SingleStyleBinding, _super1);
SingleStyleBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
SingleStyleBinding.prototype.isTwoWay = function() {
return false;
};
function SingleStyleBinding(definition, parent) {
this.parent = parent;
SingleStyleBinding.__super__.constructor.call(this, definition);
}
SingleStyleBinding.prototype.dataChange = function(value) {
return this.parent.setStyle(this.attributeName, value);
};
return SingleStyleBinding;
})(Batman.DOM.AbstractAttributeBinding);
return StyleBinding;
})(Batman.DOM.AbstractCollectionBinding);
}).call(this);
(function() {
var _ref,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.ClassBinding = (function(_super) {
__extends(ClassBinding, _super);
function ClassBinding() {
this.handleArrayChanged = __bind(this.handleArrayChanged, this);
_ref = ClassBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
ClassBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
ClassBinding.prototype.dataChange = function(value) {
if (value != null) {
this.unbindCollection();
if (typeof value === 'string') {
return this.node.className = value;
} else {
this.bindCollection(value);
return this.updateFromCollection();
}
}
};
ClassBinding.prototype.updateFromCollection = function() {
var array, k, v;
if (this.collection) {
array = this.collection.map ? this.collection.map(function(x) {
return x;
}) : (function() {
var _ref1, _results;
_ref1 = this.collection;
_results = [];
for (k in _ref1) {
if (!__hasProp.call(_ref1, k)) continue;
v = _ref1[k];
_results.push(k);
}
return _results;
}).call(this);
if (array.toArray != null) {
array = array.toArray();
}
return this.node.className = array.join(' ');
}
};
ClassBinding.prototype.handleArrayChanged = function() {
return this.updateFromCollection();
};
return ClassBinding;
})(Batman.DOM.AbstractCollectionBinding);
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.InsertionBinding = (function(_super) {
__extends(InsertionBinding, _super);
InsertionBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
InsertionBinding.prototype.bindImmediately = false;
function InsertionBinding(definition) {
this.invert = definition.invert;
InsertionBinding.__super__.constructor.apply(this, arguments);
this.placeholderNode = document.createComment("batman-insertif=\"" + this.keyPath + "\"");
}
InsertionBinding.prototype.initialized = function() {
return this.bind();
};
InsertionBinding.prototype.dataChange = function(value) {
var parentNode, view;
view = Batman.View.viewForNode(this.node, false);
parentNode = this.placeholderNode.parentNode || this.node.parentNode;
if (!!value === !this.invert) {
if (view != null) {
view.fire('viewWillShow');
}
if (this.node.parentNode == null) {
parentNode.insertBefore(this.node, this.placeholderNode);
parentNode.removeChild(this.placeholderNode);
}
return view != null ? view.fire('viewDidShow') : void 0;
} else {
if (view != null) {
view.fire('viewWillHide');
}
if (this.node.parentNode != null) {
parentNode.insertBefore(this.placeholderNode, this.node);
parentNode.removeChild(this.node);
}
return view != null ? view.fire('viewDidHide') : void 0;
}
};
InsertionBinding.prototype.die = function() {
this.placeholderNode = null;
return InsertionBinding.__super__.die.apply(this, arguments);
};
return InsertionBinding;
})(Batman.DOM.AbstractBinding);
}).call(this);
(function() {
var _ref, _ref1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.IteratorView = (function(_super) {
__extends(IteratorView, _super);
function IteratorView() {
_ref = IteratorView.__super__.constructor.apply(this, arguments);
return _ref;
}
IteratorView.prototype.loadView = function() {
return document.createComment("batman-iterator-" + this.iteratorName + "=\"" + this.iteratorPath + "\"");
};
IteratorView.prototype.addItems = function(items, indexes) {
var i, item, _i, _j, _len, _len1;
this._beginAppendItems();
if (indexes) {
for (i = _i = 0, _len = items.length; _i < _len; i = ++_i) {
item = items[i];
this._insertItem(item, indexes[i]);
}
} else {
for (_j = 0, _len1 = items.length; _j < _len1; _j++) {
item = items[_j];
this._insertItem(item);
}
}
return this._finishAppendItems();
};
IteratorView.prototype.removeItems = function(items, indexes) {
var i, item, subview, _i, _j, _len, _len1, _results, _results1;
if (indexes) {
_results = [];
for (i = _i = 0, _len = items.length; _i < _len; i = ++_i) {
item = items[i];
_results.push(this.subviews.at(indexes[i]).die());
}
return _results;
} else {
_results1 = [];
for (_j = 0, _len1 = items.length; _j < _len1; _j++) {
item = items[_j];
_results1.push((function() {
var _k, _len2, _ref1, _results2;
_ref1 = this.subviews._storage;
_results2 = [];
for (_k = 0, _len2 = _ref1.length; _k < _len2; _k++) {
subview = _ref1[_k];
if (!(subview.get(this.attributeName) === item)) {
continue;
}
subview.unset(this.attributeName);
subview.die();
break;
}
return _results2;
}).call(this));
}
return _results1;
}
};
IteratorView.prototype.moveItem = function(oldIndex, newIndex) {
var source, target;
source = this.subviews.at(oldIndex);
this.subviews._storage.splice(oldIndex, 1);
target = this.subviews.at(newIndex);
this.subviews._storage.splice(newIndex, 0, source);
return this.node.parentNode.insertBefore(source.node, (target != null ? target.node : void 0) || this.node);
};
IteratorView.prototype._beginAppendItems = function() {
var viewClassName;
if (!this.iterationViewClass && (viewClassName = this.prototypeNode.getAttribute('data-view'))) {
this.iterationViewClass = this.lookupKeypath(viewClassName);
this.prototypeNode.removeAttribute('data-view');
}
this.iterationViewClass || (this.iterationViewClass = Batman.IterationView);
this.fragment = document.createDocumentFragment();
this.appendedViews = [];
return this.get('node');
};
IteratorView.prototype._insertItem = function(item, targetIndex) {
var iterationView;
iterationView = new this.iterationViewClass({
node: this.prototypeNode.cloneNode(true),
parentNode: this.fragment
});
iterationView.set(this.iteratorName, item);
if (targetIndex != null) {
iterationView._targeted = true;
this.subviews.insert([iterationView], [targetIndex]);
} else {
this.subviews.add(iterationView);
}
iterationView.parentNode = null;
return this.appendedViews.push(iterationView);
};
IteratorView.prototype._finishAppendItems = function() {
var index, isInDOM, sibling, subview, _i, _j, _k, _len, _len1, _ref1, _ref2, _ref3, _ref4;
isInDOM = Batman.DOM.containsNode(this.node);
if (isInDOM) {
_ref1 = this.appendedViews;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
subview = _ref1[_i];
subview.propagateToSubviews('viewWillAppear');
}
}
_ref2 = this.subviews.toArray();
for (index = _j = _ref2.length - 1; _j >= 0; index = _j += -1) {
subview = _ref2[index];
if (!subview._targeted) {
continue;
}
if (sibling = (_ref3 = this.subviews.at(index + 1)) != null ? _ref3.get('node') : void 0) {
sibling.parentNode.insertBefore(subview.get('node'), sibling);
} else {
this.fragment.appendChild(subview.get('node'));
}
delete subview._targeted;
}
this.node.parentNode.insertBefore(this.fragment, this.node);
this.fire('itemsWereRendered');
if (isInDOM) {
_ref4 = this.appendedViews;
for (_k = 0, _len1 = _ref4.length; _k < _len1; _k++) {
subview = _ref4[_k];
subview.propagateToSubviews('isInDOM', isInDOM);
subview.propagateToSubviews('viewDidAppear');
}
}
this.appendedViews = null;
return this.fragment = null;
};
return IteratorView;
})(Batman.View);
Batman.IterationView = (function(_super) {
__extends(IterationView, _super);
function IterationView() {
_ref1 = IterationView.__super__.constructor.apply(this, arguments);
return _ref1;
}
return IterationView;
})(Batman.View);
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.IteratorBinding = (function(_super) {
__extends(IteratorBinding, _super);
IteratorBinding.prototype.onlyObserve = Batman.BindingDefinitionOnlyObserve.Data;
IteratorBinding.prototype.backWithView = Batman.IteratorView;
IteratorBinding.prototype.skipChildren = true;
IteratorBinding.prototype.bindImmediately = false;
function IteratorBinding(definition) {
this.handleItemMoved = __bind(this.handleItemMoved, this);
this.handleItemsRemoved = __bind(this.handleItemsRemoved, this);
this.handleItemsAdded = __bind(this.handleItemsAdded, this);
this.handleArrayChanged = __bind(this.handleArrayChanged, this);
var _this = this;
this.iteratorName = definition.attr;
this.prototypeNode = definition.node;
this.prototypeNode.removeAttribute("data-foreach-" + this.iteratorName);
definition.viewOptions = {
prototypeNode: this.prototypeNode,
iteratorName: this.iteratorName,
iteratorPath: definition.keyPath
};
definition.node = null;
IteratorBinding.__super__.constructor.apply(this, arguments);
this.backingView.set('attributeName', this.attributeName);
this.view.prevent('ready');
Batman.setImmediate(function() {
var parentNode;
parentNode = _this.prototypeNode.parentNode;
parentNode.insertBefore(_this.backingView.get('node'), _this.prototypeNode);
parentNode.removeChild(_this.prototypeNode);
_this.bind();
return _this.view.allowAndFire('ready');
});
}
IteratorBinding.prototype.dataChange = function(collection) {
var items, _items;
if (collection != null) {
if (!this.bindCollection(collection)) {
items = (collection != null ? collection.forEach : void 0) ? (_items = [], collection.forEach(function(item) {
return _items.push(item);
}), _items) : Object.keys(collection);
this.handleArrayChanged(items);
}
} else {
this.unbindCollection();
this.collection = [];
this.handleArrayChanged([]);
}
};
IteratorBinding.prototype.handleArrayChanged = function(newItems) {
if (!this.backingView.isDead) {
this.backingView.destroySubviews();
if (newItems != null ? newItems.length : void 0) {
return this.handleItemsAdded(newItems);
}
}
};
IteratorBinding.prototype.handleItemsAdded = function(addedItems, addedIndexes) {
if (!this.backingView.isDead) {
return this.backingView.addItems(addedItems, addedIndexes);
}
};
IteratorBinding.prototype.handleItemsRemoved = function(removedItems, removedIndexes) {
if (this.backingView.isDead) {
return;
}
if (this.collection.length) {
return this.backingView.removeItems(removedItems, removedIndexes);
} else {
return this.backingView.destroySubviews();
}
};
IteratorBinding.prototype.handleItemMoved = function(item, newIndex, oldIndex) {
if (!this.backingView.isDead) {
return this.backingView.moveItem(oldIndex, newIndex);
}
};
IteratorBinding.prototype.die = function() {
this.prototypeNode = null;
return IteratorBinding.__super__.die.apply(this, arguments);
};
return IteratorBinding;
})(Batman.DOM.AbstractCollectionBinding);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.StyleAttributeBinding = (function(_super) {
__extends(StyleAttributeBinding, _super);
function StyleAttributeBinding() {
_ref = StyleAttributeBinding.__super__.constructor.apply(this, arguments);
return _ref;
}
StyleAttributeBinding.prototype.dataChange = function(value) {
return this.node.style[Batman.Filters.camelize(this.attributeName, true)] = value;
};
return StyleAttributeBinding;
})(Batman.DOM.NodeAttributeBinding);
}).call(this);
(function() {
var isEmptyDataObject;
isEmptyDataObject = function(obj) {
var name;
for (name in obj) {
return false;
}
return true;
};
Batman.extend(Batman, {
cache: {},
uuid: 0,
expando: "batman" + Math.random().toString().replace(/\D/g, ''),
canDeleteExpando: (function() {
var div, e;
try {
div = document.createElement('div');
return delete div.test;
} catch (_error) {
e = _error;
return Batman.canDeleteExpando = false;
}
})(),
noData: {
"embed": true,
"EMBED": true,
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"OBJECT": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true,
"APPLET": true
},
hasData: function(elem) {
elem = (elem.nodeType ? Batman.cache[elem[Batman.expando]] : elem[Batman.expando]);
return !!elem && !isEmptyDataObject(elem);
},
data: function(elem, name, data, pvt) {
var cache, getByName, id, internalKey, ret, thisCache;
if (!Batman.acceptData(elem)) {
return;
}
internalKey = Batman.expando;
getByName = typeof name === "string";
cache = Batman.cache;
id = elem[Batman.expando];
if ((!id || (pvt && id && (cache[id] && !cache[id][internalKey]))) && getByName && data === void 0) {
return;
}
if (!id) {
if (elem.nodeType !== 3) {
elem[Batman.expando] = id = ++Batman.uuid;
} else {
id = Batman.expando;
}
}
if (!cache[id]) {
cache[id] = {};
}
if (typeof name === "object" || typeof name === "function") {
if (pvt) {
cache[id][internalKey] = Batman.extend(cache[id][internalKey], name);
} else {
cache[id] = Batman.extend(cache[id], name);
}
}
thisCache = cache[id];
if (pvt) {
thisCache[internalKey] || (thisCache[internalKey] = {});
thisCache = thisCache[internalKey];
}
if (data !== void 0) {
thisCache[name] = data;
}
if (getByName) {
ret = thisCache[name];
} else {
ret = thisCache;
}
return ret;
},
removeData: function(elem, name, pvt, all) {
var cache, id, internalCache, internalKey, isNode, thisCache;
if (!Batman.acceptData(elem)) {
return;
}
internalKey = Batman.expando;
isNode = elem.nodeType;
cache = Batman.cache;
id = elem[Batman.expando];
if (!cache[id]) {
return;
}
if (name) {
thisCache = pvt ? cache[id][internalKey] : cache[id];
if (thisCache) {
delete thisCache[name];
if (!isEmptyDataObject(thisCache)) {
return;
}
}
}
if (pvt) {
delete cache[id][internalKey];
if (!isEmptyDataObject(cache[id])) {
return;
}
}
internalCache = cache[id][internalKey];
if (Batman.canDeleteExpando || !cache.setInterval) {
delete cache[id];
} else {
cache[id] = null;
}
if (internalCache && !all) {
cache[id] = {};
return cache[id][internalKey] = internalCache;
} else {
if (Batman.canDeleteExpando) {
return delete elem[Batman.expando];
} else if (elem.removeAttribute) {
return elem.removeAttribute(Batman.expando);
} else {
return elem[Batman.expando] = null;
}
}
},
_data: function(elem, name, data) {
return Batman.data(elem, name, data, true);
},
acceptData: function(elem) {
var match;
if (!elem) {
return;
}
return elem.___acceptData || (elem.___acceptData = elem.nodeName ? (match = Batman.noData[elem.nodeName], match ? !(match === true || elem.getAttribute("classid") !== match) : true) : true);
}
});
}).call(this);
(function() {
var __hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
Batman.DOM.Yield = (function(_super) {
__extends(Yield, _super);
Yield.yields = {};
Yield.reset = function() {
return this.yields = {};
};
Yield.withName = function(name) {
var _base;
return (_base = this.yields)[name] || (_base[name] = new this(name));
};
function Yield(name) {
this.name = name;
}
Yield.accessor('contentView', {
get: function() {
return this.contentView;
},
set: function(key, view) {
if (this.contentView === view) {
return;
}
if (this.contentView) {
this.contentView.removeFromSuperview();
}
this.contentView = view;
if (this.containerNode && view) {
return view.set('parentNode', this.containerNode);
}
}
});
Yield.accessor('containerNode', {
get: function() {
return this.containerNode;
},
set: function(key, node) {
if (this.containerNode === node) {
return;
}
this.containerNode = node;
if (this.contentView) {
return this.contentView.set('parentNode', node);
}
}
});
return Yield;
})(Batman.Object);
}).call(this);
(function() {
var buntUndefined, defaultAndOr,
__slice = [].slice;
buntUndefined = function(f) {
return function(value) {
if (value == null) {
return void 0;
} else {
return f.apply(this, arguments);
}
};
};
defaultAndOr = function(lhs, rhs) {
return lhs || rhs;
};
Batman.Filters = {
raw: buntUndefined(function(value, binding) {
binding.escapeValue = false;
return value;
}),
get: buntUndefined(function(value, key) {
if (value.get != null) {
return value.get(key);
} else {
return value[key];
}
}),
equals: buntUndefined(function(lhs, rhs, binding) {
return lhs === rhs;
}),
and: function(lhs, rhs) {
return lhs && rhs;
},
or: function(lhs, rhs, binding) {
return lhs || rhs;
},
not: function(value, binding) {
return !value;
},
trim: buntUndefined(function(value, binding) {
return value.trim();
}),
matches: buntUndefined(function(value, searchFor) {
return value.indexOf(searchFor) !== -1;
}),
truncate: buntUndefined(function(value, length, end, binding) {
if (end == null) {
end = "...";
}
if (!binding) {
binding = end;
end = "...";
}
if (value.length > length) {
value = value.substr(0, length - end.length) + end;
}
return value;
}),
"default": function(value, defaultValue, binding) {
if ((value != null) && value !== '') {
return value;
} else {
return defaultValue;
}
},
prepend: function(value, string, binding) {
return (string != null ? string : '') + (value != null ? value : '');
},
append: function(value, string, binding) {
return (value != null ? value : '') + (string != null ? string : '');
},
replace: buntUndefined(function(value, searchFor, replaceWith, flags, binding) {
if (!binding) {
binding = flags;
flags = void 0;
}
if (flags === void 0) {
return value.replace(searchFor, replaceWith);
} else {
return value.replace(searchFor, replaceWith, flags);
}
}),
downcase: buntUndefined(function(value) {
return value.toLowerCase();
}),
upcase: buntUndefined(function(value) {
return value.toUpperCase();
}),
pluralize: buntUndefined(function(string, count, includeCount, binding) {
if (!binding) {
binding = includeCount;
includeCount = true;
if (!binding) {
binding = count;
count = void 0;
}
}
if (count != null) {
return Batman.helpers.pluralize(count, string, void 0, includeCount);
} else {
return Batman.helpers.pluralize(string);
}
}),
humanize: buntUndefined(function(string, binding) {
return Batman.helpers.humanize(string);
}),
join: buntUndefined(function(value, withWhat, binding) {
if (withWhat == null) {
withWhat = '';
}
if (!binding) {
binding = withWhat;
withWhat = '';
}
return value.join(withWhat);
}),
sort: buntUndefined(function(value) {
return value.sort();
}),
map: buntUndefined(function(value, key) {
return value.map(function(x) {
return Batman.get(x, key);
});
}),
has: function(set, item) {
if (set == null) {
return false;
}
return Batman.contains(set, item);
},
first: buntUndefined(function(value) {
return value[0];
}),
meta: buntUndefined(function(value, keypath) {
Batman.developer.assert(value.meta, "Error, value doesn't have a meta to filter on!");
return value.meta.get(keypath);
}),
interpolate: function(string, interpolationKeypaths, binding) {
var k, v, values;
if (!binding) {
binding = interpolationKeypaths;
interpolationKeypaths = void 0;
}
if (!string) {
return;
}
values = {};
for (k in interpolationKeypaths) {
v = interpolationKeypaths[k];
values[k] = this.lookupKeypath(v);
if (values[k] == null) {
Batman.developer.warn("Warning! Undefined interpolation key " + k + " for interpolation", string);
values[k] = '';
}
}
return Batman.helpers.interpolate(string, values);
},
withArguments: function() {
var binding, block, curryArgs, _i;
block = arguments[0], curryArgs = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), binding = arguments[_i++];
if (!block) {
return;
}
return function() {
var regularArgs;
regularArgs = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return block.call.apply(block, [this].concat(__slice.call(curryArgs), __slice.call(regularArgs)));
};
},
escape: buntUndefined(Batman.escapeHTML)
};
(function() {
var k, _i, _len, _ref, _results;
_ref = ['capitalize', 'singularize', 'underscore', 'camelize'];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
k = _ref[_i];
_results.push(Batman.Filters[k] = buntUndefined(Batman.helpers[k]));
}
return _results;
})();
Batman.developer.addFilters();
}).call(this);
(function() {
}).call(this);
|
// A module that exports a single function that accepts a function as an argument.
// The function specified will only be called when the DOM has completely been loaded,
// or will be called immediately if the DOM has already been loaded. The implementation
// of this module comes directly from the jQuery implementation of `domReady` event. In
// fact the source was copied from jQuery and converted to an AMD module.
/*global 'define'*/
define("dom-ready", ['browser'], function (browser) {
"use strict";
var ready, document, window, setTimeout, DOMContentLoaded, callbacks, toplevel;
callbacks = [];
ready = false;
document = browser.document;
window = browser.window;
setTimeout = browser.setTimeout;
function onReady() {
// Make sure body exists, at least, in case IE gets a little overzealous.
if (!document.body) {
setTimeout(onReady, 1);
return;
}
// Remember that the DOM is ready
ready = true;
var i, len = callbacks.length;
for (i = 0; i < len; i += 1) {
callbacks[i].call(document);
}
callbacks = [];
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if (ready) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
// and execute any waiting functions
onReady();
}
// Cleanup functions for the document ready method
if (document.addEventListener) {
DOMContentLoaded = function () {
document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
onReady();
};
} else if (document.attachEvent) {
DOMContentLoaded = function () {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", DOMContentLoaded);
onReady();
}
};
}
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if (document.readyState === "complete") {
ready = true;
} else {
// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
// Use the handy event callback
document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);
// A fallback to window.onload, that will always work
window.addEventListener("load", onReady, false);
// If IE event model is used
} else if (document.attachEvent) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", DOMContentLoaded);
// A fallback to window.onload, that will always work
window.attachEvent("onload", onReady);
// If IE and not a frame
// continually check to see if the document is ready
toplevel = false;
try {
toplevel = window.frameElement === null;
} catch (e) {}
if (document.documentElement.doScroll && toplevel) {
doScrollCheck();
}
}
}
return function (fn) {
if (ready) {
fn.call(document);
} else if (typeof fn === "function") {
callbacks.push(fn);
}
};
}); |
"use strict";
const _ = require('lodash');
const config = require('config');
const GitHubApi = require("github");
module.exports = function(sequelize, DataTypes) {
var Repository = sequelize.define("Repository", {
owner: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.STRING,
allowNull: false
},
token: {
type: DataTypes.STRING
}
}, {
instanceMethods: {
train() {
return Promise.all([
this.trainLabels(),
]);
},
trainLabels() {
// console.log(`Train issue labels for repository: ${this.id}`);
// Get all associated Issues
const {Issue} = require('../models');
return Issue.issuesForRepo(this.id)
.then((issues) => {
issues = _.map(issues, (issue) => issue.toJSON());
// console.log('Found issues!', issues.length, issues);
// Create dataset for training
let {owner, name} = this;
let ignoreLabels = []; // TODO
const {train} = require('../classifier');
// Start the training
return train('labels', [owner, name, issues, ignoreLabels])
.then((resp) => {
// console.log(`Finished training repository '${this.owner}/${this.name}' with ${issues.length} issues`);
// console.log(JSON.stringify(_.pick(resp, ['score','wrong','total','percentage','newly_labeled_issues']), undefined, 2));
return resp;
});
})
.catch((error) => {
console.error(error);
return error;
});
},
predictIssueLabels(issue) {
const {predictIssueLabels} = require('../classifier');
return predictIssueLabels(this.owner, this.name, issue)
.then((results) => {
return results[0];
});
},
getGitHubClient() {
const github = new GitHubApi({
debug: false,
});
// Create an authenticated GitHub client
github.authenticate({type: "oauth", token: this.token});
return github;
},
addLabelsToIssue(issue, labels) {
let {number} = issue;
let {owner, name} = this;
let github = this.getGitHubClient();
github.issues.addLabels({
user: owner,
repo: name,
number,
body: labels
});
},
addCommentToIssue(issue, body) {
let {number} = issue;
let {owner, name} = this;
let github = this.getGitHubClient();
// Add signature to body
body += config.get('comments.signature');
github.issues.createComment({
user: owner,
repo: name,
number,
body
});
}
},
classMethods: {
associate: function(models) {
Repository.hasMany(models.Issue, {
foreignKey: {
name: 'repository_id'
}
});
},
transformFields(repo) {
// Pick only the used fields
repo = _.pick(repo, ['id','owner','name','description']);
// Simplify the owner field
repo.owner = _.get(repo, 'owner.login');
return repo;
},
train(repoId) {
return Repository.findById(repoId)
.then((repo) => {
return repo.train();
});
},
forIssue(issue) {
let repoId = issue.repository_id;
// Find Repository associated with this Issue
return Repository.findById(repoId)
},
webhook(event) {
// TODO: Handle changes to repository
}
},
indexes: [
{
unique: true,
fields: ['owner', 'name']
}
]
});
return Repository;
}; |
var webpack = require('webpack');
var path = require('path');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./app/index.jsx',
],
output: {
path: __dirname + '/app/dist',
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module:{
loaders: [
{
test: /\.jsx?/,
loaders: ['react-hot','babel'],
include: path.join(__dirname, 'app')
},
{
test: /\.less$/,
loader: 'style!css!less'
},
{
test: /\.css$/,
loader: 'style!css'
}
]
}
}; |
export const config = {
redditUrl: 'http://www.reddit.com/',
popularSubs: 'subreddits/popular.json',
subredditDetail: 'r/${subreddit}.json',
comments: 'r/${subreddit}/comments/${commentsId}.json'
};
export function AppConfig() {
return config;
}
|
if (!process.env.token) {
console.log('Error: Specify token in environment');
process.exit(1);
}
var Botkit = require('./lib/Botkit.js');
var os = require('os');
var request = require('request');
var controller = Botkit.slackbot({
debug: true,
});
var bot = controller.spawn({
token: process.env.token
}).startRTM();
controller.hears(['top (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
var catagory = message.match[1];
var links = {
businesses: 'http://54.213.83.132/hackoregon/http/oregon_business_contributors/5/',
individuals: 'http://54.213.83.132/hackoregon/http/oregon_individual_contributors/5/',
committees: 'http://54.213.83.132/hackoregon/http/oregon_committee_contributors/2/'
}
if (catagory == 'businesses' || 'individuals' || 'committees') {
var link = links[catagory];
topFive(link, catagory);
} else {
bot.reply(message,{
text: 'I’m sorry. What are you looking for? I can return top `businesses`,`individuals` and `committees`.'
},function(err,resp) {
console.log(err,resp);
});
}
function topFive(link, catagory){
bot.reply(message,{text: 'Alright, let me get the top ' + catagory + ' for you.'},function(err,resp) {console.log(err,resp);});
request(link, function (error, response, body) {
if (!error && response.statusCode == 200) {
var attachments = [];
var topFive = JSON.parse(body);
topFive.forEach(function(d) {
var attachment = {
text: '*' + d.contributor_payee + '* contributed *$' + formatCurrency(d.sum) + '*.',
color: '#36A64F',
mrkdwn_in: ["text"]
};
attachments.push(attachment);
});
bot.reply(message,{
text: 'Here are the top ' + catagory + ', for all recipients, in all of Oregon:',
attachments: attachments,
},function(err,resp) {
console.log(err,resp);
});
}
})
}
});
});
controller.hears(['help'], 'direct_message,direct_mention,mention', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
bot.reply(message,{
text: '`Hello` will greet you with your name, if it has a nickname saved for your user.\n`Call me` will save a nickname to user name.\n`What is my name?` will respond with users nickname.\n`Who are you?` will respond uptime and hostname data.\n`Shutdown` will shut down the bot.' });
});
});
controller.hears(['search (.*)', 'find (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
var name = message.match[1];
bot.reply(message,{text: 'Alright, let me look up ' + name + ' for you.'},function(err,resp) {console.log(err,resp);});
request('http://54.213.83.132/hackoregon/http/candidate_search/' + name + '/', function (error, response, body) {
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
bot.reply(message,{
text: data.candidate_name + ', running for ' + data.race + ', has raised $' + formatCurrency(data.total) + '.',
attachments: [{
fields: [{
"title": "Website",
"value": data.website,
"short": true
}, {
"title": "Phone",
"value": data.phone,
"short": true
}, {
"title": "Committee Names",
"value": data.committee_names,
"short": true
}, {
"title": "Filer ID",
"value": data.filer_id,
"short": true
}]
}]
},function(err,resp) {
console.log(err,resp);
});
} else {
bot.reply(message,{text: 'Sorry, I couldn’t find ' + name + '.'},function(err,resp) {console.log(err,resp);});
}
})
});
controller.hears(['hello', 'hi'], 'direct_message,direct_mention,mention', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
if (user && user.name) {
bot.reply(message, 'Hello ' + user.name + '!');
} else {
bot.reply(message, 'Hello.');
}
});
});
controller.hears(['call me (.*)', 'my name is (.*)'], 'direct_message,direct_mention,mention', function(bot, message) {
var name = message.match[1];
controller.storage.users.get(message.user, function(err, user) {
if (!user) {
user = {
id: message.user,
};
}
user.name = name;
controller.storage.users.save(user, function(err, id) {
bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
});
});
});
controller.hears(['what is my name', 'who am i'], 'direct_message,direct_mention,mention', function(bot, message) {
controller.storage.users.get(message.user, function(err, user) {
if (user && user.name) {
bot.reply(message, 'Your name is ' + user.name);
} else {
bot.startConversation(message, function(err, convo) {
if (!err) {
convo.say('I do not know your name yet!');
convo.ask('What should I call you?', function(response, convo) {
convo.ask('You want me to call you `' + response.text + '`?', [
{
pattern: 'yes',
callback: function(response, convo) {
// since no further messages are queued after this,
// the conversation will end naturally with status == 'completed'
convo.next();
}
},
{
pattern: 'no',
callback: function(response, convo) {
// stop the conversation. this will cause it to end with status == 'stopped'
convo.stop();
}
},
{
default: true,
callback: function(response, convo) {
convo.repeat();
convo.next();
}
}
]);
convo.next();
}, {'key': 'nickname'}); // store the results in a field called nickname
convo.on('end', function(convo) {
if (convo.status == 'completed') {
bot.reply(message, 'OK! I will update my dossier...');
controller.storage.users.get(message.user, function(err, user) {
if (!user) {
user = {
id: message.user,
};
}
user.name = convo.extractResponse('nickname');
controller.storage.users.save(user, function(err, id) {
bot.reply(message, 'Got it. I will call you ' + user.name + ' from now on.');
});
});
} else {
// this happens if the conversation ended prematurely for some reason
bot.reply(message, 'OK, nevermind!');
}
});
}
});
}
});
});
controller.hears(['shutdown'], 'direct_message,direct_mention,mention', function(bot, message) {
bot.startConversation(message, function(err, convo) {
convo.ask('Are you sure you want me to shutdown?', [
{
pattern: bot.utterances.yes,
callback: function(response, convo) {
convo.say('Bye!');
convo.next();
setTimeout(function() {
process.exit();
}, 3000);
}
},
{
pattern: bot.utterances.no,
default: true,
callback: function(response, convo) {
convo.say('*Phew!*');
convo.next();
}
}
]);
});
});
controller.hears(['uptime', 'identify yourself', 'who are you', 'what is your name'],
'direct_message,direct_mention,mention', function(bot, message) {
var hostname = os.hostname();
var uptime = formatUptime(process.uptime());
bot.reply(message,
':robot_face: I am a bot named <@' + bot.identity.name +
'>. I have been running for ' + uptime + ' on ' + hostname + '.');
});
function formatUptime(uptime) {
var unit = 'second';
if (uptime > 60) {
uptime = uptime / 60;
unit = 'minute';
}
if (uptime > 60) {
uptime = uptime / 60;
unit = 'hour';
}
if (uptime != 1) {
unit = unit + 's';
}
uptime = uptime + ' ' + unit;
return uptime;
}
function formatCurrency(n){
return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
}
|
/* global require, describe, it */
'use strict';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Matrix data structure:
matrix = require( 'dstructs-matrix' ),
// Check whether an element is a finite number
isFiniteNumber = require( 'validate.io-finite' ),
// Validate a value is NaN:
isnan = require( 'validate.io-nan' ),
// Module to be tested:
mgf = require( './../lib' );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'distributions-weibull-mgf', function tests() {
it( 'should export a function', function test() {
expect( mgf ).to.be.a( 'function' );
});
it( 'should throw an error if provided an invalid option', function test() {
var values = [
'5',
5,
true,
undefined,
null,
NaN,
[],
{}
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( TypeError );
}
function badValue( value ) {
return function() {
mgf( [1,2,3], {
'accessor': value
});
};
}
});
it( 'should throw an error if provided an array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
mgf( [1,2,3], {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a typed-array and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
mgf( new Int8Array([1,2,3]), {
'dtype': value
});
};
}
});
it( 'should throw an error if provided a matrix and an unrecognized/unsupported data type option', function test() {
var values = [
'beep',
'boop'
];
for ( var i = 0; i < values.length; i++ ) {
expect( badValue( values[i] ) ).to.throw( Error );
}
function badValue( value ) {
return function() {
mgf( matrix( [2,2] ), {
'dtype': value
});
};
}
});
it( 'should return NaN if the first argument is neither a number, array-like, or matrix-like', function test() {
var values = [
// '5', // valid as is array-like (length)
true,
undefined,
null,
// NaN, // allowed
function(){},
{}
];
for ( var i = 0; i < values.length; i++ ) {
assert.isTrue( isnan( mgf( values[ i ] ) ) );
}
});
it( 'should evaluate the moment-generating function when provided a number', function test() {
var validationData = require( './fixtures/number.json' ),
data = validationData.data,
expected = validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
});
var actual;
for ( var i = 0; i < data.length; i++ ) {
actual = mgf( data[ i ], {
'lambda': validationData.lambda,
'k': validationData.k
});
if ( isFiniteNumber( actual ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual, expected[ i ] , 1e-14 );
}
}
});
it( 'should evaluate the moment-generating function when provided a plain array', function test() {
var validationData = require( './fixtures/array.json' ),
data,
actual,
expected,
i;
// make copy of data array to prevent mutation of validationData
data = validationData.data.slice();
expected = validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
});
actual = mgf( data, {
'lambda': validationData.lambda,
'k': validationData.k
});
assert.notEqual( actual, data );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-15 );
}
}
// Mutate...
actual = mgf( data, {
'copy': false,
'lambda': validationData.lambda,
'k': validationData.k
});
assert.strictEqual( actual, data );
for ( i = 0; i < data.length; i++ ) {
if ( isFiniteNumber( data[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( data[ i ], expected[ i ], 1e-15 );
}
}
});
it( 'should evaluate the moment-generating function when provided a typed array', function test() {
var validationData = require( './fixtures/typedarray.json' ),
data,
actual,
expected,
i;
data = new Float32Array( validationData.data );
expected = new Float64Array( validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
}) );
actual = mgf( data, {
'lambda': validationData.lambda,
'k': validationData.k
});
assert.notEqual( actual, data );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-14 );
}
}
// Mutate:
actual = mgf( data, {
'copy': false,
'lambda': validationData.lambda,
'k': validationData.k
});
expected = new Float32Array( validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
}) );
assert.strictEqual( actual, data );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-14 );
}
}
});
it( 'should evaluate the moment-generating function element-wise and return an array of a specific type', function test() {
var validationData = require( './fixtures/array.json' ),
// make copy of data array to prevent mutation of validationData
data = validationData.data.slice(),
actual,
expected,
i;
expected = new Float32Array( validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
}) );
actual = mgf( data, {
'dtype': 'float32',
'lambda': validationData.lambda,
'k': validationData.k
});
assert.notEqual( actual, data );
assert.strictEqual( actual.BYTES_PER_ELEMENT, 4 );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-14 );
}
}
});
it( 'should evaluate the moment-generating function element-wise using an accessor', function test() {
var validationData = require( './fixtures/accessor.json' ),
data,
actual,
expected,
i;
data = validationData.data.map( function( e, i ) {
return [ i, e ];
});
expected = validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
});
actual = mgf( data, {
'accessor': getValue,
'lambda': validationData.lambda,
'k': validationData.k
});
assert.notEqual( actual, data );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-14 );
}
}
// Mutate:
actual = mgf( data, {
'accessor': getValue,
'copy': false,
'lambda': validationData.lambda,
'k': validationData.k
});
assert.strictEqual( actual, data );
for ( i = 0; i < actual.length; i++ ) {
if ( isFiniteNumber( actual[ i ] ) && isFiniteNumber( expected[ i ] ) ) {
assert.closeTo( actual[ i ], expected[ i ], 1e-14 );
}
}
function getValue( d ) {
return d[ 1 ];
}
});
it( 'should evaluate the moment-generating function element-wise and deep set', function test() {
var validationData = require( './fixtures/deepset.json' ),
data,
actual,
expected,
i;
data = validationData.data.map( function( e ) {
return {'x': [ i, e ]};
});
actual = mgf( data, {
'path': 'x.1',
'lambda': validationData.lambda,
'k': validationData.k
});
expected = validationData.expected
.map( function( d ) {
return d === 'Inf' ? Infinity : d;
})
.map( function( e ) {
return {'x': [ i, e ]};
});
assert.strictEqual( actual, data );
for ( i = 0; i < data.length; i++ ) {
if ( isFiniteNumber( data[ i ].x[ 1 ] ) && isFiniteNumber( expected[ i ].x[ 1 ] ) ) {
assert.closeTo( data[ i ].x[ 1 ], expected[ i ].x[ 1 ], 1e-14 );
}
}
// Specify a path with a custom separator...
data = validationData.data.map( function( e ) {
return {'x': [ i, e ]};
});
actual = mgf( data, {
'path': 'x/1',
'sep': '/',
'lambda': validationData.lambda,
'k': validationData.k
});
assert.strictEqual( actual, data );
for ( i = 0; i < data.length; i++ ) {
if ( isFiniteNumber( data[ i ].x[ 1 ] ) && isFiniteNumber( expected[ i ].x[ 1 ] ) ) {
assert.closeTo( data[ i ].x[ 1 ], expected[ i ].x[ 1 ], 1e-14, 'custom separator' );
}
}
});
it( 'should evaluate the moment-generating function element-wise when provided a matrix', function test() {
var validationData = require( './fixtures/matrix.json' ),
mat,
out,
d1,
d2,
i;
d1 = new Float64Array( validationData.data );
d2 = new Float64Array( validationData.expected.map( function( d ) {
return d === 'Inf' ? Infinity : d;
}) );
mat = matrix( d1, [5,5], 'float64' );
out = mgf( mat, {
'lambda': validationData.lambda,
'k': validationData.k
});
for ( i = 0; i < out.length; i++ ) {
if ( isFiniteNumber( out.data[ i ] ) && isFiniteNumber( d2[ i ] ) ) {
assert.closeTo( out.data[ i ], d2[ i], 1e-14 );
}
}
// Mutate...
out = mgf( mat, {
'copy': false,
'lambda': validationData.lambda,
'k': validationData.k
});
assert.strictEqual( mat, out );
for ( i = 0; i < out.length; i++ ) {
if ( isFiniteNumber( out.data[ i ] ) && isFiniteNumber( d2[ i ] ) ) {
assert.closeTo( out.data[ i ], d2[ i ], 1e-14 );
}
}
});
it( 'should evaluate the moment-generating function element-wise and return a matrix of a specific type', function test() {
var validationData = require( './fixtures/matrix.json' ),
mat,
out,
d1,
d2,
i;
d1 = new Float64Array( validationData.data );
d2 = new Float32Array( validationData.expected );
mat = matrix( d1, [5,5], 'float64' );
out = mgf( mat, {
'dtype': 'float32',
'lambda': validationData.lambda,
'k': validationData.k
});
assert.strictEqual( out.dtype, 'float32' );
for ( i = 0; i < out.length; i++ ) {
if ( isFiniteNumber( out.data[ i ] ) && isFiniteNumber( d2[ i ] ) ) {
assert.closeTo( out.data[ i ], d2[ i ], 1e-14 );
}
}
});
it( 'should return an empty data structure if provided an empty data structure', function test() {
assert.deepEqual( mgf( [] ), [] );
assert.deepEqual( mgf( matrix( [0,0] ) ).data, new Float64Array() );
assert.deepEqual( mgf( new Int8Array() ), new Float64Array() );
});
});
|
describe("Integration", function() {
describe("Run integration multiple times", function() {
for(i=1; i<=5; i++) {
describe("Try "+i, function() {
var fake_api = new vk.FakeAPI()
var trav = new vk.Traverser(function(id, is_detailed, on_result) {
var friends = fake_api.getFriends(id, is_detailed)
on_result(friends)
})
var starting_id = 100
it("should complete traversing", function(done) {
trav.enqueue(starting_id, 1)
var onNext = function() {
if (!trav.isCompleted()) {
trav.next(onNext)
} else {
done()
}
}
trav.next(onNext)
})
var graph
it("should convert to graph", function() {
graph = vk.to_graph(trav.friends, trav.links, [starting_id])
})
var gexf
it("should output GEXF", function() {
gexf = format_to_gexf(graph.nodes, graph.edges, graph.attribute_conf)
})
it("GEXF should not be empty", function() {
expect(gexf).to.be.not.empty
expect(gexf).to.be.a("string")
})
})
}
})
}) |
#!/usr/local/bin/node
var Jarbas = require('./core/jarbas.js');
var pars = process.argv.slice(2);
if (pars.length) {
Jarbas.doThis(pars.join(' '));
} else {
Jarbas.salute();
Jarbas.toWork();
}
|
import { validateAndFix } from "../src/svgo";
import test from "tape";
test("fills essential plugins when empty", function(t) {
let opts = {};
validateAndFix(opts);
t.equal(opts.plugins.length, 3);
t.end();
});
test("enable disabled essential plugins", function(t) {
let opts = {
full: true,
plugins: ["removeDoctype", { removeComments: false }]
};
validateAndFix(opts);
t.equal(opts.plugins.length, 3);
t.equal(opts.plugins[1].removeComments, true);
t.end();
});
|
import React from 'react';
import { View, Image, TouchableOpacity } from 'react-native';
import navBarStyles from '../../styles/create/navBarStyles';
import TextOpenSans from '../utils/TextOpenSans';
import arrowLeft from '../../../assets/arrow-left.png';
const propTypes = {
progress: React.PropTypes.number,
navigateBackward: React.PropTypes.func,
};
const NavBarView = props => (
<View style={navBarStyles.mainContainer} >
<View style={navBarStyles.contentContainer} >
<TouchableOpacity style={navBarStyles.backIconContainer} onPress={props.navigateBackward}>
<Image source={arrowLeft} />
</TouchableOpacity>
<View style={navBarStyles.textContainer} >
<TextOpenSans style={navBarStyles.font}>
I create my Travelgram
</TextOpenSans>
</View>
<View style={navBarStyles.marginContainer} />
</View>
<View style={navBarStyles.progressLineContainer} >
<View style={[navBarStyles.progressLineLeftContainer, { flex: props.progress }]} />
<View style={[navBarStyles.progressLineRightContainer, { flex: 1 - props.progress }]} />
</View>
</View>
);
NavBarView.propTypes = propTypes;
export default NavBarView;
|
"use strict";
global.sinon = require('sinon');
global.chai = require('chai');
global.should = require('chai').should();
global.expect = require('chai').expect;
global.AssertionError = require('chai').AssertionError;
global.swallow = function (thrower) {
try {
thrower();
} catch (e) {}
};
var sinonChai = require('sinon-chai');
chai.use(sinonChai); |
/**
* @package Graph
* @file GraphSerializer.js
* @author Nagy Zoltán (NAZRAAI.ELTE) <abesto0@gmail.com>
* @license Apache License, Version 2.0
*
* Serialize a graph (model and coordinates from the UI) into JSON
*
* Copyright 2011 Nagy Zoltán
* 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.
*/
Namespace('net.abesto.graph', {
Serializer: (function() {
var SID, UIDtoSID = {};
function node(node) {
var bbox = node.ui.getBBox();
UIDtoSID[node.UID] = SID();
return {
SID: UIDtoSID[node.UID],
x: parseFloat(bbox.x) + parseFloat((bbox.width / 2).toFixed(1)),
y: parseFloat(bbox.y) + parseFloat((bbox.height / 2).toFixed(1))
};
}
function edge(edge) {
return {
n1: UIDtoSID[edge.node1().UID],
n2: UIDtoSID[edge.node2().UID]
};
}
function graph(graph) {
var nodes = [], edges = [];
SID = new UID.Generator();
console.log(graph);
graph.nodes().each(function(n) { nodes.push(node(n)); });
graph.edges().each(function(e) { edges.push(edge(e)); });
return $.toJSON({nodes: nodes, edges: edges});
}
return {
serialize: graph
};
})()
});
|
/**
* @since 2019-09-16 07:53
* @author vivaxy
*/
import React, { Component } from 'react';
export default class Child2 extends Component {
render() {
return <div>{this.props.name}</div>;
}
}
|
/**
* @fileoverview Tests for no-redundant-should-component-update
*/
'use strict';
// -----------------------------------------------------------------------------
// Requirements
// -----------------------------------------------------------------------------
const rule = require('../../../lib/rules/no-redundant-should-component-update');
const RuleTester = require('eslint').RuleTester;
const parserOptions = {
ecmaVersion: 6,
ecmaFeatures: {
experimentalObjectRestSpread: true,
jsx: true
}
};
function errorMessage(node) {
return `${node} does not need shouldComponentUpdate when extending React.PureComponent.`;
}
// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------
const ruleTester = new RuleTester();
ruleTester.run('no-redundant-should-component-update', rule, {
valid: [
{
code: `
class Foo extends React.Component {
shouldComponentUpdate() {
return true;
}
}
`,
parserOptions: parserOptions
},
{
code: `
class Foo extends React.Component {
shouldComponentUpdate = () => {
return true;
}
}
`,
parser: 'babel-eslint',
parserOptions: parserOptions
},
{
code: `
class Foo extends React.Component {
shouldComponentUpdate() {
return true;
}
}
`,
parserOptions: parserOptions
},
{
code: `
function Foo() {
return class Bar extends React.Component {
shouldComponentUpdate() {
return true;
}
};
}
`,
parserOptions: parserOptions
}
],
invalid: [
{
code: `
class Foo extends React.PureComponent {
shouldComponentUpdate() {
return true;
}
}
`,
errors: [{message: errorMessage('Foo')}],
parserOptions: parserOptions
},
{
code: `
class Foo extends PureComponent {
shouldComponentUpdate() {
return true;
}
}
`,
errors: [{message: errorMessage('Foo')}],
parserOptions: parserOptions
},
{
code: `
class Foo extends React.PureComponent {
shouldComponentUpdate = () => {
return true;
}
}
`,
errors: [{message: errorMessage('Foo')}],
parser: 'babel-eslint',
parserOptions: parserOptions
},
{
code: `
function Foo() {
return class Bar extends React.PureComponent {
shouldComponentUpdate() {
return true;
}
};
}
`,
errors: [{message: errorMessage('Bar')}],
parserOptions: parserOptions
},
{
code: `
function Foo() {
return class Bar extends PureComponent {
shouldComponentUpdate() {
return true;
}
};
}
`,
errors: [{message: errorMessage('Bar')}],
parserOptions: parserOptions
},
{
code: `
var Foo = class extends PureComponent {
shouldComponentUpdate() {
return true;
}
}
`,
errors: [{message: errorMessage('Foo')}],
parserOptions: parserOptions
}
]
});
|
/**
* Event emitter mixin. This will add emitter properties to an object so that
* it can emit events, and have others listen for them. Based on
* [node.js event emitter](https://github.com/joyent/node/blob/master/lib/events.js)
*
* @class EventEmitter
* @constructor
*/
var EventEmitter = function() {
this._events = this._events || {};
/**
* Registers a listener function to be run on an event occurance
*
* @method on
* @param type {String} The event name to listen for
* @param listener {Function} The function to execute when the event happens
* @return {mixed} Returns itself.
* @chainable
*/
this.addEventListener = this.on = function(type, listener) {
if(typeof listener !== 'function')
throw new TypeError('listener must be a function');
if(!this._events)
this._events = {};
// Optimize the case of one listener. Don't need the extra array object.
if (!this._events[type])
this._events[type] = listener;
// If we've already got an array, just append.
else if (typeof this._events[type] === 'object')
this._events[type].push(listener);
// Adding the second element, need to change to array.
else
this._events[type] = [this._events[type], listener];
return this;
};
/**
* Emits an event which will run all registered listeners for the event type
*
* @method emit
* @param type {String} The event name to emit
* @param data {mixed} Any data you want passed along with the event
* @return {mixed} Returns itself.
* @chainable
*/
this.dispatchEvent = this.emit = function(type) {
if(!this._events)
this._events = {};
var handler = this._events[type],
len = arguments.length,
htype = typeof handler,
args,
i,
listeners;
if(htype === 'undefined')
return false;
if(htype === 'function') {
switch(len) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = new Array(len - 1);
for(i = 1; i < len; ++i)
args[i - 1] = arguments[i];
handler.apply(this, args);
break;
}
} else if (htype === 'object') {
args = new Array(len - 1);
for(i = 1; i < len; ++i)
args[i - 1] = arguments[i];
/*listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);*/
len = handler.length;
listeners = handler.slice();
for(i = 0; i < len; ++i)
listeners[i].apply(this, args);
}
return this;
};
/**
* Removes a listener function for an event type
*
* @method off
* @param type {String} The event name to emit
* @param listener {Function} The function to remove
* @return {mixed} Returns itself.
* @chainable
*/
this.removeEventListener = this.off = function(type, listener) {
var list, position, length, i;
if(typeof listener !== 'function')
throw new TypeError('listener must be a function');
if(!this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if(list === listener || (typeof list.listener === 'function' && list.listener === listener)) {
delete this._events[type];
} else if(typeof list === 'object') {
for(i = length; i-- > 0;) {
if(list[i] === listener || (list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if(position < 0)
return this;
if(list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
}
return this;
};
/**
* Registers a one-time callback for an event
*
* @method once
* @param type {String} The event name to listen for
* @param listener {Function} the callback to call when the event occurs
* @return {mixed} Returns itself.
* @chainable
*/
this.once = function(type, listener) {
if(typeof listener !== 'function')
throw new TypeError('listener must be a function');
var fired = false;
function g() {
this.off(type, g);
if(!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
};
module.exports = EventEmitter;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.session = exports.passport = exports.controllers = exports.connect = undefined;
var _connect = require('./connect');
var _connect2 = _interopRequireDefault(_connect);
var _controllers = require('./controllers');
var _controllers2 = _interopRequireDefault(_controllers);
var _passport = require('./passport');
var _passport2 = _interopRequireDefault(_passport);
var _session = require('./session');
var _session2 = _interopRequireDefault(_session);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.connect = _connect2.default;
exports.controllers = _controllers2.default;
exports.passport = _passport2.default;
exports.session = _session2.default;
exports.default = {
connect: _connect2.default,
controllers: _controllers2.default,
passport: _passport2.default,
session: _session2.default
}; |
(function(window, document, Sync, undefined) {
// no strict in ie :)
"use strict";
if (document.addEventListener) return;
var eventsMap = {
click: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: true
},
mousedown: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: true,
cancel: function(event, nativeEvent) {
if (document.activeElement) {
document.activeElement.onbeforedeactivate = function() {
window.event && (window.event.returnValue = false);
this.onbeforedeactivate = null;
};
}
}
},
mousemove: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: false,
check: (function() {
var lastPageX,
lastPageY,
lastCall = 0;
return function(event) {
if ((event.timeStamp - lastCall) > 20 &&
(lastPageX !== event.pageX || lastPageY !== event.pageY)) {
lastCall = event.timeStamp;
lastPageX = event.pageX;
lastPageY = event.pageY;
return true;
}
return false;
}
}())
},
mouseup: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: false
},
mouseenter: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
mouseleave: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
dblclick: {
type: 'MouseEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: false
},
keydown: {
type: 'KeyboardEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: true
},
keypress: {
type: 'KeyboardEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: true
},
keyup: {
type: 'KeyboardEvent',
targets: {
Element: true,
},
bubbles: true,
cancelable: false
},
focus: {
type: 'FocusEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
blur: {
type: 'FocusEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
focusin: {
type: 'FocusEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: false
},
focusout: {
type: 'FocusEvent',
targets: {
Element: true
},
bubbles: true,
cancelable: false
},
scroll: {
type: 'UIEvent',
targets: {
Element: true,
Window: true
},
bubbles: false,
cancelable: false
},
resize: {
type: 'UIEvent',
targets: {
Window: true
},
bubbles: false,
cancelable: false,
check: (function() {
var width = window.innerWidth,
height = window.innerHeight;
return function(event) {
// Hardcoded for top view
if (width !== window.innerWidth || height !== window.innerHeight) {
return true;
}
}
}())
},
unload: {
type: 'UIEvent',
targets: {
Window: true
},
bubbles: false,
cancelable: false
},
beforeunload: {
type: 'UIEvent',
targets: {
Window: true
},
bubbles: false,
cancelable: true,
cancel: function(event, nativeEvent) {
nativeEvent.returnValue = '';
}
},
submit: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: true
},
change: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
error: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
abort: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false
},
load: {
type: 'UIEvent',
targets: {
Element: true,
Document: true,
Window: true
},
bubbles: false,
cancelable: false
},
message: {
type: /*'MessageEvent'*/ 'Event',
targets: {
Window: true
},
bubbles: false,
cancelable: false,
check: function(event, nativeEvent) {
var data = nativeEvent.data;
try {
data = JSON.parse(data);
} catch (e) {};
event.data = data;
event.origin = nativeEvent.origin;
event.source = nativeEvent.source;
return true;
}
},
select: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false,
checkTarget: function(target) {
if (target.nodeName.toLowerCase() === 'textarea' ||
(target.nodeName.toLowerCase() === 'input' &&
('text password').split(' ').indexOf(target.type) !== -1)) {
return true;
}
}
},
input: {
type: 'UIEvent',
targets: {
Element: true
},
bubbles: false,
cancelable: false,
checkTarget: function(target) {
if (target.nodeName.toLowerCase() === 'textarea' ||
(target.nodeName.toLowerCase() === 'input' &&
('text password').split(' ').indexOf(target.type) !== -1)) {
return true;
}
},
add: function(type, target, config) {
var handler = function() {
if (window.event.propertyName !== 'value') return;
EventTarget.prototype.dispatchEvent.call(target,
new events.UIEvent(type, {
bubbles: config.bubbles,
cancelable: config.cancelable
})
);
};
target.attachEvent('onpropertychange', handler);
return handler;
},
remove: function(type, target, config, handler) {
target.detachEvent('onpropertychange', handler);
}
},
DOMContentLoaded: {
type: 'Event',
targets: {
Document: true
},
bubbles: false,
cancelable: false,
add: function(type, target, config) {
var handler = function() {
EventTarget.prototype.dispatchEvent.call(target, new events.Event(type, {
bubbles: config.bubbles,
cancelable: config.cancelable
}));
};
target.defaultView.attachEvent('onload', handler);
return handler;
},
remove: function(type, target, config, handler) {
target.defaultView.detachEvent('onload', handler);
}
},
readystatechange: {
type: 'Event',
bubbles: false,
cancelable: false,
targets: {
XMLHttpRequest: true
}
},
timeout: {
type: 'Event',
bubbles: false,
cancelable: false,
targets: {
XMLHttpRequest: true
}
}
// wheel
},
ie = Sync.ie || (Sync.ie = {}),
events = {
normalize: function(event, type) {
type || event && (type = event.type);
if (!event || !eventsMap.hasOwnProperty(type)) {
return null;
}
var type,
config = eventsMap[type],
_interface = events[config.type],
instance = Object.create(_interface.prototype);
_interface.normalize.call(instance, event, config)
return instance;
}
},
NativeEvent = window.Event,
globalEventsCounter = 0,
globalEventsMap = {};
var IE_DOM_EVENTS_KEY = 'ie_dom_events',
EVENT_FIRE_PROPERTY = 'ie_dom_event_fire',
LAST_TARGET_HADNLER_KEY = 'ie_last_target_handler',
ATTACH_EVENT_HANDLER_KEY = 'ie_attach_event_handler';
var define = function(obj, name, value) {
if (obj.setTimeout) {
eval(name + ' = value');
} else {
Object.defineProperty(obj, name, {
value: value,
enumerable: false,
writable: true,
configurable: true
});
}
};
var getEventStore = function(node, type, capture) {
var events = Sync.cache(node, IE_DOM_EVENTS_KEY);
events = events[type] || (events[type] = {
/*bubbling: {
index: [],
listeners: []
},
capture: {*/
index: [],
listeners: []
/*}*/
});
//return capture ? events.capture : events.bubbling;
return events;
},
registerEventTarget = function(params) {
var identifier = params.identifier,
target = params.target,
needProxy = params.needProxy,
nativeEvent = params.nativeEvent;
var path = globalEventsMap[identifier] || (globalEventsMap[identifier] = []);
path.push({
target: target,
needProxy: needProxy
});
},
fireListeners = function(item, normalEvent) {
var target = item.target,
store = getEventStore(target, normalEvent.type, item.capture),
listeners = store.listeners.concat(),
length = listeners.length,
index = 0,
result;
normalEvent.currentTarget = target;
normalEvent.eventPhase = item.phase;
for (; index < length; index++) {
var listener = listeners[index];
result = listener.handleEvent.call(target, normalEvent);
if (normalEvent.eventFlags & normalEvent.STOP_IMMEDIATE_PROPAGATION) {
break;
}
}
return result;
},
bindNativeHandler = function(self, type, config) {
var targets = config.targets;
checkIs: {
if (!self.nodeType && self.setTimeout) {
var isWin = true;
} else if (self.nodeType === Node.DOCUMENT_NODE) {
var isDoc = true;
} else if (self.nodeType === Node.ELEMENT_NODE) {
var isElem = true;
if (self.ownerDocument.documentElement === self) {
var isRoot = true;
}
} else if (self.nodeType) {
var isOtherNode = true;
} else {}
}
if ((isElem && !targets.Element) ||
(isDoc && !targets.Document && !targets.Element) ||
(isWin && !targets.Window && !targets.Element)) {
return;
}
if (config.checkTarget && !config.checkTarget(self)) {
return;
}
if (isWin && targets.Element && !targets.Window) {
self = self.document;
isDoc = true;
isWin = false;
} else if (isWin) {
self = self.window;
}
var isLastTarget,
doc = isWin ? self.document : self.ownerDocument || document,
attachHandlerCache = Sync.cache(self, ATTACH_EVENT_HANDLER_KEY),
needWin = !isWin && !targets.Window &&
targets.Element && (isElem || isDoc);
if (attachHandlerCache[type]) return;
isLastTarget = !config.bubbles || (targets.Window && isWin) ||
(targets.Element && !targets.Window && (isDoc || isWin));
var lastTarget = isLastTarget ? self :
(targets.Window ? doc.defaultView : doc),
lastTargetCache = Sync.cache(lastTarget, LAST_TARGET_HADNLER_KEY),
lastTargetCacheEntry = lastTargetCache && lastTargetCache[type];
if (!isWin && !lastTargetCacheEntry) {
if (config.addLastTarget) {
var lastTargetHandler = config.addLastTarget(type, lastTarget, config);
} else {
var lastTargetHandler = function() {
var identifier = window.event.data.trim(),
normalEvent;
if (!identifier || !isFinite(identifier)) return;
if (needWin && (normalEvent = globalEventsMap[identifier])) {
fireListeners({
phase: normalEvent.BUBBLING_PHASE,
target: doc.defaultView,
capture: false,
needProxy: true
}, normalEvent);
}
delete globalEventsMap[identifier];
};
lastTarget.attachEvent('on' + type, lastTargetHandler);
}
lastTargetCacheEntry = lastTargetCache[type] = {
handler: lastTargetHandler,
bounds: []
};
}
if (!isWin && lastTargetCacheEntry) {
lastTargetCache[type].bounds.push(self);
}
if (config.add) {
attachHandlerCache[type] = config.add(type, self, config);
return;
}
self.attachEvent(
'on' + type,
attachHandlerCache[type] = function() {
var nativeEvent = window.event,
data = nativeEvent.data.trim(),
identifier,
event;
if (!isWin) {
if (data && isFinite(data)) {
identifier = data;
event = globalEventsMap[identifier];
} else {
identifier = nativeEvent.data = ++globalEventsCounter;
event = globalEventsMap[identifier] = events.normalize(nativeEvent);
}
} else {
event = events.normalize(nativeEvent);
}
var stopped = event.eventFlags & event.STOP_PROPAGATION,
config = eventsMap[event.type] || {
bubbles: event.bubbles,
cancelable: event.cancelable
},
phase = self === event.target ? event.AT_TARGET : event.BUBBLING_PHASE;
if ((config.check && !config.check(event, nativeEvent)) || stopped ||
(phase === event.BUBBLING_PHASE && !config.bubbles)) {
return;
}
var result = fireListeners({
phase: phase,
target: self,
capture: false,
needProxy: isWin || isDoc
}, event);
if (event.eventFlags & event.STOP_PROPAGATION) {
nativeEvent.cancelBubble = true;
}
if (event.defaultPrevented) {
if (config.cancelable) {
nativeEvent.returnValue = false;
if (config.cancel) {
config.cancel(event, nativeEvent, config);
}
}
} else if (result !== false && result !== void 0) {
nativeEvent.returnValue = result;
}
}
);
},
unbindNativeHandler = function(self, type, config) {
var targets = config.targets;
checkIs: {
if (!self.nodeType && self.setTimeout) {
var isWin = true;
} else if (self.nodeType === Node.DOCUMENT_NODE) {
var isDoc = true;
} else if (self.nodeType === Node.ELEMENT_NODE) {
var isElem = true;
if (self.ownerDocument.documentElement === self) {
var isRoot = true;
}
} else if (self.nodeType) {
var isOtherNode = true;
} else {}
}
if (isElem && !targets.Element ||
isDoc && !targets.Document && !targets.Element ||
isWin && !targets.Window && !targets.Element) {
return;
}
if (config.checkTarget && !config.checkTarget(self)) {
return;
}
if (isWin && targets.Element && !targets.Window) {
self = self.document;
isDoc = true;
isWin = false;
}
var isLastTarget,
doc = isWin ? self.document : self.ownerDocument || document,
attachHandlerCache = Sync.cache(self, ATTACH_EVENT_HANDLER_KEY),
needWin = !isWin && !targets.Window &&
targets.Element && (isElem || isDoc);
if (!attachHandlerCache[type]) return;
isLastTarget = !config.bubbles || (targets.Window && isWin) ||
(targets.Element && !targets.Window && (isDoc || isWin));
var lastTarget = isLastTarget ? self :
(targets.Window ? doc.defaultView : doc),
lastTargetCache = Sync.cache(lastTarget, LAST_TARGET_HADNLER_KEY),
lastTargetCacheEntry = lastTargetCache && lastTargetCache[type],
boundIndex;
if (!isWin && lastTargetCacheEntry) {
boundIndex = lastTargetCacheEntry.bounds.indexOf(self);
if (boundIndex !== -1) {
lastTargetCacheEntry.bounds.splice(boundIndex, 1);
}
if (!lastTargetCacheEntry.bounds.length) {
if (config.removeLastTarget) {
config.removeLastTarget(type, lastTarget, config, lastTargetCacheEntry.handler);
} else {
lastTarget.detachEvent('on' + type, lastTargetCacheEntry.handler);
}
lastTargetCache[type] = null;
}
}
if (config.remove) {
config.remove(type, self, config, attachHandlerCache[type]);
return;
}
self.detachEvent('on' + type, attachHandlerCache[type]);
};
Sync.each({
Event: {
constructor: function(type, params) {
this.timeStamp = Date.now();
},
normalize: function(nativeEvent, config) {
this.target = nativeEvent.srcElement || window;
this.isTrusted = true;
this.bubbles = config.bubbles;
this.cancelable = config.cancelable;
this.type = nativeEvent.type;
this.eventFlags = this.INITIALIZED | this.DISPATCH;
if (nativeEvent.returnValue === false) {
this.preventDefault();
}
if (nativeEvent.cancelBubble === true) {
this.stopPropagation();
}
},
proto: {
type: '',
target: null,
currentTarget: null,
defaultPrevented: false,
isTrusted: false,
bubbles: false,
cancelable: false,
eventPhase: 0,
eventFlags: 0,
timeStamp: 0,
stopPropagation: function() {
this.eventFlags |= this.STOP_PROPAGATION;
},
stopImmediatePropagation: function() {
this.eventFlags = this.eventFlags |
this.STOP_IMMEDIATE_PROPAGATION |
this.STOP_PROPAGATION;
},
preventDefault: function() {
if (this.cancelable) {
this.eventFlags |= this.CANCELED;
//getters are not supported, so that passing new value manually
this.defaultPrevented = true;
}
},
initEvent: function(type, bubbles, cancelable) {
if (this.eventFlags & this.DISPATCH) return;
this.type = type + '';
this.bubbles = !!bubbles;
this.cancelable = !!cancelable;
this.isTrusted = false;
this.eventFlags = this.INITIALIZED;
this.eventPhase = 0;
this.target = null;
},
NONE: 0,
CAPTURING_PHASE: 1,
AT_TARGET: 2,
BUBBLING_PHASE: 3,
STOP_PROPAGATION: 1,
STOP_IMMEDIATE_PROPAGATION: 2,
CANCELED: 4,
INITIALIZED: 8,
DISPATCH: 16
}
},
UIEvent: {
proto: {
view: null,
detail: 0
},
normalize: function(nativeEvent) {
this.view = (this.target.ownerDocument || this.target.document || document).defaultView;
},
parent: 'Event'
},
MouseEvent: {
parent: 'UIEvent',
proto: {
screenX: 0,
screenY: 0,
clientX: 0,
clientY: 0,
ctrlKey: false,
shiftKey: false,
altKey: false,
metaKey: false,
button: 0,
buttons: 0,
relatedTarget: null
},
constructor: function() {
this.pageX = this.clientX + window.pageXOffset;
this.pageY = this.clientY + window.pageYOffset;
},
normalize: function(nativeEvent, config) {
var button;
if (!nativeEvent.button || nativeEvent.button === 1 ||
this.type === 'click' || this.type === 'dblclick') {
button = 0;
} else if (nativeEvent.button & 4) {
button = 1;
} else if (nativeEvent.button & 2) {
button = 2;
}
//this.detail = 0;
this.metaKey = false;
this.ctrlKey = nativeEvent.ctrlKey || nativeEvent.ctrlLeft;
this.altKey = nativeEvent.altKey || nativeEvent.altLeft;
this.shiftKey = nativeEvent.shiftKey || nativeEvent.shiftLeft;
this.screenX = nativeEvent.screenX;
this.screenY = nativeEvent.screenY;
this.clientX = nativeEvent.clientX;
this.clientY = nativeEvent.clientY;
this.buttons = nativeEvent.button;
this.button = button;
this.relatedTarget = this.target === nativeEvent.fromElement ?
nativeEvent.toElement : nativeEvent.fromElement;
}
},
KeyboardEvent: {
parent: 'UIEvent',
proto: {
DOM_KEY_LOCATION_STANDARD: 0x00,
DOM_KEY_LOCATION_LEFT: 0x01,
DOM_KEY_LOCATION_RIGHT: 0x02,
DOM_KEY_LOCATION_NUMPAD: 0x03,
DOM_KEY_LOCATION_MOBILE: 0x04,
DOM_KEY_LOCATION_JOYSTICK: 0x05,
location: 0,
ctrlKey: false,
altKey: false,
shiftKey: false,
metaKey: false,
repeat: false,
locale: '',
keyCode: 0,
charCode: 0,
VK_ESC: 27,
VK_ENTER: 13,
VK_SPACE: 32,
VK_SHIFT: 16,
VK_CTRL: 17,
VK_ALT: 18
},
normalize: function(nativeEvent, config) {
setChar: if (this.type === 'keypress') {
this.charCode = nativeEvent.keyCode;
}
this.keyCode = nativeEvent.keyCode;
this.repeat = nativeEvent.repeat;
this.metaKey = false;
this.altKey = nativeEvent.altKey || nativeEvent.altLeft;
this.ctrlKey = nativeEvent.ctrlKey || nativeEvent.ctrlLeft;
this.shiftKey = nativeEvent.shiftKey || nativeEvent.shiftLeft;
if (this.keyCode === this.VK_ALT) {
this.location = nativeEvent.altLeft ? this.DOM_KEY_LOCATION_LEFT :
this.DOM_KEY_LOCATION_RIGHT;
}
if (this.keyCode === this.VK_CTRL) {
this.location = nativeEvent.ctrlLeft ? this.DOM_KEY_LOCATION_LEFT :
this.DOM_KEY_LOCATION_RIGHT;
}
if (this.keyCode === this.VK_SHIFT) {
this.location = nativeEvent.shiftLeft ? this.DOM_KEY_LOCATION_LEFT :
this.DOM_KEY_LOCATION_RIGHT;
}
}
},
FocusEvent: {
parent: 'UIEvent',
proto: {
relatedTarget: null
},
normalize: function(nativeEvent, config) {
this.relatedTarget = nativeEvent.toElement ?
nativeEvent.toElement : nativeEvent.fromElement;
}
},
CustomEvent: {
parent: 'Event',
proto: {
detail: null
}
}
}, function(config, _interface) {
var constructor = events[_interface] = function(type, options) {
var self = this;
if (!(this instanceof constructor)) {
self = Object.create(constructor.prototype);
}
if (!type) {
return self;
}
options || (options = {});
var bubbles = options.hasOwnProperty('bubbles') ? options.bubbles : this.bubbles,
cancelable = options.hasOwnProperty('cancelable') ? options.cancelable : this.cancelable;
self.initEvent(type, bubbles, cancelable);
delete options.bubbles;
delete options.cancelable;
Sync.each(options, function(value, param) {
if (constructor.prototype.hasOwnProperty(param)) {
self[param] = value;
}
});
config.constructor && config.constructor.apply(self, arguments);
return self;
},
parent = config.parent ? events[config.parent] : null;
constructor.normalize = function(nativeEvent, normalizeConfig) {
if (parent) {
parent.normalize.call(this, nativeEvent, normalizeConfig);
}
config.normalize.call(this, nativeEvent, normalizeConfig);
config.constructor && config.constructor.apply(this, arguments);
};
constructor.prototype = parent ?
Sync.extend(Object.create(parent.prototype), config.proto) : config.proto;
});
var EventListener = function(options) {
options || (options = {});
var type = options.type,
handler = options.handler,
capture = options.capture,
target = options.target;
if (!type || typeof type !== 'string' || !handler ||
(typeof handler !== 'object' && typeof handler !== 'function')) {
console.log('ret with null');
return null;
}
this.type = type;
this.target = target;
this.handleEvent =
(typeof handler === 'function' ? handler : handler.handleEvent);
this.capture =
(typeof capture !== 'boolean' && (capture = false)) || capture;
};
var EventTarget = function() {};
EventTarget.prototype = {
addEventListener: function(type, handler, capture) {
if (!(listener = new EventListener({
type: type,
handler: handler,
capture: capture,
target: this
}))) return;
var store = getEventStore(this, type, capture),
listener,
self = this,
config = eventsMap[type];
if (store.index.indexOf(handler) === -1) {
store.index.push(handler);
store.listeners.push(listener);
}
if (config && self.attachEvent) {
bindNativeHandler(self, type, config);
}
},
removeEventListener: function(type, handler, capture) {
if (typeof handler === 'object' && handler) {
handler = object.handleEvent;
}
if (typeof type !== 'string' || typeof handler !== 'function') {
return;
}
var store = getEventStore(this, type, capture),
self = this,
config = eventsMap[type],
index = store.index.indexOf(handler);
if (index !== -1) {
store.index.splice(index, 1);
store.listeners.splice(index, 1);
}
if (!store.listeners.length && config && self.detachEvent) {
unbindNativeHandler(self, type, config);
}
},
dispatchEvent: function(event) {
var bubbles = event.bubbles,
path = [],
target = event.target = this,
config = eventsMap[event.type],
indentifier;
if (config) {
identifier = ++globalEventsCounter;
try {
this.fireEvent('on' + event.type);
return !event.defaultPrevented;
} catch (e) {
globalEventsMap[identifier] = null;
}
}
propagation: if (bubbles && this.nodeType) {
do {
if (target.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
break propagation;
}
path.push(target);
target = target.parentNode;
} while (target && target.nodeType !== Node.DOCUMENT_NODE);
if (target.nodeType === Node.DOCUMENT_NODE) {
path.push(target);
path.push(target.defaultView);
}
(function() {
for (var index = 0, length = path.length; index < length; index++) {
target = path[index];
var phase = !index ? event.AT_TARGET : event.BUBBLING_PHASE;
fireListeners({
phase: phase,
target: target,
capture: false,
needProxy: !target.nodeType || target.nodeType === Node.DOCUMENT_NODE
}, event);
if (event.eventFlags & event.STOP_PROPAGATION) {
break;
}
}
}());
return !event.defaultPrevented;
}
fireListeners({
phase: event.AT_TARGET,
target: target,
capture: false,
needProxy: !target.nodeType || target.nodeType === Node.DOCUMENT_NODE
}, event);
return !event.defaultPrevented;
}
};
[
'Event',
'CustomEvent',
'UIEvent',
'MouseEvent',
'KeyboardEvent',
'FocusEvent'
].forEach(function(key) {
if (events.hasOwnProperty(key)) {
define(window, key, events[key]);
}
});
document.createEvent = function(inter) {
if (events.hasOwnProperty(inter)) {
return Object.create(events[inter].prototype);
}
};
Sync.each(EventTarget.prototype, function(prop, key) {
[
Element.prototype,
HTMLDocument.prototype,
// XMLHttpRequest.prototype,
window
].forEach(function(object) {
define(object, key, prop);
});
});
}(this, this.document, Sync)); |
// require("./jquery_import");
module.exports = function (config) {
// This is the default webpack config defined in the `../webpack.config.js`
// modify as you need.
};
|
(function() {
'use strict';
var app = angular.module('formlyExample', ['formly', 'formlyBootstrap']);
app.run(function(formlyConfig) {
formlyConfig.setType({
name: 'input',
templateUrl: 'input.html'
});
});
app.controller('MainCtrl', function MainCtrl() {
var vm = this;
vm.model = {};
vm.options= {
formState: {
foo: 'bar'
}
}
vm.fields = [
{
type: 'input',
key: "firstName",
templateOptions: {
label: 'Enter your first name',
required: true
},
expressionProperties: {
'templateOptions.disable': function($viewValue, $modelValue, scope) {
return !scope.model.firstName;
}
}
}
];
});
})(); |
import React, { Component, PropTypes } from 'react';
import { DISPLAY_NAME_PREFIX } from '../../constants';
import findBy from '../../utils/find-by';
import BaseCollectionHelper from '../BaseCollectionHelper';
// This can't be an SFC because it has the potential to return `null`.
class Some extends Component {
render() {
const { collection, predicate, fallback, ...baseProps } = this.props;
const match = findBy({
collection,
predicate,
component: 'Some',
});
if (!match) {
return fallback;
}
return (
<BaseCollectionHelper
collection={collection}
{...baseProps}
/>
);
}
}
Some.displayName = `${DISPLAY_NAME_PREFIX}Some`;
Some.propTypes = {
collection: PropTypes.array,
predicate: PropTypes.oneOfType([
PropTypes.func,
PropTypes.object,
]),
fallback: PropTypes.element,
};
Some.defaultProps = {
// Default to an always-true predicate, so it can be used to check for non-
// empty collections.
predicate: () => true,
fallback: null,
};
export default Some;
|
// 1.引入并使用 vuex
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 2.增加一个 state 常量对象
const state = {
count: 1
}
// 3. 加入两个改变state 的方法
const mutations = {
add(state, n) {
state.count += n;
},
reduce(state) {
state.count --;
}
}
// 4. 封装代码,让外部可以引用
export default new Vuex.Store({
state,
mutations
})
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.8/esri/copyright.txt for details.
//>>built
define({printNotes:"Introdu\u00efu les notes aqu\u00ed",printDisclaimer:"\u00f3_Directions are provided for planning purposes only and are subject to \x3ca href\x3d'http://www.esri.com/legal/licensing-translations' target\x3d'_blank'\x3eEsri's terms of use\x3c/a\x3e. Dynamic road conditions can exist that cause accuracy to differ from your directions and must be taken into account along with signs and legal restrictions. You assume all risk of use_____________________________________________________________________________________________________________\u00e0.",
printoutError:"\u00f3_There seems to have been an error___________\u00e0."}); |
// eslint-disable-next-line no-unused-vars, import/no-unresolved
const lib = require("different_node_module"); |
const _ = require('lodash');
const $ = require('jquery');
class InputReplacementService {
/**
* Input replacement service
* @param {PulsarFormComponent} pulsarFormComponent
*/
constructor (
pulsarFormComponent,
) {
this.pulsarFormComponent = pulsarFormComponent;
}
/**
* Replace an input element with another of the same type (usually a clone)
* @param elements
* @param replacement
* @returns {*|jQuery}
*/
replace (elements, replacement) {
const type = {
'radio': this.replaceRadioInput.bind(this),
'select-one': this.replaceSelect.bind(this),
'select-multiple': this.replaceSelect.bind(this)
};
// If the type is not defined we will use jQuery's replaceWith(...) method
// We are expecting an element list here, as with radio Inputs we'll have
// a chance of receiving multiple inputs with the same name
[].slice.call(elements).forEach(element => {
type[element.type] === undefined ?
$(element).replaceWith(replacement) :
type[element.type](element, replacement);
});
}
/**
* Replace radio inputs
* @param radio
* @param replacement
*/
replaceRadioInput (radio, replacement) {
const originalId = radio.getAttribute('data-pseudo-radio-id');
const replacementId = replacement.getAttribute('data-pseudo-radio-id');
if (originalId === replacementId) {
$(radio).replaceWith(replacement);
}
}
/**
* We don't need to replace the select2s here, we can update the original clone
* we'll replace regular selects with their state-full clones
* @param select
* @param replacement
*/
replaceSelect (select, replacement) {
const $select = $(select);
if ($select.hasClass('js-select2')) {
// Parse our dumped select2 data
const select2Data = JSON.parse(select.getAttribute('data-repeater-select2-data'));
if (select2Data) {
// Set each options's selected value based on the parsed select2 data
[].slice.call(select.children)
.forEach(option => {
const previousState = _.find(select2Data, s2 => s2.id === option.value);
option.selected = previousState ? previousState.selected : false;
});
}
this.pulsarFormComponent.initSelect2($select);
} else {
$select.replaceWith(replacement);
}
}
}
module.exports = InputReplacementService;
|
var iw = 1000;
var ih = 600;
var h = 32;
var r = 18;
var images = {
'wall':{'src':"wall.png", 'w':h, 'h':h},
'floor':{'src':"floor.png", 'w':32, 'h':32},
'dungeon':{'src':"input_dungeon.png"}
};
var image_promise = function(image){
return new Promise(function(resolve, reject) {
var img = document.createElement("img");
img.onload = function(){
canvas = document.createElement('canvas');
if(image.w === undefined){
canvas.width = iw;
canvas.height= ih;
image.h = canvas.height;
image.w = canvas.width;
}else{
canvas.width = image.w;
canvas.height = image.h;
}
var ctx=canvas.getContext("2d");
ctx.drawImage(img,0,0,image.w,image.h);
var imageData = ctx.getImageData(0,0,image.w,image.h);
image.imageData = imageData;
image.ctx = ctx;
image.img = img;
image.data = imageData.data;
resolve(image);
}
img.src = "img/"+image.src;
console.log(img.src);
})
};
var all_images_promise = function(){
var promises = Object.keys(images).map(function(key){
return image_promise(images[key]);
});
return Promise.all(promises);
}
function getIndex(x,y,hi,wi){
if(hi===undefined) hi = ih;
if(wi===undefined) wi = iw;
y = y % hi;
x = x % wi;
return (x+y*wi)*4;
}
function getWallHeight(x,y, read_data){
var wall = -1;
for(dy = 0; dy<=h; dy++){
var i2 = getIndex(x,y+dy);
if(images.dungeon.data[i2] == 0){
wall = dy;
}
}
return wall;
}
function getFloorShadow(x,y,read_data){
for(dx = 0; dx<=h; dx++){
var i = getIndex(x,y);
var i2 = getIndex(x-dx,y);
if(images.dungeon.data[i2] == 0 && read_data[i] != 0){
return 1;
}
}
}
function getShadow(x,y, read_data,wall){
if(wall == -1){
return getFloorShadow(x,y,images.dungeon.data);
}else{
for(dx = 0; dx<=h-wall; dx++){
var i2 = getIndex(x-dx,1+y+wall);
if(images.dungeon.data[i2] == 0){
return 1;
}
}
}
return 0;
}
function getDistToWall(x,y,read_data){
var dirs = [[+1,0],[-1,0],[0,+1],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]];
var result = r * 3;
for(var i = 0; i < 8; i++){
var dir = dirs[i];
for(var j = 0; j < r; j++){
var index = getIndex(x+dir[0]*j, y+dir[1]*j);
if(images.dungeon.data[index] == 0) result = Math.min(result,j);
}
}
if(result === r * 3){
return -1;
}else{
return result
}
}
function getDistToFloor(x,y,read_data){
var dirs = [[+1,0],[-1,0],[0,+1],[0,-1],[1,1],[-1,1],[-1,-1],[1,-1]];
var result = r * 3;
for(var i = 0; i < 8; i++){
var dir = dirs[i];
for(var j = 0; j < r; j++){
var index = getIndex(x+dir[0]*j, y+dir[1]*j);
if(images.dungeon.data[index+1] != 0) result = Math.min(result,j);
}
}
if(result === r * 3){
return -1;
}else{
return result
}
}
var render_dungeon = function(){
document.getElementById("dungeon_canvas").width = iw;
document.getElementById("dungeon_canvas").height = ih;
var canvas = document.createElement("canvas");
canvas.width = iw;
canvas.height = ih;
var ctx = canvas.getContext("2d");
ctx.drawImage(images.dungeon.img,0,0,iw,ih);
var imageData = ctx.getImageData(0,0,iw,ih);
var data = imageData.data;
for(var x = 0; x < iw; x++){
for(var y = 0; y < ih; y++){
var i = getIndex(x,y);i
var wall = getWallHeight(x,y, images.dungeon.data);
if(images.dungeon.data[getIndex(x,y+h)+1]==0){
var edge = getDistToFloor(x,y+h,images.dungeon.data);
var value = (edge/r)*256;
if(edge > r/2) value = 256 * (1 - edge/r);
if(edge >= r) value = 60;
data[i] = value;
data[i+1] =value;
data[i+2] =value;
}else if(wall!=-1){
var wi = getIndex(x,wall,h,h);
data[i] = images.wall.data[wi];
data[i+1] = images.wall.data[wi+1];
data[i+2] = images.wall.data[wi+2];
var wallLeft = getWallHeight(x-1,y, images.dungeon.data);
var wallRight = getWallHeight(x+1,y, images.dungeon.data);
var dWall = wall - wallLeft;
var predWallRight = wall + dWall;
var edge = 1;
var diff = wallRight - predWallRight;
if(diff>4 || diff < -4 || wallLeft == -1 || wallRight == -1){
edge = 0.5;
}
data[i] *= edge;
data[i+1] *=edge;
data[i+2] *=edge;
if(getShadow(x,y,images.dungeon.data,wall)===1){
data[i] *= 0.6;
data[i+1] *= 0.6;
data[i+2] *= 0.6;
}
}else if(images.dungeon.data[i]!=0){
var edge = getDistToWall(x,y,images.dungeon.data);
if(edge==-1) edge = r;
var mult = 1-(r-edge)/(r*1.5);
var fi = getIndex(x,y,images.floor.w,images.floor.h);
data[i] = images.floor.data[fi]*mult;
data[i+1] = images.floor.data[fi]*mult;
data[i+2] = images.floor.data[fi]*mult;
if(getShadow(x,y,images.dungeon.data,wall)===1){
data[i] *= 0.6;
data[i+1] *= 0.6;
data[i+2] *= 0.6;
}
}else{
data[i] = 0;
data[i+1] =0;
data[i+2] =0;
}
}
}
document.getElementById("dungeon_canvas").getContext("2d").putImageData(imageData,0,0);
}
all_images_promise().then(function(arr){
render_dungeon();
});
|
module.exports = require('./lib/bos-middleware');
|
import Team from "./Team";
const createTeam = () => new Team("id", "owner", "name");
const areTeamsEqual = (team1, team2) =>
team1.id === team2.id &&
team1.owner === team2.owner &&
team1.name === team2.name;
test("Given a team when calling Object.isFrozen then returns true", () => {
const team = createTeam();
expect(Object.isFrozen(team)).toBeTruthy();
});
test("Given an empty json when ParseTeams then an empty list is returned", () => {
const data = {};
expect(Team.parseTeams(data)).toEqual([]);
});
test("Given teams as json data when ParseTeams then a list of teams is returned", () => {
const data = {
owner1Id: {
team1Id: {
name: "team1Name"
}
},
owner2Id: {
team2Id: {
name: "team2Name"
}
}
};
const teams = Team.parseTeams(data);
expect(teams).toHaveLength(2);
expect(
areTeamsEqual(teams[0], new Team("team1Id", "owner1Id", "team1Name"))
).toBeTruthy();
expect(
areTeamsEqual(teams[1], new Team("team2Id", "owner2Id", "team2Name"))
).toBeTruthy();
});
test("Given a team and a userId when the owner of the team is not that userId then isOwner returns false", () => {
var team = new Team("teamId", "ownerId", "teamName")
expect(team.isOwner("otherId")).toBeFalsy();
})
test("Given a team and a userId when the owner of the team is that userId then isOwner returns true", () => {
var team = new Team("teamId", "ownerId", "teamName")
expect(team.isOwner("ownerId")).toBeTruthy();
}) |
function Magazine() {
this.deleteMagazine = function(magazine_id) {
var token = $("input[name=csrfmiddlewaretoken]").val();
if ( confirm("Are you sure you want to delete this magazine?") ) {
$.post("/myreadings/magazine/"+magazine_id+"/delete/", {'csrfmiddlewaretoken': token}, function(retData){location.reload(1);});
}
}
this.searchNext = function() {
var page = parseInt($("#page").val());
var totPage = parseInt($("#total-page").val());
if (page < totPage) {
$("#page").val(page+1);
$("#magazine-search").submit();
}
}
this.searchPrev = function() {
var page = parseInt($("#page").val());
if (page > 1) {
$("#page").val(page-1);
$("#magazine-search").submit();
}
}
// Resetting page (page=1) when clicking Search Button
this.search = function() {
$("#page").val(1);
$("#magazine-search").submit();
}
}
var m = new Magazine();
$(document).ready(function(){
$("#magazine-form").validate({
'rules': {
'title': 'required',
'page-count': 'number',
'number': 'number',
'published-date': 'number',
'month': 'number',
},
'messages': {
'title': '',
'page-count': '',
'number': '',
'published-date': '',
'month': '',
}
});
$("#title").change(function(evt){
$("#summary-title").text(evt.target.value);
});
$("#thumbnail").change(function(evt){
$("#summary-thumbnail").attr("src", evt.target.value);
});
}); |
$(function() {
var $wrapper = $('#wrapper');
var popupView = new Diccal.PopupView();
popupView.render($wrapper);
$wrapper.on('click', '.displayWindowId', function(event) {
event.preventDefault();
/* Act on the event */
// Todo: Viewのやることじゃない……
popupView.openCalibration($(this));
});
});
|
/*
* Copyright 2016 Rethink Robotics
*
* Copyright 2016 Chris Smith
*
* 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.
*/
"use strict";
let net = require('net');
let NetworkUtils = require('../utils/network_utils.js');
let SerializationUtils = require('../utils/serialization_utils.js');
let DeserializeStream = SerializationUtils.DeserializeStream;
let Deserialize = SerializationUtils.Deserialize;
let Serialize = SerializationUtils.Serialize;
let TcprosUtils = require('../utils/tcpros_utils.js');
let EventEmitter = require('events');
let log = require('../utils/logger.js');
class Publisher extends EventEmitter {
constructor(options, nodeHandle) {
super();
this._topic = options.topic;
this._type = options.type;
this._latching = !!options.latching;
this._tcpNoDelay = !!options.tcpNoDelay;
if (options.queueSize) {
this._queueSize = options.queueSize;
}
else {
this._queueSize = 1;
}
/**
* throttleMs interacts with queueSize to determine when to send
* messages.
* < 0 : send immediately - no interaction with queue
* >= 0 : place event at end of event queue to publish message
after minimum delay (MS)
*/
if (options.hasOwnProperty('throttleMs')) {
this._throttleMs = options.throttleMs;
}
else {
this._throttleMs = 0;
}
this._pubTimeout = null;
this._pubTime = null;
// OPTIONS STILL NOT HANDLED:
// headers: extra headers to include
// subscriber_listener: callback for new subscribers connect/disconnect
this._lastSentMsg = null;
this._nodeHandle = nodeHandle;
this._log = log.createLogger({name: 'pub' + this.getTopic()});
this._ready = false;
this._subClients = {};
this._port = 0;
this._server = null;
this._messageHandler = options.typeClass;
// messages published before this publisher
// was registered will be held here
this._msgQueue = [];
this._setupTcp()
.then(() => {
this._register();
});
};
getTopic() {
return this._topic;
}
getType() {
return this._type;
}
getLatching() {
return this._latching;
}
getNumSubscribers() {
return Object.keys(this._subClients).length;
}
disconnect() {
Object.keys(this._subClients).forEach((clientId) => {
const client = this._subClients[clientId];
client.end();
client.destroy();
});
clearTimeout(this._pubTimeout);
this._pubClients = {};
}
/**
* Schedule the msg for publishing - or publish immediately if we're
* supposed to
* @param msg {object} object type matching this._type
* @param [throttleMs] {number} optional override for publisher setting
*/
publish(msg, throttleMs) {
if (typeof throttleMs !== 'number') {
throttleMs = this._throttleMs;
}
if (throttleMs < 0) {
// short circuit JS event queue, publish synchronously
this._msgQueue.push(msg);
this._publish();
}
else {
// msg will be queued - msgs in queue will be sent when timer expires
this._msgQueue.push(msg);
// remove old messages from queue if necesary
let queueSize = this._queueSize;
if (queueSize > 0) {
if (this._msgQueue.length > queueSize) {
this._msgQueue.shift();
}
}
// if there's not currently a timer running, set one.
// msgs in queue will be published when it times out
if (this._pubTimeout === null) {
let now = Date.now();
if (this._pubTime !== null) {
// check how long to throttle for based on the last time we
// published
if (now - this._pubTime > throttleMs) {
throttleMs = 0;
}
else {
throttleMs -= now - this._pubTime;
}
}
else {
// never published, so publish 'immediately'
throttleMs = 0;
}
// any other messages we try to publish will be throttled
this._pubTimeout = setTimeout(() => {
this._publish();
this._pubTimeout = null;
}, throttleMs);
}
}
}
/**
* Pulls all msgs off queue, serializes, and publishes them
*/
_publish() {
this._pubTime = Date.now();
this._msgQueue.forEach((msg) => {
try {
let bufferInfo = {buffer: [], length: 0};
// serialize pushes buffers onto buffInfo.buffer in order
// concat them, and preprend the byte length to the message
// before sending
// console.log("_publish", this._messageHandler, msg);
bufferInfo = this._messageHandler.serialize(msg, bufferInfo);
// bufferInfo = msg.serialize();
// console.log("_publish", bufferInfo);
// prepend byte length to message
let serialized = Serialize(
Buffer.concat(bufferInfo.buffer, bufferInfo.length));
Object.keys(this._subClients).forEach((client) => {
this._subClients[client].write(serialized);
});
// if this publisher is supposed to latch,
// save the last message. Any subscribers that connect
// before another call to publish() will receive this message
if (this._latching) {
this._lastSentMsg = serialized;
}
}
catch (err) {
this._log.warn('Error when publishing message ', err.stack);
}
});
// clear out the msg queue
this._msgQueue = [];
}
_setupTcp() {
// recursively tries to setup server on open port
// calls callback when setup is done
let _createServer = (callback) => {
NetworkUtils.getFreePort()
.then((port) => {
let server = net.createServer((subscriber) => {
let subName = subscriber.remoteAddress + ":"
+ subscriber.remotePort;
subscriber.name = subName;
this._log.debug('Publisher ' + this.getTopic()
+ ' got connection from ' + subName);
// subscriber will send us tcpros handshake before we can
// start publishing to it.
subscriber.$handshake =
this._handleHandshake.bind(this, subscriber);
// handshake will be TCPROS encoded, so use a DeserializeStream to
// handle any chunking
let deserializeStream = new DeserializeStream();
subscriber.pipe(deserializeStream);
deserializeStream.on('message', subscriber.$handshake);
// if this publisher had the tcpNoDelay option set
// disable the nagle algorithm
if (this._tcpNoDelay) {
subscriber.setNoDelay(true);
}
subscriber.on('close', () => {
this._log.info('Publisher ' + this.getTopic() + ' client '
+ subscriber.name + ' disconnected!');
delete this._subClients[subscriber.name];
});
subscriber.on('end', () => {
this._log.info('Sub %s sent END', subscriber.name);
});
subscriber.on('error', () => {
this._log.info('Sub %s had error', subscriber.name);
});
}).listen(port);
// it's possible the port was taken before we could use it
server.on('error', (err) => {
if (err.code === 'EADDRINUSE') {
_createServer(callback);
}
});
// the port was available
server.on('listening', () => {
this._log.debug('Listening on port ' + port);
this._port = port;
this._server = server;
callback(port);
});
});
};
return new Promise((resolve, reject) => {
_createServer(resolve);
});
}
_handleHandshake(subscriber, data) {
if (!subscriber.$initialized) {
let header = TcprosUtils.parseSubHeader(data);
let valid = TcprosUtils.validateSubHeader(
header, this.getTopic(), this.getType(),
this._messageHandler.md5sum());
if (valid !== null) {
this._log.error('Unable to validate connection header '
+ JSON.stringify(header));
subscriber.write(Serialize(valid));
return;
}
this._log.debug('Pub ' + this.getTopic()
+ ' got connection header ' + JSON.stringify(header));
let respHeader =
TcprosUtils.createPubHeader(
this._nodeHandle.getNodeName(),
this._messageHandler.md5sum(),
this.getType(),
this.getLatching());
subscriber.write(respHeader);
if (this._lastSentMsg !== null) {
this._log.debug('Sending latched msg to new subscriber');
subscriber.write(this._lastSentMsg);
}
// if handshake good, add to list, we'll start publishing to it
this._subClients[subscriber.name] = subscriber;
this.emit('connection', subscriber.name);
}
else {
this._log.error(
'Got message from subscriber after handshake - what gives!!');
}
}
_register() {
this._nodeHandle.registerPublisher(this._topic, this._type)
.then((resp) => {
let code = resp[0];
let msg = resp[1];
let subs = resp[2];
if (code === 1) {
// registration worked
this._ready = true;
this.emit('registered');
}
})
.catch((err, resp) => {
this._log.error('reg pub err ' + err + ' resp: '
+ JSON.stringify(resp));
})
}
getSubPort() {
return this._port;
}
};
module.exports = Publisher;
|
'use strict';
angular.module('demo', ['ui.router.grant'])
.controller('DemoController', ['$scope', 'faker', function($scope, faker) {
var scope = this;
scope.roles = {
user: false,
admin: false
};
scope.toggleRole = function(role) {
scope.roles[role] = !scope.roles[role];
faker[role](scope.roles[role]);
};
}])
.factory('faker', function() {
var isUser = false,
isAdmin = false;
return {
getGuest: function() {
},
user: function(flag) {
if (!angular.isUndefined(flag)) { isUser = flag; }
return isUser;
},
admin: function(flag) {
if (!angular.isUndefined(flag)) { isAdmin = flag; }
return isAdmin;
}
};
})
.config(['$stateProvider', '$urlMatcherFactoryProvider', function($stateProvider, $urlMatcherFactoryProvider) {
$urlMatcherFactoryProvider.strictMode(false);
$stateProvider
.state('home', {
url: '',
templateUrl: 'home.html'
})
.state('denied', {
url: '/denied',
templateUrl: 'denied.html'
})
.state('guest-only', {
url: '/guests',
templateUrl: 'only-guest.html'
})
.state('user-only', {
url: '/users/:userId',
templateUrl: 'only-user.html',
resolve: {
user: function(grant) {
return grant.only({test: 'user', state: 'denied'});
}
}
})
.state('admin-only', {
url: '/admins',
templateUrl: 'only-admin.html',
resolve: {
admin: function(grant) {
return grant.only({test: 'admin', state: 'denied'});
}
}
})
.state('except-guest', {
url: '/no-guests',
templateUrl: 'except-guest.html',
resolve: {
grant: function(grant) {
return grant.except({test: 'guest', state: 'denied'});
}
}
})
.state('except-user', {
url: '/no-users',
templateUrl: 'except-user.html',
resolve: {
grant: function(grant) {
return grant.except({test: 'user', state: 'denied'});
}
}
})
.state('except-admin', {
url: '/no-admins',
templateUrl: 'except-admin.html',
resolve: {
grant: function(grant) {
return grant.except({test: 'admin', state: 'denied'});
}
}
})
.state('combined', {
url: '/combined',
templateUrl: 'combined.html',
resolve: {
grant: function(grant) {
return grant.only([
{test: 'user', state: 'denied'},
{test: 'admin', state: 'denied'},
]);
}
}
})
.state('parent', {
abstract: true,
template: '<div ui-view></div>',
resolve: {
user: function(grant) {
return grant.only({test: 'user', state: 'denied'});
}
}
})
.state('parent.child1', {
url: '/child1',
templateUrl: 'nested.html'
})
.state('parent.child2', {
url: '/child2',
templateUrl: 'nested.html'
})
.state('parent.child3', {
url: '/child3',
templateUrl: 'nested.html'
})
}])
.run(['grant', 'faker', '$q', function(grant, faker, $q) {
grant.addTest('guest', function() {
return (!faker.admin() && !faker.user());
});
grant.addTest('user', function() {
return faker.user();
});
grant.addTest('admin', function() {
return faker.admin();
});
}]);
|
import {
timeAgo
} from 'emberjs-feed-wrangler/helpers/time-ago';
module('TimeAgoHelper');
// Replace this with your real tests.
test('it works', function() {
var result = timeAgo(42);
ok(result);
});
|
var Marionette = require('backbone.marionette');
var itemView = Marionette.ItemView.extend({
template: require('../../templates/video_small.hbs'),
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
events: {
'click': 'showDetails'
},
showDetails: function() {
window.App.core.vent.trigger('app:log', 'Videos View: showDetails hit.');
window.App.controller.details(this.model.id);
}
});
module.exports = CollectionView = Marionette.CollectionView.extend({
initialize: function() {
this.listenTo(this.collection, 'change', this.render);
},
itemView: itemView
});
|
'use strict';
/* Controllers */
angular.module('myApp.controllers', [])
.controller('LandingPageController', [function() {
}])
.controller('WaitlistController', ['$scope', 'partyService', 'textMessageService', 'authService', function($scope, partyService, textMessageService, authService) {
// Bind user's parties to $scope.parties
authService.getCurrentUser().then(function(user) {
if (user) {
$scope.parties = partyService.getPartiesByUserId(user.id);
}
});
// Object to store data from the waitlist form
$scope.newParty = {name: '', phone: '', size: '', done: false, notified: 'No'};
// Function to save a new party to the waitlist
$scope.saveParty = function() {
partyService.saveParty($scope.newParty, $scope.currentUser.id);
$scope.newParty = {name: '', phone: '', size: '', done: false, notified: 'No'};
};
// Function to send text message to a party
$scope.sendTextMessage = function(party) {
textMessageService.sendTextMessage(party, $scope.currentUser.id);
};
}])
.controller('AuthController', ['$scope', 'authService', function($scope, authService) {
// Object bound to inputs on register and login pages
$scope.user = {email: '', password: ''};
// Method to register a new user using the authService
$scope.register = function() {
authService.register($scope.user);
};
// Method to log in a user using the authService
$scope.login = function() {
authService.login($scope.user);
};
// Method to log out a user using the authService
$scope.logout = function() {
authService.logout();
};
}]);
|
$(function(){
var timer;
$('#start').click(function() {
$("#saveDialog").fadeOut();
timer = setInterval( updateTime, 100);
});
$('#stop').click(function(){
clearInterval(timer);
saveDialog();
updateDisplay();
});
});
var h = 0;
var m = 15;
var s = 0;
var ms = 0
function updateTime()
{
++ms;
if( ms == 10 )
{
ms = 0;
++s;
}
if( s == 60 )
{
s = 0;
++m;
}
if( m == 60 )
{
m = 0;
++h;
}
updateDisplay();
}
function updateDisplay()
{
$("#hours").html(h);
$("#minutes").html(m);
$("#seconds").html(s);
$("#msecs").html(ms);
}
function clearTime(){ h = m = s = ms = 0; }
function saveDialog()
{
$("#saveDialog").fadeIn();
$('input[name="hours"]').val(getHours());
}
function getHours()
{
return h + (Math.ceil(m/60 * 4) / 4).toFixed(2);
} |
import ArrayLimit from './array-limit';
export default ArrayLimit;
|
const {app} = require('electron')
const roles = {
about: {
get label () {
return process.platform === 'linux' ? 'About' : `About ${app.getName()}`
}
},
close: {
label: process.platform === 'darwin' ? 'Close Window' : 'Close',
accelerator: 'CommandOrControl+W',
windowMethod: 'close'
},
copy: {
label: 'Copy',
accelerator: 'CommandOrControl+C',
webContentsMethod: 'copy'
},
cut: {
label: 'Cut',
accelerator: 'CommandOrControl+X',
webContentsMethod: 'cut'
},
delete: {
label: 'Delete',
webContentsMethod: 'delete'
},
front: {
label: 'Bring All to Front'
},
help: {
label: 'Help'
},
hide: {
get label () {
return `Hide ${app.getName()}`
},
accelerator: 'Command+H'
},
hideothers: {
label: 'Hide Others',
accelerator: 'Command+Alt+H'
},
minimize: {
label: 'Minimize',
accelerator: 'CommandOrControl+M',
windowMethod: 'minimize'
},
paste: {
label: 'Paste',
accelerator: 'CommandOrControl+V',
webContentsMethod: 'paste'
},
pasteandmatchstyle: {
label: 'Paste and Match Style',
accelerator: 'Shift+CommandOrControl+V',
webContentsMethod: 'pasteAndMatchStyle'
},
quit: {
get label () {
switch (process.platform) {
case 'darwin': return `Quit ${app.getName()}`
case 'win32': return 'Exit'
default: return 'Quit'
}
},
accelerator: process.platform === 'win32' ? null : 'CommandOrControl+Q',
appMethod: 'quit'
},
redo: {
label: 'Redo',
accelerator: 'Shift+CommandOrControl+Z',
webContentsMethod: 'redo'
},
selectall: {
label: 'Select All',
accelerator: 'CommandOrControl+A',
webContentsMethod: 'selectAll'
},
services: {
label: 'Services'
},
togglefullscreen: {
label: 'Toggle Full Screen',
accelerator: process.platform === 'darwin' ? 'Control+Command+F' : 'F11',
windowMethod: function (window) {
window.setFullScreen(!window.isFullScreen())
}
},
undo: {
label: 'Undo',
accelerator: 'CommandOrControl+Z',
webContentsMethod: 'undo'
},
unhide: {
label: 'Show All'
},
window: {
label: 'Window'
},
zoom: {
label: 'Zoom'
}
}
exports.getDefaultLabel = (role) => {
if (roles.hasOwnProperty(role)) {
return roles[role].label
} else {
return ''
}
}
exports.getDefaultAccelerator = (role) => {
if (roles.hasOwnProperty(role)) return roles[role].accelerator
}
exports.execute = (role, focusedWindow, focusedWebContents) => {
if (!roles.hasOwnProperty(role)) return false
if (process.platform === 'darwin') return false
const {appMethod, webContentsMethod, windowMethod} = roles[role]
if (appMethod) {
app[appMethod]()
return true
}
if (windowMethod && focusedWindow != null) {
if (typeof windowMethod === 'function') {
windowMethod(focusedWindow)
} else {
focusedWindow[windowMethod]()
}
return true
}
if (webContentsMethod && focusedWebContents != null) {
focusedWebContents[webContentsMethod]()
return true
}
return false
}
|
/* */
'use strict';
Object.defineProperty(exports, "__esModule", {value: true});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin');
var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin);
var _svgIcon = require('../../svg-icon');
var _svgIcon2 = _interopRequireDefault(_svgIcon);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var EditorPublish = _react2.default.createClass({
displayName: 'EditorPublish',
mixins: [_reactAddonsPureRenderMixin2.default],
render: function render() {
return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M5 4v2h14V4H5zm0 10h4v6h6v-6h4l-7-7-7 7z'}));
}
});
exports.default = EditorPublish;
module.exports = exports['default'];
|
import React from 'react';
import classnames from 'classnames';
import styles from './SettingsPopup.pcss';
import {Modal} from 'react-overlays';
import {Button} from './Button';
export class SettingsPopup extends React.Component {
static propTypes = {
availableFrameworks: React.PropTypes.array.isRequired,
currentFrameworkId: React.PropTypes.string,
showSourceOutputHeaderFooter: React.PropTypes.bool,
useChainedAttrs: React.PropTypes.bool,
attrNameForCapture: React.PropTypes.string,
show: React.PropTypes.bool,
onClose: React.PropTypes.func,
onSave: React.PropTypes.func
};
constructor(props, context) {
super(props, context);
this.state = {
currentFrameworkId: this.props.currentFrameworkId,
showSourceOutputHeaderFooter: this.props.showSourceOutputHeaderFooter,
useChainedAttrs: this.props.useChainedAttrs,
attrNameForCapture: this.props.attrNameForCapture,
errors: {}
};
}
componentWillMount() {
this.setState({
currentFrameworkId: this.props.currentFrameworkId,
showSourceOutputHeaderFooter: this.props.showSourceOutputHeaderFooter,
useChainedAttrs: this.props.useChainedAttrs,
attrNameForCapture: this.props.attrNameForCapture
});
}
onChangeFramework(e) {
this.setState({currentFrameworkId: e.target.value});
};
onChangeHeaderFooterCheckbox(e) {
this.setState({showSourceOutputHeaderFooter: e.target.checked});
}
onChangeUseChainedAttrs(e) {
this.setState({useChainedAttrs: e.target.checked});
}
onChangeAttrNameForCapture(e) {
this.setState({attrNameForCapture: e.target.value});
}
onSave(e) {
e.preventDefault();
let data = {
currentFrameworkId: this.state.currentFrameworkId,
showSourceOutputHeaderFooter: this.state.showSourceOutputHeaderFooter,
useChainedAttrs: this.state.useChainedAttrs,
attrNameForCapture: this.state.attrNameForCapture.trim()
};
let validationResult = this.validateFormData(data);
this.setState({errors: validationResult});
if (Object.keys(validationResult).length === 0 && this.props.onSave) {
this.props.onSave(data);
}
}
onCancelButtonClick(e) {
e.preventDefault();
if (this.props.onClose) {
this.props.onClose();
}
}
validateFormData(formData) {
let result = {};
if (!/^[-_:.a-z0-9]+$/i.test(formData.attrNameForCapture)) {
result.attrNameForCapture = 'invalid attribute name';
}
return result;
}
renderFrameworksList() {
let list = this.props.availableFrameworks.map((item, index) => {
return (
<p key={index}>
<input
name="framework"
type="radio"
id={`frameworkItem${index}`}
value={item.id}
className="with-gap"
checked={this.state.currentFrameworkId === item.id}
onChange={::this.onChangeFramework}
/>
<label htmlFor={`frameworkItem${index}`}>{item.title}</label>
</p>
);
});
return (
<div>
{list}
</div>
);
}
renderAttrNameField() {
return (
<div className="input-field col s12">
<input placeholder="Attribute name for capture"
id="attrNameForCapture"
type="text"
className={classnames(
{
validate: true,
invalid: !!this.state.errors.attrNameForCapture
}
)}
value={this.state.attrNameForCapture}
onChange={::this.onChangeAttrNameForCapture}
/>
<label htmlFor="attrNameForCapture" className="active"
data-error={this.state.errors.attrNameForCapture}>
Attribute name for capture
</label>
</div>
);
}
renderChainedAttrsField() {
return (
<div>
<input type="checkbox"
id="useChainedAttrs"
onChange={::this.onChangeUseChainedAttrs}
checked={this.state.useChainedAttrs} />
<label htmlFor="useChainedAttrs">Chaining attributes</label>
</div>
);
}
renderHeaderFooterField() {
return (
<div>
<input type="checkbox"
id="showSourceOutputHeaderFooter"
onChange={::this.onChangeHeaderFooterCheckbox}
checked={this.state.showSourceOutputHeaderFooter} />
<label htmlFor="showSourceOutputHeaderFooter">Show header/footer code blocks</label>
</div>
);
}
render() {
return (
<Modal
aria-labelledby='modal-label'
className={styles.modal}
backdropClassName={styles.backdrop}
show={this.props.show}
onHide={this.props.onClose}
>
<div className={classnames(styles['modal-body'], 'z-depth-2')}>
<h5 id='modal-label'>Settings</h5>
<form onSubmit={::this.onSave}>
<div className={styles['section']}>
<p>Choose the preferred syntax</p>
{this.renderFrameworksList()}
</div>
<div className={styles['section']}>
<p>Visualisation</p>
<p>
{this.renderHeaderFooterField()}
</p>
</div>
<div className={styles['section']}>
<p>Web page capture / test output</p>
<p className="row">
{this.renderAttrNameField()}
</p>
<p>
{this.renderChainedAttrsField()}
</p>
</div>
<div className={classnames(styles['modal-footer'], 'right-align')}>
<Button flat onClick={::this.onCancelButtonClick}>Cancel</Button>
<Button type='submit' flat primary>Save</Button>
</div>
</form>
</div>
</Modal>
);
}
}
|
// Download the Node helper library from twilio.com/docs/node/install
// These consts are your accountSid and authToken from https://www.twilio.com/console
// To set up environmental variables, see http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client
.queues('QU32a3c49700934481addd5ce1659f04d2')
.update({ maxSize: '123' })
.then(queue => console.log(queue.averageWaitTime));
|
const width = 600;
const height = 600;
const radius = 5;
const nodeCount = 1000;
const anim = 50;
var draw = SVG('svgCanvas').size(width, height);
var nodeList = [];
var slider1 = document.getElementById("range1");
var slider2 = document.getElementById("range2");
var slider3 = document.getElementById("range3");
var slider4 = document.getElementById("range4");
var slider5 = document.getElementById("range5");
var v1 = slider1.value;
var v2 = slider2.value;
var v3 = slider3.value;
var v4 = slider4.value;
var v5 = slider5.value;
initNodeList();
slider1.oninput = function() {
v1 = this.value;
updateNodeList();
}
slider2.oninput = function() {
v2 = this.value;
updateNodeList();
}
slider3.oninput = function() {
v3 = this.value;
updateNodeList();
}
slider4.oninput = function() {
v4 = this.value;
updateNodeList();
}
slider5.oninput = function() {
v5 = this.value;
updateNodeList();
}
function initNodeList() {
for (var i = 0; i < nodeCount; i++) {
let agent = draw.circle(radius*2, radius*2);
agent.fill('Black');
nodeList.push(agent);
}
updateNodeList();
}
function updateNodeList() {
for (var i = 0; i < nodeCount; i++) {
let agent = nodeList[i];
let angle = v1 * i * Math.PI / 360;
let dist = i * 1;
let x = (width / 2) + (Math.cos(angle) * dist);
let y = (height / 2) + (Math.sin(angle) * dist);
let blockStrength = v3/100;
//Distance from center
let dx = x - width/2;
let dy = y - height/2;
let ax = Math.abs(dx);
let ay = Math.abs(dy);
//Sign of distance from center
let sx = 1;
let sy = 1;
if (ax != 0) sx = dx/ax;
if (ay != 0) sy = dy/ay;
//Distance from the modulo point
mx = ax % v2;
my = ay % v2;
//Offset distance from modulo point
ox = mx - (v2/2);
oy = my - (v2/2);
//Offset multiplied by blocking strength
bx = -ox * blockStrength * sx;
by = -oy * blockStrength * sy;
x += bx;
y += by;
agent.cx(x);
agent.cy(y);
let h = Math.floor(v4 * i * 360 / 500);
agent.fill('hsl('+h+',100%,50%)');
let rad = 8 + 8 * Math.sin(v5 * i * Math.PI/ 500);
agent.radius(rad);
}
}
|
'use strict';
var jwt = require('jsonwebtoken');
var DEFAULT_ALGORITHM = 'HS256';
var VALID_ALGORITHMS = ['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512'];
var SECRET_KEY_MIN_LENGTH = 6;
// private fields
var _secretKey;
var _algorithm;
var _inited;
/*
[private static function]
Checks the given algorithm
params:
alg: [string] the givent algorithm
returns:
[boolean]: if algorithm is valid return true.
*/
var isValidAlgorithm = function(alg) {
if (typeof alg !== 'string')
return false;
if (VALID_ALGORITHMS.indexOf(alg.toUpperCase()) === -1)
return false;
return true;
};
/*
[private static function]
Checks the given secretKey
params:
secretKey: [string] the givent secret
returns:
[boolean]: if secretKey is valid return true.
*/
var isValidSecretKey = function(secretKey) {
if (!secretKey || typeof secretKey !== 'string')
return false;
if (secretKey.length < SECRET_KEY_MIN_LENGTH)
return false;
return true;
};
/*
[private static function]
Checks that module has been initialized or not.
returns:
[boolean]: if module is initialized true.
*/
var isInited = function() {
return _inited || false;
}
/*
[private static function]
create error function
params:
name: [string] name of the error
message: [string] message of the error
returns:
[Error]
*/
var createError = function(name, message) {
var error = new Error(name);
error.message = message;
return error;
};
// initial the module with the given parameters.
var _init = function(secretKey, algorithm) {
// set the attributes
_secretKey = secretKey;
_algorithm = algorithm || DEFAULT_ALGORITHM;
// check the valid attributes
if (!isValidSecretKey(_secretKey))
throw createError(TokenGenerator.ERRORS.SECRET_KEY, 'Given secret key is not valid.');
if (!isValidAlgorithm(_algorithm))
throw createError(TokenGenerator.ERRORS.ALGORITHM, 'Given algorithm is not valid.');
_inited = true;
}
/*
[public method]
Generate new random token acording to the secretKey.
returns:
[string]: new generated token.
*/
var _generateToken = function() {
if (!isInited())
throw createError(_ERRORS.NOT_INITED);
var jwtOptions = {
algorithm: _algorithm
};
var randomNumber = Date.now() + '.' + Date.now() + '.' + Math.random() + '-.-' + Math.random();
var nextRandomNumber = Date.now() + '.' + Date.now() + '.' + Math.random() + '-.-' + Math.random();
var object = {
rn: randomNumber,
rn2: nextRandomNumber
};
var jwtToken = jwt.sign(object, _secretKey, jwtOptions);
return jwtToken;
}
/*
[public method]
verify the given token acording to the secretKey.
params:
token: [string] the token to verify.
returns:
[boolean]
true: token is verified.
false: token is not verified.
*/
var _isValidToken = function(token) {
if (!isInited())
throw createError(_ERRORS.NOT_INITED)
try {
var jwtOptions = {
algorithm: _algorithm
};
var decoded = jwt.verify(token, _secretKey);
if (decoded.rn && decoded.rn2)
return true;
} catch (error) {}
return false;
}
/*
*/
var _ERRORS = {
ALGORITHM: 'BAD_ALGORITHM',
SECRET_KEY: 'BAD_SECRET_KEY',
NOT_INITED: 'NOT_INITED'
};
/*
[public singleton class]
TokenGenerator to create random token and verify the given token.
*/
var TokenGenerator = {
init: _init,
generateToken: _generateToken,
isValidToken: _isValidToken,
ERRORS: _ERRORS
}
exports = module.exports = TokenGenerator; |
var fullMonth = require('./day');
var month = require('./month');
var zeller = require('./zellers');
var _ = require('lodash');
formatMonths = function(year) {
var monthArr = [];
var monthTitles;
var chunkedArr = [];
var yearArr = [];
var dayArr = []
var numWeekArr = [];
//for each month in year. Call the formatDays function.
for(var i = 1; i <= 12; i++) {
var dateInput = [i, year];
var zelDay = Zellers(dateInput)
var numWeeks = Math.ceil((parseInt(month[i].days) + parseInt(zelDay)) / 7)
var remainder = (parseInt(numWeeks) * 7) - (parseInt(month[i].days) + parseInt(zelDay))
numWeekArr.push(remainder)
//have to change the heading for each calendar
var monthName = month[i].name + " " + year;
var spacing = (20 - monthName.length) / 2; //number of spaces needed on each side
var spacing2 = (20 - month[i].name.length) / 2;
var sliceNum = spacing + monthName.length;
//Changing the number of spaces needed in header into actual spaces.
var spaces = '';
for(var s = 1; s <= spacing2; s++) {
spaces += ' ';
}
//get each month for year. Loop through and get each start day.
var calendar = formatDays(dateInput)
//slice off the first row and add new month
var newCalendar = calendar.slice(sliceNum)
monthTitles = spaces + month[i].name + spaces;
newCalendar = monthTitles + newCalendar;
newCalendar = newCalendar.split('\n');
monthArr.push(newCalendar) //an array of all the month lines
} //end of for loop
for(var i = 0; i <= monthArr.length; i++) { //dividing month lines
chunkedArr.push(_.chunk(monthArr[i], 1))
}
var lineArr = []
var chunk;
var newArr = [];
var newChunkArr = [];
for(var c = 0; c < 13; c++) {
for(var a = 0; a <= 8; a++) {
chunk = chunkedArr[c][a];
if(chunk === undefined) { //trying to ignore the undefined chunk
} else{
chunk = chunk.join('');
while (chunk.length < 20) {
lineArr = chunk.split('');
lineArr.push(' ');
chunk = lineArr.join('');
}
newArr.push(chunk)
}
} //now I have a string for every line.
}
newChunkArr = _.chunk(newArr, 8)
//Creating the column format for months
var title = ' ' + year + '\n' + '\n'
var rows = [];
rows.push(title)
for(var i = 0; i <=7; i++ ) {
rows.push([newChunkArr[0][i] + ' ' + newChunkArr[1][i] + ' ' + _.trimRight(newChunkArr[2][i]) + '\n'].join(''));
}
for(var i = 0; i <=7; i++ ) {
rows.push([newChunkArr[3][i] + ' ' + newChunkArr[4][i] + ' ' + _.trimRight(newChunkArr[5][i]) + '\n'].join(''));
}
for(var i = 0; i <=7; i++ ) {
rows.push([newChunkArr[6][i] + ' ' + newChunkArr[7][i] + ' ' + _.trimRight(newChunkArr[8][i]) + '\n'].join(''));
}
for(var i = 0; i <=7; i++ ) {
rows.push([newChunkArr[9][i] + ' ' + newChunkArr[10][i] + ' ' + _.trimRight(newChunkArr[11][i]) + '\n'].join(''));
}
rows = rows.join('')
rows = rows.substr(0, rows.length-1);
console.log(rows)
return rows
}
module.exports = formatMonths;
|
const path = require('path');
function defaultIndexTemplate(filePaths) {
const exportEntries = filePaths.map((filePath) => {
const basename = path.basename(filePath, path.extname(filePath));
const exportName = /^\d/.test(basename) ? `Svg${basename}` : basename;
return `export { default as ${exportName} } from './${basename}'`;
});
return exportEntries.join('\n');
}
module.exports = defaultIndexTemplate;
|
const hexFont = [
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80, // F
];
export default hexFont; |
'use strict';
const manualApiClient = require('../app/services/manualApiClient.server.services');
const config = require('../config/config');
const should = require('should');
const nock = require('nock');
describe('The manualApiClient service', () => {
let manualApiEndpointMock, responseBodies, email;
beforeEach((done) => {
email = {
_id: '55f93c46ac0b4b0300619e4d',
subject: 'do not edit'
};
responseBodies = {
successGet: email,
successPatch: email,
successOutstanding: [email]
};
manualApiEndpointMock = nock(config.manualApiEndpoint);
manualApiEndpointMock
.defaultReplyHeaders({
'Content-Type':'application/json'
});
done();
});
afterEach((done) => {
nock.cleanAll();
done();
});
describe('The getEmailsToSend method', () => {
it('should fulfill a promise providing a list of emails when the underlying request succeeds', (done) => {
manualApiEndpointMock
.get('/eme-emails/?toSend')
.reply(200, responseBodies.successGet);
let result = manualApiClient.getEmailsToSend();
result.then((json) => {
json.should.have.a.property('_id', responseBodies.successGet._id);
json.should.have.a.property('subject', responseBodies.successGet.subject);
done();
}).catch(done);
});
});
describe('markEmailStatus', () => {
it('should fulfill a promise providing the patched email when the underlying request succeeds', (done) => {
manualApiEndpointMock
.patch('/eme-emails/' + email._id)
.reply(200, responseBodies.successPatch);
let result = manualApiClient.markEmailStatus(email._id, {sendJobId: '123', pending: true});
result.then((json) => {
json.should.have.a.property('_id', responseBodies.successGet._id);
json.should.have.a.property('subject', responseBodies.successGet.subject);
done();
}).catch(done);
});
});
describe('The getEmail method', () => {
it('should fulfill a promise providing a list of emails when the underlying request succeeds', (done) => {
manualApiEndpointMock
.get('/eme-emails/1234')
.reply(200, responseBodies.successGet);
let result = manualApiClient.getEmail(1234);
result.then((json) => {
json.should.have.a.property('_id', responseBodies.successGet._id);
json.should.have.a.property('subject', responseBodies.successGet.subject);
done();
}).catch(done);
});
});
describe('The getOutstandingEmails method', () => {
it('should fulfill a promise providing a list of outstanding emails when the underlying request succeeds', (done) => {
manualApiEndpointMock
.get('/eme-emails?outstanding')
.reply(200, responseBodies.successOutstanding);
let result = manualApiClient.getOutstandingEmails();
result.then((json) => {
json.should.be.an.Array()
json.should.have.length(1);
done();
}).catch(done);
});
});
});
|
#! /usr/bin/env node
require('colors');
var fs = require('fs'),
license = require('./license.js'),
_ = require('lodash');
var configPath = process.cwd() + '/license.json';
var config = {};
if (fs.existsSync(configPath)) {
config = require(configPath);
} else {
console.log('No license.json found'.yellow);
}
license(config, function (invalids) {
if (invalids.length) {
_.each(invalids, function (moduleData) {
console.log(moduleData.id, moduleData.summary().join(', ').red);
});
} else {
console.log('All licenses are compatible'.green);
}
});
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { isAccessCodeGenerated, isAccessCodePending } from '../../../../../app/shared/reservation-access-code/helpers';
import TooltipOverlay from '../../../../common/tooltip/TooltipOverlay';
import iconClock from '../../../../../app/assets/icons/clock-o.svg';
import PopoverOverlay from '../../../../common/popover/PopoverOverlay';
class ManageReservationsPincode extends Component {
renderPincodeField() {
const { reservation } = this.props;
if (isAccessCodeGenerated(reservation)) {
return (
<TooltipOverlay
content={(
<p>{reservation.accessCode}</p>
)}
>
<span>****</span>
</TooltipOverlay>
);
}
if (isAccessCodePending(reservation, reservation.resource)) {
return (
<PopoverOverlay
content={<FormattedMessage id="ReservationAccessCode.pending" />}
>
<img alt="reservationAccessCodePending" src={iconClock} />
</PopoverOverlay>
);
}
return '';
}
render() {
return (
<div className="app-ManageReservationPincode">
{this.renderPincodeField()}
</div>
);
}
}
ManageReservationsPincode.propTypes = {
reservation: PropTypes.object.isRequired,
};
export default ManageReservationsPincode;
|
/**
* @module ember-flexberry
*/
import Ember from 'ember';
export default Ember.Component.extend({
module: 'message',
classNameBindings: ['cssClass'],
visible: true,
floating: false,
compact: false,
attached: false,
closeable: false,
type: null,
color: null,
size: null,
icon: null,
title: null,
message: null,
cssClass: Ember.computed('size', 'type', 'color', 'floating', 'compact', 'attached', 'visible', 'icon', function() {
var isNonEmptyString = function(str) {
return Ember.typeOf(str) === 'string' && str.trim().length > 0;
};
var result = 'ui ';
// Message size ('small', 'large', 'huge', 'massive', or some custom size class).
var sizeClass = this.get('size');
var hasSize = isNonEmptyString(sizeClass);
result += hasSize ? sizeClass + ' ' : '';
// Message type ('info', 'positive', 'success', 'negative', 'error', or some custom type class).
var typeClass = this.get('type');
var hasType = isNonEmptyString(typeClass);
result += hasType ? typeClass + ' ' : '';
// Message color ('red', 'orange', 'yellow', 'olive', 'green', 'teal', 'blue', 'violet', 'purple',
// 'pink', 'brown', 'black', or some custom color class).
var colorClass = this.get('color');
var hasColor = isNonEmptyString(colorClass);
result += hasColor ? colorClass + ' ' : '';
// Message block variations.
// Note! Variations 'ui floating message', 'ui compact message', 'ui attached message' doesn't work
// with 'icon', 'visible' and 'hidden' subclasses.
// For example 'ui compact icon message' will be with icon, but not compact.
var isFloating = this.get('floating');
result += isFloating ? 'floating ' : '';
var isCompact = this.get('compact');
result += isCompact ? 'compact ' : '';
var isAttached = this.get('attached');
result += isAttached ? 'attached ' : '';
// Message block visibility.
// Note! It is better to use empty string '' instead of 'visible' subclass.
var isVisible = this.get('visible');
result += isVisible ? '' : 'hidden ';
// Message icon.
var iconClass = this.get('icon');
var hasIcon = isNonEmptyString(iconClass);
result += hasIcon ? 'icon ' : '';
result += 'message';
return result;
}),
didInsertElement: function() {
var isCloseable = this.get('closeable');
if (isCloseable) {
// Inside 'click'-callback 'this' would refer to a jQuery-object.
var _this = this;
_this.$('.close').on('click', function() {
_this.hide();
});
}
},
show: function() {
this.set('visible', true);
// Send component 'onShow'-action with component itself as an argument.
this.sendAction('onShow', this);
},
hide: function() {
this.set('visible', false);
// Send component 'onHide'-action with component itself as an argument.
this.sendAction('onHide', this);
}
});
|
var
assert = require("assert"),
request = require("request"),
zlib = require("zlib"),
HttpCache = require("./setup").HttpCache,
CacheServer = require("./cache-server")
;
describe("http-cache", function() {
var server, cache, ops;
before(function(done) {
opts = {
rules: function(req, res, cb) {
if (/\/asyncRule\//.test(req.url) === true) {
setTimeout(function() {
if (/no-cache/.test(req.url) === true) {
cb(null, false); // do not cache
} else if (/cache/.test(req.url) === true) {
cb(null, true); // cache
} else {
cb("error"); // something went wrong, do not cache
}
}, 100);
} else {
// do not cache users folder
return (/\/users\//i.test(req.url) === false);
}
}, ttl: 2, purgeAll: true, provider: require("./setup").provider
, confirmCacheBeforeEnd: true
, varyByHeader: [ "magic-sprinkles" ]
, varyByParam: [ "missle-toe" ]
};
cache = HttpCache(opts); // do NOT call new, this is one of our tests
server = new CacheServer(6852, cache, done);
server.app.use(function(req, res) {
switch (req.url) {
case "/writeHead":
res.writeHead(200, { "X-TEST": new Date().getTime().toString() });
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
case "/setHeader":
res.setHeader("X-TEST", new Date().getTime().toString());
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
case "/write":
res.setHeader("X-TEST", new Date().getTime().toString());
res.write("123");
res.write("456");
res.end();
break;
case "/writeEncoding":
res.setHeader("X-TEST", new Date().getTime().toString());
res.write("123", "ascii");
res.end();
break;
case "/endEncoding":
res.setHeader("X-TEST", new Date().getTime().toString());
res.end("Caching page '" + req.url + "' at " + new Date().getTime(), "ascii");
break;
case "/cacheControl/private":
res.setHeader("X-TEST", new Date().getTime().toString());
res.setHeader("Cache-Control", "private");
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
case "/cacheControl/no-cache":
res.setHeader("X-TEST", new Date().getTime().toString());
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
case "/acceptEncoding":
case "/acceptEncoding/gzipFirst":
res.setHeader("X-TEST", new Date().getTime().toString());
res.end("TEST" + (new Array(1024).join("X-X"))); // big enough to gzip
break;
case "/exclude-header":
res.setHeader("Set-Cookie", new Date().getTime().toString());
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
case "/reasonPhrase":
res.writeHead(200, "TEST");
res.end();
break;
case "/endNoData":
res.end();
break;
case "/contentLength":
res.end("TEST");
break;
default:
res.setHeader("X-TEST", new Date().getTime().toString());
res.end("Caching page '" + req.url + "' at " + new Date().getTime());
break;
}
});
});
after(function() {
server.close();
});
it("provider.clear", function(done) {
cache.provider.set("TEST", "TEST", 10, function(err) {
assert.ifError(err);
cache.provider.get("TEST", function(err, val) {
assert.ifError(err);
assert.equal(val, "TEST");
cache.provider.clear(function(err) {
assert.ifError(err);
cache.provider.get("TEST", function(err, val) {
assert.ifError(err);
assert.ok(!val);
done();
});
});
});
});
});
it("provider.get", function(done) {
cache.provider.get("TEST", function(err, val) {
assert.ifError(err);
assert.ok(!val);
done();
});
});
it("provider.set", function(done) {
cache.provider.set("TEST", "TEST", 10, function(err) {
assert.ifError(err);
cache.provider.get("TEST", function(err, val) {
assert.ifError(err);
assert.equal(val, "TEST");
done();
});
});
});
it("provider.remove", function(done) {
cache.provider.remove("TEST", function(err, val) {
assert.ifError(err);
cache.provider.get("TEST", function(err, val) {
assert.ifError(err);
assert.ok(!val);
done();
});
});
});
it("rule-based exclusion", function(done) {
var lastResponse;
request.get("http://localhost:6852/users/1", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
lastResponse = body;
request.get("http://localhost:6852/users/1", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.notEqual(body, lastResponse);
done();
});
});
});
it("asyncRule/cache", function(done) {
var xTest;
request.get("http://localhost:6852/asyncRule/cache", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/asyncRule/cache", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("asyncRule/no-cache", function(done) {
var xTest;
request.get("http://localhost:6852/asyncRule/no-cache", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/asyncRule/no-cache", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
it("asyncRule/error", function(done) {
var xTest;
request.get("http://localhost:6852/asyncRule/error", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/asyncRule/error", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
it("Accept-Encoding:undefined", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["content-encoding"], "gzip");
assert.equal(body.substr(0, 4), "TEST");
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("Accept-Encoding:none", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "none" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["content-encoding"], "gzip");
assert.equal(body.substr(0, 4), "TEST");
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "none" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("Accept-Encoding:gzip", function(done) {
var xTest, lastBody;
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "gzip" }, encoding:null }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["content-encoding"], "gzip");
zlib.gunzip(body, function(err, result) {
assert.equal(result.toString("utf8").substr(0, 4), "TEST");
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/acceptEncoding", headers: { "Accept-Encoding": "gzip" }, encoding:null }, function(err, res, body2) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
assert.equal(body.length, body2.length);
done();
});
});
});
});
it("Accept-Encoding:gzip", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/acceptEncoding/gzipFirst", headers: { "Accept-Encoding": "gzip" }, encoding:null }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["content-encoding"], "gzip");
//assert.equal(body.substr(0, 4), "TEST");
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/acceptEncoding/gzipFirst", headers: { "Accept-Encoding": "gzip" }, encoding:null }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("setHeader support", function(done) {
var xTest;
request.get("http://localhost:6852/setHeader", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/setHeader", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("endEncoding support", function(done) {
var xTest;
request.get("http://localhost:6852/endEncoding", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/endEncoding", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("writeHead support", function(done) {
var xTest;
request.get("http://localhost:6852/writeHead", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/writeHead", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("writeEncoding support", function(done) {
var xTest;
request.get("http://localhost:6852/writeEncoding", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/writeEncoding", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("chunk support", function(done) {
var xTest;
request.get("http://localhost:6852/write", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(body, "123456");
xTest = res.headers["x-test"];
request.get("http://localhost:6852/write", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("Cache-Control:private", function(done) {
var xTest;
request.get("http://localhost:6852/cacheControl/private", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/cacheControl/private", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
it("Cache-Control:no-cache", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/cacheControl/no-cache", headers: { "cache-control": "no-cache" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/cacheControl/no-cache", headers: { "cache-control": "no-cache" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
it("if-modified-since", function(done) {
var lastModified;
request.get("http://localhost:6852/if-modified-since", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["last-modified"]);
lastModified = res.headers["last-modified"];
request.get({ url: "http://localhost:6852/if-modified-since", headers: { "if-modified-since": lastModified } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 304);
done();
});
});
});
it("exclude-header", function(done) {
request.get("http://localhost:6852/exclude-header", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["set-cookie"]);
request.get("http://localhost:6852/exclude-header", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(!res.headers["set-cookie"]);
done();
});
});
});
it("reasonPhrase", function(done) {
request.get("http://localhost:6852/reasonPhrase", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
// todo: node does not currently expose mechanism to extract reason, will add more verification later
done();
});
});
it("contentLength", function(done) {
request.get("http://localhost:6852/contentLength", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.equal(body, "TEST");
assert.equal(res.headers["content-length"], 4);
done();
});
});
it("endNoData", function(done) {
request.get("http://localhost:6852/endNoData", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.equal(body, "");
request.get("http://localhost:6852/endNoData", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.equal(body, "");
done();
});
});
});
it("ttl support", function(done) {
var xTest;
request.get("http://localhost:6852/ttl", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get("http://localhost:6852/ttl", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
setTimeout(function() {
// /ttl should be purged by now based on a ttl of 1s
request.get("http://localhost:6852/ttl", function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
}, 2200);
});
});
});
it("varyByHeader.found", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/varyByHeader.found", headers: { "magic-sprinkles": "1" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/varyByHeader.found", headers: { "magic-sprinkles": "1" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("varyByHeader.notFound", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/varyByHeader.notFound", headers: { "magic-sprinkles": "1" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/varyByHeader.notFound", headers: { "magic-sprinkles": "2" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
it("varyByParam.found", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/varyByParam.found?missle-toe=1", headers: { "magic-sprinkles": "1" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/varyByParam.found?missle-toe=1", headers: { "magic-sprinkles": "1" } }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.equal(res.headers["x-test"], xTest);
done();
});
});
});
it("varyByParam.notFound", function(done) {
var xTest;
request.get({ url: "http://localhost:6852/varyByParam.notFound?missle-toe=1" }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
xTest = res.headers["x-test"];
request.get({ url: "http://localhost:6852/varyByParam.notFound?missle-toe=2" }, function(err, res, body) {
assert.ifError(err);
assert.equal(res.statusCode, 200);
assert.ok(res.headers["x-test"]);
assert.notEqual(res.headers["x-test"], xTest);
done();
});
});
});
});
|
function FaveFood(){
}
FaveFood.prototype.showText = function(){
}
FaveFood.prototype.init = function(){
this.showText();
}
|
const destPath = require('../dest-path')
test('Basic usage', () => {
expect(destPath('foo/bar/baz.html')).toBe('bar/baz')
})
test('Argument path has ./ at the head.', () => {
expect(destPath('./foo/bar/baz.html')).toBe('bar/baz')
})
|
var path = require('path')
module.exports = function() {
return {
test: /\.js$/,
loader: 'babel-loader',
include: path.resolve(GULP_CONFIG.root.src, GULP_CONFIG.tasks.js.src),
query: {
"presets": ["es2015", "stage-1"],
"plugins": []
}
};
}
|
'use strict'
const test = require('tape')
const ApiWrapper = require('./api-wrapper')
const registryMock = { model (modelName) { return {name: modelName} } }
test('ApiWrapper', (t) => {
const someModelMock = {
name: 'some-model-name',
attributesSerialize: [],
schema: { tableName: 'some' }
}
const apiWrappedSomeModel = new ApiWrapper({
model: someModelMock,
serializer: {}, deserializer: {},
registryMock
})
t.throws(
() => new ApiWrapper(),
/Cannot match against 'undefined' or 'null'/,
'needs at least a {model: model}'
)
t.throws(
() => new ApiWrapper({ model: {} }),
/ApiWrapper needs a model with 'name' and 'schema' fields/,
'model should be with a name'
)
t.throws(
() => new ApiWrapper({ model: {name: 'some-name'} }),
/ApiWrapper needs a model with 'name' and 'schema' fields/,
'and model should be with a schema'
)
t.doesNotThrow(
() => new ApiWrapper(someModelMock),
/ApiWrapper needs a model with 'name' and 'schema' fields/,
'model could be provided directly'
)
const aRegistryMock = {}
t.doesNotThrow(
() => new ApiWrapper(someModelMock, aRegistryMock),
'registry could be passed as a second argument for testing'
)
t.equal(apiWrappedSomeModel.model, someModelMock, '`model` property holds a model')
t.end()
})
test('apiWrapper.apiCreate()', (t) => {
t.plan(5)
const newDataFromClient = { some: 'does not matter' }
const deserializedNewData = { someOther: 'also does not matter' }
const dataFromCreate = { some2: '2' }
const deserializer = {
deserialize (newData) {
t.equal(newData, newDataFromClient, 'passes to deserializer newData')
return Promise.resolve(deserializedNewData)
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
create (deserialized) {
t.equal(
deserialized,
deserializedNewData,
'provides deserialized data to model`s create() method'
)
return Promise.resolve(dataFromCreate)
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
t.throws(
() => apiWrappedModel.apiCreate(/* no data */),
/newData cannot be undefined/,
'needs a newData'
)
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = (record) => {
t.equal(
record,
dataFromCreate,
'joins relations and serializes the result from model.create()'
)
return 'joined and serialized record'
}
apiWrappedModel.apiCreate(newDataFromClient)
.then((result) => t.equal(result, 'joined and serialized record'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('apiWrapper.apiCreate() returns error from deserializer', (t) => {
t.plan(2)
const deserializer = {
deserialize (newData) {
t.equal(newData, 'new data from client', 'passes to deserializer newData')
return Promise.reject(new Error('some deserializer`s error'))
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
create (deserialized) {
t.fail('model.create() should not be called')
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = () => {
t.fail('_joinRelationsAndSerialize() should not be called')
}
apiWrappedModel.apiCreate('new data from client')
.then(() => t.fail('should not be called'))
.catch((e) => {
t.equal(
e.message,
'some deserializer`s error',
'returns error from deserializer'
)
})
.then(() => t.end())
})
test('apiWrapper.apiCreate() returns error from model.create()', (t) => {
t.plan(3)
const deserializer = {
deserialize (newData) {
t.equal(newData, 'new data from client', 'passes to deserializer newData')
return Promise.resolve('deserializedNewData')
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
create (deserialized) {
t.equal(
deserialized,
'deserializedNewData',
'provides deserialized data to model`s create() method'
)
return Promise.reject(new Error('some create()`s error'))
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = () => {
t.fail('_joinRelationsAndSerialize() should not be called')
}
apiWrappedModel.apiCreate('new data from client')
.then(() => t.fail('should not be called'))
.catch((e) => {
t.equal(
e.message,
'some create()`s error',
'returns error from model.create()'
)
})
.then(() => t.end())
})
test('apiWrapper.apiUpdate()', (t) => {
t.plan(6)
const updatesDataFromClient = { some: 'does not matter' }
const deserializedUpdatesData = { someOther: 'also does not matter' }
const dataFromUpdate = { some2: '2' }
const deserializer = {
deserialize (data) {
t.equal(data, updatesDataFromClient, 'passes to deserializer updates data')
return Promise.resolve(deserializedUpdatesData)
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
update (id, deserialized) {
t.equal(id, 131, 'provides id to model`s update method')
t.equal(
deserialized,
deserializedUpdatesData,
'provides deserialized data to model`s update() method'
)
return Promise.resolve(dataFromUpdate)
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
t.throws(
() => apiWrappedModel.apiUpdate(/* no id */),
/id and updates cannot be undefined/,
'needs id and updates'
)
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = (record) => {
t.equal(
record,
dataFromUpdate,
'joins relations and serializes the result from model.update()'
)
return 'joined and serialized record'
}
apiWrappedModel.apiUpdate(131, updatesDataFromClient)
.then((result) => t.equal(result, 'joined and serialized record'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('apiWrapper.apiUpdate() returns error from deserializer', (t) => {
t.plan(1)
const deserializer = {
deserialize () {
return Promise.reject(new Error('some deserializer`s error'))
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
update () {
t.fail('model.update() should not be called')
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = () => {
t.fail('_joinRelationsAndSerialize() should not be called')
}
apiWrappedModel.apiUpdate(131, {updatesData: 'from client'})
.then(() => t.fail('should not be called'))
.catch((e) => {
t.equal(
e.message,
'some deserializer`s error',
'returns error from deserializer'
)
})
.then(() => t.end())
})
test('apiWrapper.apiUpdate() returns error from model.update()', (t) => {
t.plan(1)
const deserializer = {
deserialize () {
return Promise.resolve('deserializedNewData')
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
update () {
return Promise.reject(new Error('some update()`s error'))
}
}
const apiWrappedModel = new ApiWrapper({model, deserializer, serializer: {}, registryMock})
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = () => {
t.fail('_joinRelationsAndSerialize() should not be called')
}
apiWrappedModel.apiUpdate(131, {updatesData: 'from client'})
.then(() => t.fail('should not be called'))
.catch((e) => {
t.equal(
e.message,
'some update()`s error',
'returns error from model.update()'
)
})
.then(() => t.end())
})
test('apiWrapper.apiFind()', (t) => {
t.plan(4)
const dataFromSelect = { some: 'some' }
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
selectOne ({id}) {
t.equal(id, 1001, 'provides id to model`s selectOne() method')
return Promise.resolve(dataFromSelect)
}
}
const apiWrappedModel = new ApiWrapper({ model, deserializer: {}, serializer: {}, registryMock })
t.throws(
() => apiWrappedModel.apiFind(/* no id */),
/id cannot be undefined/,
'needs an id'
)
// mock it for testing
apiWrappedModel._joinRelationsAndSerialize = (record) => {
t.equal(
record,
dataFromSelect,
'joins relations and serializes the result from model.selectOne()'
)
return 'joined and serialized record'
}
apiWrappedModel.apiFind(1001)
.then((result) => t.equal(result, 'joined and serialized record'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('apiWrapper.apiFetchMany() without related', (t) => {
t.plan(4)
const serializer = {
withoutRelated (data) {
t.equal(data, '"joined" data', 'passes to serializer data after joining')
return Promise.resolve('serialized data')
},
withRelated () {
t.fail('serializer.withRelated() should no be called')
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
selectMany (options) {
t.deepEqual(options, {}, 'options for model.selectMany()')
return Promise.resolve('data from selectMany')
}
}
const apiWrappedModel = new ApiWrapper({model, serializer, deserializer: {}, registryMock})
// mock it for testing
apiWrappedModel.relations = {
justEmbedJoinedIds (parentRows) {
t.equal(
parentRows,
'data from selectMany',
'joins relations and serializes the result from model.update()'
)
return '"joined" data'
}
}
apiWrappedModel.apiFetchMany(/* no options */)
.then((result) => t.equal(result, 'serialized data'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('apiWrapper.apiFetchMany() with JOIN-ed relations', (t) => {
t.plan(4)
const serializer = {
withRelated (data) {
t.equal(data, '"joined" data', 'passes to serializer data after joining')
return Promise.resolve('serialized data')
},
withoutRelated () {
t.fail('serializer.withoutRelated() should no be called')
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
selectMany (options) {
t.deepEqual(options, {sideloadJoinedRelations: true}, 'options for model.selectMany()')
return Promise.resolve('data from selectMany')
}
}
const apiWrappedModel = new ApiWrapper({model, serializer, deserializer: {}, registryMock})
// mock it for testing
apiWrappedModel.relations = {
fetchAndEmbedJoined (parentRows) {
t.equal(
parentRows,
'data from selectMany',
'joins relations and serializes the result from model.update()'
)
return '"joined" data'
}
}
apiWrappedModel._joinBelongsToRelations = () => t.fail('this._joinBelongsToRelations() should not be called')
apiWrappedModel.apiFetchMany({sideloadJoinedRelations: true})
.then((result) => t.equal(result, 'serialized data'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('apiWrapper.apiFetchMany(options) with options for relations', (t) => {
t.plan(5)
const serializer = {
withRelated (data) {
t.equal(data, '"joined" data', 'passes to serializer data after joining')
return Promise.resolve('serialized data')
},
withoutRelated () {
t.fail('serializer.withoutRelated() should no be called')
}
}
const model = {
name: 'someModelName',
schema: { tableName: 'some' },
selectMany (options) {
t.deepEqual(
options,
{
sideloadJoinedRelations: true,
fieldsOnly: ['name', 'active', 'hide', 'group'],
where: {active: true},
orderBy: 'name'
},
'options for parent`s model.selectMany()'
)
return Promise.resolve('data from selectMany')
}
}
const apiWrappedModel = new ApiWrapper({model, serializer, deserializer: {}, registryMock})
// mock it for testing
apiWrappedModel.relations = {
fetchAndEmbedJoined (parentRows, options) {
t.deepEqual(
options,
{
parentWhere: {active: true},
// additional constraints for relations` models
group: { where: {hide: false} },
divisions: { fieldsOnly: ['name', 'manager'], where: {hide: false} }
},
'it passes options for relations'
)
t.equal(
parentRows,
'data from selectMany',
'joins relations and serializes the result from model.update()'
)
return '"joined" data'
}
}
const options = {
sideloadJoinedRelations: true, // main testing option
// constraints for parent model
fieldsOnly: ['name', 'active', 'hide', 'group'],
where: {active: true},
orderBy: 'name',
// constraints for relations` models
relationsOptions: {
group: { where: {hide: false} },
divisions: { fieldsOnly: ['name', 'manager'], where: {hide: false} }
}
}
apiWrappedModel.apiFetchMany(options)
.then((result) => t.equal(result, 'serialized data'))
.catch((e) => t.fail(e))
.then(() => t.end())
})
/**
* REST Api methods
*/
function getMinimalWrapper () {
const model = { name: 'someModelName', schema: { tableName: 'some' } }
return new ApiWrapper({model, deserializer: {}, serializer: {}, registryMock})
}
test('apiWrapper.create()', (t) => {
t.plan(5)
const wrapper = getMinimalWrapper()
wrapper.apiCreate = (body) => {
t.pass('it calls apiCreate()')
t.equal(body, 'request body data', 'passes req.body')
return Promise.resolve({data: {field: 'serialized data'}})
}
const next = () => t.fail('next() should not be called')
const req = { body: 'request body data' }
const res = {}
res.status = (code) => {
t.equal(code, 201, 'calls status with 201')
return res
}
res.json = (serialized) => {
t.deepEqual(serialized, {data: {field: 'serialized data'}}, 'calls json')
t.end()
}
t.doesNotThrow(
() => wrapper.create(req, res, next),
'additional check'
)
})
test('apiWrapper.update()', (t) => {
t.plan(6)
const wrapper = getMinimalWrapper()
wrapper.apiUpdate = (id, body) => {
t.pass('it calls apiUpdate()')
t.equal(id, 123, 'passes parsed req.id')
t.equal(body, 'request body data', 'passes req.body')
return Promise.resolve({data: {field: 'serialized data'}})
}
const next = () => t.fail('next() should not be called')
const req = { id: 123, body: 'request body data' }
const res = {}
res.status = (code) => {
t.equal(code, 201, 'calls status with 201')
return res
}
res.json = (serialized) => {
t.deepEqual(serialized, {data: {field: 'serialized data'}}, 'calls json')
t.end()
}
t.doesNotThrow(
() => wrapper.update(req, res, next),
'additional check'
)
})
test('apiWrapper.delete()', (t) => {
t.plan(2)
const wrapper = getMinimalWrapper()
const next = (err) => t.equal(err.message, 'REST delete() is not implemented')
t.doesNotThrow(
() => wrapper.delete({}, {}, next),
'additional check'
)
t.end()
})
test('apiWrapper.readOne()', (t) => {
t.plan(4)
const wrapper = getMinimalWrapper()
wrapper.apiFind = (id) => {
t.pass('it calls apiFind()')
t.equal(id, 123, 'passes parsed req.id')
return Promise.resolve({data: {field: 'serialized data'}})
}
const next = () => t.fail('next() should not be called')
const req = { id: 123 }
const res = {
json (serialized) {
t.deepEqual(serialized, {data: {field: 'serialized data'}}, 'calls json')
t.end()
}
}
t.doesNotThrow(
() => wrapper.readOne(req, res, next),
'additional check'
)
})
test('apiWrapper.readMany() default', (t) => {
t.plan(4)
const wrapper = getMinimalWrapper()
wrapper.apiFetchMany = (options) => {
t.pass('it calls apiFetchMany()')
t.deepEqual(
options,
{},
'by default client will get data w/o related data'
)
return Promise.resolve({data: {field: 'serialized data'}})
}
const next = () => t.fail('next() should not be called')
const req = { query: {} }
const res = {
json (serialized) {
t.deepEqual(serialized, {data: {field: 'serialized data'}}, 'calls json')
t.end()
}
}
t.doesNotThrow(
() => wrapper.readMany(req, res, next), 'additional check'
)
})
test('apiWrapper.readMany() with /?includeJoined=true', (t) => {
t.plan(2)
const wrapper = getMinimalWrapper()
wrapper.apiFetchMany = (options) => {
t.deepEqual(
options,
{ sideloadJoinedRelations: true },
'with /?includeJoined=true'
)
return Promise.resolve()
}
const next = () => t.fail('next() should not be called')
const req = { query: { includeJoined: 'true' } } // /?includeJoined=true
const res = { json (serialized) { t.end() } }
t.doesNotThrow(
() => wrapper.readMany(req, res, next), 'additional check'
)
})
/**
* apiWrapper.connect(router) connects REST api to router
*/
function getRouterMock (t) {
const model = { name: 'someModelName', schema: { tableName: 'some' } }
const wrapper = new ApiWrapper({model, deserializer: {}, serializer: {}, registryMock})
const paths = {
'/': {},
'/:id': {}
}
const routerMock = {
param (id, idParamParser) {
t.equal(id, 'id', 'connects id param parser')
t.equal((typeof idParamParser), 'function', 'second parameter is middleware')
},
route (path) {
const pathObject = paths[path]
if (!pathObject) t.fail(`router.route(${path}) has been called`)
return pathObject
}
}
return { routerMock, wrapper, forMany: paths['/'], forOne: paths['/:id'] }
}
test('apiWrapper.connect(router) connects REST api to router', (t) => {
t.plan(7)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.readMany = () => 'readMany'
wrapper.readOne = () => 'readOne'
wrapper.create = () => 'create'
wrapper.update = () => 'update'
wrapper.delete = () => 'delete'
forMany.get = (m) => { t.equal(m(), 'readMany', 'get / readMany'); return forMany }
forMany.post = (m) => { t.equal(m(), 'create', 'post / create'); return forMany }
forOne.get = (m) => { t.equal(m(), 'readOne', 'get /:id readOne'); return forOne }
forOne.patch = (m) => { t.equal(m(), 'update', 'patch /:id update'); return forOne }
forOne.delete = (m) => { t.equal(m(), 'delete', 'delete /:id delete'); return forOne }
wrapper.connect(routerMock, 'create read update delete')
wrapper.readMany()
wrapper.readOne()
wrapper.create()
wrapper.update()
wrapper.delete()
t.end()
})
test('apiWrapper.connect(router) by default connects only read methods', (t) => {
t.plan(4)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.readMany = () => 'readMany'
wrapper.readOne = () => 'readOne'
forMany.get = (m) => { t.equal(m(), 'readMany', 'get / readMany'); return forMany }
forMany.post = (m) => { t.fail('post / create should not be connected'); return forMany }
forOne.get = (m) => { t.equal(m(), 'readOne', 'get /:id readOne'); return forOne }
forOne.patch = (m) => { t.fail('patch /:id update should not be connected'); return forOne }
forOne.delete = (m) => { t.fail('delete /:id delete should not be connected'); return forOne }
wrapper.connect(routerMock /* no options */)
wrapper.readMany()
wrapper.readOne()
t.end()
})
test('apiWrapper.connect(router) "update" option', (t) => {
t.plan(3)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.update = () => 'update'
forMany.get = (m) => { t.fail('get / readMany should not be connected'); return forMany }
forMany.post = (m) => { t.fail('post / create should not be connected'); return forMany }
forOne.get = (m) => { t.fail('get /:id readOne should not be connected'); return forOne }
forOne.patch = (m) => { t.equal(m(), 'update', 'patch /:id update'); return forOne }
forOne.delete = (m) => { t.fail('delete /:id delete should not be connected'); return forOne }
wrapper.connect(routerMock, 'update')
wrapper.update()
t.end()
})
test('apiWrapper.connect(router) "create" option', (t) => {
t.plan(3)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.create = () => 'create'
forMany.get = (m) => { t.fail('get / readMany should not be connected'); return forMany }
forMany.post = (m) => { t.equal(m(), 'create', 'post / create'); return forMany }
forOne.get = (m) => { t.fail('get /:id readOne should not be connected'); return forOne }
forOne.patch = (m) => { t.fail('patch /:id update should not be connected'); return forOne }
forOne.delete = (m) => { t.fail('delete /:id delete should not be connected'); return forOne }
wrapper.connect(routerMock, 'create')
wrapper.create()
t.end()
})
test('apiWrapper.connect(router) "delete" option', (t) => {
t.plan(3)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.delete = () => 'delete'
forMany.get = (m) => { t.fail('get / readMany should not be connected'); return forMany }
forMany.post = (m) => { t.fail('post / create should not be connected'); return forMany }
forOne.get = (m) => { t.fail('get /:id readOne should not be connected'); return forOne }
forOne.patch = (m) => { t.fail('patch /:id update should not be connected'); return forOne }
forOne.delete = (m) => { t.equal(m(), 'delete', 'delete /:id delete'); return forOne }
wrapper.connect(routerMock, 'delete')
wrapper.delete()
t.end()
})
test('apiWrapper.connect(router) binds methods to wrapper', (t) => {
t.plan(11)
const { routerMock, wrapper, forMany, forOne } = getRouterMock(t)
wrapper.readMany = function () { t.equal(this, wrapper, 'readMany.bind(this)'); return 'readMany' }
wrapper.readOne = function () { t.equal(this, wrapper, 'readOne.bind(this)'); return 'readOne' }
wrapper.create = function () { t.equal(this, wrapper, 'create.bind(this)'); return 'create' }
wrapper.update = function () { t.equal(this, wrapper, 'update.bind(this)'); return 'update' }
wrapper.delete = function () { t.equal(this, wrapper, 'delete.bind(this)'); return 'delete' }
forMany.get = (m) => { t.equal(m(), 'readMany', 'get / readMany'); return forMany }
forMany.post = (m) => { t.equal(m(), 'create', 'post / create'); return forMany }
forOne.get = (m) => { t.equal(m(), 'readOne', 'get /:id readOne'); return forOne }
forOne.patch = (m) => { t.equal(m(), 'update', 'patch /:id update'); return forOne }
forOne.delete = (m) => { t.equal(m(), 'delete', 'delete /:id delete'); return forOne }
wrapper.connect(routerMock, 'read')
wrapper.readMany()
wrapper.readOne()
wrapper.create()
wrapper.update()
wrapper.delete()
t.end()
})
/**
* Integration testing
*/
const BaseModel = require('../models/base-model')
const dbMock = { exec () { return Promise.resolve() } }
test('I&T apiWrapper.apiCreate()', (t) => {
t.plan(3)
class UserModel extends BaseModel {
create (deserializedNewData) {
t.deepEqual(
deserializedNewData,
{
name: 'John',
rights: { id: '12' },
userGroup: { id: '101' }
},
'create(newData) has been called'
)
return Promise.resolve({
id: '1', // sql assigns an ID
name: 'John',
rightsId: '12',
userGroupId: '101'
})
}
}
const userModel = new UserModel({
db: dbMock, name: 'user',
schema: {
tableName: 'some',
name: 'string',
userGroup: { belongsTo: 'userGroup' },
rights: { belongsTo: 'rights' }
}
})
const apiWrappedUserModel = new ApiWrapper(userModel, registryMock)
const newData = {
data: {
attributes: { name: 'John' },
relationships: {
userGroup: { data: { id: '101', type: 'user-groups' } },
rights: { data: { id: '12', type: 'rights' } }
},
type: 'users'
}
}
apiWrappedUserModel.apiCreate(newData)
.then((savedSerialized) => {
t.equal(savedSerialized.data.id, '1', 'returns with ID')
t.deepEqual(
savedSerialized,
{
data: {
attributes: { name: 'John' },
id: '1',
relationships: {
'user-group': { data: { id: '101', type: 'userGroups' } },
rights: { data: { id: '12', type: 'rights' } }
},
type: 'users'
}
},
'result of integration testing'
)
})
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('I&T apiWrapper.apiUpdate()', (t) => {
t.plan(3)
class UserModel extends BaseModel {
update (id, deserializedData) {
t.pass('update(id, data) has been called')
t.deepEqual(
deserializedData,
{
id: '1', name: 'John',
rights: { id: '12' },
userGroup: { id: '101' }
},
'receives deserialized data'
)
const sqlResult = {
id: '1', name: 'John',
rightsId: '12',
userGroupId: '101'
}
return Promise.resolve(sqlResult)
}
}
const userModel = new UserModel({
db: dbMock, name: 'user',
schema: {
tableName: 'some',
name: 'string',
userGroup: { belongsTo: 'userGroup' },
rights: { belongsTo: 'rights' }
}
})
const apiWrappedUserModel = new ApiWrapper(userModel, registryMock)
const updatesData = {
data: {
attributes: { name: 'John' },
id: '1',
relationships: {
'user-group': { data: { id: '101', type: 'user-groups' } },
rights: { data: { id: '12', type: 'rights' } }
},
type: 'users'
}
}
apiWrappedUserModel.apiUpdate(1, updatesData)
.then((updatedSerialized) => {
t.deepEqual(
updatedSerialized,
{
data: {
attributes: { name: 'John' },
id: '1',
relationships: {
'user-group': { data: { id: '101', type: 'userGroups' } },
rights: { data: { id: '12', type: 'rights' } }
},
type: 'users'
}
},
'returns updated serialized row without relations included'
)
})
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('I&T apiWrapper.apiFind()', (t) => {
t.plan(1)
class UserModel extends BaseModel {
selectOne (options) {
const rows = {
1: {id: '1', name: 'John', userGroupId: '101', rightsId: '12'},
2: {id: '2', name: 'Smith', userGroupId: '102', rightsId: '13'}
}
return Promise.resolve(rows[options.id])
}
}
const userModel = new UserModel({
db: dbMock, name: 'user',
schema: {
tableName: 'some',
name: 'string',
group: { belongsTo: 'userGroup' },
rights: { belongsTo: 'rights' }
}
})
const apiWrappedUserModel = new ApiWrapper(userModel, registryMock)
apiWrappedUserModel.apiFind(1)
.then((serialized) => {
t.deepEqual(
serialized,
{
data: {
attributes: { name: 'John' },
id: '1',
relationships: {
group: { data: { id: '101', type: 'groups' } },
rights: { data: { id: '12', type: 'rights' } }
},
type: 'users'
}
},
'returns serialized row without relations included'
)
})
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('I&T apiWrapper.apiFetchMany({sideloadJoinedRelations: true})', (t) => {
t.plan(1)
class RightsModel extends BaseModel {
selectMany () {
return Promise.resolve([
{id: '12', fullName: 'Full'},
{id: '13', fullName: 'Part'}
])
}
}
const rightsModel = new RightsModel({
db: dbMock, name: 'rights',
schema: {
tableName: 'rights',
fullName: 'string'
}
})
class UserGroupModel extends BaseModel {
selectMany () {
return Promise.resolve([
{id: '101', shortName: 'Admins'},
{id: '102', shortName: 'Users'}
])
}
}
const userGroupModel = new UserGroupModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'GrpID',
tableName: 'sPepTree',
shortName: 'string'
}
})
class DivisionModel extends BaseModel {
selectMany () {
return Promise.resolve([
{ id: '23', name: 'Kitchen', hide: false, userId: '1' },
{ id: '24', name: 'Sad', hide: false, userId: '1' },
{ id: '25', name: 'Mangal', hide: false, userId: '2' },
{ id: '26', name: 'Tandyr', hide: false, userId: '2' }
])
}
}
const divisionModel = new DivisionModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'DivID',
tableName: 'sDivisions',
name: 'string',
hide: 'boolean',
staff: { belongsTo: 'user' }
}
})
class ClientModel extends BaseModel {
selectMany () {
return Promise.resolve([
{ id: '101', name: 'John', cardcode: '123', hide: false, userId: '1' },
{ id: '102', name: 'Simona', cardcode: '455', hide: false, userId: '1' },
{ id: '103', name: 'Whatson', cardcode: '', hide: false, userId: '2' },
{ id: '104', name: 'Vaschev', cardcode: '9022', hide: false, userId: '2' }
])
}
}
const clientModel = new ClientModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'CliID',
tableName: 'sClients',
name: 'string',
cardcode: 'string',
hide: 'boolean',
manager: { belongsTo: 'user' }
}
})
// divisionModel.attributesSerialize = ['name', 'hide'] // , 'staff']
// clientModel.attributesSerialize = ['name', 'cardcode', 'hide'] // , 'manager']
const registryMock = {
model (modelName) {
const _models = {
rights: rightsModel,
userGroup: userGroupModel,
division: divisionModel,
client: clientModel
}
return _models[modelName]
}
}
class UserModel extends BaseModel {
selectMany () {
return Promise.resolve([
{id: '1', name: 'John', userGroupId: '101', rightsId: '12'},
{id: '2', name: 'Smith', userGroupId: '102', rightsId: '13'}
])
}
}
const userModel = new UserModel({
db: dbMock, registry: registryMock, name: 'user',
schema: {
tableName: 'some',
name: 'string',
group: { belongsTo: 'userGroup' },
rights: { belongsTo: 'rights' },
divisions: { hasMany: 'division', fkField: 'UserID' },
clients: { hasMany: 'client', fkField: 'UserID' }
}
})
const apiWrappedUserModel = new ApiWrapper(userModel, registryMock)
apiWrappedUserModel.apiFetchMany({sideloadJoinedRelations: true})
.then((serialized) => {
t.deepEqual(
serialized,
{
data: [{
attributes: { name: 'John' },
id: '1',
relationships: {
group: { data: { id: '101', type: 'groups' } },
rights: { data: { id: '12', type: 'rights' } },
clients: { data: [ { id: '101', type: 'clients' }, { id: '102', type: 'clients' } ] },
divisions: { data: [ { id: '23', type: 'divisions' }, { id: '24', type: 'divisions' } ] }
},
type: 'users'
}, {
attributes: { name: 'Smith' },
id: '2',
relationships: {
group: { data: { id: '102', type: 'groups' } },
rights: { data: { id: '13', type: 'rights' } },
clients: { data: [ { id: '103', type: 'clients' }, { id: '104', type: 'clients' } ] },
divisions: { data: [ { id: '25', type: 'divisions' }, { id: '26', type: 'divisions' } ] }
},
type: 'users'
}],
included: [{
attributes: { 'short-name': 'Admins' },
id: '101', type: 'groups'
}, {
attributes: { 'full-name': 'Full' },
id: '12', type: 'rights'
}, {
// attributes: { hide: false, name: 'Kitchen', staff: { id: '1' } },
attributes: { hide: false, name: 'Kitchen' },
id: '23', type: 'divisions'
}, {
// attributes: { hide: false, name: 'Sad', staff: { id: '1' } },
attributes: { hide: false, name: 'Sad' },
id: '24', type: 'divisions'
}, {
// attributes: { cardcode: '123', hide: false, manager: { id: '1' }, name: 'John' },
attributes: { cardcode: '123', hide: false, name: 'John' },
id: '101', type: 'clients'
}, {
// attributes: { cardcode: '455', hide: false, manager: { id: '1' }, name: 'Simona' },
attributes: { cardcode: '455', hide: false, name: 'Simona' },
id: '102', type: 'clients'
}, {
attributes: { 'short-name': 'Users' },
id: '102', type: 'groups'
}, {
attributes: { 'full-name': 'Part' },
id: '13', type: 'rights'
}, {
// attributes: { hide: false, name: 'Mangal', staff: { id: '2' } },
attributes: { hide: false, name: 'Mangal' },
id: '25', type: 'divisions'
}, {
// attributes: { hide: false, name: 'Tandyr', staff: { id: '2' } },
attributes: { hide: false, name: 'Tandyr' },
id: '26', type: 'divisions'
}, {
// attributes: { cardcode: '', hide: false, manager: { id: '2' }, name: 'Whatson' },
attributes: { cardcode: '', hide: false, name: 'Whatson' },
id: '103', type: 'clients'
}, {
// attributes: { cardcode: '9022', hide: false, manager: { id: '2' }, name: 'Vaschev' },
attributes: { cardcode: '9022', hide: false, name: 'Vaschev' },
id: '104', type: 'clients'
}]
},
'returns serialized rows with relations data included'
)
})
.catch((e) => t.fail(e))
.then(() => t.end())
})
test('I&T apiWrapper.apiFetchMany() with options for relations', (t) => {
t.plan(4)
class RightsModel extends BaseModel {}
const rightsModel = new RightsModel({
db: dbMock, name: 'rights',
schema: {
tableName: 'rights',
fullName: 'string'
}
})
class UserGroupModel extends BaseModel {}
const userGroupModel = new UserGroupModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'GrpID',
tableName: 'sPepTree',
shortName: 'string'
}
})
class DivisionModel extends BaseModel {
selectMany (opts) {
t.equal(opts.fieldsOnly, 'idAndRelations', 'it needs only hasMany IDs')
t.deepEqual(
opts,
{
fieldsOnly: 'idAndRelations',
where: { hide: false }, // passes relation's model constraints
whereIn: {
parentIdFieldName: 'id',
parentTableName: 'some',
relationFkName: 'UserID',
parentWhere: { hide: false } // passes parent's 'where'
}
},
'passes relations` constraints'
)
return Promise.resolve([
{ id: '23', userId: '1' },
{ id: '24', userId: '1' },
{ id: '25', userId: '2' },
{ id: '26', userId: '2' }
])
}
}
const divisionModel = new DivisionModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'DivID',
tableName: 'sDivisions',
name: 'string',
hide: 'boolean',
staff: { belongsTo: 'user' }
}
})
class ClientModel extends BaseModel {
selectMany (opts) {
t.equal(opts.fieldsOnly, 'idAndRelations', 'it needs only hasMany IDs')
return Promise.resolve([
{ id: '101', userId: '1' },
{ id: '102', userId: '1' },
{ id: '103', userId: '2' },
{ id: '104', userId: '2' }
])
}
}
const clientModel = new ClientModel({
db: dbMock, name: 'userGroup',
schema: {
id: 'CliID',
tableName: 'sClients',
name: 'string',
cardcode: 'string',
hide: 'boolean',
manager: { belongsTo: 'user' }
}
})
const registryMock = {
model (modelName) {
const _models = {
rights: rightsModel,
userGroup: userGroupModel,
division: divisionModel,
client: clientModel
}
return _models[modelName]
}
}
class UserModel extends BaseModel {
selectMany () {
return Promise.resolve([
{id: '1', name: 'John', userGroupId: '101', rightsId: '12'},
{id: '2', name: 'Smith', userGroupId: '102', rightsId: '13'}
])
}
}
const userModel = new UserModel({
db: dbMock, registry: registryMock, name: 'user',
schema: {
tableName: 'some',
name: 'string',
group: { belongsTo: 'userGroup' },
rights: { belongsTo: 'rights' },
divisions: { hasMany: 'division', fkField: 'UserID' },
clients: { hasMany: 'client', fkField: 'UserID' }
}
})
const apiWrappedUserModel = new ApiWrapper(userModel, registryMock)
const options = {
sideloadJoinedRelations: false,
fieldsOnly: ['id', 'name', 'group', 'rights'],
where: {hide: false},
orderBy: 'name',
relationsOptions: {
division: {
where: {hide: false}
}
}
}
apiWrappedUserModel.apiFetchMany(options)
.then((serialized) => {
t.deepEqual(
serialized,
{
data: [{
attributes: { name: 'John' },
id: '1',
relationships: {
group: { data: { id: '101', type: 'groups' } },
rights: { data: { id: '12', type: 'rights' } },
clients: { data: [ { id: '101', type: 'clients' }, { id: '102', type: 'clients' } ] },
divisions: { data: [ { id: '23', type: 'divisions' }, { id: '24', type: 'divisions' } ] }
},
type: 'users'
}, {
attributes: { name: 'Smith' },
id: '2',
relationships: {
group: { data: { id: '102', type: 'groups' } },
rights: { data: { id: '13', type: 'rights' } },
clients: { data: [ { id: '103', type: 'clients' }, { id: '104', type: 'clients' } ] },
divisions: { data: [ { id: '25', type: 'divisions' }, { id: '26', type: 'divisions' } ] }
},
type: 'users'
}]
},
'returns serialized rows without relations included'
)
})
.catch((e) => t.fail(e))
.then(() => t.end())
})
|
var todoApp = angular.module('todo', ['ui.sortable']);
todoApp.factory('todoAppStorage', function () {
var STORAGE_ID = 'godo-angularjs';
return {
get: function () {
return JSON.parse(localStorage.getItem(STORAGE_ID)) || [
{
description: "Walk the dog",
complete: true,
itemID: 0
},
{
description: "Buy groceries",
complete: false,
itemID: 1
},
{
description: "Call mom",
complete: false,
itemID: 2
},
{
description: "Go jogging",
complete: true,
itemID: 3
}
];
},
put: function (items) {
localStorage.setItem(STORAGE_ID, JSON.stringify(items));
}
};
});
todoApp.factory('selectedStorage', function () {
var STORAGE_ID = 'godo-selected';
return {
get: function () {
return JSON.parse(localStorage.getItem(STORAGE_ID)) || {};
},
put: function (selected) {
localStorage.setItem(STORAGE_ID, JSON.stringify(selected));
}
}
});
function ItemsController($scope, todoAppStorage, selectedStorage) {
var items = $scope.items = todoAppStorage.get();
var search = $scope.search = selectedStorage.get();
$scope.editingItem = null;
$scope.$watch('items', function (newValue, oldValue) {
$scope.activeCount = $scope.itemCount(false);
$scope.completedCount = items.length - $scope.activeCount;
if (newValue !== oldValue) {
todoAppStorage.put(items);
}
}, true);
$scope.$watch('search', function (newValue, oldValue) {
if (newValue !== oldValue) {
selectedStorage.put(search);
}
}, true);
$scope.itemCount = function (complete) {
if (typeof (complete) === 'undefined' || complete === null) {
return $scope.items.length;
}
else {
var count = 0;
angular.forEach($scope.items, function (item) {
if (item.complete == complete) {
count++;
}
});
return count;
}
}
$scope.addItem = function (item) {
var id = $scope.itemID++;
$scope.trimItem(item);
$scope.items.push({
description: item.description,
complete: false
});
item.description = "";
}
$scope.deleteItem = function (item) {
$scope.items.splice($scope.items.indexOf(item), 1);
}
$scope.complete = function (item, complete) {
if (typeof (complete) === 'undefined' || complete === null) {
delete item.complete;
}
else {
item.complete = complete;
}
}
$scope.edit = function (item) {
item.editing = true;
$scope.editingItem = item;
}
$scope.doneEditing = function (item) {
item.editing = false;
if (item.description.length == 0) {
$scope.deleteItem(item);
}
else {
$scope.trimItem(item);
}
$scope.editingItem = null;
}
$scope.trimItem = function (item) {
var maxLength = 29;
if (item.description.length > maxLength) {
item.description = item.description.substring(0, maxLength - 1);
}
}
};
todoApp.directive('onBlur', function () {
return function (scope, elem, attrs) {
elem.bind('blur', function () {
scope.$apply(attrs.onBlur);
});
};
});
todoApp.directive('giveFocus', function todoFocus($timeout) {
return function (scope, elem, attrs) {
scope.$watch(attrs.giveFocus, function (newVal) {
if (newVal) {
$timeout(function () {
elem[0].focus();
}, 0, false);
}
});
};
}); |
angular.module('teamformApp')
//everything that changes view is in controller
//everything that's an object is in the factory
.controller("myProfileCtrl", ['$scope', '$state', '$stateParams', '$firebaseArray', '$firebaseObject',
function ($scope, $state, $stateParams, $firebaseArray, $firebaseObject) {
$scope.currentUser = firebase.auth().currentUser;
var database = firebase.database();
var storage = firebase.storage();
$scope.user = {};
$scope.isAdmin = false;
database.ref('TeamForm/users/' + $stateParams.id).once('value', function (info) {
$scope.user = info.val();
$scope.tags = info.val().tags;
$scope.isAdmin = $scope.currentUser ? $scope.currentUser.uid == $stateParams.id : false;
$scope.$digest();
});
var teams = [];
var teamsRef = database.ref('TeamForm/RelationUT/').orderByChild("user").equalTo($stateParams.id);
$firebaseArray(teamsRef).$loaded().then(function (data) {
data.forEach(function (value) {
$firebaseObject(firebase.database().ref("TeamForm/teams/" + value.team)).$loaded().then(function (data) {
teams.push({name: data.name, ref: data.$id});
});
});
$scope.teams = teams;
});
$scope.submit = function () {
var inputtags = $('#profile_tags').tokenfield('getTokensList');
var re = new RegExp(", |,");
var tags = inputtags.split(re);
if (tags[tags.length - 1] == "")
tags.splice(tags.length - 1, 1);
$scope.user.tags = tags;
database.ref('TeamForm/users/' + $stateParams.id).update({
name: $scope.user.name,
description: $scope.user.description,
tags: $scope.user.tags
});
};
$scope.upload = function () {
var fileUpload = document.getElementById('fileUpload');
fileUpload.addEventListener('change', function (e) {
//get file
var file = e.target.files[0];
// create storage ref
var profileRef = storage.ref('users/' + $scope.currentUser.uid + ".png");
// upload
var task = profileRef.put(file);
// handle progress bar
task.on('state_changed',
function progress(snapshot) {
},
function error(err) {
},
function complete() {
var imgSrc;
storage.ref().child('users/' + $scope.currentUser.uid + '.png').getDownloadURL().then(function (url) {
imgSrc = url;
database.ref('TeamForm/users/' + $stateParams.id).update({
profile_picture: imgSrc
});
}).catch(function (error) {
});
alert('upload complete!');
});
});
};
}
]); |
var basePath = '/api';
var app = angular.module('adminApp');
app.controller('AccountController', [
'$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
var self = this;
self.accounts = [];
self.account = null;
self.queryCriteria = null;
self.queryResult = null;
self.temp = {
email: null,
dob: {
month: null,
day: null,
year: null
}
};
self.references = {};
loadReferences();
function loadReferences()
{
self.references.days = new Array(31);
self.references.months = ReferenceResource.lookup('months');
self.references.genders = ReferenceResource.lookup('genders');;
}
// Loads either the account in session or the list of accounts
if ($routeParams.accountId && $routeParams.accountId != 'new') {
self.account = AccountResource.get({id: $routeParams.accountId}, function(data) {
// nothing to do, data is updated when async is returned.
self.temp.dob = decomposeIsoDate(data.profile.dob);
}, function(error) {
alert(JSON.stringify(error));
});
} else {
// initialize
query();
}
this.go = function(path) {
return $location.path( path );
};
this.goToPage = function(pageIdx) {
var retval = '/?_page=' + pageIdx;
if (self.queryResult.limit) {
retval += '&limit=' + self.queryResult.limit;
}
$location.path('/').search('_page', pageIdx).search('_limit', self.queryResult.limit);
};
/**
* Is any user selected?
*/
this.selectedAccount = function() {
return self.account;
};
/**
* Removes an account
*/
this.remove = function(account) {
AccountResource.remove({id:account.uuid}, function(data) {
// nothing to do, data is updated when async is returned.
// temp:
alert('Account: ' + account.displayName + ' was removed. Please refresh page');
}, function(error) {
alert(JSON.stringify(error));
});
};
this.doQuery = function(id) {
query();
};
this.getAccount = function(id) {
self.account = AccountResource.get(id);
if (!self.account) {
alert ('Not found for ' + id);
}
};
/**
* Submit for update
*/
this.submit = function() {
//self.account.primaryEmail = [self.temp.email];
var dob = new Date(self.temp.dob.year, self.temp.dob.month, self.temp.dob.day);
self.account.profile.dob = moment(dob).format();
if (self.account.uuid) {
// Update existing
delete self.account._id;
AccountResource.update({id: self.account.uuid}, self.account);
self.retrieveRelations();
} else {
// Create new
var newAccount = new AccountResource(self.account);
newAccount.kind = 'normal';
newAccount.auth = {
authSource: 'local',
username: 'test',
security: { password: 'test' }
};
newAccount.$save();
}
};
/**
* Query accounts
*/
function query(criteria) {
var qparms = $location.search();
var queryArgs = {
_meta: 'true',
_page: qparms._page,
_limit: qparms._limit
};
// Fetch from remote
self.accounts = AccountResource.query2(queryArgs, function(data) {
self.queryResult = data;
self.queryResult.numPages = Math.ceil(self.queryResult.totalHits / self.queryResult.limit);
self.accounts = data.documents;
}, function(error) {
alert(JSON.stringify(error));
});
};
/**
* Parses and decomposes date (in ISO8601) into object with
* year, month, day, hours, minutes, seconds
*/
function decomposeIsoDate(isoDate)
{
var date = new Date(isoDate);
var dateObj = {};
if (date) {
dateObj.year = date.getUTCFullYear();
dateObj.month = date.getUTCMonth(); // 0-base
dateObj.day = date.getUTCDate();
dateObj.hours = date.getUTCHours();
dateObj.minutes = date.getUTCMinutes();
dateObj.seconds = date.getUTCSeconds();
}
return dateObj;
}
}]);
app.controller('RelationsController', [
'$http', '$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource', 'RelationResource'
, function($http, $routeParams, $location, AuthService, ReferenceResource, AccountResource, RelationResource)
{
self = this;
/* relations */
self.relations = [];
self.session = null;
AuthService.fetchMyAccount()
.then(function(account) {
self.session = account;
retrieveRelations();
})
.catch(function(error) {
});
/**
* Retrieve relations
*/
function retrieveRelations(criteria) {
var qparms = $location.search();
var queryArgs = {
accountId: self.session.uuid,
_meta: 'true',
_page: qparms._page,
_limit: qparms._limit,
_q: ''
};
// Fetch from remote
RelationResource.query2(queryArgs, function(data) {
//data.documents;
self.relations = normalizeResult(self.session.uuid, data.documents);
}, function(error) {
alert(JSON.stringify(error));
});
};
/**
* Normalizes the resut (list of relations) such that includes
* properties:
* thisRole : the role of the account in session
* counterpartAccount : the other account
* counterpartRole : the role of the other account
*/
function normalizeResult(thisUuid, result)
{
for(i=0; i < result.length; i++) {
if (thisUuid == result[i].account1Uuid) {
result[i].thisRole = result[i].role1;
result[i].counterpartAccount = result[i].account2;
result[i].counterpartRole = result[i].role2;
} else {
result[i].thisRole = result[i].role2;
result[i].counterpartAccount = result[i].account1;
result[i].counterpartRole = result[i].role1;
}
}
return result;
}
}]);
app.controller('ImportController', [
'$http', '$routeParams', '$location', 'AuthService', 'ReferenceResource', 'AccountResource'
, function($http, $routeParams, $location, AuthService, ReferenceResource, AccountResource)
{
var self = this;
self.dataToImport = null;
self.validated = {
errors: null,
records: null
};
/**
* Submit dataToImport to server for validation
*/
this.process = function(mode)
{
var objs = Papa.parse(self.dataToImport, {header: true});
preprocessInput(objs.data);
var payload = {
type: "account",
mode: mode,
onmatch: "skip",
data: objs.data
}
$http.post(basePath + '/import', payload)
.then(function(response) {
self.validated = response.data;
})
.catch(function(error) {
// Error wrapped by $http containing config, data, status, statusMessage, etc.
//if (error.data)
self.validated.errors = error;
throw error;
});
}
/**
*
* Convert those properties in which names has dot notation
* into nested object
*
* @param objs {Array<Object>}
*/
function preprocessInput(objs)
{
for(var i=0; i < objs.length; i++)
{
var obj = objs[i];
for (var prop in obj) {
if (prop.indexOf('.') !== -1) {
// create nested property
var val = obj[prop];
dotAccess(obj, prop, val);
delete obj[prop];
}
}
}
}
/**
* Converts those properties
* Precondition: the json should be an array of objects, the objects can
* contain nested objects but should not contain nested array
*/
function postprocessResponse(json)
{
for(var i=0; i < json.length; i++)
{
json[i]
}
}
}]);
|
const Bear = require(__dirname + '/../models/bear');
const handleError = require(__dirname + '/../lib/handle_error');
const router = module.exports = exports = require('koa-router')({
prefix: '/api'
});
var koaBody = require('koa-body')();
router.post('/bears', koaBody,
function *(next) {
this.body = yield Bear.create(this.request.body,(err, data) => {
if(err) handleError(err);
console.log(data);
});
});
router.get('/bears', function *(next) {
this.body = yield Bear.find({},(err, data) => {
if(err) handleError(err);
console.log(data);
});
});
router.put('/bears/:id', koaBody, function *(next) {
var bearData = this.request.body;
delete bearData._id;
Bear.update({_id: this.params.id}, bearData, (err, data) => {
if (err) handleError(err);
console.log(data);
});
this.body = 'success';
});
router.delete('/bears/:id', koaBody, function *(next) {
Bear.remove({_id: this.params.id}, (err, data) => {
if (err) return handleError(err);
console.log(data.result);
});
this.body = 'success';
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.