code
stringlengths 2
1.05M
|
---|
'use strict';
/*
* Defining the Package
*/
var Module = require('meanio').Module;
var Recruits = new Module('recruits');
/*
* All MEAN packages require registration
* Dependency injection is used to define required modules
*/
Recruits.register(function(app, auth, database) {
//We enable routing. By default the Package Object is passed to the routes
Recruits.routes(app, auth, database);
//We are adding a link to the main menu for all authenticated users
Recruits.menus.add({
title: 'View Recruits',
link: 'recruitsIndex',
roles: ['authenticated'],
menu: 'main'
});
Recruits.angularDependencies(['ui.validate', 'ngToast', 'ngMessages']);
Recruits.aggregateAsset('css', 'recruits.css');
Recruits.aggregateAsset('css', '../lib/ngToast/dist/ngToast.min.css', {
absolute: false,
global: true
});
Recruits.aggregateAsset('css', '../lib/ngToast/dist/ngToast-animations.min.css', {
absolute: false,
global: true
});
Recruits.aggregateAsset('js', '../lib/angular-ui-validate/dist/validate.min.js', {
absolute: false,
global: true
});
Recruits.aggregateAsset('js', '../lib/angular-messages/angular-messages.min.js', {
absolute: false,
global: true
});
Recruits.aggregateAsset('js', '../lib/ngToast/dist/ngToast.min.js', {
absolute: false,
global: true
});
Recruits.aggregateAsset('js', '../lib/zeroclipboard/dist/ZeroClipboard.js', {
absolute: false,
global: true
});
return Recruits;
});
|
'use strict';
var path = require('path');
var fs = require('fs');
var errorHandler = require('errorhandler');
var logger = require('@bicjs/bic-logger').get('routers/web');
var bic = require('@bicjs/bic');
var cfg = bic.config.getAll();
var template = require('../template');
var pageNames = [];
// Get the name of each page to check for 404s.
pageNames = fs
.readdirSync(cfg.dir.pages)
.filter(function(file) {
// https://stackoverflow.com/questions/8905680/nodejs-check-for-hidden-files
if ((/(^|.\/)\.+[^\/\.]/g).test(file) === false) {
return fs.statSync(path.join(cfg.dir.projectRoot, cfg.dir.pages, file)).isDirectory();
}
});
module.exports = function(express, sendOptions) {
var router = express.Router();
// Index Page
router.get('/', function(req, res) {
res.cacheControl(sendOptions);
res.send(template('', req));
});
// Static Page
router.get('/:page', function(req, res, next) {
logger.info('Page', req.params.page);
if (pageNames.indexOf(req.params.page) > -1) {
res.cacheControl(sendOptions);
res.send(template(req.params.page, req));
} else {
next();
}
});
// CMS Page
router.get('/:page/:id', function(req, res, next) {
var cmsPageDataKey = path.join(req.params.page, req.params.id);
if (cfg.model.cms.active.pages[cmsPageDataKey]) {
res.cacheControl(sendOptions);
res.send(template(path.join(req.params.page, 'template'), req, cmsPageDataKey));
} else {
next();
}
});
router.use(function(req, res) {
res.status(404).send(template('404', req));
});
// Handle errors
if (cfg.NODE_ENV === cfg.envType.DEVELOPMENT) {
router.use(errorHandler());
} else {
// Express requires the `next` parameter to be there even if it's not used.
// Without it, this middleware won't be used as an error handler.
router.use(function(err, req, res, next) {// jshint ignore:line
logger.error(err.stack);
res.status(500).send(template('500', req));
});
}
return router;
};
|
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import actions from 'components/modal-share/modal-share-actions';
import Component from './share-button-component';
export default withRouter(connect(null, actions)(Component));
|
version https://git-lfs.github.com/spec/v1
oid sha256:5151413f0c21a6b1fa730b459d7b2cc3ef9aafaa23d4512a11812c3d34ce6250
size 17841
|
'use strict';
class ListNode {
constructor(value, next) {
this._value = value;
this._next = next;
}
get value() {
return this._value;
}
set value(val) {
this._value = val;
}
get next() {
return this._next;
}
set next(val) {
this._next = val;
}
}
class LinkedList {
/* globals Symbol */
constructor() {
this._length = 0;
this._first = null;
this._last = null;
}
append(...values) {
if (!values.length) {
throw 'At least one item to append must be provided!';
}
if (!this._first) {
this._initialize(values[0]);
values.splice(0, 1);
}
for (let i = 0, len = values.length; i < len; i += 1) {
let nodeToApend = new ListNode(values[i], null);
if (!this._first.next) {
this._first.next = nodeToApend;
} else {
this._last.next = nodeToApend;
}
this._last = nodeToApend;
this._length += 1;
}
return this;
}
prepend(...values) {
if (!values.length) {
throw 'At least one item to prepend must be provided.';
}
if (!this._first) {
this._initialize(values[values.length - 1]);
values.splice(values.length - 1, 1);
}
for (let i = values.length - 1; i >= 0; i -= 1) {
let nodeToPrepend = new ListNode(values[i], this._first);
this._first = nodeToPrepend;
this._length += 1;
}
return this;
}
insert(index, ...values) {
if (!values.length) {
throw 'At least one item to insert must be provided';
}
if (index > this._length + 1) {
throw 'Insert index cannot be greater than the LinkedList length';
} else if (index < 0) {
throw 'Insert index cannot be negative';
}
if (!this._first) {
this._initialize(values[values.length - 1]);
values.splice(values.length - 1, 1);
}
for (let i = values.length - 1; i >= 0; i -= 1) {
let nodeBeforeIndex, nodeAfterIndex;
if (index === 0) {
nodeBeforeIndex = null;
nodeAfterIndex = this._first;
} else {
nodeBeforeIndex = this._getElementAt(index - 1);
nodeAfterIndex = nodeBeforeIndex.next;
}
let nodeToInsert = new ListNode(values[i], nodeAfterIndex);
if (!nodeAfterIndex) {
this._last = nodeToInsert;
}
if (nodeBeforeIndex) {
nodeBeforeIndex.next = nodeToInsert;
} else {
this._first = nodeToInsert;
}
this._length += 1;
}
return this;
}
at(index, value) {
if (typeof index === 'undefined' && typeof value === 'undefined') {
throw 'All required parameters must be provided (index[, value])';
} else if (index < 0 || index > this._length - 1) {
throw 'Index out of range';
}
let elementAtIndex = this._getElementAt(index);
if (typeof value === 'undefined') {
return elementAtIndex.value;
} else {
elementAtIndex.value = value;
}
}
removeAt(index) {
if (index < 0 || index > this.length - 1) {
throw 'Index out of range';
}
let elementAtIndex = this._getElementAt(index);
if (this._length === 1) {
this._first = null;
} else {
let elementBeforeIndex = this._getElementAt(index - 1),
elementAfterIndex = this._getElementAt(index + 1);
if (!elementBeforeIndex) {
this._first = elementAfterIndex;
} else if (!elementAfterIndex) {
elementBeforeIndex.next = null;
this._last = elementBeforeIndex;
} else {
elementBeforeIndex.next = elementAfterIndex;
}
}
this._length -= 1;
return elementAtIndex.value;
}
toString() {
let values = this.toArray(),
valuesAsString = values.join(' -> ');
return valuesAsString;
}
toArray() {
let values = [];
for (let value of this) {
values.push(value);
}
return values;
}
_initialize(value) {
let node = new ListNode(value, null);
this._first = node;
this._last = node;
this._length += 1;
}
_getElementAt(index) {
if (index < 0 || index > this._length - 1) {
return null;
}
let currentNode = this._first;
for (let i = 0; i < index; i += 1) {
currentNode = currentNode.next;
}
return currentNode;
}
get length() {
return this._length;
}
get first() {
if (!this._first) {
return null;
}
return this._first.value;
}
get last() {
if (!this._last) {
return null;
}
return this._last.value;
}
*[Symbol.iterator]() {
let currentNode = this._first;
while (currentNode) {
yield currentNode.value;
currentNode = currentNode.next;
}
}
}
module.exports = LinkedList;
|
// flow-typed signature: 867a600e6b26ddfb663b6b5bb8d80bcf
// flow-typed version: <<STUB>>/redux-thunk_v2.2.0/flow_v0.41.0
/**
* This is an autogenerated libdef stub for:
*
* 'redux-thunk'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module 'redux-thunk' {
declare module.exports: any;
}
/**
* We include stubs for each file inside this npm package in case you need to
* require those files directly. Feel free to delete any files that aren't
* needed.
*/
declare module 'redux-thunk/dist/redux-thunk' {
declare module.exports: any;
}
declare module 'redux-thunk/dist/redux-thunk.min' {
declare module.exports: any;
}
declare module 'redux-thunk/es/index' {
declare module.exports: any;
}
declare module 'redux-thunk/lib/index' {
declare module.exports: any;
}
declare module 'redux-thunk/src/index' {
declare module.exports: any;
}
// Filename aliases
declare module 'redux-thunk/dist/redux-thunk.js' {
declare module.exports: $Exports<'redux-thunk/dist/redux-thunk'>;
}
declare module 'redux-thunk/dist/redux-thunk.min.js' {
declare module.exports: $Exports<'redux-thunk/dist/redux-thunk.min'>;
}
declare module 'redux-thunk/es/index.js' {
declare module.exports: $Exports<'redux-thunk/es/index'>;
}
declare module 'redux-thunk/lib/index.js' {
declare module.exports: $Exports<'redux-thunk/lib/index'>;
}
declare module 'redux-thunk/src/index.js' {
declare module.exports: $Exports<'redux-thunk/src/index'>;
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Axis = require('./Axis');
var _Axis2 = _interopRequireDefault(_Axis);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var AxisBottom = function (_Component) {
_inherits(AxisBottom, _Component);
function AxisBottom() {
_classCallCheck(this, AxisBottom);
return _possibleConstructorReturn(this, (AxisBottom.__proto__ || Object.getPrototypeOf(AxisBottom)).apply(this, arguments));
}
_createClass(AxisBottom, [{
key: 'render',
value: function render() {
return _react2.default.createElement(_Axis2.default, _extends({}, this.props, { placement: 'bottom' }));
}
}]);
return AxisBottom;
}(_react.Component);
exports.default = AxisBottom;
|
var isFunction = require('./isFunction')
module.exports = function isNativeCode (input) {
return isFunction(input) && input.toString().indexOf('{ [native code] }') > -1
}
|
import React from 'react'
import {Grid, Row, Col} from 'react-bootstrap'
import Topbar from '../../components/top-bar/top-bar'
import Footer from '../../components/footer/footer'
export default class AboutUS extends React.Component {
render() {
const style = require('./about-us.scss');
return (
<div>
<div>
<Topbar />
<Grid>
<Row>
<Col md={12}>
<h2>About Us</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisici elit,
sed eiusmod tempor incidunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud</p>
</Col>
</Row>
</Grid>
</div>
<Footer />
</div>
)
}
}
|
var gulp = require("gulp");
var plugins = {};
var config = {};
function copy(src, dest) {
return gulp.src(src)
.pipe(gulp.dest(dest));
}
module.exports = function (callback) {
plugins = this.opts.plugins;
config = this.opts.config;
plugins.runSequence(
"copy:scripts:app",
"copy:scripts:common",
"copy:scripts:main",
"copy:scripts:services",
"copy:scripts:startpage",
callback
);
};
gulp.task("copy:scripts:app", () => {
return copy([config.build.app.js, `!${config.build.app.spec}`], config.wwwroot.app.path);
});
gulp.task("copy:scripts:common", () => {
return copy([config.build.common.js, `!${config.build.common.spec}`], config.wwwroot.common.path);
});
gulp.task("copy:scripts:main", () => {
return copy([config.build.main.js, `!${config.build.main.spec}`], config.wwwroot.main.path);
});
gulp.task("copy:scripts:services", () => {
return copy([config.build.services.js, `!${config.build.services.spec}`], config.wwwroot.services.path);
});
gulp.task("copy:scripts:startpage", () => {
return copy([config.build.startpage.js, `!${config.build.startpage.spec}`], config.wwwroot.startpage.path);
});
|
// test/setup.js
Agent.create();
// test/fixture/posts.js
var postIds = Agent.instance.makeIds('posts', 2);
Agent.instance.group('posts', function() {
var commentIds = Agent.instance.getIds('comments');
this.fixture(postIds[1], {
title: 'Title 1',
body: 'Body content.',
comments: [commentIds[1], commentIds[2]]
});
this.fixture(postIds[2], {
title: 'Title 2',
body: 'Body content.',
comments: [commentIds[3], commentIds[4]]
});
});
// test/fixture/comments.js
var commentIds = Agent.instance.makeIds('comments', 4);
Agent.instance.group('comments', function() {
var postIds = Agent.instance.getIds('posts');
this.fixture(commentIds[1], {
body: 'Comment content 1.',
post: postIds[1]
});
this.fixture(commentIds[2], {
body: 'Comment content 2.',
post: postIds[1]
});
this.fixture(commentIds[3], {
body: 'Comment content 3.',
post: postIds[2]
});
this.fixture(commentIds[4], {
body: 'Comment content 4.',
post: postIds[2]
});
});
// test/server.js
function jsonResponse(str) {
return [200, { "Content-Type": "application/json" }, str];
}
function toArray(obj) {
var arr = [], i;
for i in obj {
if (obj.hasOwnProperty(i)) { arr.push(obj[i]); }
}
}
Agent.instance.build();
Agent.instance.server(function(agent) {
this.get('/users', function() {
var obj = { users: toArray(agent.fixtures('users')) };
return jsonResponse(JSON.stringify(obj));
});
this.get('/users/:id', function() {
var obj = { users: [agent.fixtures('users')[this.params.id]] };
return jsonResponse(JSON.stringify(obj));
});
});
|
/**
* Created by mitch on 2014-03-31.
*/
var express = require('express');
var server = express();
server.use(express.static(__dirname + "/app"));
var port = process.env.PORT || 8000;
server.listen(port, function () {
console.log("Listening on port " + port)
});
|
_bb10_toggle = {
apply: function(elements) {
for (var i = 0; i < elements.length; i++) {
bb.toggle.style(elements[i],true);
}
},
style: function(outerElement,offdom) {
var table,
tr,
td,
color = bb.screen.controlColor;
outerElement.checked = false;
outerElement.enabled = true;
outerElement.buffer = (bb.device.is1024x600) ? 35 : 70;
outerElement.isActivated = false;
outerElement.initialXPos = 0;
outerElement.currentXPos = 0;
outerElement.transientXPos = 0;
outerElement.movedWithSlider = false;
outerElement.startValue = false;
// See if the toggle button is disabled
if (outerElement.hasAttribute('data-bb-disabled')) {
outerElement.enabled = !(outerElement.getAttribute('data-bb-disabled').toLowerCase() == 'true');
}
// Set our styling and create the inner divs
outerElement.className = 'bb-toggle';
outerElement.outer = document.createElement('div');
if (outerElement.enabled) {
if (bb.device.newerThan10dot1) {
outerElement.normal = 'outer bb-toggle-outer-'+ color +'-10dot2 bb-toggle-outer-enabled-'+color;
} else {
outerElement.normal = 'outer bb-toggle-outer-'+color + ' bb-toggle-outer-enabled-'+color;
}
} else {
outerElement.normal = 'outer bb-toggle-outer-'+color + ' bb-toggle-outer-disabled';
}
outerElement.outer.setAttribute('class',outerElement.normal);
outerElement.appendChild(outerElement.outer);
outerElement.fill = document.createElement('div');
outerElement.fill.className = 'fill';
outerElement.fill.style.background = outerElement.fill.dormant;
outerElement.outer.appendChild(outerElement.fill);
// Our inner area that will contain the text
outerElement.inner = document.createElement('div');
outerElement.inner.className = 'inner';
outerElement.inner.outerElement = outerElement;
outerElement.fill.appendChild(outerElement.inner);
// Create our table holder for the captions
table = document.createElement('table');
table.className = 'table';
tr = document.createElement('tr');
table.appendChild(tr);
outerElement.inner.appendChild(table);
// The yes option
td = document.createElement('td');
td.className = 'left';
tr.appendChild(td);
outerElement.yes = document.createElement('div');
outerElement.yes.className = 'yes';
outerElement.yes.innerHTML = outerElement.getAttribute('data-bb-on');
td.appendChild(outerElement.yes);
// Center section where the indicator will hover over
td = document.createElement('td');
td.className = 'center';
tr.appendChild(td);
// The no option
td = document.createElement('td');
td.className = 'right';
tr.appendChild(td);
outerElement.no = document.createElement('div');
outerElement.no.className = 'no';
outerElement.no.innerHTML = outerElement.getAttribute('data-bb-off');
td.appendChild(outerElement.no);
// Indicator container
outerElement.container = document.createElement('div');
outerElement.container.className = 'indicator-container';
outerElement.appendChild(outerElement.container);
// Create the Halo
outerElement.halo = document.createElement('div');
outerElement.halo.className = 'halo';
outerElement.halo.style.background = '-webkit-gradient(radial, 50% 50%, 0, 50% 50%, 43, from(rgba('+ bb.options.shades.R +', '+ bb.options.shades.G +', '+ bb.options.shades.B +', 0.15)), color-stop(0.8, rgba('+ bb.options.shades.R +', '+ bb.options.shades.G +', '+ bb.options.shades.B +', 0.15)), to(rgba('+ bb.options.shades.R +', '+ bb.options.shades.G +', '+ bb.options.shades.B +', 0.7)))';
outerElement.container.appendChild(outerElement.halo);
// Create the indicator
outerElement.indicator = document.createElement('div');
if (outerElement.enabled) {
outerElement.indicator.normal = 'indicator bb-toggle-indicator-enabled-' + color;
} else {
outerElement.indicator.normal = 'indicator bb-toggle-indicator-disabled-' + color;
}
outerElement.indicator.setAttribute('class',outerElement.indicator.normal);
outerElement.container.appendChild(outerElement.indicator);
// Get our onchange event if any
if (outerElement.hasAttribute('onchange')) {
outerElement.onchangeEval = outerElement.getAttribute('onchange');
outerElement.onchange = function() {
eval(this.onchangeEval);
};
}
// Setup our touch events
outerElement.inner.animateBegin = function(event) {
if (!this.outerElement.enabled) return;
if (this.outerElement.isActivated === false) {
this.outerElement.startValue = this.outerElement.checked;
this.outerElement.movedWithSlider = false;
this.outerElement.isActivated = true;
this.outerElement.initialXPos = event.touches[0].pageX;
this.outerElement.halo.style['-webkit-transform'] = 'scale(1)';
this.outerElement.halo.style['-webkit-animation-name'] = 'explode';
this.outerElement.indicator.setAttribute('class','indicator bb-toggle-indicator-enabled-' + color+ ' indicator-hover-'+color);
this.outerElement.indicator.style.background = '-webkit-linear-gradient(top, rgb('+ bb.options.shades.R +', '+ bb.options.shades.G +', '+ bb.options.shades.B +') 0%, rgb('+ (bb.options.shades.R + 16) +', '+ (bb.options.shades.G + 16) +', '+ (bb.options.shades.B + 16) +') 100%)';
}
};
outerElement.inner.animateBegin = outerElement.inner.animateBegin.bind(outerElement.inner);
outerElement.inner.addEventListener("touchstart", outerElement.inner.animateBegin, false);
outerElement.container.addEventListener("touchstart", outerElement.inner.animateBegin, false);
outerElement.inner.animateEnd = function () {
if (!this.outerElement.enabled) return;
if (this.outerElement.isActivated === true) {
this.outerElement.isActivated = false;
this.outerElement.currentXPos = this.outerElement.transientXPos;
this.outerElement.halo.style['-webkit-transform'] = 'scale(0)';
this.outerElement.halo.style['-webkit-animation-name'] = 'implode';
this.outerElement.indicator.setAttribute('class','indicator bb-toggle-indicator-enabled-' + color);
this.outerElement.indicator.style.background = '';
this.outerElement.positionButton();
if (this.outerElement.movedWithSlider) {
if (this.outerElement.startValue != this.outerElement.checked) {
if (this.outerElement.onchange) {
this.outerElement.onchange();
}
}
}
}
};
outerElement.inner.animateEnd = outerElement.inner.animateEnd.bind(outerElement.inner);
outerElement.addEventListener('touchend', outerElement.inner.animateEnd, false);
// Handle moving the toggle
outerElement.moveToggle = function (event) {
if (!this.enabled) return;
if (this.isActivated === true) {
this.movedWithSlider = true;
event.stopPropagation();
event.preventDefault();
var endPos = parseInt(window.getComputedStyle(this.fill).width) - this.buffer,
percent;
this.transientXPos = this.currentXPos + event.touches[0].pageX - this.initialXPos;
this.transientXPos = Math.max(0, Math.min(this.transientXPos, endPos));
this.inner.style['-webkit-transform'] = 'translate3d(' + this.transientXPos + 'px,0px,0px)';
this.container.style['-webkit-transform'] = 'translate3d(' + this.transientXPos + 'px,0px,0px)';
// Set our checked state
percent = this.transientXPos/endPos;
this.checked = (percent > 0.5);
}
};
outerElement.moveToggle = outerElement.moveToggle.bind(outerElement);
// Handle the click of a toggle
outerElement.doClick = function() {
if (!this.enabled) return;
if (!this.movedWithSlider) {
this.setChecked(!this.checked);
}
};
outerElement.doClick = outerElement.doClick.bind(outerElement);
outerElement.addEventListener('click', outerElement.doClick, false);
// Position the button
outerElement.positionButton = function() {
var location = (this.checked) ? parseInt(window.getComputedStyle(this.fill).width) - this.buffer : 0;
// Set our animations
this.inner.style['-webkit-transform'] = 'translate3d(' + location + 'px,0px,0px)';
this.inner.style['-webkit-transition-duration'] = '0.1s';
this.inner.style['-webkit-transition-timing-function'] = 'linear';
this.inner.addEventListener('webkitTransitionEnd', function() {
this.style['-webkit-transition'] = '';
});
this.container.style['-webkit-transform'] = 'translate3d(' + location + 'px,0px,0px)';
this.container.style['-webkit-transition-duration'] = '0.1s';
this.container.style['-webkit-transition-timing-function'] = 'linear';
this.container.addEventListener('webkitTransitionEnd', function() {
this.style['-webkit-transition'] = '';
});
if (this.checked && this.enabled) {
this.indicator.style['background-image'] = '-webkit-linear-gradient(top, '+ bb.options.highlightColor +' 0%, '+ bb.options.shades.darkHighlight +' 100%)';
} else {
this.indicator.style['background-image'] = '';
}
this.currentXPos = location;
};
outerElement.positionButton = outerElement.positionButton.bind(outerElement);
// Add our setChecked function
outerElement.setChecked = function(value) {
if (value != this.checked) {
this.checked = value;
if (this.onchange) {
this.onchange();
}
}
this.positionButton();
};
outerElement.setChecked = outerElement.setChecked.bind(outerElement);
// Add our getChecked function
outerElement.getChecked = function() {
return this.checked;
};
outerElement.getChecked = outerElement.getChecked.bind(outerElement);
// Add our show function
outerElement.show = function() {
this.style.display = 'block';
bb.refresh();
};
outerElement.show = outerElement.show.bind(outerElement);
// Add our hide function
outerElement.hide = function() {
this.style.display = 'none';
bb.refresh();
};
outerElement.hide = outerElement.hide.bind(outerElement);
// Add remove function
outerElement.remove = function() {
this.parentNode.removeChild(this);
bb.refresh();
};
outerElement.remove = outerElement.remove.bind(outerElement);
// Add setOnCaption function
outerElement.setOnCaption = function(value) {
this.yes.innerHTML = value;
};
outerElement.setOnCaption = outerElement.setOnCaption.bind(outerElement);
// Add setOffCaption function
outerElement.setOffCaption = function(value) {
this.no.innerHTML = value;
};
outerElement.setOffCaption = outerElement.setOffCaption.bind(outerElement);
// Add getOnCaption function
outerElement.getOnCaption = function() {
return this.yes.innerHTML;
};
outerElement.getOnCaption = outerElement.getOnCaption.bind(outerElement);
// Add getOffCaption function
outerElement.getOffCaption = function() {
return this.no.innerHTML;
};
outerElement.getOffCaption = outerElement.getOffCaption.bind(outerElement);
// Add enable function
outerElement.enable = function() {
if (this.enabled) return;
this.enabled = true;
// change our styles
this.indicator.normal = 'indicator bb-toggle-indicator-enabled-' + color;
this.indicator.setAttribute('class',this.indicator.normal);
if (bb.device.newerThan10dot1) {
this.normal = 'outer bb-toggle-outer-'+ color +'-10dot2 bb-toggle-outer-enabled-'+color;
} else {
this.normal = 'outer bb-toggle-outer-'+color + ' bb-toggle-outer-enabled-'+color;
}
this.outer.setAttribute('class',this.normal);
// update the button
this.positionButton();
};
outerElement.enable = outerElement.enable.bind(outerElement);
// Add disable function
outerElement.disable = function() {
if (!this.enabled) return;
this.enabled = false;
// change our styles
this.indicator.normal = 'indicator bb-toggle-indicator-disabled-' + color;
this.indicator.setAttribute('class',this.indicator.normal);
this.normal = 'outer bb-toggle-outer-'+color + ' bb-toggle-outer-disabled';
this.outer.setAttribute('class',this.normal);
// Update the button
this.positionButton();
};
outerElement.disable = outerElement.disable.bind(outerElement);
// set our checked state
outerElement.checked = (outerElement.hasAttribute('data-bb-checked')) ? outerElement.getAttribute('data-bb-checked').toLowerCase() == 'true' : false;
if (offdom) {
// Create our event handler for when the dom is ready
outerElement.onbbuidomready = function() {
this.positionButton();
document.removeEventListener('bbuidomready', this.onbbuidomready,false);
};
outerElement.onbbuidomready = outerElement.onbbuidomready.bind(outerElement);
/* Add our event listener for the domready to move our selected item. We want to
do it this way because it will ensure the screen transition animation is finished before
the toggle button move transition happens. This will help for any animation stalls/delays */
document.addEventListener('bbuidomready', outerElement.onbbuidomready,false);
} else {
// Use a simple timeout to trigger the animation once inserted into the DOM
setTimeout(outerElement.positionButton,0);
}
// Assign our document event listeners
document.addEventListener('touchmove', outerElement.moveToggle, false);
bb.documentListeners.push({name: 'touchmove', eventHandler: outerElement.moveToggle});
document.addEventListener('touchend', outerElement.inner.animateEnd, false);
bb.documentListeners.push({name: 'touchend', eventHandler: outerElement.inner.animateEnd});
return outerElement;
}
};
|
import makeActionCreator from 'utils/makeActionCreator';
export const UPDATE_LOGIN_MODAL_VISIBILITY = 'UPDATE_LOGIN_MODAL_VISIBILITY';
export const UPDATE_USER_LOGGED_STATUS = 'UPDATE_USER_LOGGED_STATUS';
export const UPDATE_BACK_END_AUTH_SUPPORT = 'UPDATE_BACK_END_AUTH_SUPPORT';
export const UPDATE_LOGGED_USERNAME = 'UPDATE_LOGGED_USERNAME';
export const updateLoginModalVisibilility =
makeActionCreator(UPDATE_LOGIN_MODAL_VISIBILITY, 'isModalVisible');
export const updateUserLoggedStatus =
makeActionCreator(UPDATE_USER_LOGGED_STATUS, 'isUserLoggedIn');
export const updateBackEndAuthSupport =
makeActionCreator(UPDATE_BACK_END_AUTH_SUPPORT, 'isEndUserAuthSupported');
export const updateLoggedUsername =
makeActionCreator(UPDATE_LOGGED_USERNAME, 'username');
|
#!/usr/bin/env node
module.exports = function(context) {
var fs = context.requireCordovaModule('fs'),
path = context.requireCordovaModule('path');
var platformRoot = path.join(context.opts.projectRoot, 'platforms/android');
var manifestFile = path.join(platformRoot, 'AndroidManifest.xml');
if (fs.existsSync(manifestFile)) {
fs.readFile(manifestFile, 'utf8', function (err,data) {
if (err) {
throw new Error('Unable to find AndroidManifest.xml: ' + err);
}
var result;
if (!(/<application[^>]*\bandroid:isGame="true"/).test(data)) {
result = data.replace(/<application/g, '<application android:isGame="true"');
}
else {
result = data;
}
fs.writeFile(manifestFile, result, 'utf8', function (err) {
if (err) throw new Error('Unable to write into AndroidManifest.xml: ' + err);
})
});
}
};
|
var classHelix_1_1Logic_1_1dev_1_1ProjectDataTest =
[
[ "ProjectDataTest", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#adf151731e2b95574f0d386a52320f6d6", null ],
[ "ProjectDataTest", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a0f8be0f4f9e3333ff9fec292568beb34", null ],
[ "~ProjectDataTest", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a58c69c1bffb4b87681e03e6ee41dd9c7", null ],
[ "compareLists", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#ae4f43f3b867ccacf0c9207cd7c5cb979", null ],
[ "compareObjects", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#aebb402c0fe2cf65524d55228225259ae", null ],
[ "deleteByID", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a804804aff89319035cfbc644c2a85495", null ],
[ "insert", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a78a35ea8c105ba3ac1c5cb3b6b1ad0f2", null ],
[ "operator=", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a4ffbe7e54591e82dec9d0f2249d3bb47", null ],
[ "runTests", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a1c652d90e085f60cd2a00a22e668d8dc", null ],
[ "selectAllForProj", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a8e80cc3a2b978137cf2928b9b10d38ed", null ],
[ "selectByID", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#aa7afc35536655c7cf28ee32eb6ee6676", null ],
[ "update", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a952ebbbb50f93c4fd75ecddc257d7f22", null ],
[ "reg", "classHelix_1_1Logic_1_1dev_1_1ProjectDataTest.html#a3e526140509a60ee213f9df2cca64b42", null ]
];
|
(function(module) {
var password = 'accessGranted';
var passAtempts = 0;
var access = false;
$('#password-input').focus();
$('#password-input').on('keydown', function(enter) {
if(enter.which === 13) {
if($('#password-input').val() === password) {
$('.password').hide();
$('.contentDiv').show();
console.log('works');
} else {
$('#password-input').val('');
++passAtempts;
}
if(passAtempts > 4) {
$('.password').remove('password-input').append('<p></p>').text('You have tried to many times to access the admin page.');
}
}
});
editAboutME();
function editAboutME() {
var $aboutMeEdit = $('#about-me-edit');
$aboutMeEdit.val(module.AboutMeObj.biography);
$('#submit-about-me').on('click', function(enter) {
console.log('about me updated');
module.AboutMeObj.biography = $aboutMeEdit.val();
});
}
})(window);
|
(function() {
define(['jquery', 'backbone', 'mustache', 'text!javascripts/template/base.js.html'], function($, Backbone, Mustache, baseTemplate) {
return Backbone.View.extend({
initialize: function(options) {
options = options || {};
this.template = baseTemplate;
return this.app = options.app || {};
},
render: function() {
var rendered;
rendered = Mustache.to_html(this.template, {});
$(this.el).html(rendered);
return this;
},
events: {
"click a": "handleClick"
},
handleClick: function(e) {
var $target, type;
$target = $(e.target);
type = $target.data('type');
if (type === "app-page") {
this.app.navigate($target.attr('href'), {
trigger: true
});
return e.preventDefault();
}
}
});
});
}).call(this);
|
'use strict'
function resolveStringValues(strings, values) {
let resolved = ''
strings.forEach((string, index) => {
resolved += string
if (values.length > index) {
const value = values[ index ]
if (typeof value === 'function') {
throw new Error(`Functions are not supported (value #${index}).`)
}
else if (typeof value === 'object') {
resolved += `###VALUE:${index}###`
}
else {
resolved += JSON.stringify(value)
}
}
})
return resolved
}
function parseAtomicValue(value) {
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith('\'') && value.endsWith('\''))) {
return value.substr(1, value.length - 2)
}
else if (value.match(/^[0-9]*(\.[0-9]+)?$/)) {
return parseFloat(value)
}
else {
return value
}
}
function parseAtomicRule(line, styleObject) {
const colonIndex = line.indexOf(':')
const key = line.substring(0, colonIndex).trim()
const value = line.substr(colonIndex + 1).trim()
styleObject[ key ] = parseAtomicValue(value)
}
function parseSelector(line) {
return line.replace(/\{$/, '').trim()
}
function parseJCSSLine(line, styleObjectStack, values) {
line = line.replace(/;+$/, '').trim()
if (!line) { return }
const styleObject = styleObjectStack[ styleObjectStack.length - 1 ]
if (line.match(/(###VALUE:([0-9]+)###)/)) {
if (line.length > RegExp.$1.length) {
throw new Error('No other statements than the object expression allowed on one line.')
}
const value = values[ parseInt(RegExp.$2, 10) ]
Object.assign(styleObject, value)
}
else if (line.match(/^[a-z0-9-]+\s*:/i)) {
parseAtomicRule(line, styleObject)
}
else if (line.match(/\{/)) {
const selector = parseSelector(line)
const newNestedStyle = {}
styleObject[ selector ] = newNestedStyle
styleObjectStack.push(newNestedStyle)
}
else if (line === '}') {
styleObjectStack.pop()
if (styleObjectStack.length === 0) {
throw new Error('Too many closing curly braces.')
}
}
else {
throw new Error(`Cannot parse line: "${line}"`)
}
}
function parseJCSS(jcssString, values) {
if (jcssString.startsWith('\n')) {
// Strip leading line break to align the line no. with the developer's expectation
jcssString = jcssString.substr(1)
}
const styleObjectStack = [ {} ]
const lines = jcssString.split('\n')
lines.forEach((line, lineIndex) => {
try {
parseJCSSLine(line, styleObjectStack, values)
} catch (error) {
error.message += ` (Style line ${lineIndex + 1})`
throw error
}
})
if (styleObjectStack.length > 1) {
throw new Error('Expected closing curly braces.')
}
return styleObjectStack[ 0 ]
}
/**
* Usage: style`
* background: white
* color: ${colors.text}
*
* :hover {
* text-decoration: underline
* }
* `
*/
function style(strings, ...values) {
const stringValuesResolved = resolveStringValues(strings, values)
return parseJCSS(stringValuesResolved, values)
}
module.exports = style
|
const Config = {
LOAD_LIVE_DATA: false
};
export default Config;
|
import curryN from 'funny-curry-n'
import fold from 'funny-fold'
/**
* Reduce applies a function to an accumulator and each value of an array (from
* left-to-right), reducing it to a single value.
*
* @param {Function} reducer Reducer function.
* @param {Array} list List to reduce.
* @return {*} Accumulated value.
*/
function _reduce (reducer, list) {
let [acc, ...rest] = list
return fold((acc, item, index, list) => reducer(acc, item, index + 1, list), acc, rest)
}
const reduce = curryN(2, _reduce)
export default reduce
|
var should = require('should');
describe('Battle', function() {
it('should test the player battling');
})
|
const assign = require('../util/assign');
module.exports = request => {
const Order = {
name: 'Order',
path: 'orders',
authenticate: function() {
return request(assign(Order._authenticate(), { args: Array.prototype.slice.call(arguments) }));
},
cancelForMe: function() {
return request(assign(Order._cancelForMe(), { args: Array.prototype.slice.call(arguments) }));
},
cancelRefundForMe: function() {
return request(assign(Order._cancelRefundForMe(), { args: Array.prototype.slice.call(arguments) }));
},
countForMe: function() {
return request(assign(Order._countForMe(), { args: Array.prototype.slice.call(arguments) }));
},
createDownloadUrlForMe: function() {
return request(assign(Order._createDownloadUrlForMe(), { args: Array.prototype.slice.call(arguments) }));
},
getForMe: function() {
return request(assign(Order._getForMe(), { args: Array.prototype.slice.call(arguments) }));
},
listBySubscriptionForMe: function() {
return request(assign(Order._listBySubscriptionForMe(), { args: Array.prototype.slice.call(arguments) }));
},
listForMe: function() {
return request(assign(Order._listForMe(), { args: Array.prototype.slice.call(arguments) }));
},
markAsNotReceivedForMe: function() {
return request(assign(Order._markAsNotReceivedForMe(), { args: Array.prototype.slice.call(arguments) }));
},
markAsReceivedForMe: function() {
return request(assign(Order._markAsReceivedForMe(), { args: Array.prototype.slice.call(arguments) }));
},
requestRefundForMe: function() {
return request(assign(Order._requestRefundForMe(), { args: Array.prototype.slice.call(arguments) }));
},
updateCancellationForMe: function() {
return request(assign(Order._updateCancellationForMe(), { args: Array.prototype.slice.call(arguments) }));
},
updateForMe: function() {
return request(assign(Order._updateForMe(), { args: Array.prototype.slice.call(arguments) }));
},
updateRefundCancellationForMe: function() {
return request(assign(Order._updateRefundCancellationForMe(), { args: Array.prototype.slice.call(arguments) }));
},
updateRefundForMe: function() {
return request(assign(Order._updateRefundForMe(), { args: Array.prototype.slice.call(arguments) }));
},
updateTransactionsForMe: function() {
return request(assign(Order._updateTransactionsForMe(), { args: Array.prototype.slice.call(arguments) }));
},
};
Order._authenticate = function() {
return {
modelName: Order.name,
methodName: 'authenticate',
httpMethod: 'POST',
path: '/v1/orders/{orderId}/auth',
params: ['orderId', ],
};
};
Order._cancelForMe = function() {
return {
modelName: Order.name,
methodName: 'cancelForMe',
httpMethod: 'POST',
path: '/v1/me/orders/{orderId}/cancellation',
params: ['orderId', ],
};
};
Order._cancelRefundForMe = function() {
return {
modelName: Order.name,
methodName: 'cancelRefundForMe',
httpMethod: 'POST',
path: '/v1/me/orders/{orderId}/refunds/{refundId}/cancellation',
params: ['orderId', 'refundId', ],
};
};
Order._countForMe = function() {
return {
modelName: Order.name,
methodName: 'countForMe',
httpMethod: 'GET',
path: '/v1/me/orders/count',
params: [],
};
};
Order._createDownloadUrlForMe = function() {
return {
modelName: Order.name,
methodName: 'createDownloadUrlForMe',
httpMethod: 'POST',
path: '/v1/me/orders/{orderId}/items/{itemId}/download/url',
params: ['orderId', 'itemId', ],
withoutPayload: true,
};
};
Order._getForMe = function() {
return {
modelName: Order.name,
methodName: 'getForMe',
httpMethod: 'GET',
path: '/v1/me/orders/{orderId}',
params: ['orderId', ],
};
};
Order._listBySubscriptionForMe = function() {
return {
modelName: Order.name,
methodName: 'listBySubscriptionForMe',
httpMethod: 'GET',
path: '/v1/me/subscriptions/{subscriptionId}/orders',
params: ['subscriptionId', ],
};
};
Order._listForMe = function() {
return {
modelName: Order.name,
methodName: 'listForMe',
httpMethod: 'GET',
path: '/v1/me/orders',
params: [],
};
};
Order._markAsNotReceivedForMe = function() {
return {
modelName: Order.name,
methodName: 'markAsNotReceivedForMe',
httpMethod: 'DELETE',
path: '/v1/me/orders/{orderId}/received',
params: ['orderId', ],
};
};
Order._markAsReceivedForMe = function() {
return {
modelName: Order.name,
methodName: 'markAsReceivedForMe',
httpMethod: 'POST',
path: '/v1/me/orders/{orderId}/received',
params: ['orderId', ],
withoutPayload: true,
};
};
Order._requestRefundForMe = function() {
return {
modelName: Order.name,
methodName: 'requestRefundForMe',
httpMethod: 'POST',
path: '/v1/me/orders/{orderId}/refunds',
params: ['orderId', ],
};
};
Order._updateCancellationForMe = function() {
return {
modelName: Order.name,
methodName: 'updateCancellationForMe',
httpMethod: 'PUT',
path: '/v1/me/orders/{orderId}/cancellation',
params: ['orderId', ],
};
};
Order._updateForMe = function() {
return {
modelName: Order.name,
methodName: 'updateForMe',
httpMethod: 'PUT',
path: '/v1/me/orders/{orderId}',
params: ['orderId', ],
};
};
Order._updateRefundCancellationForMe = function() {
return {
modelName: Order.name,
methodName: 'updateRefundCancellationForMe',
httpMethod: 'PUT',
path: '/v1/me/orders/{orderId}/refunds/{refundId}/cancellation',
params: ['orderId', 'refundId', ],
};
};
Order._updateRefundForMe = function() {
return {
modelName: Order.name,
methodName: 'updateRefundForMe',
httpMethod: 'PUT',
path: '/v1/me/orders/{orderId}/refunds/{refundId}',
params: ['orderId', 'refundId', ],
};
};
Order._updateTransactionsForMe = function() {
return {
modelName: Order.name,
methodName: 'updateTransactionsForMe',
httpMethod: 'PUT',
path: '/v1/me/orders/{orderId}/transactions',
params: ['orderId', ],
withoutPayload: true,
};
};
return Order;
};
|
var gulp = require('gulp'),
util = require('gulp-util'),
ts = require('gulp-typescript'),
tslint = require('gulp-tslint'),
gulpprint = require('gulp-print'),
sourcemaps = require('gulp-sourcemaps'),
gulpprint = require('gulp-print');
var config = require('../config')();
var tsProject = ts.createProject('src/tsconfig.json');
var tsFiles = config.src.tsFiles; //[].concat(config.tsFiles, tsUnitFiles, tsE2EFiles);
// TypeScript compile
gulp.task('ts', ['clean-ts'], function () {
return compileTs(tsFiles);
});
gulp.task('tslint', function () {
util.log('Running tslint...');
return gulp.src(tsFiles, { cwd: config.src.app })
.pipe(tslint({
formatter: 'verbose'
}))
.pipe(gulpprint())
.pipe(tslint.report({
summarizeFailureOutput: true,
emitError: true
}));
});
/* Watch changed typescripts file and compile it */
gulp.task('watch.ts', function () {
return gulp.watch(tsFiles, { cwd: config.src.app }, function (file) {
util.log('Compiling ' + file.path + '...');
return compileTs(file.path, true);
});
});
function compileTs(files, watchMode) {
watchMode = watchMode || false;
var srcOptions = {};
//a fix, because it works in different way when ('gulp build', 'gulp rebuild') and 'gulp watch'
if (watchMode === true) {
srcOptions.base = config.src.app;
}
else {
srcOptions.cwd = config.src.app;
}
var allFiles = files; //[].concat(files, typingFiles);
var res = gulp.src(allFiles, srcOptions)
.pipe(tslint({
formatter: 'verbose'
}))
.pipe(gulpprint())
.pipe(tslint.report({
summarizeFailureOutput: true,
emitError: false
}))
.pipe(sourcemaps.init())
.pipe(tsProject());
// .on('error', function () {
// if (watchMode) {
// return;
// }
// process.exit(1);
// });
return res.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.dest.app));
}
|
import * as APIUtil from '../util/project_api_util';
export const RECEIVE_ERRORS = 'RECEIVE_ERRORS';
export const RECEIVE_GIF = 'RECEIVE_GIF';
export const scrapeGif = () => dispatch => (
APIUtil.scrapeGif()
.then((gif) => (dispatch(receiveGif(gif))))
.fail((errors) => (dispatch(receiveErrors(errors.responseJSON))))
);
export const receiveErrors = errors => ({
type: RECEIVE_ERRORS,
errors
});
export const receiveGif = gif => ({
type: RECEIVE_GIF,
gif
});
|
'use strict';
/**
* @ngdoc object
* @name conferenceApp
* @requires $routeProvider
* @requires conferenceControllers
* @requires ui.bootstrap
*
* @description
* Root app, which routes and specifies the partial html and controller depending on the url requested.
*
*/
var app = angular.module('conferenceApp',
['conferenceControllers', 'ngRoute', 'ui.bootstrap']).
config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/conference', {
templateUrl: '/partials/show_conferences.html',
controller: 'ShowConferenceCtrl'
}).
when('/conference/create', {
templateUrl: '/partials/create_conferences.html',
controller: 'CreateConferenceCtrl'
}).
when('/conference/detail/:websafeConferenceKey', {
templateUrl: '/partials/conference_detail.html',
controller: 'ConferenceDetailCtrl'
}).
when('/profile', {
templateUrl: '/partials/profile.html',
controller: 'MyProfileCtrl'
}).
when('/', {
templateUrl: '/partials/home.html'
}).
otherwise({
redirectTo: '/'
});
}]);
/**
* @ngdoc filter
* @name startFrom
*
* @description
* A filter that extracts an array from the specific index.
*
*/
app.filter('startFrom', function () {
/**
* Extracts an array from the specific index.
*
* @param {Array} data
* @param {Integer} start
* @returns {Array|*}
*/
var filter = function (data, start) {
return data.slice(start);
}
return filter;
});
/**
* @ngdoc constant
* @name HTTP_ERRORS
*
* @description
* Holds the constants that represent HTTP error codes.
*
*/
app.constant('HTTP_ERRORS', {
'UNAUTHORIZED': 401
});
/**
* @ngdoc service
* @name oauth2Provider
*
* @description
* Service that holds the OAuth2 information shared across all the pages.
*
*/
app.factory('oauth2Provider', function ($modal) {
var oauth2Provider = {
CLIENT_ID: '246167447429-mpl2hspm0i3lsu4hkgp564tq1ebi7p5s.apps.googleusercontent.com',
SCOPES: 'email profile',
signedIn: false
}
/**
* Calls the OAuth2 authentication method.
*/
oauth2Provider.signIn = function (callback) {
gapi.auth.signIn({
'clientid': oauth2Provider.CLIENT_ID,
'cookiepolicy': 'single_host_origin',
'accesstype': 'online',
'approveprompt': 'auto',
'scope': oauth2Provider.SCOPES,
'callback': callback
});
};
/**
* Logs out the user.
*/
oauth2Provider.signOut = function () {
gapi.auth.signOut();
// Explicitly set the invalid access token in order to make the API calls fail.
gapi.auth.setToken({access_token: ''})
oauth2Provider.signedIn = false;
};
/**
* Shows the modal with Google+ sign in button.
*
* @returns {*|Window}
*/
oauth2Provider.showLoginModal = function() {
var modalInstance = $modal.open({
templateUrl: '/partials/login.modal.html',
controller: 'OAuth2LoginModalCtrl'
});
return modalInstance;
};
return oauth2Provider;
});
|
window.onload = function () {
var tl1 = new TimelineMax({repeat:4, repeatDelay:1.8})
tl1
.to("#text1", 1.2, { delay: 0.3, autoAlpha: 0, autoAlpha: 1}, "intro")
.to("#text1", 0.3, { autoAlpha: 1, autoAlpha: 0}, "intro2")
.fromTo("#image2", 2, {delay: 1.8, visibility: "hidden", autoAlpha: 0}, { scale:"1", visibility: "visible", autoAlpha: 1},"intro2")
.to("#text2", 1.2, {delay: 1.8, autoAlpha: 0, autoAlpha: 1}, "intro2")
.fromTo("#button", 0.8, {autoAlpha: 1}, {autoAlpha: 1 }, "intro2")
console.log(tl1.totalDuration());
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
require('./less/style.less');
ReactDOM.render(<App />, document.getElementById('root'));
|
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var buildPath = path.resolve('./dist');
var webpack_config = {
entry: {
'app' : ['./src/js/app.js'],
'vendor' : ['react','react-dom','classnames']
},
output: {
path: buildPath,
filename: 'js/[name]-bundle.js'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /(node_modules)/,
query: {
cacheDirectory: true,
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader", {publicPath: '../'})
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract("style-loader", "css-loader!less-loader", {publicPath: '../'})
},
{
test: /\.(png|gif|jpg)/,
loader: 'url-loader?limit=10000&mimetype=image/png&name=images/[name].[ext]'
},
{
test: /\.(otf|eot|svg|ttf|woff|woff2)$/,
loader: "url-loader?limit=8192&name=fonts/[name].[ext]"
}
]
},
plugins: [
new HtmlWebpackPlugin({
inject: 'body',
template: './src/index.html',
hash: true
}),
new ExtractTextPlugin("css/[name]-bundle.css", {publicPath: '../'}),
new webpack.optimize.CommonsChunkPlugin('vendor', 'js/vendor-bundle.js')
]
};
module.exports = webpack_config;
|
/* eslint-env node, mocha */
/* global $pg_database, $should */
import expect from 'unexpected';
import { isNull } from 'lodash';
import cleanDB from '../../dbCleaner';
import { dbAdapter, Comment, Post, User } from '../../../app/models';
describe('Comment', () => {
before(() => cleanDB($pg_database));
describe('#update()', () => {
let userA, comment, post;
beforeEach(async () => {
userA = new User({
username: 'Luna',
password: 'password',
});
await userA.create();
const postAttrs = { body: 'Post body' };
post = await userA.newPost(postAttrs);
await post.create();
const commentAttrs = {
body: 'Comment body',
postId: post.id,
};
comment = await userA.newComment(commentAttrs);
await comment.create();
});
afterEach(async () => {
await dbAdapter.deleteUser(userA.id); // comment will be destroyed recursively
userA = comment = post = null;
});
it('should update without error', async () => {
const body = 'Body';
const attrs = { body };
await comment.update(attrs);
const newComment = await dbAdapter.getCommentById(comment.id);
newComment.body.should.eql(body);
});
});
describe('#create()', () => {
let user, post;
beforeEach(async () => {
user = new User({
username: 'Luna',
password: 'password',
});
await user.create();
const postsTimelineId = await user.getPostsTimelineId();
post = new Post({
body: 'Post body',
userId: user.id,
timelineIds: [postsTimelineId],
});
await post.create();
});
afterEach(async () => {
await dbAdapter.deleteUser(user.id); // post will be destroyed recursively
user = post = null;
});
it('should create without error', async () => {
const comment = new Comment({
body: 'Comment body',
userId: user.id,
postId: post.id,
});
await comment.create();
comment.should.be.an.instanceOf(Comment);
comment.should.not.be.empty;
comment.should.have.property('id');
const newComment = await dbAdapter.getCommentById(comment.id);
newComment.should.be.an.instanceOf(Comment);
newComment.should.not.be.empty;
newComment.should.have.property('id');
newComment.id.should.eql(comment.id);
});
it('should ignore whitespaces in body', (done) => {
const body = ' Comment body ';
const comment = new Comment({
body,
userId: user.id,
postId: post.id,
});
comment
.create()
.then(() => dbAdapter.getCommentById(comment.id))
.then((newComment) => {
newComment.should.be.an.instanceOf(Comment);
newComment.should.not.be.empty;
newComment.should.have.property('id');
newComment.id.should.eql(comment.id);
newComment.body.should.eql(body.trim());
done();
})
.catch((e) => {
done(e);
});
});
it('should not create with empty body', (done) => {
const comment = new Comment({
body: '',
userId: user.id,
postId: post.id,
});
comment.create().catch((e) => {
e.message.should.eql('Comment text must not be empty');
done();
});
});
});
describe('#findById()', () => {
let user, post;
beforeEach(async () => {
user = new User({
username: 'Luna',
password: 'password',
});
await user.create();
const postsTimelineId = await user.getPostsTimelineId();
post = new Post({
body: 'Post body',
userId: user.id,
timelineIds: [postsTimelineId],
});
await post.create();
});
afterEach(async () => {
await dbAdapter.deleteUser(user.id); // post will be destroyed recursively
user = post = null;
});
it('should find comment with a valid id', (done) => {
const comment = new Comment({
body: 'Comment body',
userId: user.id,
postId: post.id,
});
comment
.create()
.then(() => dbAdapter.getCommentById(comment.id))
.then((newComment) => {
newComment.should.be.an.instanceOf(Comment);
newComment.should.not.be.empty;
newComment.should.have.property('id');
newComment.id.should.eql(comment.id);
done();
})
.catch((e) => {
done(e);
});
});
it('should not find comment with invalid id', (done) => {
const identifier = 'comment:identifier';
dbAdapter
.getCommentById(identifier)
.then((comment) => {
$should.not.exist(comment);
done();
})
.catch((e) => {
done(e);
});
});
});
describe('#destroy()', () => {
let userA, post;
beforeEach(async () => {
userA = new User({
username: 'Luna',
password: 'password',
});
await userA.create();
const postAttrs = { body: 'Post body' };
post = await userA.newPost(postAttrs);
await post.create();
const commentAttrs = {
body: 'Comment body',
postId: post.id,
};
const comment = await userA.newComment(commentAttrs);
await comment.create();
});
afterEach(async () => {
await dbAdapter.deleteUser(userA.id); // post will be destroyed recursively
userA = post = null;
});
it('should destroy comment', async () => {
let comments = await post.getComments();
const [comment] = comments;
await comment.destroy();
const oldComment = await dbAdapter.getCommentById(comment.id);
isNull(oldComment).should.be.true;
comments = await post.getComments();
comments.should.be.empty;
});
});
describe('Comment numbers', () => {
let userA, post;
before(async () => {
userA = new User({
username: 'Luna',
password: 'password',
});
await userA.create();
const postAttrs = { body: 'Post body' };
post = await userA.newPost(postAttrs);
await post.create();
});
after(async () => {
await dbAdapter.deleteUser(userA.id); // comment will be destroyed recursively
userA = post = null;
});
it(`should create first comment with number 1`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 1);
expect(await post.getComments(), 'to have length', 1);
});
it(`should create second comment with number 2`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 2);
expect(await post.getComments(), 'to have length', 2);
});
it(`should remove first comment`, async () => {
const [firstComment] = await dbAdapter.getPostComments(post.id);
const deleted = await firstComment.destroy();
expect(deleted, 'to be', true);
expect(await post.getComments(), 'to have length', 1);
});
it(`should create next comment with number 3`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 3);
expect(await post.getComments(), 'to have length', 2);
});
it(`should create next comment with number 4`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 4);
expect(await post.getComments(), 'to have length', 3);
});
it(`should remove last comment`, async () => {
const comments = await dbAdapter.getPostComments(post.id);
const deleted = await comments.pop().destroy();
expect(deleted, 'to be', true);
expect(await post.getComments(), 'to have length', 2);
});
it(`should create next comment with number 4 again`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 4);
expect(await post.getComments(), 'to have length', 3);
});
it(`should remove all comments and create a new comment with number 1`, async () => {
let comments = await dbAdapter.getPostComments(post.id);
await Promise.all(comments.map((c) => c.destroy()));
comments = await dbAdapter.getPostComments(post.id);
expect(comments, 'to be empty');
expect(await post.getComments(), 'to have length', 0);
});
it(`should create a new comment with number 1`, async () => {
const comment = await userA.newComment({ body: 'Comment body', postId: post.id });
await comment.create();
expect(comment.seqNumber, 'to be', 1);
expect(await post.getComments(), 'to have length', 1);
});
});
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends2 = require('babel-runtime/helpers/extends');
var _extends3 = _interopRequireDefault(_extends2);
var _defineProperty2 = require('babel-runtime/helpers/defineProperty');
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
exports["default"] = wrapPicker;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Panel = require('rc-time-picker/lib/Panel');
var _Panel2 = _interopRequireDefault(_Panel);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _warning = require('warning');
var _warning2 = _interopRequireDefault(_warning);
var _getLocale = require('../_util/getLocale');
var _getLocale2 = _interopRequireDefault(_getLocale);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function wrapPicker(Picker, defaultFormat) {
var PickerWrapper = _react2["default"].createClass({
displayName: 'PickerWrapper',
getDefaultProps: function getDefaultProps() {
return {
format: defaultFormat || 'YYYY-MM-DD',
transitionName: 'slide-up',
popupStyle: {},
onChange: function onChange() {},
onOk: function onOk() {},
onOpenChange: function onOpenChange() {},
locale: {},
align: {
offset: [0, -9]
},
prefixCls: 'ant-calendar',
inputPrefixCls: 'ant-input'
};
},
contextTypes: {
antLocale: _react.PropTypes.object
},
handleOpenChange: function handleOpenChange(open) {
var _props = this.props;
var onOpenChange = _props.onOpenChange;
var toggleOpen = _props.toggleOpen;
onOpenChange(open);
if (toggleOpen) {
(0, _warning2["default"])(false, '`toggleOpen` is deprecated and will be removed in the future, ' + 'please use `onOpenChange` instead');
toggleOpen({ open: open });
}
},
render: function render() {
var _classNames2, _classNames3;
var props = this.props;
var prefixCls = props.prefixCls;
var inputPrefixCls = props.inputPrefixCls;
var pickerClass = (0, _classnames2["default"])((0, _defineProperty3["default"])({}, prefixCls + '-picker', true));
var pickerInputClass = (0, _classnames2["default"])((_classNames2 = {}, (0, _defineProperty3["default"])(_classNames2, prefixCls + '-range-picker', true), (0, _defineProperty3["default"])(_classNames2, inputPrefixCls, true), (0, _defineProperty3["default"])(_classNames2, inputPrefixCls + '-lg', props.size === 'large'), (0, _defineProperty3["default"])(_classNames2, inputPrefixCls + '-sm', props.size === 'small'), _classNames2));
var locale = (0, _getLocale2["default"])(this.props, this.context, 'DatePicker', function () {
return require('./locale/zh_CN');
});
var timeFormat = props.showTime && props.showTime.format || 'HH:mm:ss';
var rcTimePickerProps = {
format: timeFormat,
showSecond: timeFormat.indexOf('ss') >= 0,
showHour: timeFormat.indexOf('HH') >= 0
};
var timePickerCls = (0, _classnames2["default"])((_classNames3 = {}, (0, _defineProperty3["default"])(_classNames3, prefixCls + '-time-picker-1-column', !(rcTimePickerProps.showSecond || rcTimePickerProps.showHour)), (0, _defineProperty3["default"])(_classNames3, prefixCls + '-time-picker-2-columns', rcTimePickerProps.showSecond !== rcTimePickerProps.showHour), _classNames3));
var timePicker = props.showTime ? _react2["default"].createElement(_Panel2["default"], (0, _extends3["default"])({}, rcTimePickerProps, props.showTime, { prefixCls: prefixCls + '-time-picker', className: timePickerCls, placeholder: locale.timePickerLocale.placeholder, transitionName: 'slide-up' })) : null;
return _react2["default"].createElement(Picker, (0, _extends3["default"])({}, props, { pickerClass: pickerClass, pickerInputClass: pickerInputClass, locale: locale, timePicker: timePicker, onOpenChange: this.handleOpenChange }));
}
});
return PickerWrapper;
}
module.exports = exports['default'];
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var chance = require('../../extlibs/wrap_chance');
var math = require('../../extlibs/wrap_math');
var _ = require('../../extlibs/wrap_lodash');
var memoize_1 = require('../../decorators/memoize');
var Question = (function () {
function Question() {
this.time = chance.natural({ min: 5, max: 25 }) * 2;
this.speed = chance.natural({ min: 5, max: 25 }) * 2;
}
Object.defineProperty(Question.prototype, "time_x_speed", {
get: function () {
return this.time * this.speed;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Question.prototype, "m_plus_1", {
get: function () {
var _this = this;
return math.gcd(chance.pickone(_.range(3, 16).filter(function (val) { return math.gcd(_this.time_x_speed, val) > 2; })), this.time_x_speed);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Question.prototype, "m", {
get: function () {
return this.m_plus_1 - 1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Question.prototype, "tlen", {
get: function () {
return this.time_x_speed / this.m_plus_1;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Question.prototype, "cans", {
get: function () {
return this.speed;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Question.prototype, "qtxt", {
get: function () {
return "A " + this.tlen + " m train crosses a bridge " + this.m + " times its length in " + this.time + " seconds. Speed of the train in m/s?";
},
enumerable: true,
configurable: true
});
Question = __decorate([
memoize_1.memoizeall
], Question);
return Question;
}());
exports.Question = Question;
//# sourceMappingURL=q_00001.js.map
|
"use strict";
module.exports = function(sequelize, DataTypes) {
var DeploymentsHistory = sequelize.define("DeploymentsHistory", {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
autoIncrement: true,
primaryKey: true
},
deployment_id: DataTypes.INTEGER(10),
package_id: DataTypes.INTEGER(10),
created_at: DataTypes.DATE
}, {
tableName: 'deployments_history',
underscored: true,
updatedAt: false,
paranoid: true
});
return DeploymentsHistory;
};
|
import React from 'react'
import { View, Button } from 'react-native'
import EaseTitle from '../../components/art/easeTitle'
export default class CreamScreen extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() { }
render() {
const { navigation, banner } = this.props
return (
<View>
<EaseTitle></EaseTitle>
<Button
onPress={() => navigation.navigate('CreamDetail')}
title="to Cream Detail"
color="#841584"
accessibilityLabel="navigate to Cream's detail" />
</View>
)
}
}
|
//this function is for switch To Primary Window when using FB, twitter, google+
exports.command = function ( socialmedia ) {
this.windowHandles( function ( newwindow ) {
var new_handle = newwindow.value[ 0 ];
this.switchWindow( new_handle );
} ).
//check whether the new window open a facebook link
verify.urlContains( socialmedia ).pause( 2000 ).windowMaximize();
return this;
};
|
import path from 'path';
const repoRoot = path.resolve(__dirname, '../');
const srcRoot = path.join(repoRoot, 'src/');
const distRoot = path.join(repoRoot, 'dist/');
const libRoot = path.join(repoRoot, 'lib/');
const docsRoot = path.join(repoRoot, 'docs-built/');
export {
repoRoot,
srcRoot,
distRoot,
libRoot,
docsRoot
};
|
import { POPOVERS_OPEN } from '../constants/ActionsType'
const initialState = false;
export function isOpen( state = initialState, action=[]) {
switch( action.type )
{
case POPOVERS_OPEN:
return !state;
default:
return state;
}
}
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Web Client
* Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
var controller = {
id : "Options",
defaultPage : "pop",
// set up the initial page
init : function(templateId) {
this.masterTemplateId = templateId;
var body = Dwt.byTag("BODY")[0],
outerTemplate = templateId+"#OptionsOuter"
;
AjxTemplate.setContent(body, outerTemplate, controller);
this.showPage(util.getParamOrCookie("page", this.defaultPage));
},
showPage : function(pageName) {
AjxCookie.setCookie(document,"page",pageName);
var pageController = window.pageController = this.pageController = data[pageName];
if (pageController == null) {
return alert("Page " + pageName + " not found.");
}
// select proper tab
this.selectTab("Options_outer_tabs", pageName);
// set page title
Dwt.byId(controller.id+"_page_title").innerHTML = pageController._labels.pageHeader;
// install sub-templates
pageController.masterTemplateId = templateId;
this.initSubTemplates(pageController);
// call init on the pageController, if defined
if (typeof this.pageController.init == "function") this.pageController.init();
},
initSubTemplates : function(controller) {
// instantiate the controller templates, in order
var templates = controller.templates;
for (var i = 0; i < templates.length; i++) {
var template = templates[i],
elementId = template.elementId,
templateId = template.templateId
;
if (elementId.charAt(0) == "_") {
elementId = controller.id + elementId;
}
if (templateId.charAt(0) == "#") {
templateId = controller.masterTemplateId + templateId;
}
AjxTemplate.setContent(elementId, templateId, controller);
}
},
selectTab : function(tabListId, itemToSelectId) {
var list = Dwt.byId(tabListId);
itemToSelectId = tabListId + "_" + itemToSelectId;
for (var i = 0; i < list.childNodes.length; i++) {
var child = list.childNodes[i];
if (child.tagName == "LI") {
if (child.id == itemToSelectId) {
Dwt.addClass(child, "selected");
} else {
Dwt.delClass(child, "selected");
}
}
}
}
}
var data = {
id: controller.id
};
/////
//
// Individual forms
//
/////
//
// Identity form
//
data.identity = {
controller : "data.identity",
id: data.id+"_identity",
defaultPage : "options",
templates : [
{
elementId : "Options_page_container",
templateId : "#ListOptionPage"
},
{
elementId : "_form_container",
templateId : "#IdentityForm"
}
],
_labels : {
pageHeader: "Mail Identities",
infoTitle: ZmMsg.identityInfoTitle,
infoContents: ZmMsg.identityInfoContent,
listHeader: ZmMsg.identities,
detailsHeader: ZmMsg.identitiesLabel
},
init : function() {
var subFormPage = util.getParamOrCookie("IdentitySubPage", this.defaultPage);
this.showPage(subFormPage);
},
showPage : function(pageName) {
AjxCookie.setCookie(document, "IdentitySubPage", pageName);
controller.selectTab(this.id + "_tabs", pageName);
AjxTemplate.setContent(this.id + "_subFormContainer",
this.masterTemplateId + "#IdentityForm_" + pageName,
this);
if (pageName == "advanced") {
this._toggleAdvancedSettings(false);
}
},
_advancedEnabled : true,
_advancedFields : [
'_replyForwardSelect',
'_replyIncludeSelect',
'_forwardIncludeSelect',
'_prefixSelect'
],
_advancedLabels : [
'_replyForwardSelect_label',
'_replyIncludeSelect_label',
'_forwardIncludeSelect_label',
'_prefixSelect_label'
],
_toggleAdvancedSettings : function(enable) {
if (enable == null) {
enable = !this._advancedEnabled;
}
this._advancedEnabled = enable;
Dwt.byId(this.id + '_useDefaultsCheckbox_default').checked = !enable;
Dwt.byId(this.id + '_useDefaultsCheckbox_custom').checked = enable;
for (var i = 0, id; id = this._advancedFields[i]; i++) {
Dwt.byId(this.id + id).disabled = (!enable);
}
var addClass = (enable ? null : "ZDisabled");
for (var i = 0, id; id = this._advancedLabels[i]; i++) {
Dwt.delClass(Dwt.byId(this.id + id), "ZDisabled", addClass);
}
}
};
//
// Pop account form
//
data.pop = {
controller : "data.pop",
id: data.id+"_pop",
templates : [
{
elementId : "Options_page_container",
templateId : "#ListOptionPage"
},
{
elementId : "_form_container",
templateId : "#PopForm"
}
],
_labels : {
pageHeader: "POP Email Accounts",
infoTitle: ZmMsg.popAccountsInfoHeader,
infoContents: ZmMsg.popAccountsInfo,
listHeader: ZmMsg.popAccounts,
detailsHeader: ZmMsg.popAccountSettings
},
init : function() {
//this.toggleIdentitySection();
this.toggleIdentityFields(false);
// this.toggleAdvanced(false);
},
_toggleInfoBoxHandler : function() {
Dwt.toggle(this.id + "_infoBox_container");
},
// hide the entire identities section (for 'edit')
toggleIdentitySection : function(newState) {
Dwt.toggle(this.id + "_identity_title_row",newState);
Dwt.toggle(this.id + "_identity_help_row",newState);
Dwt.toggle(this.id + "_identity_create_row",newState);
this.toggleIdentityFields(newState);
},
// hide the identity fields dependent on the checkbox
toggleIdentityFields : function(newState) {
Dwt.toggle(this.id + "_identity_spacer_row",newState);
Dwt.toggle(this.id + "_identity_name_row",newState);
Dwt.toggle(this.id + "_identity_email_row",newState);
Dwt.toggle(this.id + "_identity_use_address_row",newState);
Dwt.toggle(this.id + "_identity_use_folder_row",newState);
},
// show advanced options
toggleAdvanced : function(newState) {
Dwt.toggle(this.id + "_ssl_row",newState);
Dwt.toggle(this.id + "_port_row",newState);
}
};
/* NOT CURRENTLY BEING USED
data.pop.form = {
// list of required fields
required : ["name", "username","password"],
// map of 'item:relevantCondition(s)' for the form
// (note: item may be a field, or might be a div/td/etc)
relevant: {
"identity_sub_form" : {field:"create_identity", test:"==true", behavior:"hide"},
"password_text" : {field:"show_password", test:"==true", behavior:"hide"},
"password_pass" : {field:"show_password", test:"==false", behavior:"hide"}
},
// map of 'item:scripts' for the form
// (item == field, script is script to execute when item changes)
changeHandlers: {
"ssl" : "form.setValue('port', newValue ? '995' : '110');",
"name" : "form.setValue('identity_name', newValue);",
"server" : "form.setValue('email', form.getValue('username') + '@' + form.getValue('server'));",
"username" : "form.setValue('email', form.getValue('username') + '@' + form.getValue('server'));"
},
// default values for items not in our data model or for a new instance
defaults: {
port : 110,
show_password : false,
create_identity : false,
location : "Inbox",
identity_use_address: true,
identity_use_folder : true
}
};
*/
//
// General options form
//
data.general = {
controller: "data.general",
id: data.id + "_general",
_labels : {
pageHeader: "General Options",
},
templates: [
{
elementId: "Options_page_container",
templateId: "#GeneralForm"
}
]
}
|
import Vue from 'vue'
const noopData = () => ({})
// window.onNuxtReady(() => console.log('Ready')) hook
// Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading)
if (process.browser) {
window._nuxtReadyCbs = []
window.onNuxtReady = function (cb) {
window._nuxtReadyCbs.push(cb)
}
}
export function applyAsyncData(Component, asyncData) {
const ComponentData = Component.options.data || noopData
// Prevent calling this method for each request on SSR context
if (!asyncData && Component.options.hasAsyncData) {
return
}
Component.options.hasAsyncData = true
Component.options.data = function () {
const data = ComponentData.call(this)
if (this.$ssrContext) {
asyncData = this.$ssrContext.asyncData[Component.cid]
}
return { ...data, ...asyncData }
}
if (Component._Ctor && Component._Ctor.options) {
Component._Ctor.options.data = Component.options.data
}
}
export function sanitizeComponent(Component) {
// If Component already sanitized
if (Component.options && Component._Ctor === Component) {
return Component
}
if (!Component.options) {
Component = Vue.extend(Component) // fix issue #6
Component._Ctor = Component
} else {
Component._Ctor = Component
Component.extendOptions = Component.options
}
// For debugging purpose
if (!Component.options.name && Component.options.__file) {
Component.options.name = Component.options.__file
}
return Component
}
export function getMatchedComponents(route, matches = false) {
return [].concat.apply([], route.matched.map(function (m, index) {
return Object.keys(m.components).map(function (key) {
matches && matches.push(index)
return m.components[key]
})
}))
}
export function getMatchedComponentsInstances(route, matches = false) {
return [].concat.apply([], route.matched.map(function (m, index) {
return Object.keys(m.instances).map(function (key) {
matches && matches.push(index)
return m.instances[key]
})
}))
}
export function flatMapComponents(route, fn) {
return Array.prototype.concat.apply([], route.matched.map(function (m, index) {
return Object.keys(m.components).map(function (key) {
return fn(m.components[key], m.instances[key], m, key, index)
})
}))
}
export function resolveRouteComponents(route) {
return Promise.all(
flatMapComponents(route, async (Component, _, match, key) => {
// If component is a function, resolve it
if (typeof Component === 'function' && !Component.options) {
Component = await Component()
}
return match.components[key] = sanitizeComponent(Component)
})
)
}
export async function getRouteData(route) {
// Make sure the components are resolved (code-splitting)
await resolveRouteComponents(route)
// Send back a copy of route with meta based on Component definition
return {
...route,
meta: getMatchedComponents(route).map((Component) => {
return Component.options.meta || {}
})
}
}
export async function setContext(app, context) {
const route = (context.to ? context.to : context.route)
// If context not defined, create it
if (!app.context) {
app.context = {
get isServer() {
console.warn('context.isServer has been deprecated, please use process.server instead.')
return process.server
},
get isClient() {
console.warn('context.isClient has been deprecated, please use process.client instead.')
return process.client
},
isStatic: process.static,
isDev: true,
isHMR: false,
app,
store: app.store,
payload: context.payload,
error: context.error,
base: '/',
env: {"hubpressVersion":"1.0.0","baseUrl":"http://localhost:3000"}
}
// Only set once
if (context.req) app.context.req = context.req
if (context.res) app.context.res = context.res
app.context.redirect = function (status, path, query) {
if (!status) return
app.context._redirected = true // Used in middleware
// if only 1 or 2 arguments: redirect('/') or redirect('/', { foo: 'bar' })
let pathType = typeof path
if (typeof status !== 'number' && (pathType === 'undefined' || pathType === 'object')) {
query = path || {}
path = status
pathType = typeof path
status = 302
}
if (pathType === 'object') {
path = app.router.resolve(path).href
}
// "/absolute/route", "./relative/route" or "../relative/route"
if (/(^[.]{1,2}\/)|(^\/(?!\/))/.test(path)) {
app.context.next({
path: path,
query: query,
status: status
})
} else {
path = formatUrl(path, query)
if (process.server) {
app.context.next({
path: path,
status: status
})
}
if (process.client) {
// https://developer.mozilla.org/en-US/docs/Web/API/Location/replace
window.location.replace(path)
// Throw a redirect error
throw new Error('ERR_REDIRECT')
}
}
}
if (process.server) app.context.beforeNuxtRender = (fn) => context.beforeRenderFns.push(fn)
if (process.client) app.context.nuxtState = window.__NUXT__
}
// Dynamic keys
app.context.next = context.next
app.context._redirected = false
app.context._errored = false
app.context.isHMR = !!context.isHMR
if (context.route) app.context.route = await getRouteData(context.route)
app.context.params = app.context.route.params || {}
app.context.query = app.context.route.query || {}
if (context.from) app.context.from = await getRouteData(context.from)
}
export function middlewareSeries(promises, appContext) {
if (!promises.length || appContext._redirected || appContext._errored) {
return Promise.resolve()
}
return promisify(promises[0], appContext)
.then(() => {
return middlewareSeries(promises.slice(1), appContext)
})
}
export function promisify(fn, context) {
let promise
if (fn.length === 2) {
// fn(context, callback)
promise = new Promise((resolve) => {
fn(context, function (err, data) {
if (err) {
context.error(err)
}
data = data || {}
resolve(data)
})
})
} else {
promise = fn(context)
}
if (!promise || (!(promise instanceof Promise) && (typeof promise.then !== 'function'))) {
promise = Promise.resolve(promise)
}
return promise
}
// Imported from vue-router
export function getLocation(base, mode) {
var path = window.location.pathname
if (mode === 'hash') {
return window.location.hash.replace(/^#\//, '')
}
if (base && path.indexOf(base) === 0) {
path = path.slice(base.length)
}
return (path || '/') + window.location.search + window.location.hash
}
export function urlJoin() {
return [].slice.call(arguments).join('/').replace(/\/+/g, '/')
}
// Imported from path-to-regexp
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
export function compile(str, options) {
return tokensToFunction(parse(str, options))
}
export function getQueryDiff(toQuery, fromQuery) {
const diff = {}
const queries = { ...toQuery, ...fromQuery }
for (const k in queries) {
if (String(toQuery[k]) !== String(fromQuery[k])) {
diff[k] = true
}
}
return diff
}
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
const PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g')
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse(str, options) {
var tokens = []
var key = 0
var index = 0
var path = ''
var defaultDelimiter = options && options.delimiter || '/'
var res
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0]
var escaped = res[1]
var offset = res.index
path += str.slice(index, offset)
index = offset + m.length
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1]
continue
}
var next = str[index]
var prefix = res[2]
var name = res[3]
var capture = res[4]
var group = res[5]
var modifier = res[6]
var asterisk = res[7]
// Push the current path onto the tokens.
if (path) {
tokens.push(path)
path = ''
}
var partial = prefix != null && next != null && next !== prefix
var repeat = modifier === '+' || modifier === '*'
var optional = modifier === '?' || modifier === '*'
var delimiter = res[2] || defaultDelimiter
var pattern = capture || group
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
})
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index)
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path)
}
return tokens
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty(str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk(str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction(tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length)
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
}
}
return function(obj, opts) {
var path = ''
var data = obj || {}
var options = opts || {}
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
path += token
continue
}
var value = data[token.name]
var segment
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (Array.isArray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j])
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value)
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString(str) {
return str.replace(/([.+*?=^!:()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup(group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Format given url, append query to url query string
*
* @param {string} url
* @param {string} query
* @return {string}
*/
function formatUrl (url, query) {
let protocol
let index = url.indexOf('://')
if (index !== -1) {
protocol = url.substring(0, index)
url = url.substring(index + 3)
} else if (url.indexOf('//') === 0) {
url = url.substring(2)
}
let parts = url.split('/')
let result = (protocol ? protocol + '://' : '//') + parts.shift()
let path = parts.filter(Boolean).join('/')
let hash
parts = path.split('#')
if (parts.length === 2) {
path = parts[0]
hash = parts[1]
}
result += path ? '/' + path : ''
if (query && JSON.stringify(query) !== '{}') {
result += (url.split('?').length === 2 ? '&' : '?') + formatQuery(query)
}
result += hash ? '#' + hash : ''
return result
}
/**
* Transform data object to query string
*
* @param {object} query
* @return {string}
*/
function formatQuery (query) {
return Object.keys(query).sort().map(key => {
var val = query[key]
if (val == null) {
return ''
}
if (Array.isArray(val)) {
return val.slice().map(val2 => [key, '=', val2].join('')).join('&')
}
return key + '=' + val
}).filter(Boolean).join('&')
}
|
/**
* Interface to the User model.
*/
var util = require('util');
/**
* Constructor to the Log object.
*
* @param model
* The model of the log document.
*/
function UserActivity(model) {
this.docModel = model;
}
/**
* Converts a timestamp in seconds to a Date object.
*
* @param timestamp
* Timestamp in seconds.
*/
var convertToDate = function(timestamp) {
return new Date(timestamp * 1000);
};
/**
* Create a log document from the supplied values for a user activity.
*
* @param req
* The request object in a POST callback.
* @param res
* The response object in a POST callback.
*/
UserActivity.prototype.post = function(req, res) {
this.request = req;
this.response = res;
var addArgs = {};
// Include parameter values in post
addArgs.email = this.request.body.email;
addArgs.source = this.request.body.source.toUpperCase();
addArgs.activity = this.request.query.type;
addArgs.activity_date = this.request.body.activity_date;
addArgs.activity_details = this.request.body.activity_details;
addArgs.logged_date = new Date();
var logEntry = new this.docModel(addArgs);
logEntry.save(function(err) {
if (err) {
res.send(500, err);
}
// Added log entry to db
res.send(201, addArgs);
console.log('Save executed on: ' + util.inspect(addArgs, false, null) + '.');
});
};
/**
* Retrieve existing user activity log documents. Example request GET:
* /api/v1/user/activity?type=vote&&source=AGG&offset=300&interval=300
*
* @param req
* The request object in the GET callback.
* @param res
* The response object in the GET callback.
*/
UserActivity.prototype.get = function(req, res) {
// NOTE: Typically offset and interval would be the same value.
if (req.param("offset") === undefined) {
// Default to current date if not set
var targetStartDate = new Date();
}
else {
var targetStartDate = new Date();
targetStartDate.setSeconds(targetStartDate.getSeconds() - req.param("offset"));
}
if (req.param("interval") === undefined) {
var targetEndDate = new Date(targetStartDate);
// Default to one week if not set
targetEndDate.setSeconds(targetEndDate.getSeconds() - 604800);
}
else {
var targetEndDate = new Date(targetStartDate);
targetEndDate.setSeconds(targetEndDate.getSeconds() - req.param("interval"));
}
var data = {
request: req,
response: res
};
this.docModel.find( {
$and : [
{ 'activity_date' : {$gte : targetEndDate, $lte : targetStartDate} },
{ 'source' : req.param("source") },
{ 'activity' : req.param("type") }
]},
function (err, docs) {
if (err) {
data.response.send(500, err);
return;
}
// Send results
console.log('Logged votes returned for source: ' + req.param("source") + ' and activity: ' + req.param("type") + '.');
data.response.send(201, docs);
})
};
module.exports = UserActivity;
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
module.exports = {
moduleType: 'locale',
name: 'bs',
dictionary: {},
format: {
days: [
'Nedelja', 'Ponedeljak', 'Utorak', 'Srijeda',
'Četvrtak', 'Petak', 'Subota'
],
shortDays: ['Ned', 'Pon', 'Uto', 'Sri', 'Čet', 'Pet', 'Sub'],
months: [
'Januar', 'Februar', 'Mart', 'April', 'Maj', 'Juni',
'Juli', 'August', 'Septembar', 'Oktobar', 'Novembar', 'Decembar'
],
shortMonths: [
'Jan', 'Feb', 'Mar', 'Apr', 'Maj', 'Jun',
'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dec'
],
date: '%d.%m.%Y'
}
};
|
import { RelationshipChange } from "ember-data/system/changes";
var get = Ember.get;
var set = Ember.set;
var isNone = Ember.isNone;
var map = Ember.ArrayPolyfills.map;
var merge = Ember.merge;
/**
In Ember Data a Serializer is used to serialize and deserialize
records when they are transferred in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializing relationships.
For maximum performance Ember Data recommends you use the
[RESTSerializer](DS.RESTSerializer.html) or one of its subclasses.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
@class JSONSerializer
@namespace DS
*/
export default Ember.Object.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` property to store the id of
the record. The external source may not always follow this
convention. In these cases it is useful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
@default 'id'
*/
primaryKey: 'id',
/**
The `attrs` object can be used to declare a simple mapping between
property names on `DS.Model` records and payload keys in the
serialized JSON object representing the record. An object with the
property `key` can also be used to designate the attribute's key on
the response payload.
Example
```javascript
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string'),
admin: DS.attr('boolean')
});
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: 'is_admin',
occupation: {key: 'career'}
}
});
```
You can also remove attributes by setting the `serialize` key to
false in your mapping object.
Example
```javascript
App.PersonSerializer = DS.JSONSerializer.extend({
attrs: {
admin: {serialize: false},
occupation: {key: 'career'}
}
});
```
When serialized:
```javascript
{
"career": "magician"
}
```
Note that the `admin` is now not included in the payload.
@property attrs
@type {Object}
*/
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function(key, type) {
if (!data.hasOwnProperty(key)) { return; }
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.normalizeId(hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
this.normalizeUsingDeclaredMapping(type, hash);
this.applyTransforms(type, hash);
return hash;
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalizePayload: function(payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {Object} payload
@return {Object} the normalized payload
*/
normalizePayload: function(payload) {
return payload;
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey, key;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, key;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
if (!hash.hasOwnProperty(payloadKey)) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = get(this, 'attrs'), payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = this._getMappedKey(key);
if (!hash.hasOwnProperty(payloadKey)) { continue; }
if (payloadKey !== key) {
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
}
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
Looks up the property key that was set by the custom `attr` mapping
passed to the serializer.
@method _getMappedKey
@private
@param {String} key
@return {String} key
*/
_getMappedKey: function(key) {
var attrs = get(this, 'attrs');
var mappedKey;
if (attrs && attrs[key]) {
mappedKey = attrs[key];
//We need to account for both the {title: 'post_title'} and
//{title: {key: 'post_title'}} forms
if (mappedKey.key){
mappedKey = mappedKey.key;
}
if (typeof mappedKey === 'string'){
key = mappedKey;
}
}
return key;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapBy('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {subclass of DS.Model} record
@param {Object} options
@return {Object} json
*/
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = id;
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
/**
You can use this method to customize how a serialized record is added to the complete
JSON hash to be sent to the server. By default the JSON Serializer does not namespace
the payload and just sends the raw serialized JSON object.
If your server expects namespaced keys, you should consider using the RESTSerializer.
Otherwise you can override this method to customize how the record is added to the hash.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
merge(hash, this.serialize(record, options));
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all your attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(record, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(record, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Model} record
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(record, json, key, attribute) {
var attrs = get(this, 'attrs');
var value = get(record, key);
var type = attribute.type;
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// If attrs.key.serialize is false, do not include the value in the
// response to the server at all.
if (attrs && attrs[key] && attrs[key].serialize === false) {
return;
}
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForAttribute) {
payloadKey = this.keyForAttribute(key);
}
json[payloadKey] = value;
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var attrs = get(this, 'attrs');
var key = relationship.key;
var belongsTo = get(record, key);
// if provided, use the mapping provided by `attrs` in
// the serializer
var payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "belongsTo");
}
if (isNone(belongsTo)) {
json[payloadKey] = belongsTo;
} else {
json[payloadKey] = get(belongsTo, 'id');
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(record, json, relationship);
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var attrs = get(this, 'attrs');
var key = relationship.key;
var payloadKey;
// if provided, use the mapping provided by `attrs` in
// the serializer
payloadKey = this._getMappedKey(key);
if (payloadKey === key && this.keyForRelationship) {
payloadKey = this.keyForRelationship(key, "hasMany");
}
var relationshipType = RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[payloadKey] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "_type"] = belongsTo.constructor.typeKey;
}
});
```
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method delegates to a more specific extract method based on
the `requestType`.
Example
```javascript
var get = Ember.get;
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
var type = store.modelFor(modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, get(data, 'id'), 'single');
store.push(modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindAll: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindQuery: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindMany: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: function(store, type, payload, id, requestType){
return this.extractArray(store, type, payload, id, requestType);
},
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Store#createRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractCreateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Store#update`. By default this method is alias
for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractUpdateRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Store#deleteRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractDeleteRecord: function(store, type, payload, id, requestType) {
return this.extractSave(store, type, payload, id, requestType);
},
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFind: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSave: function(store, type, payload, id, requestType) {
return this.extractSingle(store, type, payload, id, requestType);
},
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload, id, requestType) {
payload = this.normalizePayload(payload);
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(store, type, json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, arrayPayload, id, requestType) {
var normalizedPayload = this.normalizePayload(arrayPayload);
var serializer = this;
return map.call(normalizedPayload, function(singlePayload) {
return serializer.normalize(type, singlePayload);
});
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.metaForType(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.metaForType(type, payload.meta);
delete payload.meta;
}
},
/**
`keyForAttribute` can be used to define rules for how to convert an
attribute name in your model to a key in your JSON.
Example
```javascript
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
@method keyForAttribute
@param {String} key
@return {String} normalized key
*/
keyForAttribute: function(key){
return key;
},
/**
`keyForRelationship` can be used to define a custom key when
serializing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
keyForRelationship: function(key, type){
return key;
},
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
|
siege = require('siege');
siege()
.concurrent(100)
.on(8001)
.get('/rooms').for(10000).times
.get('/rooms/1').for(10000).times
/* .get('/persons').for(10000).times
.get('/buildings').for(10000).times
.get('/users').for(10000).times
.get('/users/1').for(10000).times
*/ .attack()
|
/*jshint camelcase: false*/
module.exports = function (grunt) {
'use strict';
// load all grunt tasks
require('time-grunt')(grunt);
require('load-grunt-tasks')(grunt);
// configurable paths
var config = {
app: 'app',
min: '.min',
vendor: 'vendor',
dist: 'dist',
distMac32: 'dist/MacOS32',
distMac64: 'dist/MacOS64',
distLinux32: 'dist/Linux32',
distLinux64: 'dist/Linux64',
distWin: 'dist/Win',
tmp: 'buildTmp',
resources: 'resources'
};
grunt.initConfig({
config: config,
clean: {
vendor: {
files: [{
dot: true,
src: [
'<%= config.app %>/lib/js/*',
'<%= config.app %>/lib/css/*',
'<%= config.app %>/lib/fonts/*',
]
}]
},
dist: {
files: [{
dot: true,
src: [
'<%= config.dist %>/*',
'<%= config.tmp %>/*'
]
}]
},
distMac32: {
files: [{
dot: true,
src: [
'<%= config.distMac32 %>/*',
'<%= config.tmp %>/*'
]
}]
},
distMac64: {
files: [{
dot: true,
src: [
'<%= config.distMac64 %>/*',
'<%= config.tmp %>/*'
]
}]
},
distLinux64: {
files: [{
dot: true,
src: [
'<%= config.distLinux64 %>/*',
'<%= config.tmp %>/*'
]
}]
},
distLinux32: {
files: [{
dot: true,
src: [
'<%= config.distLinux32 %>/*',
'<%= config.tmp %>/*'
]
}]
},
distWin: {
files: [{
dot: true,
src: [
'<%= config.distWin %>/*',
'<%= config.tmp %>/*'
]
}]
}
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
files: '<%= config.app %>/js/*.js'
},
copy: {
vendor: {
files: [
{
expand: true,
flatten: true,
cwd: '<%= config.vendor %>',
src: ['**/*<%= config.min %>.css'],
dest: '<%= config.app %>/lib/css'
},
{
expand: true,
flatten: true,
cwd: '<%= config.vendor %>',
src: ['**/*<%= config.min %>.js'],
dest: '<%= config.app %>/lib/js',
},
{
expand: true,
flatten: true,
cwd: '<%= config.vendor %>',
src: ['bootstrap/fonts/*'],
dest: '<%= config.app %>/lib/fonts',
},
{
src: ['<%= config.vendor %>/bootbox/bootbox.js'],
dest: '<%= config.app %>/lib/js/bootbox.js'
}]
},
appLinux: {
files: [{
expand: true,
cwd: '<%= config.app %>',
dest: '<%= config.distLinux64 %>/app.nw',
src: '**'
}]
},
appLinux32: {
files: [{
expand: true,
cwd: '<%= config.app %>',
dest: '<%= config.distLinux32 %>/app.nw',
src: '**'
}]
},
appMacos32: {
files: [{
expand: true,
cwd: '<%= config.app %>',
dest: '<%= config.distMac32 %>/node-webkit.app/Contents/Resources/app.nw',
src: '**'
}, {
expand: true,
cwd: '<%= config.resources %>/mac/',
dest: '<%= config.distMac32 %>/node-webkit.app/Contents/',
filter: 'isFile',
src: '*.plist'
}, {
expand: true,
cwd: '<%= config.resources %>/mac/',
dest: '<%= config.distMac32 %>/node-webkit.app/Contents/Resources/',
filter: 'isFile',
src: '*.icns'
}, {
expand: true,
cwd: '<%= config.app %>/../node_modules/',
dest: '<%= config.distMac32 %>/node-webkit.app/Contents/Resources/app.nw/node_modules/',
src: '**'
}]
},
appMacos64: {
files: [{
expand: true,
cwd: '<%= config.app %>',
dest: '<%= config.distMac64 %>/node-webkit.app/Contents/Resources/app.nw',
src: '**'
}, {
expand: true,
cwd: '<%= config.resources %>/mac/',
dest: '<%= config.distMac64 %>/node-webkit.app/Contents/',
filter: 'isFile',
src: '*.plist'
}, {
expand: true,
cwd: '<%= config.resources %>/mac/',
dest: '<%= config.distMac64 %>/node-webkit.app/Contents/Resources/',
filter: 'isFile',
src: '*.icns'
}, {
expand: true,
cwd: '<%= config.app %>/../node_modules/',
dest: '<%= config.distMac64 %>/node-webkit.app/Contents/Resources/app.nw/node_modules/',
src: '**'
}]
},
webkit32: {
files: [{
expand: true,
cwd: '<%=config.resources %>/node-webkit/MacOS32',
dest: '<%= config.distMac32 %>/',
src: '**'
}]
},
webkit64: {
files: [{
expand: true,
cwd: '<%=config.resources %>/node-webkit/MacOS64',
dest: '<%= config.distMac64 %>/',
src: '**'
}]
},
copyWinToTmp: {
files: [{
expand: true,
cwd: '<%= config.resources %>/node-webkit/Windows/',
dest: '<%= config.tmp %>/',
src: '**'
}]
}
},
compress: {
appToTmp: {
options: {
archive: '<%= config.tmp %>/app.zip'
},
files: [{
expand: true,
cwd: '<%= config.app %>',
src: ['**']
}]
},
finalWindowsApp: {
options: {
archive: '<%= config.distWin %>/tinyCompta.zip'
},
files: [{
expand: true,
cwd: '<%= config.tmp %>',
src: ['**']
}]
}
},
rename: {
macApp32: {
files: [{
src: '<%= config.distMac32 %>/node-webkit.app',
dest: '<%= config.distMac32 %>/tinyCompta.app'
}]
},
macApp64: {
files: [{
src: '<%= config.distMac64 %>/node-webkit.app',
dest: '<%= config.distMac64 %>/tinyCompta.app'
}]
},
zipToApp: {
files: [{
src: '<%= config.tmp %>/app.zip',
dest: '<%= config.tmp %>/app.nw'
}]
}
}
});
grunt.registerTask('chmod32', 'Add lost Permissions.', function () {
var fs = require('fs'),
path = config.distMac32 + '/tinyCompta.app/Contents/';
fs.chmodSync(path + 'Frameworks/node-webkit Helper EH.app/Contents/MacOS/node-webkit Helper EH', '555');
fs.chmodSync(path + 'Frameworks/node-webkit Helper NP.app/Contents/MacOS/node-webkit Helper NP', '555');
fs.chmodSync(path + 'Frameworks/node-webkit Helper.app/Contents/MacOS/node-webkit Helper', '555');
fs.chmodSync(path + 'MacOS/node-webkit', '555');
});
grunt.registerTask('chmod64', 'Add lost Permissions.', function () {
var fs = require('fs'),
path = config.distMac64 + '/tinyCompta.app/Contents/';
fs.chmodSync(path + 'Frameworks/node-webkit Helper EH.app/Contents/MacOS/node-webkit Helper EH', '555');
fs.chmodSync(path + 'Frameworks/node-webkit Helper NP.app/Contents/MacOS/node-webkit Helper NP', '555');
fs.chmodSync(path + 'Frameworks/node-webkit Helper.app/Contents/MacOS/node-webkit Helper', '555');
fs.chmodSync(path + 'MacOS/node-webkit', '555');
});
grunt.registerTask('createLinuxApp', 'Create linux distribution.', function (version) {
var done = this.async();
var childProcess = require('child_process');
var exec = childProcess.exec;
var path = './' + (version === 'Linux64' ? config.distLinux64 : config.distLinux32);
exec('mkdir -p ' + path + '; cp resources/node-webkit/' + version + '/nw.pak ' + path + ' && cp resources/node-webkit/' + version + '/nw ' + path + '/node-webkit', function (error, stdout, stderr) {
var result = true;
if (stdout) {
grunt.log.write(stdout);
}
if (stderr) {
grunt.log.write(stderr);
}
if (error !== null) {
grunt.log.error(error);
result = false;
}
done(result);
});
});
grunt.registerTask('createWindowsApp', 'Create windows distribution.', function () {
var done = this.async();
var concat = require('concat-files');
concat([
'buildTmp/nw.exe',
'buildTmp/app.nw'
], 'buildTmp/tinyCompta.exe', function () {
var fs = require('fs');
fs.unlink('buildTmp/app.nw', function (error, stdout, stderr) {
if (stdout) {
grunt.log.write(stdout);
}
if (stderr) {
grunt.log.write(stderr);
}
if (error !== null) {
grunt.log.error(error);
done(false);
} else {
fs.unlink('buildTmp/nw.exe', function (error, stdout, stderr) {
var result = true;
if (stdout) {
grunt.log.write(stdout);
}
if (stderr) {
grunt.log.write(stderr);
}
if (error !== null) {
grunt.log.error(error);
result = false;
}
done(result);
});
}
});
});
});
grunt.registerTask('setVersion', 'Set version to all needed files', function (version) {
var config = grunt.config.get(['config']);
var appPath = config.app;
var resourcesPath = config.resources;
var mainPackageJSON = grunt.file.readJSON('package.json');
var appPackageJSON = grunt.file.readJSON(appPath + '/package.json');
var infoPlistTmp = grunt.file.read(resourcesPath + '/mac/Info.plist.tmp', {
encoding: 'UTF8'
});
var infoPlist = grunt.template.process(infoPlistTmp, {
data: {
version: version
}
});
mainPackageJSON.version = version;
appPackageJSON.version = version;
grunt.file.write('package.json', JSON.stringify(mainPackageJSON, null, 2), {
encoding: 'UTF8'
});
grunt.file.write(appPath + '/package.json', JSON.stringify(appPackageJSON, null, 2), {
encoding: 'UTF8'
});
grunt.file.write(resourcesPath + '/mac/Info.plist', infoPlist, {
encoding: 'UTF8'
});
});
grunt.registerTask('copy-vendor', [
'clean:vendor',
'copy:vendor',
]);
grunt.registerTask('dist-linux', [
'jshint',
'clean:distLinux64',
'copy:appLinux',
'createLinuxApp:Linux64'
]);
grunt.registerTask('dist-linux32', [
'jshint',
'clean:distLinux32',
'copy:appLinux32',
'createLinuxApp:Linux32'
]);
grunt.registerTask('dist-win', [
'jshint',
'clean:distWin',
'copy:copyWinToTmp',
'compress:appToTmp',
'rename:zipToApp',
'createWindowsApp',
'compress:finalWindowsApp'
]);
grunt.registerTask('dist-mac', [
'jshint',
'clean:distMac64',
'copy:webkit64',
'copy:appMacos64',
'rename:macApp64',
'chmod64'
]);
grunt.registerTask('dist-mac32', [
'jshint',
'clean:distMac32',
'copy:webkit32',
'copy:appMacos32',
'rename:macApp32',
'chmod32'
]);
grunt.registerTask('check', [
'jshint'
]);
grunt.registerTask('dmg', 'Create dmg from previously created app folder in dist.', function () {
var done = this.async();
var createDmgCommand = 'resources/mac/package.sh "tinyCompta"';
require('child_process').exec(createDmgCommand, function (error, stdout, stderr) {
var result = true;
if (stdout) {
grunt.log.write(stdout);
}
if (stderr) {
grunt.log.write(stderr);
}
if (error !== null) {
grunt.log.error(error);
result = false;
}
done(result);
});
});
};
|
// Import a renamed version of d3 with just the formatting methods
// It should avoid compatibility issues
require('./d3f')
/* o looks like :
{
value: 567.456,
unitLabel: 'km'
}
*/
function format(fmt, o, appendUnit) {
/*
We're using d3's value formatter https://github.com/mbostock/d3/wiki/Formatting
*/
if (o.value === Infinity || o.value === -Infinity) {
o.value = NaN // These are correctly handled by the formatter
}
var unit = appendUnit && o.unitLabel ? ' ' + o.unitLabel : ''
var number = o.value === 0 ? "0" : d3f.format(fmt)(o.value)
return number + unit
}
/* Outputs for example 2.5k, 26k, or 245k. */
function shortFormat(o, sign) {
sign = sign || ''
var v = Math.abs(o.value)
if (v < 0.1) {
return format(sign + ".2f", o)
} else if (v < 1) {
return format(sign + ".1f", o)
} else if (v >= 1) {
var reste = d3f.formatPrefix(v).scale(v) // e.g. 17 892 -> 17.892
if (reste < 10 && d3f.round(reste) === reste) {
return format(sign + ".1s", o)
} else if (reste < 100) {
return format(sign + ".2s", o)
} else {
return format(sign + ".3s", o)
}
}
}
/* A more precise, common (US) representation of the value, e.g. 1,234,567.78 */
function altValue(o, sign) {
sign = sign || ''
var p = o.precision
/* Do not add a .00 when value is a round number (thanks d3 for not including this... or did I miss something ?) */
if (d3f.round(o.value) === o.value) {
p = 0
} else if (p == undefined) {
/* default precision */
p = 2
}
return format(sign + ",." + p + "f", o, true)
}
function rounded(o, sign) {
sign = sign || ''
/* Do not add a .00 when value is a round number (thanks d3 for not including this... or did I miss something ?) */
return format(sign + ",.0f", o, true)
}
module.exports = {
//TODO test this
'regular': function(o) {
return {
regular: shortFormat(o),
alt: altValue(o),
rounded: rounded(o),
unitLabel: o.unitLabel
}
},
'evolution': function(o) {
return {
regular: shortFormat(o, '+'),
alt: altValue(o, '+'),
unitLabel: o.unitLabel
}
},
'percentage': function(o) {
return {
regular: format(".0%", o),
alt: format(".2%", o),
unitLabel: o.unitLabel
}
},
'evolutionPercentage': function(o) {
return {
regular: format("+.0%", o),
alt: format("+.2%", o),
unitLabel: o.unitLabel
}
},
'humanPercentage': function(o) {
/* Get a human version of a percentage : 1/3, half, about 20%, ... */
var human = '1/3' //TODO
return {
regular: human,
alt: format(".0%", o),
unitLabel: o.unitLabel
}
},
/* Format 185 seconds to 3:5 minutes (alt : 3 minutes and 5 seconds) (TODO)*/
'minutesSeconds': function(o) {
return {
regular: D.formatDuration(o.value),
alt: D.formatDurationFull(o.value)
}
},
'superShort': function(o) {
return {
regular: format(".1s", o),
alt: format(",.2f", o),
unitLabel: o.unitLabel
}
},
};
|
/**
* THIS FILE IS AUTO-GENERATED
* DON'T MAKE CHANGES HERE
*/
import { createSubset } from '../../factoriesNumber.js';
export var subsetDependencies = {
createSubset: createSubset
};
|
// import { connect } from 'react-redux'
// import { firebaseConnect } from 'react-redux-firebase'
// import { compose } from 'recompose'
// import withAuth from 'hocs/withAuth'
// import withIntl from 'hocs/withIntl'
// import EditorView from '../components/EditorView'
// const mapDispatchToProps = dispatch => {
// return {
// }
// }
// const mapStateToProps = (state) => {
// return {
// }
// }
// const wrappedEditorView = compose(
// firebaseConnect(),
// withAuth(false),
// withIntl
// )(EditorView)
// export default connect(mapStateToProps, mapDispatchToProps)(wrappedEditorView)
|
/*
* Copyright Adam Pritchard 2014
* MIT License : http://adampritchard.mit-license.org/
*/
/*
* Utilities and helpers that are needed in multiple places.
* If this module is being instantiated without a global `window` object being
* available (providing XMLHttpRequest, for example), then `Utils.global` must
* be set to an equivalent object by the caller.
*/
;(function() {
"use strict";
/*global module:false, chrome:false, safari:false*/
var Utils = {};
// For some reason the other two ways of creating properties don't work.
Utils.__defineSetter__('global', function(val) { Utils._global = val; });
Utils.__defineGetter__('global', function() {
if (typeof(Utils._global) === 'function') {
return Utils._global.call();
}
return Utils._global;
});
Utils.global = this;
function consoleLog(logString) {
if (typeof(console) !== 'undefined') {
console.log(logString);
}
else {
var consoleService = Components.classes['@mozilla.org/consoleservice;1']
.getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage(String(logString));
}
}
// TODO: Try to use `insertAdjacentHTML` for the inner and outer HTML functions.
// https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
// Assigning a string directly to `element.innerHTML` is potentially dangerous:
// e.g., the string can contain harmful script elements. (Additionally, Mozilla
// won't let us pass validation with `innerHTML` assignments in place.)
// This function provides a safer way to append a HTML string into an element.
function saferSetInnerHTML(parentElem, htmlString) {
// Jump through some hoops to avoid using innerHTML...
var range = parentElem.ownerDocument.createRange();
range.selectNodeContents(parentElem);
var docFrag = range.createContextualFragment(htmlString);
docFrag = sanitizeDocumentFragment(docFrag);
range.deleteContents();
range.insertNode(docFrag);
range.detach();
}
// Approximating equivalent to assigning to `outerHTML` -- completely replaces
// the target element with `htmlString`.
// Note that some caveats apply that also apply to `outerHTML`:
// - The element must be in the DOM. Otherwise an exception will be thrown.
// - The original element has been removed from the DOM, but continues to exist.
// Any references to it (such as the one passed into this function) will be
// references to the original.
function saferSetOuterHTML(elem, htmlString) {
if (!isElementinDocument(elem)) {
throw new Error('Element must be in document');
}
var range = elem.ownerDocument.createRange();
range.selectNode(elem);
var docFrag = range.createContextualFragment(htmlString);
docFrag = sanitizeDocumentFragment(docFrag);
range.deleteContents();
range.insertNode(docFrag);
range.detach();
}
// Removes potentially harmful elements and attributes from `docFrag`.
// Returns a santized copy.
function sanitizeDocumentFragment(docFrag) {
var i;
// Don't modify the original
docFrag = docFrag.cloneNode(true);
var scriptTagElems = docFrag.querySelectorAll('script');
for (i = 0; i < scriptTagElems.length; i++) {
scriptTagElems[i].parentNode.removeChild(scriptTagElems[i]);
}
function cleanAttributes(node) {
var i;
if (typeof(node.removeAttribute) === 'undefined') {
// We can't operate on this node
return;
}
// Remove event handler attributes
for (i = node.attributes.length-1; i >= 0; i--) {
if (node.attributes[i].name.match(/^on/)) {
node.removeAttribute(node.attributes[i].name);
}
}
}
walkDOM(docFrag.firstChild, cleanAttributes);
return docFrag;
}
// Walk the DOM, executing `func` on each element.
// From Crockford.
function walkDOM(node, func) {
func(node);
node = node.firstChild;
while(node) {
walkDOM(node, func);
node = node.nextSibling;
}
}
// Next three functions from: http://stackoverflow.com/a/1483487/729729
// Returns true if `node` is in `range`.
// NOTE: This function is broken in Postbox: https://github.com/adam-p/markdown-here/issues/179
function rangeIntersectsNode(range, node) {
var nodeRange;
// adam-p: I have found that Range.intersectsNode gives incorrect results in
// Chrome (but not Firefox). So we're going to use the fail-back code always,
// regardless of whether the current platform implements Range.intersectsNode.
if (false && range.intersectsNode) {
return range.intersectsNode(node);
}
else {
nodeRange = node.ownerDocument.createRange();
try {
nodeRange.selectNode(node);
}
catch (e) {
nodeRange.selectNodeContents(node);
}
// Workaround for this old Mozilla bug, which is still present in Postbox:
// https://bugzilla.mozilla.org/show_bug.cgi?id=665279
var END_TO_START = node.ownerDocument.defaultView.Range.END_TO_START || Utils.global.Range.END_TO_START;
var START_TO_END = node.ownerDocument.defaultView.Range.START_TO_END || Utils.global.Range.START_TO_END;
return range.compareBoundaryPoints(
END_TO_START,
nodeRange) === -1 &&
range.compareBoundaryPoints(
START_TO_END,
nodeRange) === 1;
}
}
// Returns array of elements in selection.
function getSelectedElementsInDocument(doc) {
var range, sel, containerElement;
sel = doc.getSelection();
if (sel.rangeCount > 0) {
range = sel.getRangeAt(0);
}
if (!range) {
return [];
}
return getSelectedElementsInRange(range);
}
// Returns array of elements in range
function getSelectedElementsInRange(range) {
var elems = [], treeWalker, containerElement;
if (range) {
containerElement = range.commonAncestorContainer;
if (containerElement.nodeType != 1) {
containerElement = containerElement.parentNode;
}
elems = [treeWalker.currentNode];
walkDOM(
containerElement,
function(node) {
if (rangeIntersectsNode(range, node)) {
elems.push(node);
}
});
/*
// This code is probably superior, but TreeWalker is not supported by Postbox.
// If this ends up getting used, it should probably be moved into walkDOM
// (or walkDOM should be removed).
treeWalker = doc.createTreeWalker(
containerElement,
range.commonAncestorContainerownerDocument.defaultView.NodeFilter.SHOW_ELEMENT,
function(node) { return rangeIntersectsNode(range, node) ? range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_ACCEPT : range.commonAncestorContainerownerDocument.defaultView.NodeFilter.FILTER_REJECT; },
false
);
elems = [treeWalker.currentNode];
while (treeWalker.nextNode()) {
elems.push(treeWalker.currentNode);
}
*/
}
return elems;
}
function isElementinDocument(element) {
var doc = element.ownerDocument;
while (!!(element = element.parentNode)) {
if (element === doc) {
return true;
}
}
return false;
}
// From: http://stackoverflow.com/a/3819589/729729
// Postbox doesn't support `node.outerHTML`.
function outerHTML(node, doc) {
// if IE, Chrome take the internal method otherwise build one
return node.outerHTML || (
function(n){
var div = doc.createElement('div'), h;
div.appendChild(n.cloneNode(true));
h = div.innerHTML;
div = null;
return h;
})(node);
}
// From: http://stackoverflow.com/a/5499821/729729
var charsToReplace = {
'&': '&',
'<': '<',
'>': '>'
};
function replaceChar(char) {
return charsToReplace[char] || char;
}
// An approximate equivalent to outerHTML for document fragments.
function getDocumentFragmentHTML(docFrag) {
var html = '', i;
for (i = 0; i < docFrag.childNodes.length; i++) {
var node = docFrag.childNodes[i];
if (node.nodeType === node.TEXT_NODE) {
html += node.nodeValue.replace(/[&<>]/g, replaceChar);
}
else { // going to assume ELEMENT_NODE
html += outerHTML(node, docFrag.ownerDocument);
}
}
return html;
}
function isElementDescendant(parent, descendant) {
var ancestor = descendant;
while (!!(ancestor = ancestor.parentNode)) {
if (ancestor === parent) {
return true;
}
}
return false;
}
// Take a URL that refers to a file in this extension and makes it absolute.
// Note that the URL *must not* be relative to the current path position (i.e.,
// no "./blah" or "../blah"). So `url` must start with `/`.
function getLocalURL(url) {
if (url[0] !== '/') {
throw 'relative url not allowed: ' + url;
}
if (url.indexOf('://') >= 0) {
// already absolute
return url;
}
if (typeof(chrome) !== 'undefined') {
return chrome.extension.getURL(url);
}
else if (typeof(safari) !== 'undefined') {
return safari.extension.baseURI + 'markdown-here/src' + url;
}
else {
// Mozilla platform.
// HACK The proper URL depends on values in `chrome.manifest`. But we "know"
// that there are only a couple of locations we request from, so we're going
// to branch depending on the presence of "common".
var COMMON = '/common/';
var CONTENT = '/firefox/chrome/';
if (url.indexOf(COMMON) === 0) {
return 'resource://markdown_here_common/' + url.slice(COMMON.length);
}
else if (url.indexOf(CONTENT) === 0) {
return 'chrome://markdown_here/' + url.slice(CONTENT.length);
}
}
throw 'unknown url type: ' + url;
}
// Makes an asynchrous XHR request for a local file (basically a thin wrapper).
// `mimetype` is optional. `callback` will be called with the responseText as
// argument.
// If error occurs, `callback`'s second parameter will be an error.
function getLocalFile(url, mimetype, callback) {
if (!callback) {
// optional mimetype not provided
callback = mimetype;
mimetype = null;
}
var xhr = new Utils.global.XMLHttpRequest();
if (mimetype) {
xhr.overrideMimeType(mimetype);
}
xhr.open('GET', url);
xhr.onload = function() {
if (callback) {
callback(this.responseText);
callback = null;
}
};
xhr.onerror = function(e) {
if (callback) {
callback(null, e);
callback = null;
}
};
try {
// On some platforms, xhr.send throws an error if the url is not found.
// On some platforms, it will call onerror and on some it won't.
xhr.send();
}
catch(e) {
if (callback) {
callback(null, e);
callback = null;
return;
}
}
}
// Does async XHR request to get data at `url`, then passes it to `callback`
// Base64-encoded.
// Intended to be used get the logo image file in a form that can be put in a
// data-url image element.
// If error occurs, `callback`'s second parameter will be an error.
function getLocalFileAsBase64(url, callback) {
var xhr = new Utils.global.XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
var uInt8Array = new Uint8Array(this.response);
var base64Data = base64EncArr(uInt8Array);
if (callback) {
callback(base64Data);
callback = null;
}
};
xhr.onerror = function(e) {
if (callback) {
callback(null, e);
callback = null;
}
};
try {
// On some platforms, xhr.send throws an error if the url is not found.
// On some platforms, it will call onerror and on some it won't.
xhr.send();
}
catch(e) {
if (callback) {
callback(null, e);
callback = null;
return;
}
}
}
// Events fired by Markdown Here will have this property set to true.
var MARKDOWN_HERE_EVENT = 'markdown-here-event';
// Fire a mouse event on the given element. (Note: not super robust.)
function fireMouseClick(elem) {
var clickEvent = elem.ownerDocument.createEvent('MouseEvent');
clickEvent.initMouseEvent(
'click',
false, // bubbles: We want to target this element and do not want the event to bubble.
true, // cancelable
elem.ownerDocument.defaultView, // view,
1, // detail,
0, // screenX
0, // screenY
0, // clientX
0, // clientY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
null); // relatedTarget
clickEvent[MARKDOWN_HERE_EVENT] = true;
elem.dispatchEvent(clickEvent);
}
var PRIVILEGED_REQUEST_EVENT_NAME = 'markdown-here-request-event';
function makeRequestToPrivilegedScript(doc, requestObj, callback) {
if (typeof(chrome) !== 'undefined') {
// If `callback` is undefined and we pass it anyway, Chrome complains with this:
// Uncaught Error: Invocation of form extension.sendMessage(object, undefined, null) doesn't match definition extension.sendMessage(optional string extensionId, any message, optional function responseCallback)
if (callback) {
chrome.extension.sendMessage(requestObj, callback);
}
else {
chrome.extension.sendMessage(requestObj);
}
}
else if (typeof(safari) !== 'undefined') {
/*
Unlike Chrome, Safari doesn't provide a way to pass a callback to a background-
script request. Instead the background script sends a separate message to
the content script. We'll keep a set of outstanding callbacks to process as
the responses come in.
*/
// If this is the first call, do some initialization.
if (typeof(makeRequestToPrivilegedScript.requestCallbacks) === 'undefined') {
makeRequestToPrivilegedScript.requestCallbacks = {};
// Handle messages received from the background script.
var backgroundMessageHandler = function(event) {
// Note that this message handler will get triggered by any request sent
// from the background script to the content script for a page, and
// it'll get triggered once for each frame in the page. So we need to
// make very sure that we should be acting on the message.
if (event.name === 'request-response') {
var responseObj = Utils.global.JSON.parse(event.message);
if (responseObj.requestID &&
makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID]) {
// Call the stored callback.
makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID](responseObj.response);
// And remove the stored callback.
delete makeRequestToPrivilegedScript.requestCallbacks[responseObj.requestID];
}
}
};
safari.self.addEventListener('message', backgroundMessageHandler, false);
}
// Store the callback for later use in the response handler.
if (callback) {
var reqID = Math.random();
makeRequestToPrivilegedScript.requestCallbacks[reqID] = callback;
requestObj.requestID = reqID;
}
safari.self.tab.dispatchMessage('request', Utils.global.JSON.stringify(requestObj));
}
else {
// See: https://developer.mozilla.org/en-US/docs/Code_snippets/Interaction_between_privileged_and_non-privileged_pages#Chromium-like_messaging.3A_json_request_with_json_callback
// Make a unique event name to use. (Bad style to modify the input like this...)
requestObj.responseEventName = 'markdown-here-response-event-' + Math.floor(Math.random()*1000000);
var request = doc.createTextNode(JSON.stringify(requestObj));
var responseHandler = function(event) {
var response = null;
// There may be no response data.
if (request.nodeValue) {
response = JSON.parse(request.nodeValue);
}
request.parentNode.removeChild(request);
if (callback) {
callback(response);
}
};
request.addEventListener(requestObj.responseEventName, responseHandler, false);
(doc.head || doc.body).appendChild(request);
var event = doc.createEvent('HTMLEvents');
event.initEvent(PRIVILEGED_REQUEST_EVENT_NAME, true, false);
request.dispatchEvent(event);
}
}
// Gives focus to the element.
// Setting focus into elements inside iframes is not simple.
function setFocus(elem) {
// We need to do some tail-recursion focus setting up through the iframes.
if (elem.document) {
// This is a window
if (elem.frameElement) {
// This is the window of an iframe. Set focus to the parent window.
setFocus(elem.frameElement.ownerDocument.defaultView);
}
}
else if (elem.ownerDocument.defaultView.frameElement) {
// This element is in an iframe. Set focus to its owner window.
setFocus(elem.ownerDocument.defaultView);
}
elem.focus();
}
// Gets the URL of the top window that elem belongs to.
// May recurse up through iframes.
function getTopURL(win, justHostname) {
if (win.frameElement) {
// This is the window of an iframe
return getTopURL(win.frameElement.ownerDocument.defaultView);
}
var url;
// We still want a useful value if we're in Thunderbird, etc.
if (!win.location.href || win.location.href === 'about:blank') {
url = win.navigator.userAgent.match(/Thunderbird|Postbox'/);
if (url) {
url = url[0];
}
}
else if (justHostname) {
url = win.location.hostname;
}
else {
url = win.location.href;
}
return url;
}
// Sets a short timeout and then calls callback
function nextTick(callback, context) {
var runner = function nextTickInner() {
callback.call(context);
};
Utils.global.setTimeout(runner, 0);
}
// `context` is optional. Will be `this` when `callback` is called.
function nextTickFn(callback, context) {
return function nextTickFnInner() {
var args = arguments;
var runner = function() {
callback.apply(context, args);
};
Utils.global.setTimeout(runner, 0);
};
}
/*
* i18n/l10n
*/
/*
This is a much bigger hassle than it should be. i18n support is great on Chrome,
a bit of a hassle on Firefox/Thunderbird, and basically nonexistent on Safari.
In Chrome, we can use `chrome.i18n.getMessage` to just get the string we want,
in either content or background scripts, synchronously and with no extra prep
work.
In Firefox, we need to load the `strings.properties` string bundle for both the
current locale and English (our fallback language) and combine them. This can
only be done from a privileged script. Then we can use the strings. The loading
is synchronous for the privileged script, but asynchronous for the unprivileged
script (because it needs to make a request to the privileged script).
In Safari, we need to read in the JSON files for the current locale and English
(our fallback language) and combine them. This can only be done from a privileged
script. Then we can use the strings. The loading is asynchronous for both
privileged and unprivileged scripts (because async XHR is used for the former
and a request is made to the privileged script for the latter).
It can happen that attempts to access the strings are made before the loading
has actually occurred. This has been observed on Safari in the MDH Options page.
This necessitated the addition of `registerStringBundleLoadListener` and
`triggerStringBundleLoadListeners`, which may be used to ensure that `getMessage`
calls wait until the loading is complete.
*/
var g_stringBundleLoadListeners = [];
function registerStringBundleLoadListener(callback) {
if (typeof(chrome) !== 'undefined' ||
(typeof(g_mozStringBundle) === 'object' && Object.keys(g_mozStringBundle).length > 0) ||
(typeof(g_safariStringBundle) === 'object' && Object.keys(g_safariStringBundle).length > 0)) {
// Already loaded
Utils.nextTick(callback);
return;
}
g_stringBundleLoadListeners.push(callback);
}
function triggerStringBundleLoadListeners() {
var listener;
while (g_stringBundleLoadListeners.length > 0) {
listener = g_stringBundleLoadListeners.pop();
listener();
}
}
// Must only be called from a priviledged Mozilla script
function getMozStringBundle() {
if (typeof(Components) === 'undefined' || typeof(Components.classes) === 'undefined') {
return false;
}
// Return a cached bundle, if we have one
if (typeof(g_mozStringBundle) !== 'undefined' &&
Object.keys(g_mozStringBundle).length > 0) {
return g_mozStringBundle;
}
// Adapted from: https://developer.mozilla.org/en-US/docs/Code_snippets/Miscellaneous#Using_string_bundles_from_JavaScript
// and: https://developer.mozilla.org/en-US/docs/Using_nsISimpleEnumerator
var stringBundleObj = {}, stringBundle, stringBundleEnum, property;
// First load the English fallback strings
stringBundle = Utils.global.Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
// Notice the explicit locale in this path:
.createBundle("resource://markdown_here_locale/en/strings.properties");
stringBundleEnum = stringBundle.getSimpleEnumeration();
while (stringBundleEnum.hasMoreElements()) {
property = stringBundleEnum.getNext().QueryInterface(Components.interfaces.nsIPropertyElement);
stringBundleObj[property.key] = property.value;
}
// Then load the strings that are overridden for the current locale
stringBundle = Utils.global.Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle("chrome://markdown_here/locale/strings.properties");
stringBundleEnum = stringBundle.getSimpleEnumeration();
while (stringBundleEnum.hasMoreElements()) {
property = stringBundleEnum.getNext().QueryInterface(Components.interfaces.nsIPropertyElement);
stringBundleObj[property.key] = property.value;
}
return stringBundleObj;
}
// Load the Mozilla string bundle
if (typeof(chrome) === 'undefined' && typeof(safari) === 'undefined') {
var g_mozStringBundle = getMozStringBundle();
if ((!g_mozStringBundle || Object.keys(g_mozStringBundle).length === 0) &&
Utils.global.setTimeout) {
Utils.global.setTimeout(function requestMozStringBundle() {
makeRequestToPrivilegedScript(Utils.global.document, {action: 'get-string-bundle'}, function(response) {
g_mozStringBundle = response;
triggerStringBundleLoadListeners();
});
}, 0);
}
else {
// g_mozStringBundle is filled in
triggerStringBundleLoadListeners();
}
}
// Will only succeed when called from a privileged Safari script.
// `callback(data, err)` is passed a non-null value for err in case of total
// failure, which should be interpreted as being called from a non-privileged
// (content) script.
// Otherwise `data` will contain the string bundle object.
function getSafariStringBundle(callback) {
// Can't use Utils.functionname in this function, since the exports haven't
// been set up at the time it's called.
var stringBundle = {};
// Return a cached bundle, if we have one
if (typeof(g_safariStringBundle) !== 'undefined' &&
Object.keys(g_safariStringBundle).length > 0) {
nextTickFn(callback)(g_safariStringBundle);
return;
}
// Get the English fallback
getStringBundle('en', function(data, err) {
if (err) {
consoleLog('Error getting English string bundle:');
consoleLog(err);
return callback(null, err);
}
extendBundle(stringBundle, data);
var locale = Utils.global.navigator.language;
if (locale.indexOf('en') === 0) {
// The locale is English, nothing more to do
return callback(stringBundle, null);
}
// Get the actual locale string bundle
getStringBundle(locale, function(data, err) {
if (err) {
// The locale in navigator.language typically looks like "ja-JP", but
// MDH's locale typically looks like "ja".
locale = locale.split('-')[0];
getStringBundle(locale, function(data, err) {
if (err) {
// Couldn't find it. We'll just have to use the fallback.
consoleLog('Markdown Here has no language support for: ' + locale);
return callback(stringBundle);
}
extendBundle(stringBundle, data);
return callback(stringBundle);
});
}
extendBundle(stringBundle, data);
return callback(stringBundle);
});
});
function getStringBundle(locale, callback) {
var url = getLocalURL('/_locales/' + locale + '/messages.json');
getLocalFile(url, 'application/json', function(data, err) {
if (err) {
return callback(null, err);
}
// Chrome's messages.json uses "$" as placeholders and "$$" as an explicit
// "$". We're not yet using placeholders, so we'll just convert double to singles.
data = data.replace(/\$\$/g, '$');
return callback(JSON.parse(data));
});
}
function extendBundle(intoBundle, fromObj) {
var key;
for (key in fromObj) {
intoBundle[key] = fromObj[key].message;
}
}
}
// Load the Safari string bundle
if (typeof(safari) !== 'undefined') {
var g_safariStringBundle = {};
// This is effectively checking if we're calling from a privileged script.
// We could instead just try getSafariStringBundle() and check the error, but
// that's surely less efficient.
if (typeof(safari.application) !== 'undefined') {
// calling from a privileged script
getSafariStringBundle(function(data, err) {
if (err) {
consoleLog('Markdown Here: privileged script failed to load string bundle: ' + err);
return;
}
g_safariStringBundle = data;
triggerStringBundleLoadListeners();
});
}
else {
// Call from the privileged script
makeRequestToPrivilegedScript(Utils.global.document, {action: 'get-string-bundle'}, function(response) {
if (response) {
g_safariStringBundle = response;
triggerStringBundleLoadListeners();
}
else {
consoleLog('Markdown Here: content script failed to get string bundle from privileged script');
}
});
}
}
// Get the translated string indicated by `messageID`.
// Note that there's no support for placeholders as yet.
// Throws exception if message is not found or if the platform doesn't support
// internationalization (yet).
function getMessage(messageID) {
var message = '';
if (typeof(chrome) !== 'undefined') {
message = chrome.i18n.getMessage(messageID);
}
else if (typeof(safari) !== 'undefined') {
if (g_safariStringBundle) {
message = g_safariStringBundle[messageID];
}
else {
// We don't yet have the string bundle available
return '';
}
}
else { // Mozilla
if (g_mozStringBundle) {
message = g_mozStringBundle[messageID];
}
else {
// We don't yet have the string bundle available
return '';
}
}
if (!message) {
throw new Error('Could not find message ID: ' + messageID);
}
return message;
}
/*****************************************************************************/
/*\
|*|
|*| Base64 / binary data / UTF-8 strings utilities
|*|
|*| https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
|*|
\*/
/* Array of bytes to base64 string decoding */
function b64ToUint6 (nChr) {
return nChr > 64 && nChr < 91 ?
nChr - 65
: nChr > 96 && nChr < 123 ?
nChr - 71
: nChr > 47 && nChr < 58 ?
nChr + 4
: nChr === 43 ?
62
: nChr === 47 ?
63
:
0;
}
function base64DecToArr (sBase64, nBlocksSize) {
var
sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
/* Base64 string to array encoding */
function uint6ToB64 (nUint6) {
return nUint6 < 26 ?
nUint6 + 65
: nUint6 < 52 ?
nUint6 + 71
: nUint6 < 62 ?
nUint6 - 4
: nUint6 === 62 ?
43
: nUint6 === 63 ?
47
:
65;
}
function base64EncArr (aBytes) {
var nMod3 = 2, sB64Enc = "";
for (var nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
nMod3 = nIdx % 3;
if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
if (nMod3 === 2 || aBytes.length - nIdx === 1) {
sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
nUint24 = 0;
}
}
return sB64Enc.substr(0, sB64Enc.length - 2 + nMod3) + (nMod3 === 2 ? '' : nMod3 === 1 ? '=' : '==');
}
/* UTF-8 array to DOMString and vice versa */
function UTF8ArrToStr (aBytes) {
var sView = "";
for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
nPart = aBytes[nIdx];
sView += String.fromCharCode(
nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
/* (nPart - 252 << 32) is not possible in ECMAScript! So...: */
(nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
(nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
(nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
(nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
: nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
(nPart - 192 << 6) + aBytes[++nIdx] - 128
: /* nPart < 127 ? */ /* one byte */
nPart
);
}
return sView;
}
function strToUTF8Arr (sDOMStr) {
var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0;
/* mapping... */
for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) {
nChr = sDOMStr.charCodeAt(nMapIdx);
nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6;
}
aBytes = new Uint8Array(nArrLen);
/* transcription... */
for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) {
nChr = sDOMStr.charCodeAt(nChrIdx);
if (nChr < 128) {
/* one byte */
aBytes[nIdx++] = nChr;
} else if (nChr < 0x800) {
/* two bytes */
aBytes[nIdx++] = 192 + (nChr >>> 6);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x10000) {
/* three bytes */
aBytes[nIdx++] = 224 + (nChr >>> 12);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x200000) {
/* four bytes */
aBytes[nIdx++] = 240 + (nChr >>> 18);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else if (nChr < 0x4000000) {
/* five bytes */
aBytes[nIdx++] = 248 + (nChr >>> 24);
aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
} else /* if (nChr <= 0x7fffffff) */ {
/* six bytes */
aBytes[nIdx++] = 252 + /* (nChr >>> 32) is not possible in ECMAScript! So...: */ (nChr / 1073741824);
aBytes[nIdx++] = 128 + (nChr >>> 24 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
aBytes[nIdx++] = 128 + (nChr & 63);
}
}
return aBytes;
}
/*****************************************************************************/
function utf8StringToBase64(str) {
return base64EncArr(strToUTF8Arr(str));
}
function base64ToUTF8String(str) {
return UTF8ArrToStr(base64DecToArr(str));
}
// Expose these functions
Utils.saferSetInnerHTML = saferSetInnerHTML;
Utils.saferSetOuterHTML = saferSetOuterHTML;
Utils.walkDOM = walkDOM;
Utils.sanitizeDocumentFragment = sanitizeDocumentFragment;
Utils.rangeIntersectsNode = rangeIntersectsNode;
Utils.getDocumentFragmentHTML = getDocumentFragmentHTML;
Utils.isElementDescendant = isElementDescendant;
Utils.getLocalURL = getLocalURL;
Utils.getLocalFile = getLocalFile;
Utils.getLocalFileAsBase64 = getLocalFileAsBase64;
Utils.fireMouseClick = fireMouseClick;
Utils.MARKDOWN_HERE_EVENT = MARKDOWN_HERE_EVENT;
Utils.makeRequestToPrivilegedScript = makeRequestToPrivilegedScript;
Utils.PRIVILEGED_REQUEST_EVENT_NAME = PRIVILEGED_REQUEST_EVENT_NAME;
Utils.consoleLog = consoleLog;
Utils.setFocus = setFocus;
Utils.getTopURL = getTopURL;
Utils.nextTick = nextTick;
Utils.nextTickFn = nextTickFn;
Utils.getMozStringBundle = getMozStringBundle;
Utils.getSafariStringBundle = getSafariStringBundle;
Utils.registerStringBundleLoadListener = registerStringBundleLoadListener;
Utils.getMessage = getMessage;
Utils.utf8StringToBase64 = utf8StringToBase64;
Utils.base64ToUTF8String = base64ToUTF8String;
var EXPORTED_SYMBOLS = ['Utils'];
if (typeof module !== 'undefined') {
module.exports = Utils;
} else {
this.Utils = Utils;
this.EXPORTED_SYMBOLS = EXPORTED_SYMBOLS;
}
}).call(function() {
return this || (typeof window !== 'undefined' ? window : global);
}());
|
function DragToHighlight(contentSelector, options) {
const ELEMENT_NODE_TYPE = 1;
const TEXT_NODE_TYPE = 3;
var _this = this;
// User-configurable options
var options = options || {};
var contentEls;
var highlightableElements = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote'];
var highlightColor = '#fff178';
var wrapElName = 'hl-wrap'; // A custom element to wrap each word in paragraphs to detect user click position
var highlightElName = 'hl-highlight'; // Class of highlighted element
var highlightableClassName = 'hl-highlightable'; // Custom class to allow highlighting
// Stacks used to keep undo/redo history
var undoHistoryStack = [];
var redoHistoryStack = [];
// Register custom elements
var WrapElement = document.registerElement(wrapElName);
var HighlightElement = document.registerElement(highlightElName);
// Paragraph elements
var paragraphEls = [];
/**
* Initialize the highlighter plug-in
*/
var init = function() {
contentEls = document.querySelectorAll(contentSelector);
contentEls.forEach(function(contentEl) {
var contentChildNodes = contentEl.childNodes;
contentChildNodes.forEach(function (el) {
if ((el.classList != undefined && el.classList.contains(highlightableClassName)) || (highlightableElements.indexOf(el.nodeName.toLowerCase()) > -1)) {
paragraphEls.push(el);
el.innerHTML = wrapAllWordsInElement(el.innerHTML);
el.addEventListener('click', handleClick);
}
});
});
attachEventHandlers();
};
/**
* Attach event handlers
*/
var attachEventHandlers = function() {
window.addEventListener('mouseup', handleWindowMouseUp);
};
/**
* Wrap all words
*
* @param html Target DOM element
*/
var wrapAllWordsInElement = function(html) {
return html.replace(/([^\s-.,;:!?()[\]{}<>"]+)/g, '<' + wrapElName + '>$1</' + wrapElName + '>');
};
/**
* Event handler for mouseup event
* mouseup event is fired when user releases a mouse click or drag
*
* @param e
*/
// 1. Get selection
// 2. Check whether the user has began and ended the highlight in words, or in whitespaces or other chars (dot, semicolon, etc)
// 3. Highlight
var handleWindowMouseUp = function() {
// Get current selection (range to highlight)
var selection = window.getSelection ? window.getSelection() : document.selection;
// If no selection has made, do nothing and return
if (selection.toString().trim() === "") {
return;
}
// The Node in which the selection begins
var startNode = selection.anchorNode;
// The Node in which the selection ends
var endNode = selection.focusNode;
// If user selected in reverse direction (dragged from right to left), swap start and end node
if (startNode.compareDocumentPosition(endNode) & Node.DOCUMENT_POSITION_PRECEDING) {
var tempNode = startNode;
startNode = endNode;
endNode = tempNode;
}
var beginParagraphEl, beginSpanEl, endParagraphEl, endSpanEl;
if (startNode.parentNode.nodeName.toLowerCase() === wrapElName.toLowerCase()) {
beginParagraphEl = startNode.parentNode.parentNode;
beginSpanEl = startNode.parentNode;
} else if (startNode.parentNode.nodeName === "P") {
beginParagraphEl = startNode.parentNode;
beginSpanEl = startNode.nextSibling;
}
if (endNode.parentNode.nodeName.toLowerCase() === wrapElName.toLowerCase()) {
endParagraphEl = endNode.parentNode.parentNode;
endSpanEl = endNode.parentNode;
} else if (endNode.parentNode.nodeName === "P") {
endParagraphEl = endNode.parentNode;
endSpanEl = endNode.previousSibling;
}
var highlightedInnerHTML;
var isHighlighting = false;
var isHighlightComplete = false;
var originalStatus = [];
// Highlight
paragraphEls.forEach(function (pEl) {
// If highlighting is complete
// or highlighting hasn't started but we haven't reached the beginning paragraph,
// do nothing and skip iteration
if (isHighlightComplete || (!isHighlighting && (pEl !== beginParagraphEl))) {
return;
}
highlightedInnerHTML = '';
if (isHighlighting) {
highlightedInnerHTML += '<' + highlightElName + ' style="background-color: ' + highlightColor + ';">';
}
pEl.childNodes.forEach(function (el) {
if (el === beginSpanEl) {
isHighlighting = true;
highlightedInnerHTML += '<' + highlightElName + ' style="background-color: ' + highlightColor + ';">';
highlightedInnerHTML += el.innerText;
}
else if (el === endSpanEl) {
isHighlighting = false;
isHighlightComplete = true;
highlightedInnerHTML += el.innerText + '</' + highlightElName + '>';
}
else if (isHighlighting) {
if (el.nodeType === ELEMENT_NODE_TYPE) {
highlightedInnerHTML += el.innerText;
} else if (el.nodeType === TEXT_NODE_TYPE) {
highlightedInnerHTML += el.nodeValue;
}
}
else if (!isHighlighting) {
if (el.nodeName.toLowerCase() === highlightElName) {
highlightedInnerHTML += el.outerHTML;
}
else if (el.nodeType === ELEMENT_NODE_TYPE) {
highlightedInnerHTML += el.outerHTML;
} else if (el.nodeType === TEXT_NODE_TYPE) {
highlightedInnerHTML += el.nodeValue;
}
}
}); // END: pEl.childNodes.forEach(function(el, index, childNodes) {}
if (isHighlighting) {
highlightedInnerHTML += '</' + highlightElName + '>';
}
// Save a patch to highlight history
originalStatus.push({
el: pEl,
html: pEl.innerHTML
});
// Render
pEl.innerHTML = highlightedInnerHTML;
}); // END: paragraphEls.forEach(function(pEl, pIndex, pEls) {}
undoHistoryStack.push(originalStatus);
redoHistoryStack = [];
// Remove selection if highlighting is complete
if (isHighlightComplete) {
if (selection.removeAllRanges) {
selection.removeAllRanges();
} else if (selection.empty) {
selection.empty();
}
}
};
/**
* Event handler for click events
*
* @param e Click event
*/
var handleClick = function(e) {
deleteHighlightedElement(e.target);
};
/**
* Delete a highlighted element
*
* @param targetEl Element to unhighlight
*/
var deleteHighlightedElement = function(targetEl) {
if (targetEl && targetEl.nodeName.toLowerCase() == highlightElName) {
var originalStatus = [];
originalStatus.push({
el: targetEl.parentNode,
html: targetEl.parentNode.innerHTML
});
targetEl.insertAdjacentHTML('beforebegin', wrapAllWordsInElement(targetEl.innerHTML));
targetEl.parentNode.removeChild(targetEl);
undoHistoryStack.push(originalStatus);
redoHistoryStack = [];
}
};
/**
* Restore changed elements to original state
* Used internally to perform undo/redo actions
*
* @param stateToRestore
* @returns {Array}
*/
var restore = function(stateToRestore) {
var originalState = [];
for (var i = 0; i < stateToRestore.length; i++) {
var status = stateToRestore[i];
originalState.push({
el: status.el,
html: status.el.innerHTML
});
status.el.innerHTML = status.html;
}
stateToRestore.html = status.innerHTML;
return originalState;
};
var rgb2hex = function(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
};
var hex = function(x) {
var hexDigits = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
};
/**
* Undo highlighting action
*
* If no previous state exists, this function will do nothing
*/
_this.undo = function() {
// If no state exists for undoing, do nothing
if (undoHistoryStack.length === 0) {
return;
}
var stateToRestore = undoHistoryStack.pop();
var originalState = restore(stateToRestore);
redoHistoryStack.push(originalState);
};
/**
* Redo highlighting action
*
* If at latest state, do nothing
*/
_this.redo = function() {
// If no state exists for redoing, do nothing
if (redoHistoryStack.length === 0) {
return;
}
var stateToRestore = redoHistoryStack.pop();
var originalState = restore(stateToRestore);
undoHistoryStack.push(originalState);
};
/**
* Getter for highlighting color
*
* @returns {string} current highlighting color
*/
_this.getColor = function() {
return highlightColor;
};
/**
* Setter for highlighting color
*
* @param newColor new highlighting color
*/
_this.setColor = function(newColor) {
highlightColor = newColor;
};
/**
* Clear all highlights of specific color
*
* @param hexColor Target highlight color
*/
_this.clearHighlightsByColor = function(hexColor) {
var allHighlightedEls = document.querySelectorAll(highlightElName);
allHighlightedEls.forEach(function(el) {
var highlightedColor = rgb2hex(el.style.backgroundColor);
if (highlightedColor === hexColor) {
deleteHighlightedElement(el);
}
});
console.log(allHighlightedEls);
};
init();
}
|
import * as actions from './constants';
import api from '../services/authApi';
export function getProfile(status) {
return dispatch => {
dispatch({ type: actions.FETCHING_PROFILE });
api.getUser(status)
.then(profile => {
dispatch({ type: actions.FETCHED_PROFILE, payload: profile });
})
.catch(error => {
dispatch({ type: actions.FETCHED_PROFILE_ERROR, payload: error });
});
};
}
export function updateImage(status, data) {
return dispatch => {
dispatch({ type: actions.UPDATING_IMAGE });
api.update(status, data)
.then(updated => {
dispatch({ type: actions.UPDATED_IMAGE, payload: updated });
})
.catch(error => {
dispatch({ type: actions.UPDATED_IMAGE_ERROR, payload: error });
});
};
}
|
'use strict';
/**
* Module dependencies.
*/
var AbstractGrantType = require('./abstract-grant-type');
var InvalidArgumentError = require('../errors/invalid-argument-error');
var InvalidGrantError = require('../errors/invalid-grant-error');
var InvalidRequestError = require('../errors/invalid-request-error');
var Promise = require('bluebird');
var promisify = require('promisify-any').use(Promise);
var is = require('../validator/is');
var util = require('util');
/**
* Constructor.
*/
function PasswordGrantType(options) {
options = options || {};
if (!options.model) {
throw new InvalidArgumentError('Missing parameter: `model`');
}
if (!options.model.getUser) {
throw new InvalidArgumentError('Invalid argument: model does not implement `getUser()`');
}
if (!options.model.saveToken) {
throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`');
}
AbstractGrantType.call(this, options);
}
/**
* Inherit prototype.
*/
util.inherits(PasswordGrantType, AbstractGrantType);
/**
* Retrieve the user from the model using a username/password combination.
*
* @see https://tools.ietf.org/html/rfc6749#section-4.3.2
*/
PasswordGrantType.prototype.handle = function(request, client) {
if (!request) {
throw new InvalidArgumentError('Missing parameter: `request`');
}
if (!client) {
throw new InvalidArgumentError('Missing parameter: `client`');
}
var scope = this.getScope(request);
return Promise.bind(this)
.then(function() {
return this.getUser(request);
})
.then(function(user) {
return this.saveToken(user, client, scope);
});
};
/**
* Get user using a username/password combination.
*/
PasswordGrantType.prototype.getUser = function(request) {
if (!request.body.username) {
throw new InvalidRequestError('Missing parameter: `username`');
}
if (!request.body.password) {
throw new InvalidRequestError('Missing parameter: `password`');
}
if (!is.uchar(request.body.username)) {
throw new InvalidRequestError('Invalid parameter: `username`');
}
if (!is.uchar(request.body.password)) {
throw new InvalidRequestError('Invalid parameter: `password`');
}
return promisify(this.model.getUser, 2)(request.body.username, request.body.password)
.then(function(user) {
if (!user) {
throw new InvalidGrantError('Invalid grant: user credentials are invalid');
}
return user;
});
};
/**
* Save token.
*/
PasswordGrantType.prototype.saveToken = function(user, client, scope) {
var fns = [
this.validateScope(user, client, scope),
this.generateAccessToken(client, user, scope),
this.generateRefreshToken(client, user, scope),
this.getAccessTokenExpiresAt(),
this.getRefreshTokenExpiresAt()
];
return Promise.all(fns)
.bind(this)
.spread(function(scope, accessToken, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt) {
var token = {
accessToken: accessToken,
accessTokenExpiresAt: accessTokenExpiresAt,
refreshToken: refreshToken,
refreshTokenExpiresAt: refreshTokenExpiresAt,
scope: scope
};
return promisify(this.model.saveToken, 3)(token, client, user);
});
};
/**
* Export constructor.
*/
module.exports = PasswordGrantType;
|
'use strict';
var fs = require('fs');
var path = require('path');
var gulp = require('gulp');
var git = require('gulp-git');
var tag_version = require('gulp-tag-version');
var argv = require('yargs').argv;
var $ = require('gulp-load-plugins')();
module.exports = function(options) {
var packageSrc = './package.json';
var bump = function(type='patch'){
return function bump(){
return gulp.src(['./bower.json',packageSrc])
.pipe($.bump({
// version: options.version,
type: type
}))
.pipe(gulp.dest('./'));
}
}
gulp.task('git:tag', function () {
return gulp.src(packageSrc)
.pipe(tag_version({
message: '[Release] %VERSION%'
}));
});
gulp.task('git:push',function(done){
return git.push('origin', 'HEAD', {
args: '--tags'
},function(err){
if(err) console.error(err);
done();
});
});
gulp.task('git:add', function () {
return gulp.src(packageSrc)
.pipe(git.add({args: ". -A"}));
});
gulp.task('git:commit_release', gulp.series('git:add', function commit_release () {
var pkg = JSON.parse(fs.readFileSync(path.join(__dirname,'../package.json')));
var msg = 'v '+pkg.version;
if(argv.m && argv!==true) msg = [msg].concat([argv.m])
return gulp.src('./')
.pipe(git.commit(msg));
}));
gulp.task('git:commit', gulp.series('git:add', function commit () {
return gulp.src('./')
.pipe(git.commit((argv.m && argv!==true ? argv.m : 'Minor changes :coffee:')));
}));
gulp.task('p', gulp.series('git:commit','git:push', function p(){
process.exit();
}));
gulp.task('bump', gulp.series(bump(argv.major ? 'major' : (argv.minor ? 'minor' : 'patch'))));
gulp.task('patch', gulp.series('build', bump('patch'),'git:commit_release','git:tag','git:push'));
gulp.task('minor', gulp.series('build', bump('minor'),'git:commit_release','git:tag','git:push'));
gulp.task('major', gulp.series('build', bump('major'),'git:commit_release','git:tag','git:push'));
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import Test from 'legit-tests/no-dom';
import * as middleware from 'test/helpers/middleware';
export function createRender(containerTag = 'div') {
const dummy = document.createElement(containerTag);
return function(instance) {
return ReactDOM.render(instance, dummy);
};
}
export function renderOnce(instance, containerTag) {
return createRender(containerTag)(instance);
}
function createWrapper(Component, props) {
class WrapperClass extends React.Component {
constructor(...args) {
super(...args);
this.state = props;
}
render() {
return Component(this.state);
}
}
return React.createElement(WrapperClass);
}
export function render(Component, props) {
return Test(createWrapper(Component, props)).mixin(middleware);
}
|
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
|
module.exports = function (config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],
// list of files / patterns to load in the browser
files: [
//'app/**/*.js',
'app/scripts/QueueRunner.js/*.js',
'test/**/*.js'
// 'test/**/*_test.js'
],
// list of files to exclude
exclude: [],
preprocessors: {
// source files, that you wanna generate coverage for
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
'app/**/*.js': ['coverage']
},
// use dots reporter, as travis terminal does not support escaping sequences
// possible values: 'dots', 'progress'
// CLI --reporters progress
reporters: ['progress', 'coverage'],
// web server port
// CLI --port 9876
port: 9876,
// enable / disable colors in the output (reporters and logs)
// CLI --colors --no-colors
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
// CLI --log-level debug
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
// CLI --auto-watch --no-auto-watch
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
// CLI --browsers Chrome,Firefox,Safari
browsers: [],
// If browser does not capture in given timeout [ms], kill it
// CLI --capture-timeout 5000
captureTimeout: 20000,
// Auto run tests on start (when browsers are captured) and exit
// CLI --single-run --no-single-run
singleRun: false,
// report which specs are slower than 500ms
// CLI --report-slower-than 500
reportSlowerThan: 500,
// optionally, configure the reporter
coverageReporter: {
type: 'lcov',
dir: 'coverage/',
// subdir: 'reports/',
subdir: function(browser) {
// normalization process to keep a consistent browser name accross different
// OS
// Would output the results into: './coverage/firefox/'
return 'reports/' + browser.toLowerCase().split(/[ /-]/)[0];
},
reporters: [
// reporters supporting the `file` property, use `subdir` to directly
// output them in the `dir` directory
{type: 'html', dir:'coverage/'}//,
// { type: 'cobertura', subdir: '.', file: 'cobertura.txt' },
// { type: 'lcovonly', subdir: '.', file: 'report-lcovonly.txt' },
// { type: 'teamcity', subdir: '.', file: 'teamcity.txt' },
// { type: 'text', subdir: '.', file: 'text.txt' },
// { type: 'text-summary', subdir: '.', file: 'text-summary.txt' },
]
}
});
};
|
window.Cow = window.Cow || {};
//Synstore keeps track of records
Cow.syncstore = function(config){
var self = this;
this._dbname = config.dbname;
this._core = config.core;
console.log('new store',this._dbname);
this.loaded = new Promise(function(resolve, reject){
console.log('reading db ',self._dbname);
if (config.noIDB){
resolve();
}
else {
/**
See for indexeddb wrapper:
https://github.com/aaronpowell/db.js
**/
db.open( {
server: self._dbname,
version: 1,
schema: {
main: {
key: { keyPath: '_id' , autoIncrement: false },
// Optionally add indexes
indexes: {
updated: { },
_id: { unique: true }
}
}
}
} ).done( function ( s ) {
self._db = s;
self._db_getRecords().then(function(rows){
console.log('Got records from db ',self._dbname);
rows.forEach(function(d){
//console.log(d);
var record = self._recordproto(d._id);
record.inflate(d);
var existing = false;
//Not likely to exist in the _records at this time but better safe then sorry..
for (var i=0;i<self._records.length;i++){
if (self._records[i]._id == record._id) {
//existing = true; //Already in list
//record = -1;
}
}
if (!existing){
self._records.push(record); //Adding to the list
}
});
self.trigger('datachange');
resolve();
}).catch(function(e){
console.warn(e.message);
});
});
}
});
};
/**
See for use of promises:
1. http://www.html5rocks.com/en/tutorials/es6/promises/
2. https://github.com/jakearchibald/ES6-Promises
**/
Cow.syncstore.prototype =
{ //db object
//All these calls will be asynchronous and thus returning a promise instead of data
//_db_addRecord: function(config){
_db_write: function(config){
var data = config.data;
var source = config.source;
data._id = data._id.toString();
var self = this;
var db = this._db;
return new Promise(function(resolve, reject){
db.main.remove(data._id).done(function(){
db.main.add(data).done(function(d){
resolve(d);
}).fail(function(d,e){
console.warn(e);
reject(e);
});
}).fail(function(e){
console.warn(e);
reject(e);
});
});
},
_db_getRecords: function(){
var self = this;
return new Promise(function(resolve, reject){
self._db.main.query().filter().execute().done(function(doc){
resolve(doc);
}).fail(function(e){
reject(e);
});
});
}, //returns promise
_db_getRecord: function(id){
var self = this;
return new Promise(function(resolve, reject){
self._db.main.query().filter('_id',id).execute().done(function(doc){
resolve(doc);
}).fail(function(doc){
reject(doc);
});
});
}, //returns promise
_db_removeRecord: function(id){
var self = this;
return new Promise(function(resolve, reject){
db.main.remove(data._id).done(function(){
resolve();
}).fail(function(){
reject();
});
});
}, //returns promise
_initRecords: function(){ //This will start the process of getting records from db (returns promise)
var promise = this._db_getRecords();
var self = this;
promise.then(function(r){
r.forEach(function(d){
//console.log(d.doc);
var record = self._recordproto(d._id);
record.inflate(d);
var existing = false; //Not likely to exist in the _records at this time but better safe then sorry..
for (var i=0;i<self._records.length;i++){
if (self._records[i]._id == record._id) {
existing = true; //Already in list
record = -1;
}
}
if (!existing){
self._records.push(record); //Adding to the list
}
});
self.trigger('datachange');
});
return promise;
},
//_getRecords([<string>]) - return all records, if ID array is filled, only return that records
_getRecords: function(idarray){
var returnArray = [];
for (var i=0;i<this._records.length;i++){
var record = this._records[i];
if (idarray.indexOf(record._id) > -1) {
returnArray.push(record);
}
}
return returnArray;
},
//_getRecord(<string>) - return record or create new one based on id
_getRecord: function(id){
for (var i=0;i<this._records.length;i++){
var record = this._records[i];
if (record._id == id) {
return record;
}
}
//var config = {_id: id};
//return this._addRecord({source: 'UI', data: config}).status('dirty');
//TODO: rethink this strategy: should we make a new record on non-existing or just return null
return null;
},
/**
_addRecord - creates a new record and replaces an existing one with the same _id
when the source is 'WS' it immidiately sends to the _db, if not the record needs a manual record.sync()
**/
_addRecord: function(config){
if (!config.source || !config.data){
console.warn('Wrong input: ',config);
return false;
}
var promise = null;
var source = config.source;
var data = config.data;
var existing = false;
var record;
//Check to see if the record is existing or new
for (var i=0;i<this._records.length;i++){
if (this._records[i]._id == data._id) {
existing = true; //Already in list
record = this._records[i];
record.inflate(data);
if (this._db && source == 'WS'){ //update the db
//promise = this._db_updateRecord({source:source, data: record.deflate()});
this._db_write({source:source, data: record.deflate()});
}
}
}
if (!existing){
//Create a new record and inflate with the data we got
record = this._recordproto(data._id);
record.inflate(data);
if (this._db && source == 'WS'){
promise = this._db_write({source:source,data:record.deflate()});
}
this._records.push(record); //Adding to the list
//console.log(this._records.length);
}
this.trigger('datachange');
return record;
},
_getRecordsOn: function(timestamp){
var returnarr = [];
_.each(this._records, function(d){
//If request is older than feature itself, disregard
if (timestamp < d._created){
//don't add
}
//If request is younger than last feature update, return normal data
else if (timestamp > d._updated){
returnarr.push(d);
}
else if (d.data(timestamp)){
returnarr.push(d); //TODO: hier gebleven
}
});
return returnarr;
},
/**
Only to be used from client API
records() - returns array of all records
records(timestamp) - returns array of records created before timestamp
records(id) - returns record with id (or null)
records([id]) - returns array of records from id array
records({config}) - creates and returns record
**/
records: function(config){
if (config && Array.isArray(config)){
return this._getRecords(config);
}
else if (config && typeof(config) == 'object'){
return this._addRecord({source: 'UI', data: config}).status('dirty');
}
else if (config && typeof(config) == 'string'){
return this._getRecord(config);
}
else if (config && typeof(config) == 'number'){
return this._getRecordsOn(config);
}
else{
return this._records;
}
},
//Removing records is only useful if no local dbase is used among peers
_removeRecord: function(id){
for (var i=0;i<this._records.length;i++){
if (this._records[i]._id == id) {
this._records.splice(i,1);
this.trigger('datachange');
return true;
}
}
return false;
},
/**
clear() - remove all records, generally not useful since other peers will resent the data
**/
clear: function(){
this._records = [];
},
/**
deleteAll() - sets all records to deleted=true
**/
deleteAll: function(){
for (var i=0;i<this._records.length;i++){
this._records[i].deleted(true);
}
this.syncRecords();
this.trigger('datachange');
return this;
},
/**
syncRecord() - sync 1 record, returns record
**/
syncRecord: function(record){
var self = this;
var message = {};
message.syncType = this._type;
record.status('clean');
if (this._projectid){ //parent store
message.project = this._projectid;
}
if (this._db){
//var promise = this._db_updateRecord({source:'UI', data: record.deflate()});
var promise = this._db_write({source:'UI', data: record.deflate()});
promise.then(function(d){ //wait for db
message.record = record.deflate();
self.trigger('datachange');
self._core.websocket().sendData(message, 'updatedRecord');
},function(err){
console.warn(err);
});
} else { //No db, proceed immediately
message.record = record.deflate();
self.trigger('datachange');
self._core.websocket().sendData(message, 'updatedRecord');
}//TODO: remove this double code, but keep promise/non-promise intact
return record;
},
/**
syncRecords() - looks for dirty records and returns them all at once for syncing them
**/
syncRecords: function(){
var pushlist = [];
for (var i=0;i<this._records.length;i++){
var record = this._records[i];
if (record._status == 'dirty') {
//this.syncRecord(record);
record.status('clean');
pushlist.push(record.deflate());
}
}
var data = {
"syncType" : this._type,
"project" : this._projectid,
"list" : pushlist
};
this._core.websocket().sendData(data, 'requestedRecords');
},
/**
deltaList() - needed to sync the delta's
**/
deltaList: function(){
},
/**
**/
compareDeltas: function(){
},
/**
idList() - needed to start the syncing with other peers
only makes sense after fully loading the indexeddb
**/
idList: function(){
var fids = [];
for (var i=0;i<this._records.length;i++){
var item = this._records[i];
var iditem = {};
iditem._id = item._id;
iditem.timestamp = item.timestamp();
iditem.deleted = item.deleted();
fids.push(iditem);
}
return fids;
},
/**
requestItems(array) - returns the items that were requested
**/
requestRecords: function(fidlist){
var pushlist = [];
for (i=0;i<this._records.length;i++){
var localrecord = this._records[i];
for (j=0;j<fidlist.length;j++){
var rem_val = fidlist[j];
if (rem_val == localrecord._id){
pushlist.push(localrecord.deflate());
}
}
}
return pushlist;
},
/**
compareRecords(config) - compares incoming idlist with idlist from current stack based on timestamp and status
generates 2 lists: requestlist and pushlist
**/
compareRecords: function(config){
var uid = config.uid; //id of peer that sends syncrequest
var fidlist = config.list;
var returndata = {};
var copyof_rem_list = [];
returndata.requestlist = [];
returndata.pushlist = [];
var i;
//Prepare copy of remote fids as un-ticklist, but only for non-deleted items
if (fidlist){
for (i=0;i<fidlist.length;i++){
if (fidlist[i].deleted != 'true'){
copyof_rem_list.push(fidlist[i]._id);
}
}
for (i=0;i<this._records.length;i++){
var local_item = this._records[i];
var found = -1;
for (var j=0;j<fidlist.length;j++){
//in both lists
var rem_val = fidlist[j];
if (rem_val._id == local_item._id){
found = 1;
//local is newer
if (rem_val.timestamp < local_item._updated){
returndata.pushlist.push(local_item.deflate());
}
//remote is newer
else if (rem_val.timestamp > local_item._updated){
returndata.requestlist.push(rem_val._id);
}
//remove from copyremotelist
//OBS var tmppos = $.inArray(local_item._id,copyof_rem_list);
var tmppos = copyof_rem_list.indexOf(local_item._id);
if (tmppos >= 0){
copyof_rem_list.splice(tmppos,1);
}
}
}
//local but not remote and not deleted
if (found == -1 && local_item.deleted() != 'true'){
returndata.pushlist.push(local_item.deflate());
}
}
}
//Add remainder of copyof_rem_list to requestlist
for (i=0;i<copyof_rem_list.length;i++){
var val = copyof_rem_list[i];
returndata.requestlist.push(val);
}
//This part is only for sending the data
/* Obsolete by new websocket prototcol. Still interesting for partial syncing method though.
var message = {};
//First the requestlist
message.requestlist = returndata.requestlist;
message.pushlist = []; //empty
//message.storename = payload.storename;
message.dbname = this._dbname;
//this._core.websocket().sendData(message,'syncPeer',uid);
//Now the pushlist bit by bit
message.requestlist = []; //empty
var k = 0;
for (j=0;j<returndata.pushlist.length;j++){
var item = returndata.pushlist[j];
message.pushlist.push(item);
k++;
if (k >= 1) { //max 1 feat every time
k = 0;
//this._core.websocket().sendData(message,'syncPeer',uid);
message.pushlist = []; //empty
}
}
//sent the remainder of the list
if (k > 0){
//this._core.websocket().sendData(message,'syncPeer',uid);
}
*/
//end of sending data
return returndata;
}
};
//Adding some Backbone event binding functionality to the store
_.extend(Cow.syncstore.prototype, Events);
|
/*
* grunt-phantom-benchmark
* https://github.com/kevincennis/grunt-phantom-benchmark
*
* Copyright (c) 2014 Kevin Ennis
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'tasks/*.js'
],
options: {
jshintrc: '.jshintrc'
}
}
});
// Actually load this plugin's task(s).
grunt.loadTasks('tasks');
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
// By default, lint and run all tests.
grunt.registerTask('default', ['jshint']);
};
|
var listing = require('./listing.js'),
mapping = require('./mapping.js');
/**
* The base implementation of `convert` which accepts a `util` object of methods
* required to perform conversions.
*
* @param {Object} util The util object.
* @param {string} name The name of the function to wrap.
* @param {Function} func The function to wrap.
* @returns {Function|Object} Returns the converted function or object.
*/
function baseConvert(util, name, func) {
if (!func) {
func = name;
name = null;
}
if (func == null) {
throw new TypeError;
}
var isLib = name == null && typeof func.VERSION == 'string';
var _ = isLib ? func : {
'ary': util.ary,
'curry': util.curry,
'forEach': util.forEach,
'isFunction': util.isFunction,
'iteratee': util.iteratee,
'keys': util.keys,
'rearg': util.rearg
};
var ary = _.ary,
curry = _.curry,
each = _.forEach,
isFunction = _.isFunction,
keys = _.keys,
rearg = _.rearg;
var baseAry = function(func, n) {
return function() {
var args = arguments,
length = Math.min(args.length, n);
switch (length) {
case 1: return func(args[0]);
case 2: return func(args[0], args[1]);
}
args = Array(length);
while (length--) {
args[length] = arguments[length];
}
return func.apply(undefined, args);
};
};
var iterateeAry = function(func, n) {
return function() {
var length = arguments.length,
args = Array(length);
while (length--) {
args[length] = arguments[length];
}
args[0] = baseAry(args[0], n);
return func.apply(undefined, args);
};
};
var wrappers = {
'iteratee': function(iteratee) {
return function(func, arity) {
arity = arity > 2 ? (arity - 2) : 1;
func = iteratee(func);
var length = func.length;
return length <= arity ? func : baseAry(func, arity);
};
},
'mixin': function(mixin) {
return function(source) {
var func = this;
if (!isFunction(func)) {
return mixin(func, source);
}
var methods = [],
methodNames = [];
each(keys(source), function(key) {
var value = source[key];
if (isFunction(value)) {
methodNames.push(key);
methods.push(func.prototype[key]);
}
});
mixin(func, source);
each(methodNames, function(methodName, index) {
var method = methods[index];
if (isFunction(method)) {
func.prototype[methodName] = method;
} else {
delete func.prototype[methodName];
}
});
return func;
};
},
'runInContext': function(runInContext) {
return function(context) {
return baseConvert(util, runInContext(context));
};
}
};
var wrap = function(name, func) {
var wrapper = wrappers[name];
if (wrapper) {
return wrapper(func);
}
var result;
each(listing.caps, function(cap) {
each(mapping.aryMethodMap[cap], function(otherName) {
if (name == otherName) {
result = ary(func, cap);
if (cap > 1 && !mapping.skipReargMap[name]) {
result = rearg(result, mapping.aryReargMap[cap]);
}
var n = !isLib && mapping.aryIterateeMap[name];
if (n) {
result = iterateeAry(result, n);
}
if (cap > 1) {
result = curry(result, cap);
}
return false;
}
});
return !result;
});
return result || func;
};
if (!isLib) {
return wrap(name, func);
}
// Disable custom `_.indexOf` use by these methods.
_.mixin({
'difference': util.difference,
'includes': util.includes,
'intersection': util.intersection,
'omit': util.omit,
'pull': util.pull,
'union': util.union,
'uniq': util.uniq,
'uniqBy': util.uniqBy,
'without': util.without,
'xor': util.xor
});
// Iterate over methods for the current ary cap.
var pairs = [];
each(listing.caps, function(cap) {
each(mapping.aryMethodMap[cap], function(name) {
var func = _[mapping.keyMap[name] || name];
if (func) {
// Wrap the lodash method and its aliases.
var wrapped = wrap(name, func);
pairs.push([name, wrapped]);
each(mapping.aliasMap[name] || [], function(alias) { pairs.push([alias, wrapped]); });
}
});
});
// Assign to `_` leaving `_.prototype` unchanged to allow chaining.
_.iteratee = wrappers.iteratee(_.iteratee);
_.mixin = wrappers.mixin(_.mixin);
_.runInContext = wrappers.runInContext(_.runInContext);
each(pairs, function(pair) { _[pair[0]] = pair[1]; });
return _;
}
module.exports = convert;
|
module.exports = {
name: "isBlank",
ns: "string",
async: true,
description: "Determines whether a string is blank (whitespace, new line, etc.)",
phrases: {
active: "Checking for blank string"
},
ports: {
input: {
"in": {
title: "String",
type: "string",
async: true,
required: true,
fn: function __IN__(data, source, state, input, $, output, underscore_string) {
var r = function() {
output({
out: $.write('in', underscore_string.isBlank($.in))
});
}.call(this);
return {
state: state,
return: r
};
}
}
},
output: {
out: {
title: "String",
type: "string"
}
}
},
dependencies: {
npm: {
"underscore.string": "##underscore.string##"
}
},
state: {}
}
|
'use strict';
// Configuring the Consumptions module
angular.module('consumptions').run(['Menus',
function (Menus) {
}
]);
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
*
* @class Phaser.TilemapParser
*/
Phaser.TilemapParser = {
/**
* Parse tilemap data from the cache and creates a Tilemap object.
*
* @method Phaser.TilemapParser.parse
* @param {Phaser.Game} game - Game reference to the currently running game.
* @param {string} key - The key of the tilemap in the Cache.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
* @return {object} The parsed map object.
*/
parse: function (game, key, tileWidth, tileHeight, width, height) {
if (typeof tileWidth === 'undefined') { tileWidth = 32; }
if (typeof tileHeight === 'undefined') { tileHeight = 32; }
if (typeof width === 'undefined') { width = 10; }
if (typeof height === 'undefined') { height = 10; }
if (typeof key === 'undefined')
{
return this.getEmptyData();
}
if (key === null)
{
return this.getEmptyData(tileWidth, tileHeight, width, height);
}
var map = game.cache.getTilemapData(key);
if (map)
{
if (map.format === Phaser.Tilemap.CSV)
{
return this.parseCSV(key, map.data, tileWidth, tileHeight);
}
else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
{
return this.parseTiledJSON(map.data);
}
}
else
{
console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
}
},
/**
* Parses a CSV file into valid map data.
*
* @method Phaser.TilemapParser.parseCSV
* @param {string} data - The CSV file data.
* @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
* @return {object} Generated map data.
*/
parseCSV: function (key, data, tileWidth, tileHeight) {
var map = this.getEmptyData();
// Trim any rogue whitespace from the data
data = data.trim();
var output = [];
var rows = data.split("\n");
var height = rows.length;
var width = 0;
for (var y = 0; y < rows.length; y++)
{
output[y] = [];
var column = rows[y].split(",");
for (var x = 0; x < column.length; x++)
{
output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
}
if (width === 0)
{
width = column.length;
}
}
map.format = Phaser.Tilemap.CSV;
map.name = key;
map.width = width;
map.height = height;
map.tileWidth = tileWidth;
map.tileHeight = tileHeight;
map.widthInPixels = width * tileWidth;
map.heightInPixels = height * tileHeight;
map.layers[0].width = width;
map.layers[0].height = height;
map.layers[0].widthInPixels = map.widthInPixels;
map.layers[0].heightInPixels = map.heightInPixels;
map.layers[0].data = output;
return map;
},
/**
* Returns an empty map data object.
*
* @method Phaser.TilemapParser.getEmptyData
* @return {object} Generated map data.
*/
getEmptyData: function (tileWidth, tileHeight, width, height) {
var map = {};
map.width = 0;
map.height = 0;
map.tileWidth = 0;
map.tileHeight = 0;
if (typeof tileWidth !== 'undefined' && tileWidth !== null) { map.tileWidth = tileWidth; }
if (typeof tileHeight !== 'undefined' && tileHeight !== null) { map.tileHeight = tileHeight; }
if (typeof width !== 'undefined' && width !== null) { map.width = width; }
if (typeof height !== 'undefined' && height !== null) { map.height = height; }
map.orientation = 'orthogonal';
map.version = '1';
map.properties = {};
map.widthInPixels = 0;
map.heightInPixels = 0;
var layers = [];
var layer = {
name: 'layer',
x: 0,
y: 0,
width: 0,
height: 0,
widthInPixels: 0,
heightInPixels: 0,
alpha: 1,
visible: true,
properties: {},
indexes: [],
callbacks: [],
bodies: [],
data: []
};
// fill with nulls?
layers.push(layer);
map.layers = layers;
map.images = [];
map.objects = {};
map.collision = {};
map.tilesets = [];
map.tiles = [];
return map;
},
/**
* Parses a Tiled JSON file into valid map data.
* @method Phaser.TilemapParser.parseJSON
* @param {object} json - The JSON map data.
* @return {object} Generated and parsed map data.
*/
parseTiledJSON: function (json) {
if (json.orientation !== 'orthogonal')
{
console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser');
return null;
}
// Map data will consist of: layers, objects, images, tilesets, sizes
var map = {};
map.width = json.width;
map.height = json.height;
map.tileWidth = json.tilewidth;
map.tileHeight = json.tileheight;
map.orientation = json.orientation;
map.format = Phaser.Tilemap.TILED_JSON;
map.version = json.version;
map.properties = json.properties;
map.widthInPixels = map.width * map.tileWidth;
map.heightInPixels = map.height * map.tileHeight;
// Tile Layers
var layers = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'tilelayer')
{
continue;
}
var layer = {
name: json.layers[i].name,
x: json.layers[i].x,
y: json.layers[i].y,
width: json.layers[i].width,
height: json.layers[i].height,
widthInPixels: json.layers[i].width * json.tilewidth,
heightInPixels: json.layers[i].height * json.tileheight,
alpha: json.layers[i].opacity,
visible: json.layers[i].visible,
properties: {},
indexes: [],
callbacks: [],
bodies: []
};
if (json.layers[i].properties)
{
layer.properties = json.layers[i].properties;
}
var x = 0;
var row = [];
var output = [];
// Loop through the data field in the JSON.
// This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
// If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
// Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.
for (var t = 0, len = json.layers[i].data.length; t < len; t++)
{
// index, x, y, width, height
if (json.layers[i].data[t] > 0)
{
row.push(new Phaser.Tile(layer, json.layers[i].data[t], x, output.length, json.tilewidth, json.tileheight));
}
else
{
row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
}
x++;
if (x === json.layers[i].width)
{
output.push(row);
x = 0;
row = [];
}
}
layer.data = output;
layers.push(layer);
}
map.layers = layers;
// Images
var images = [];
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'imagelayer')
{
continue;
}
var image = {
name: json.layers[i].name,
image: json.layers[i].image,
x: json.layers[i].x,
y: json.layers[i].y,
alpha: json.layers[i].opacity,
visible: json.layers[i].visible,
properties: {}
};
if (json.layers[i].properties)
{
image.properties = json.layers[i].properties;
}
images.push(image);
}
map.images = images;
// Tilesets
var tilesets = [];
for (var i = 0; i < json.tilesets.length; i++)
{
// name, firstgid, width, height, margin, spacing, properties
var set = json.tilesets[i];
if (set.image)
{
var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
if (set.tileproperties)
{
newSet.tileProperties = set.tileproperties;
}
// For a normal sliced tileset the row/count/size information is computed when updated.
// This is done (again) after the image is set.
newSet.updateTileData(set.imagewidth, set.imageheight);
tilesets.push(newSet);
}
else
{
// TODO: Handle Tileset Image Collections (multiple images in a tileset, no slicing into each image)
console.warn("Phaser.TilemapParser - Image Collection Tilesets are not support");
}
}
map.tilesets = tilesets;
// Objects & Collision Data (polylines, etc)
var objects = {};
var collision = {};
function slice (obj, fields) {
var sliced = {};
for (var k in fields) {
var key = fields[k];
sliced[key] = obj[key];
}
return sliced;
}
for (var i = 0; i < json.layers.length; i++)
{
if (json.layers[i].type !== 'objectgroup')
{
continue;
}
objects[json.layers[i].name] = [];
collision[json.layers[i].name] = [];
for (var v = 0, len = json.layers[i].objects.length; v < len; v++)
{
// Object Tiles
if (json.layers[i].objects[v].gid)
{
var object = {
gid: json.layers[i].objects[v].gid,
name: json.layers[i].objects[v].name,
type: json.layers[i].objects[v].type,
x: json.layers[i].objects[v].x,
y: json.layers[i].objects[v].y,
visible: json.layers[i].objects[v].visible,
properties: json.layers[i].objects[v].properties
};
objects[json.layers[i].name].push(object);
}
else if (json.layers[i].objects[v].polyline)
{
var object = {
name: json.layers[i].objects[v].name,
type: json.layers[i].objects[v].type,
x: json.layers[i].objects[v].x,
y: json.layers[i].objects[v].y,
width: json.layers[i].objects[v].width,
height: json.layers[i].objects[v].height,
visible: json.layers[i].objects[v].visible,
properties: json.layers[i].objects[v].properties
};
object.polyline = [];
// Parse the polyline into an array
for (var p = 0; p < json.layers[i].objects[v].polyline.length; p++)
{
object.polyline.push([ json.layers[i].objects[v].polyline[p].x, json.layers[i].objects[v].polyline[p].y ]);
}
collision[json.layers[i].name].push(object);
objects[json.layers[i].name].push(object);
}
// polygon
else if (json.layers[i].objects[v].polygon)
{
var object = slice(json.layers[i].objects[v],
["name", "type", "x", "y", "visible", "properties" ]);
// Parse the polygon into an array
object.polygon = [];
for (var p = 0; p < json.layers[i].objects[v].polygon.length; p++)
{
object.polygon.push([ json.layers[i].objects[v].polygon[p].x, json.layers[i].objects[v].polygon[p].y ]);
}
objects[json.layers[i].name].push(object);
}
// ellipse
else if (json.layers[i].objects[v].ellipse)
{
var object = slice(json.layers[i].objects[v],
["name", "type", "ellipse", "x", "y", "width", "height", "visible", "properties" ]);
objects[json.layers[i].name].push(object);
}
// otherwise it's a rectangle
else
{
var object = slice(json.layers[i].objects[v],
["name", "type", "x", "y", "width", "height", "visible", "properties" ]);
object.rectangle = true;
objects[json.layers[i].name].push(object);
}
}
}
map.objects = objects;
map.collision = collision;
map.tiles = [];
// Finally lets build our super tileset index
for (var i = 0; i < map.tilesets.length; i++)
{
var set = map.tilesets[i];
var x = set.tileMargin;
var y = set.tileMargin;
var count = 0;
var countX = 0;
var countY = 0;
for (var t = set.firstgid; t < set.firstgid + set.total; t++)
{
// Can add extra properties here as needed
map.tiles[t] = [x, y, i];
x += set.tileWidth + set.tileSpacing;
count++;
if (count === set.total)
{
break;
}
countX++;
if (countX === set.columns)
{
x = set.tileMargin;
y += set.tileHeight + set.tileSpacing;
countX = 0;
countY++;
if (countY === set.rows)
{
break;
}
}
}
}
// assign tile properties
var i,j,k;
var layer, tile, sid, set;
// go through each of the map layers
for (i = 0; i < map.layers.length; i++)
{
layer = map.layers[i];
// rows of tiles
for (j = 0; j < layer.data.length; j++)
{
row = layer.data[j];
// individual tiles
for (k = 0; k < row.length; k++)
{
tile = row[k];
if(tile.index < 0) { continue; }
// find the relevant tileset
sid = map.tiles[tile.index][2];
set = map.tilesets[sid];
// if that tile type has any properties, add them to the tile object
if(set.tileProperties && set.tileProperties[tile.index - set.firstgid]) {
tile.properties = set.tileProperties[tile.index - set.firstgid];
}
}
}
}
return map;
}
};
|
(function () {
'use strict';
/** Virtual DOM Node */
function VNode() {}
function getGlobal() {
if (typeof global !== 'object' || !global || global.Math !== Math || global.Array !== Array) {
return self || window || global || function () {
return this;
}();
}
return global;
}
/** Global options
* @public
* @namespace options {Object}
*/
var options = {
store: null,
root: getGlobal()
};
var stack = [];
var EMPTY_CHILDREN = [];
function h(nodeName, attributes) {
var children = EMPTY_CHILDREN,
lastSimple = void 0,
child = void 0,
simple = void 0,
i = void 0;
for (i = arguments.length; i-- > 2;) {
stack.push(arguments[i]);
}
if (attributes && attributes.children != null) {
if (!stack.length) stack.push(attributes.children);
delete attributes.children;
}
while (stack.length) {
if ((child = stack.pop()) && child.pop !== undefined) {
for (i = child.length; i--;) {
stack.push(child[i]);
}
} else {
if (typeof child === 'boolean') child = null;
if (simple = typeof nodeName !== 'function') {
if (child == null) child = '';else if (typeof child === 'number') child = String(child);else if (typeof child !== 'string') simple = false;
}
if (simple && lastSimple) {
children[children.length - 1] += child;
} else if (children === EMPTY_CHILDREN) {
children = [child];
} else {
children.push(child);
}
lastSimple = simple;
}
}
var p = new VNode();
p.nodeName = nodeName;
p.children = children;
p.attributes = attributes == null ? undefined : attributes;
p.key = attributes == null ? undefined : attributes.key;
// if a "vnode hook" is defined, pass every created VNode to it
if (options.vnode !== undefined) options.vnode(p);
return p;
}
/**
* @license
* Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
(function () {
if (
// No Reflect, no classes, no need for shim because native custom elements
// require ES2015 classes or Reflect.
window.Reflect === undefined || window.customElements === undefined ||
// The webcomponentsjs custom elements polyfill doesn't require
// ES2015-compatible construction (`super()` or `Reflect.construct`).
window.customElements.hasOwnProperty('polyfillWrapFlushCallback')) {
return;
}
var BuiltInHTMLElement = HTMLElement;
window.HTMLElement = function HTMLElement() {
return Reflect.construct(BuiltInHTMLElement, [], this.constructor);
};
HTMLElement.prototype = BuiltInHTMLElement.prototype;
HTMLElement.prototype.constructor = HTMLElement;
Object.setPrototypeOf(HTMLElement, BuiltInHTMLElement);
})();
function cssToDom(css) {
var node = document.createElement('style');
node.textContent = css;
return node;
}
function npn(str) {
return str.replace(/-(\w)/g, function ($, $1) {
return $1.toUpperCase();
});
}
function extend(obj, props) {
for (var i in props) {
obj[i] = props[i];
}return obj;
}
/** Invoke or update a ref, depending on whether it is a function or object ref.
* @param {object|function} [ref=null]
* @param {any} [value]
*/
function applyRef(ref, value) {
if (ref != null) {
if (typeof ref == 'function') ref(value);else ref.current = value;
}
}
/**
* Call a function asynchronously, as soon as possible. Makes
* use of HTML Promise to schedule the callback if available,
* otherwise falling back to `setTimeout` (mainly for IE<11).
* @type {(callback: function) => void}
*/
var defer = typeof Promise == 'function' ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout;
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
function nProps(props) {
if (!props || isArray(props)) return {};
var result = {};
Object.keys(props).forEach(function (key) {
result[key] = props[key].value;
});
return result;
}
// render modes
var ATTR_KEY = '__omiattr_';
// DOM properties that should NOT have "px" added when numeric
var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i;
/**
* Check if two nodes are equivalent.
*
* @param {Node} node DOM Node to compare
* @param {VNode} vnode Virtual DOM node to compare
* @param {boolean} [hydrating=false] If true, ignores component constructors when comparing.
* @private
*/
function isSameNodeType(node, vnode, hydrating) {
if (typeof vnode === 'string' || typeof vnode === 'number') {
return node.splitText !== undefined;
}
if (typeof vnode.nodeName === 'string') {
return !node._componentConstructor && isNamedNode(node, vnode.nodeName);
}
return hydrating || node._componentConstructor === vnode.nodeName;
}
/**
* Check if an Element has a given nodeName, case-insensitively.
*
* @param {Element} node A DOM Element to inspect the name of.
* @param {String} nodeName Unnormalized name to compare against.
*/
function isNamedNode(node, nodeName) {
return node.normalizedNodeName === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase();
}
/**
* Create an element with the given nodeName.
* @param {string} nodeName The DOM node to create
* @param {boolean} [isSvg=false] If `true`, creates an element within the SVG
* namespace.
* @returns {Element} The created DOM node
*/
function createNode(nodeName, isSvg) {
/** @type {Element} */
var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName);
node.normalizedNodeName = nodeName;
return node;
}
/**
* Remove a child node from its parent if attached.
* @param {Node} node The node to remove
*/
function removeNode(node) {
var parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}
/**
* Set a named attribute on the given Node, with special behavior for some names
* and event handlers. If `value` is `null`, the attribute/handler will be
* removed.
* @param {Element} node An element to mutate
* @param {string} name The name/key to set, such as an event or attribute name
* @param {*} old The last value that was set for this name/node pair
* @param {*} value An attribute value, such as a function to be used as an
* event handler
* @param {boolean} isSvg Are we currently diffing inside an svg?
* @private
*/
function setAccessor(node, name, old, value, isSvg) {
if (name === 'className') name = 'class';
if (name === 'key') {
// ignore
} else if (name === 'ref') {
applyRef(old, null);
applyRef(value, node);
} else if (name === 'class' && !isSvg) {
node.className = value || '';
} else if (name === 'style') {
if (!value || typeof value === 'string' || typeof old === 'string') {
node.style.cssText = value || '';
}
if (value && typeof value === 'object') {
if (typeof old !== 'string') {
for (var i in old) {
if (!(i in value)) node.style[i] = '';
}
}
for (var _i in value) {
node.style[_i] = typeof value[_i] === 'number' && IS_NON_DIMENSIONAL.test(_i) === false ? value[_i] + 'px' : value[_i];
}
}
} else if (name === 'dangerouslySetInnerHTML') {
if (value) node.innerHTML = value.__html || '';
} else if (name[0] == 'o' && name[1] == 'n') {
var useCapture = name !== (name = name.replace(/Capture$/, ''));
name = name.toLowerCase().substring(2);
if (value) {
if (!old) {
node.addEventListener(name, eventProxy, useCapture);
if (name == 'tap') {
node.addEventListener('touchstart', touchStart, useCapture);
node.addEventListener('touchstart', touchEnd, useCapture);
}
}
} else {
node.removeEventListener(name, eventProxy, useCapture);
if (name == 'tap') {
node.removeEventListener('touchstart', touchStart, useCapture);
node.removeEventListener('touchstart', touchEnd, useCapture);
}
}
(node._listeners || (node._listeners = {}))[name] = value;
} else if (name !== 'list' && name !== 'type' && !isSvg && name in node) {
// Attempt to set a DOM property to the given value.
// IE & FF throw for certain property-value combinations.
try {
node[name] = value == null ? '' : value;
} catch (e) {}
if ((value == null || value === false) && name != 'spellcheck') node.removeAttribute(name);
} else {
var ns = isSvg && name !== (name = name.replace(/^xlink:?/, ''));
// spellcheck is treated differently than all other boolean values and
// should not be removed when the value is `false`. See:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-spellcheck
if (value == null || value === false) {
if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase());else node.removeAttribute(name);
} else if (typeof value === 'string') {
if (ns) {
node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value);
} else {
node.setAttribute(name, value);
}
}
}
}
/**
* Proxy an event to hooked event handlers
* @param {Event} e The event object from the browser
* @private
*/
function eventProxy(e) {
return this._listeners[e.type](options.event && options.event(e) || e);
}
function touchStart(e) {
this.___touchX = e.touches[0].pageX;
this.___touchY = e.touches[0].pageY;
this.___scrollTop = document.body.scrollTop;
}
function touchEnd(e) {
if (Math.abs(e.changedTouches[0].pageX - this.___touchX) < 30 && Math.abs(e.changedTouches[0].pageY - this.___touchY) < 30 && Math.abs(document.body.scrollTop - this.___scrollTop) < 30) {
this.dispatchEvent(new CustomEvent('tap', { detail: e }));
}
}
/** Diff recursion count, used to track the end of the diff cycle. */
var diffLevel = 0;
/** Global flag indicating if the diff is currently within an SVG */
var isSvgMode = false;
/** Global flag indicating if the diff is performing hydration */
var hydrating = false;
/** Apply differences in a given vnode (and it's deep children) to a real DOM Node.
* @param {Element} [dom=null] A DOM node to mutate into the shape of the `vnode`
* @param {VNode} vnode A VNode (with descendants forming a tree) representing the desired DOM structure
* @returns {Element} dom The created/mutated element
* @private
*/
function diff(dom, vnode, context, mountAll, parent, componentRoot) {
// diffLevel having been 0 here indicates initial entry into the diff (not a subdiff)
var ret = void 0;
if (!diffLevel++) {
// when first starting the diff, check if we're diffing an SVG or within an SVG
isSvgMode = parent != null && parent.ownerSVGElement !== undefined;
// hydration is indicated by the existing element to be diffed not having a prop cache
hydrating = dom != null && !(ATTR_KEY in dom);
}
if (isArray(vnode)) {
ret = [];
var parentNode = null;
if (isArray(dom)) {
var domLength = dom.length;
var vnodeLength = vnode.length;
var maxLength = domLength >= vnodeLength ? domLength : vnodeLength;
parentNode = dom[0].parentNode;
for (var i = 0; i < maxLength; i++) {
ret.push(idiff(dom[i], vnode[i], context, mountAll, componentRoot));
}
} else {
vnode.forEach(function (item) {
ret.push(idiff(dom, item, context, mountAll, componentRoot));
});
}
if (parent) {
ret.forEach(function (vnode) {
parent.appendChild(vnode);
});
} else if (isArray(dom)) {
dom.forEach(function (node) {
parentNode.appendChild(node);
});
}
} else {
if (isArray(dom)) {
ret = idiff(dom[0], vnode, context, mountAll, componentRoot);
} else {
ret = idiff(dom, vnode, context, mountAll, componentRoot);
}
// append the element if its a new parent
if (parent && ret.parentNode !== parent) parent.appendChild(ret);
}
// diffLevel being reduced to 0 means we're exiting the diff
if (! --diffLevel) {
hydrating = false;
// invoke queued componentDidMount lifecycle methods
}
return ret;
}
/** Internals of `diff()`, separated to allow bypassing diffLevel / mount flushing. */
function idiff(dom, vnode, context, mountAll, componentRoot) {
if (dom && vnode && dom.props) {
dom.props.children = vnode.children;
}
var out = dom,
prevSvgMode = isSvgMode;
// empty values (null, undefined, booleans) render as empty Text nodes
if (vnode == null || typeof vnode === 'boolean') vnode = '';
// Fast case: Strings & Numbers create/update Text nodes.
if (typeof vnode === 'string' || typeof vnode === 'number') {
// update if it's already a Text node:
if (dom && dom.splitText !== undefined && dom.parentNode && (!dom._component || componentRoot)) {
/* istanbul ignore if */ /* Browser quirk that can't be covered: https://github.com/developit/preact/commit/fd4f21f5c45dfd75151bd27b4c217d8003aa5eb9 */
if (dom.nodeValue != vnode) {
dom.nodeValue = vnode;
}
} else {
// it wasn't a Text node: replace it with one and recycle the old Element
out = document.createTextNode(vnode);
if (dom) {
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
recollectNodeTree(dom, true);
}
}
out[ATTR_KEY] = true;
return out;
}
// If the VNode represents a Component, perform a component diff:
var vnodeName = vnode.nodeName;
// Tracks entering and exiting SVG namespace when descending through the tree.
isSvgMode = vnodeName === 'svg' ? true : vnodeName === 'foreignObject' ? false : isSvgMode;
// If there's no existing element or it's the wrong type, create a new one:
vnodeName = String(vnodeName);
if (!dom || !isNamedNode(dom, vnodeName)) {
out = createNode(vnodeName, isSvgMode);
if (dom) {
// move children into the replacement node
while (dom.firstChild) {
out.appendChild(dom.firstChild);
} // if the previous Element was mounted into the DOM, replace it inline
if (dom.parentNode) dom.parentNode.replaceChild(out, dom);
// recycle the old element (skips non-Element node types)
recollectNodeTree(dom, true);
}
}
var fc = out.firstChild,
props = out[ATTR_KEY],
vchildren = vnode.children;
if (props == null) {
props = out[ATTR_KEY] = {};
for (var a = out.attributes, i = a.length; i--;) {
props[a[i].name] = a[i].value;
}
}
// Optimization: fast-path for elements containing a single TextNode:
if (!hydrating && vchildren && vchildren.length === 1 && typeof vchildren[0] === 'string' && fc != null && fc.splitText !== undefined && fc.nextSibling == null) {
if (fc.nodeValue != vchildren[0]) {
fc.nodeValue = vchildren[0];
}
}
// otherwise, if there are existing or new children, diff them:
else if (vchildren && vchildren.length || fc != null) {
if (!(out.constructor.is == 'WeElement' && out.constructor.noSlot)) {
innerDiffNode(out, vchildren, context, mountAll, hydrating || props.dangerouslySetInnerHTML != null);
}
}
// Apply attributes/props from VNode to the DOM Element:
diffAttributes(out, vnode.attributes, props);
if (out.props) {
out.props.children = vnode.children;
}
// restore previous SVG mode: (in case we're exiting an SVG namespace)
isSvgMode = prevSvgMode;
return out;
}
/** Apply child and attribute changes between a VNode and a DOM Node to the DOM.
* @param {Element} dom Element whose children should be compared & mutated
* @param {Array} vchildren Array of VNodes to compare to `dom.childNodes`
* @param {Object} context Implicitly descendant context object (from most recent `getChildContext()`)
* @param {Boolean} mountAll
* @param {Boolean} isHydrating If `true`, consumes externally created elements similar to hydration
*/
function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) {
var originalChildren = dom.childNodes,
children = [],
keyed = {},
keyedLen = 0,
min = 0,
len = originalChildren.length,
childrenLen = 0,
vlen = vchildren ? vchildren.length : 0,
j = void 0,
c = void 0,
f = void 0,
vchild = void 0,
child = void 0;
// Build up a map of keyed children and an Array of unkeyed children:
if (len !== 0) {
for (var i = 0; i < len; i++) {
var _child = originalChildren[i],
props = _child[ATTR_KEY],
key = vlen && props ? _child._component ? _child._component.__key : props.key : null;
if (key != null) {
keyedLen++;
keyed[key] = _child;
} else if (props || (_child.splitText !== undefined ? isHydrating ? _child.nodeValue.trim() : true : isHydrating)) {
children[childrenLen++] = _child;
}
}
}
if (vlen !== 0) {
for (var _i = 0; _i < vlen; _i++) {
vchild = vchildren[_i];
child = null;
// attempt to find a node based on key matching
var _key = vchild.key;
if (_key != null) {
if (keyedLen && keyed[_key] !== undefined) {
child = keyed[_key];
keyed[_key] = undefined;
keyedLen--;
}
}
// attempt to pluck a node of the same type from the existing children
else if (!child && min < childrenLen) {
for (j = min; j < childrenLen; j++) {
if (children[j] !== undefined && isSameNodeType(c = children[j], vchild, isHydrating)) {
child = c;
children[j] = undefined;
if (j === childrenLen - 1) childrenLen--;
if (j === min) min++;
break;
}
}
}
// morph the matched/found/created DOM child to match vchild (deep)
child = idiff(child, vchild, context, mountAll);
f = originalChildren[_i];
if (child && child !== dom && child !== f) {
if (f == null) {
dom.appendChild(child);
} else if (child === f.nextSibling) {
removeNode(f);
} else {
dom.insertBefore(child, f);
}
}
}
}
// remove unused keyed children:
if (keyedLen) {
for (var _i2 in keyed) {
if (keyed[_i2] !== undefined) recollectNodeTree(keyed[_i2], false);
}
}
// remove orphaned unkeyed children:
while (min <= childrenLen) {
if ((child = children[childrenLen--]) !== undefined) recollectNodeTree(child, false);
}
}
/** Recursively recycle (or just unmount) a node and its descendants.
* @param {Node} node DOM node to start unmount/removal from
* @param {Boolean} [unmountOnly=false] If `true`, only triggers unmount lifecycle, skips removal
*/
function recollectNodeTree(node, unmountOnly) {
// If the node's VNode had a ref function, invoke it with null here.
// (this is part of the React spec, and smart for unsetting references)
if (node[ATTR_KEY] != null && node[ATTR_KEY].ref) node[ATTR_KEY].ref(null);
if (unmountOnly === false || node[ATTR_KEY] == null) {
removeNode(node);
}
removeChildren(node);
}
/** Recollect/unmount all children.
* - we use .lastChild here because it causes less reflow than .firstChild
* - it's also cheaper than accessing the .childNodes Live NodeList
*/
function removeChildren(node) {
node = node.lastChild;
while (node) {
var next = node.previousSibling;
recollectNodeTree(node, true);
node = next;
}
}
/** Apply differences in attributes from a VNode to the given DOM Element.
* @param {Element} dom Element with attributes to diff `attrs` against
* @param {Object} attrs The desired end-state key-value attribute pairs
* @param {Object} old Current/previous attributes (from previous VNode or element's prop cache)
*/
function diffAttributes(dom, attrs, old) {
var name = void 0;
var update = false;
var isWeElement = dom.update;
// remove attributes no longer present on the vnode by setting them to undefined
for (name in old) {
if (!(attrs && attrs[name] != null) && old[name] != null) {
setAccessor(dom, name, old[name], old[name] = undefined, isSvgMode);
if (isWeElement) {
delete dom.props[name];
update = true;
}
}
}
// add new & update changed attributes
for (name in attrs) {
//diable when using store system?
//!dom.store &&
if (isWeElement && typeof attrs[name] === 'object') {
dom.props[npn(name)] = attrs[name];
update = true;
} else if (name !== 'children' && name !== 'innerHTML' && (!(name in old) || attrs[name] !== (name === 'value' || name === 'checked' ? dom[name] : old[name]))) {
setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode);
if (isWeElement) {
dom.props[npn(name)] = attrs[name];
update = true;
}
}
}
dom.parentNode && update && isWeElement && dom.update();
}
/*!
* https://github.com/Palindrom/JSONPatcherProxy
* (c) 2017 Starcounter
* MIT license
*/
/** Class representing a JS Object observer */
var JSONPatcherProxy = function () {
/**
* Deep clones your object and returns a new object.
*/
function deepClone(obj) {
switch (typeof obj) {
case 'object':
return JSON.parse(JSON.stringify(obj)); //Faster than ES5 clone - http://jsperf.com/deep-cloning-of-objects/5
case 'undefined':
return null; //this is how JSON.stringify behaves for array items
default:
return obj; //no need to clone primitives
}
}
JSONPatcherProxy.deepClone = deepClone;
function escapePathComponent(str) {
if (str.indexOf('/') == -1 && str.indexOf('~') == -1) return str;
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
JSONPatcherProxy.escapePathComponent = escapePathComponent;
/**
* Walk up the parenthood tree to get the path
* @param {JSONPatcherProxy} instance
* @param {Object} obj the object you need to find its path
*/
function findObjectPath(instance, obj) {
var pathComponents = [];
var parentAndPath = instance.parenthoodMap.get(obj);
while (parentAndPath && parentAndPath.path) {
// because we're walking up-tree, we need to use the array as a stack
pathComponents.unshift(parentAndPath.path);
parentAndPath = instance.parenthoodMap.get(parentAndPath.parent);
}
if (pathComponents.length) {
var path = pathComponents.join('/');
return '/' + path;
}
return '';
}
/**
* A callback to be used as th proxy set trap callback.
* It updates parenthood map if needed, proxifies nested newly-added objects, calls default callbacks with the changes occurred.
* @param {JSONPatcherProxy} instance JSONPatcherProxy instance
* @param {Object} target the affected object
* @param {String} key the effect property's name
* @param {Any} newValue the value being set
*/
function setTrap(instance, target, key, newValue) {
var parentPath = findObjectPath(instance, target);
var destinationPropKey = parentPath + '/' + escapePathComponent(key);
if (instance.proxifiedObjectsMap.has(newValue)) {
var newValueOriginalObject = instance.proxifiedObjectsMap.get(newValue);
instance.parenthoodMap.set(newValueOriginalObject.originalObject, {
parent: target,
path: key
});
}
/*
mark already proxified values as inherited.
rationale: proxy.arr.shift()
will emit
{op: replace, path: '/arr/1', value: arr_2}
{op: remove, path: '/arr/2'}
by default, the second operation would revoke the proxy, and this renders arr revoked.
That's why we need to remember the proxies that are inherited.
*/
var revokableInstance = instance.proxifiedObjectsMap.get(newValue);
/*
Why do we need to check instance.isProxifyingTreeNow?
We need to make sure we mark revokables as inherited ONLY when we're observing,
because throughout the first proxification, a sub-object is proxified and then assigned to
its parent object. This assignment of a pre-proxified object can fool us into thinking
that it's a proxified object moved around, while in fact it's the first assignment ever.
Checking isProxifyingTreeNow ensures this is not happening in the first proxification,
but in fact is is a proxified object moved around the tree
*/
if (revokableInstance && !instance.isProxifyingTreeNow) {
revokableInstance.inherited = true;
}
// if the new value is an object, make sure to watch it
if (newValue && typeof newValue == 'object' && !instance.proxifiedObjectsMap.has(newValue)) {
instance.parenthoodMap.set(newValue, {
parent: target,
path: key
});
newValue = instance._proxifyObjectTreeRecursively(target, newValue, key);
}
// let's start with this operation, and may or may not update it later
var operation = {
op: 'remove',
path: destinationPropKey
};
if (typeof newValue == 'undefined') {
// applying De Morgan's laws would be a tad faster, but less readable
if (!Array.isArray(target) && !target.hasOwnProperty(key)) {
// `undefined` is being set to an already undefined value, keep silent
return Reflect.set(target, key, newValue);
}
// when array element is set to `undefined`, should generate replace to `null`
if (Array.isArray(target)) {
operation.op = 'replace', operation.value = null;
}
var oldValue = instance.proxifiedObjectsMap.get(target[key]);
// was the deleted a proxified object?
if (oldValue) {
instance.parenthoodMap.delete(target[key]);
instance.disableTrapsForProxy(oldValue);
instance.proxifiedObjectsMap.delete(oldValue);
}
} else {
if (Array.isArray(target) && !Number.isInteger(+key.toString())) {
/* array props (as opposed to indices) don't emit any patches, to avoid needless `length` patches */
if (key != 'length') {
console.warn('JSONPatcherProxy noticed a non-integer prop was set for an array. This will not emit a patch');
}
return Reflect.set(target, key, newValue);
}
operation.op = 'add';
if (target.hasOwnProperty(key)) {
if (typeof target[key] !== 'undefined' || Array.isArray(target)) {
operation.op = 'replace'; // setting `undefined` array elements is a `replace` op
}
}
operation.value = newValue;
}
operation.oldValue = target[key];
var reflectionResult = Reflect.set(target, key, newValue);
instance.defaultCallback(operation);
return reflectionResult;
}
/**
* A callback to be used as th proxy delete trap callback.
* It updates parenthood map if needed, calls default callbacks with the changes occurred.
* @param {JSONPatcherProxy} instance JSONPatcherProxy instance
* @param {Object} target the effected object
* @param {String} key the effected property's name
*/
function deleteTrap(instance, target, key) {
if (typeof target[key] !== 'undefined') {
var parentPath = findObjectPath(instance, target);
var destinationPropKey = parentPath + '/' + escapePathComponent(key);
var revokableProxyInstance = instance.proxifiedObjectsMap.get(target[key]);
if (revokableProxyInstance) {
if (revokableProxyInstance.inherited) {
/*
this is an inherited proxy (an already proxified object that was moved around),
we shouldn't revoke it, because even though it was removed from path1, it is still used in path2.
And we know that because we mark moved proxies with `inherited` flag when we move them
it is a good idea to remove this flag if we come across it here, in deleteProperty trap.
We DO want to revoke the proxy if it was removed again.
*/
revokableProxyInstance.inherited = false;
} else {
instance.parenthoodMap.delete(revokableProxyInstance.originalObject);
instance.disableTrapsForProxy(revokableProxyInstance);
instance.proxifiedObjectsMap.delete(target[key]);
}
}
var reflectionResult = Reflect.deleteProperty(target, key);
instance.defaultCallback({
op: 'remove',
path: destinationPropKey
});
return reflectionResult;
}
}
/* pre-define resume and pause functions to enhance constructors performance */
function resume() {
var _this = this;
this.defaultCallback = function (operation) {
_this.isRecording && _this.patches.push(operation);
_this.userCallback && _this.userCallback(operation);
};
this.isObserving = true;
}
function pause() {
this.defaultCallback = function () {};
this.isObserving = false;
}
/**
* Creates an instance of JSONPatcherProxy around your object of interest `root`.
* @param {Object|Array} root - the object you want to wrap
* @param {Boolean} [showDetachedWarning = true] - whether to log a warning when a detached sub-object is modified @see {@link https://github.com/Palindrom/JSONPatcherProxy#detached-objects}
* @returns {JSONPatcherProxy}
* @constructor
*/
function JSONPatcherProxy(root, showDetachedWarning) {
this.isProxifyingTreeNow = false;
this.isObserving = false;
this.proxifiedObjectsMap = new Map();
this.parenthoodMap = new Map();
// default to true
if (typeof showDetachedWarning !== 'boolean') {
showDetachedWarning = true;
}
this.showDetachedWarning = showDetachedWarning;
this.originalObject = root;
this.cachedProxy = null;
this.isRecording = false;
this.userCallback;
/**
* @memberof JSONPatcherProxy
* Restores callback back to the original one provided to `observe`.
*/
this.resume = resume.bind(this);
/**
* @memberof JSONPatcherProxy
* Replaces your callback with a noop function.
*/
this.pause = pause.bind(this);
}
JSONPatcherProxy.prototype.generateProxyAtPath = function (parent, obj, path) {
var _this2 = this;
if (!obj) {
return obj;
}
var traps = {
set: function set(target, key, value, receiver) {
return setTrap(_this2, target, key, value, receiver);
},
deleteProperty: function deleteProperty(target, key) {
return deleteTrap(_this2, target, key);
}
};
var revocableInstance = Proxy.revocable(obj, traps);
// cache traps object to disable them later.
revocableInstance.trapsInstance = traps;
revocableInstance.originalObject = obj;
/* keeping track of object's parent and path */
this.parenthoodMap.set(obj, { parent: parent, path: path });
/* keeping track of all the proxies to be able to revoke them later */
this.proxifiedObjectsMap.set(revocableInstance.proxy, revocableInstance);
return revocableInstance.proxy;
};
// grab tree's leaves one by one, encapsulate them into a proxy and return
JSONPatcherProxy.prototype._proxifyObjectTreeRecursively = function (parent, root, path) {
for (var key in root) {
if (root.hasOwnProperty(key)) {
if (root[key] instanceof Object) {
root[key] = this._proxifyObjectTreeRecursively(root, root[key], escapePathComponent(key));
}
}
}
return this.generateProxyAtPath(parent, root, path);
};
// this function is for aesthetic purposes
JSONPatcherProxy.prototype.proxifyObjectTree = function (root) {
/*
while proxyifying object tree,
the proxyifying operation itself is being
recorded, which in an unwanted behavior,
that's why we disable recording through this
initial process;
*/
this.pause();
this.isProxifyingTreeNow = true;
var proxifiedObject = this._proxifyObjectTreeRecursively(undefined, root, '');
/* OK you can record now */
this.isProxifyingTreeNow = false;
this.resume();
return proxifiedObject;
};
/**
* Turns a proxified object into a forward-proxy object; doesn't emit any patches anymore, like a normal object
* @param {Proxy} proxy - The target proxy object
*/
JSONPatcherProxy.prototype.disableTrapsForProxy = function (revokableProxyInstance) {
if (this.showDetachedWarning) {
var message = "You're accessing an object that is detached from the observedObject tree, see https://github.com/Palindrom/JSONPatcherProxy#detached-objects";
revokableProxyInstance.trapsInstance.set = function (targetObject, propKey, newValue) {
console.warn(message);
return Reflect.set(targetObject, propKey, newValue);
};
revokableProxyInstance.trapsInstance.set = function (targetObject, propKey, newValue) {
console.warn(message);
return Reflect.set(targetObject, propKey, newValue);
};
revokableProxyInstance.trapsInstance.deleteProperty = function (targetObject, propKey) {
return Reflect.deleteProperty(targetObject, propKey);
};
} else {
delete revokableProxyInstance.trapsInstance.set;
delete revokableProxyInstance.trapsInstance.get;
delete revokableProxyInstance.trapsInstance.deleteProperty;
}
};
/**
* Proxifies the object that was passed in the constructor and returns a proxified mirror of it. Even though both parameters are options. You need to pass at least one of them.
* @param {Boolean} [record] - whether to record object changes to a later-retrievable patches array.
* @param {Function} [callback] - this will be synchronously called with every object change with a single `patch` as the only parameter.
*/
JSONPatcherProxy.prototype.observe = function (record, callback) {
if (!record && !callback) {
throw new Error('You need to either record changes or pass a callback');
}
this.isRecording = record;
this.userCallback = callback;
/*
I moved it here to remove it from `unobserve`,
this will also make the constructor faster, why initiate
the array before they decide to actually observe with recording?
They might need to use only a callback.
*/
if (record) this.patches = [];
this.cachedProxy = this.proxifyObjectTree(this.originalObject);
return this.cachedProxy;
};
/**
* If the observed is set to record, it will synchronously return all the patches and empties patches array.
*/
JSONPatcherProxy.prototype.generate = function () {
if (!this.isRecording) {
throw new Error('You should set record to true to get patches later');
}
return this.patches.splice(0, this.patches.length);
};
/**
* Revokes all proxies rendering the observed object useless and good for garbage collection @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/revocable}
*/
JSONPatcherProxy.prototype.revoke = function () {
this.proxifiedObjectsMap.forEach(function (el) {
el.revoke();
});
};
/**
* Disables all proxies' traps, turning the observed object into a forward-proxy object, like a normal object that you can modify silently.
*/
JSONPatcherProxy.prototype.disableTraps = function () {
this.proxifiedObjectsMap.forEach(this.disableTrapsForProxy, this);
};
return JSONPatcherProxy;
}();
var callbacks = [];
var nextTickCallback = [];
function tick(fn, scope) {
callbacks.push({ fn: fn, scope: scope });
}
function fireTick() {
callbacks.forEach(function (item) {
item.fn.call(item.scope);
});
nextTickCallback.forEach(function (nextItem) {
nextItem.fn.call(nextItem.scope);
});
nextTickCallback.length = 0;
}
function nextTick(fn, scope) {
nextTickCallback.push({ fn: fn, scope: scope });
}
function observe(target) {
target.observe = true;
}
function proxyUpdate(ele) {
var timeout = null;
ele.data = new JSONPatcherProxy(ele.data).observe(false, function (info) {
if (ele._willUpdate || info.op === 'replace' && info.oldValue === info.value) {
return;
}
clearTimeout(timeout);
timeout = setTimeout(function () {
ele.update();
fireTick();
}, 0);
});
}
var _class, _temp;
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var id = 0;
var WeElement = (_temp = _class = function (_HTMLElement) {
_inherits(WeElement, _HTMLElement);
function WeElement() {
_classCallCheck(this, WeElement);
var _this = _possibleConstructorReturn(this, _HTMLElement.call(this));
_this.props = Object.assign(nProps(_this.constructor.props), _this.constructor.defaultProps);
_this.__elementId = id++;
_this.data = _this.constructor.data || {};
return _this;
}
WeElement.prototype.connectedCallback = function connectedCallback() {
if (!this.constructor.pure) {
var p = this.parentNode;
while (p && !this.store) {
this.store = p.store;
p = p.parentNode || p.host;
}
if (this.store) {
this.store.instances.push(this);
}
}
!this._isInstalled && this.install();
var shadowRoot = void 0;
if (!this.shadowRoot) {
shadowRoot = this.attachShadow({
mode: 'open'
});
} else {
shadowRoot = this.shadowRoot;
var fc = void 0;
while (fc = shadowRoot.firstChild) {
shadowRoot.removeChild(fc);
}
}
this.css && shadowRoot.appendChild(cssToDom(this.css()));
!this._isInstalled && this.beforeRender();
options.afterInstall && options.afterInstall(this);
if (this.constructor.observe) {
proxyUpdate(this);
}
this.host = diff(null, this.render(this.props, this.data, this.store), {}, false, null, false);
if (isArray(this.host)) {
this.host.forEach(function (item) {
shadowRoot.appendChild(item);
});
} else {
shadowRoot.appendChild(this.host);
}
!this._isInstalled && this.installed();
this._isInstalled = true;
};
WeElement.prototype.disconnectedCallback = function disconnectedCallback() {
this.uninstall();
if (this.store) {
for (var i = 0, len = this.store.instances.length; i < len; i++) {
if (this.store.instances[i] === this) {
this.store.instances.splice(i, 1);
break;
}
}
}
};
WeElement.prototype.update = function update() {
this._willUpdate = true;
this.beforeUpdate();
this.beforeRender();
this.host = diff(this.host, this.render(this.props, this.data, this.store), null, null, this.shadowRoot);
this.afterUpdate();
this._willUpdate = false;
};
WeElement.prototype.fire = function fire(name, data) {
this.dispatchEvent(new CustomEvent(name, { detail: data }));
};
WeElement.prototype.install = function install() {};
WeElement.prototype.installed = function installed() {};
WeElement.prototype.uninstall = function uninstall() {};
WeElement.prototype.beforeUpdate = function beforeUpdate() {};
WeElement.prototype.afterUpdate = function afterUpdate() {};
WeElement.prototype.beforeRender = function beforeRender() {};
return WeElement;
}(HTMLElement), _class.is = 'WeElement', _temp);
function render(vnode, parent, store) {
parent = typeof parent === 'string' ? document.querySelector(parent) : parent;
if (store) {
store.instances = [];
extendStoreUpate(store);
var timeout = null;
var patchs = {};
store.data = new JSONPatcherProxy(store.data).observe(false, function (patch) {
clearTimeout(timeout);
if (patch.op === 'remove') {
// fix arr splice
var kv = getArrayPatch(patch.path, store);
patchs[kv.k] = kv.v;
timeout = setTimeout(function () {
update(patchs, store);
patchs = {};
}, 0);
} else {
var key = fixPath(patch.path);
patchs[key] = patch.value;
timeout = setTimeout(function () {
update(patchs, store);
patchs = {};
}, 0);
}
});
parent.store = store;
}
return diff(null, vnode, {}, false, parent, false);
}
function update(patch, store) {
store.update(patch);
}
function extendStoreUpate(store) {
store.update = function (patch) {
var _this = this;
var updateAll = matchGlobalData(this.globalData, patch);
if (Object.keys(patch).length > 0) {
this.instances.forEach(function (instance) {
if (updateAll || _this.updateAll || instance.constructor.updatePath && needUpdate(patch, instance.constructor.updatePath)) {
instance.update();
}
});
this.onChange && this.onChange(patch);
}
};
}
function matchGlobalData(globalData, diffResult) {
if (!globalData) return false;
for (var keyA in diffResult) {
if (globalData.indexOf(keyA) > -1) {
return true;
}
for (var i = 0, len = globalData.length; i < len; i++) {
if (includePath(keyA, globalData[i])) {
return true;
}
}
}
return false;
}
function needUpdate(diffResult, updatePath) {
for (var keyA in diffResult) {
if (updatePath[keyA]) {
return true;
}
for (var keyB in updatePath) {
if (includePath(keyA, keyB)) {
return true;
}
}
}
return false;
}
function includePath(pathA, pathB) {
if (pathA.indexOf(pathB) === 0) {
var next = pathA.substr(pathB.length, 1);
if (next === '[' || next === '.') {
return true;
}
}
return false;
}
function fixPath(path) {
var mpPath = '';
var arr = path.replace('/', '').split('/');
arr.forEach(function (item, index) {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item;
} else {
mpPath += '[' + item + ']';
}
} else {
mpPath += item;
}
});
return mpPath;
}
function getArrayPatch(path, store) {
var arr = path.replace('/', '').split('/');
var current = store.data[arr[0]];
for (var i = 1, len = arr.length; i < len - 1; i++) {
current = current[arr[i]];
}
return { k: fixArrPath(path), v: current };
}
function fixArrPath(path) {
var mpPath = '';
var arr = path.replace('/', '').split('/');
var len = arr.length;
arr.forEach(function (item, index) {
if (index < len - 1) {
if (index) {
if (isNaN(Number(item))) {
mpPath += '.' + item;
} else {
mpPath += '[' + item + ']';
}
} else {
mpPath += item;
}
}
});
return mpPath;
}
function _classCallCheck$1(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn$1(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$1(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var OBJECTTYPE = '[object Object]';
var ARRAYTYPE = '[object Array]';
function define(name, ctor) {
if (ctor.is === 'WeElement') {
customElements.define(name, ctor);
if (ctor.data && !ctor.pure) {
ctor.updatePath = getUpdatePath(ctor.data);
}
} else {
var Element = function (_WeElement) {
_inherits$1(Element, _WeElement);
function Element() {
var _temp, _this, _ret;
_classCallCheck$1(this, Element);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn$1(this, _WeElement.call.apply(_WeElement, [this].concat(args))), _this), _this._useId = 0, _this._useMap = {}, _temp), _possibleConstructorReturn$1(_this, _ret);
}
Element.prototype.render = function render(props, data) {
return ctor.call(this, props, data);
};
Element.prototype.beforeRender = function beforeRender() {
this._useId = 0;
};
Element.prototype.useCss = function useCss(css) {
var style = this.shadowRoot.querySelector('style');
style && this.shadowRoot.removeChild(style);
this.shadowRoot.appendChild(cssToDom(css));
};
Element.prototype.useData = function useData(data) {
return this.use({ data: data });
};
Element.prototype.use = function use(option) {
var _this2 = this;
this._useId++;
var updater = function updater(newValue) {
var item = _this2._useMap[updater.id];
item.data = newValue;
_this2.update();
item.effect && item.effect();
};
updater.id = this._useId;
if (!this._isInstalled) {
this._useMap[this._useId] = option;
return [option.data, updater];
}
return [this._useMap[this._useId].data, updater];
};
Element.prototype.installed = function installed() {
this._isInstalled = true;
};
return Element;
}(WeElement);
customElements.define(name, Element);
}
}
function getUpdatePath(data) {
var result = {};
dataToPath(data, result);
return result;
}
function dataToPath(data, result) {
Object.keys(data).forEach(function (key) {
result[key] = true;
var type = Object.prototype.toString.call(data[key]);
if (type === OBJECTTYPE) {
_objToPath(data[key], key, result);
} else if (type === ARRAYTYPE) {
_arrayToPath(data[key], key, result);
}
});
}
function _objToPath(data, path, result) {
Object.keys(data).forEach(function (key) {
result[path + '.' + key] = true;
delete result[path];
var type = Object.prototype.toString.call(data[key]);
if (type === OBJECTTYPE) {
_objToPath(data[key], path + '.' + key, result);
} else if (type === ARRAYTYPE) {
_arrayToPath(data[key], path + '.' + key, result);
}
});
}
function _arrayToPath(data, path, result) {
data.forEach(function (item, index) {
result[path + '[' + index + ']'] = true;
delete result[path];
var type = Object.prototype.toString.call(item);
if (type === OBJECTTYPE) {
_objToPath(item, path + '[' + index + ']', result);
} else if (type === ARRAYTYPE) {
_arrayToPath(item, path + '[' + index + ']', result);
}
});
}
function tag(name, pure) {
return function (target) {
target.pure = pure;
define(name, target);
};
}
/**
* Clones the given VNode, optionally adding attributes/props and replacing its children.
* @param {VNode} vnode The virtual DOM element to clone
* @param {Object} props Attributes/props to add when cloning
* @param {VNode} rest Any additional arguments will be used as replacement children.
*/
function cloneElement(vnode, props) {
return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children);
}
function getHost(ele) {
var p = ele.parentNode;
while (p) {
if (p.host) {
return p.host;
} else {
p = p.parentNode;
}
}
}
function rpx(str) {
return str.replace(/([1-9]\d*|0)(\.\d*)*rpx/g, function (a, b) {
return window.innerWidth * Number(b) / 750 + 'px';
});
}
var Component = WeElement;
var omi = {
tag: tag,
WeElement: WeElement,
Component: Component,
render: render,
h: h,
createElement: h,
options: options,
define: define,
observe: observe,
cloneElement: cloneElement,
getHost: getHost,
rpx: rpx,
tick: tick,
nextTick: nextTick
};
options.root.Omi = omi;
options.root.Omi.version = '4.1.4';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class2, _temp2;
function _classCallCheck$2(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn$2(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits$2(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
define('todo-list', function (_WeElement) {
_inherits$2(_class, _WeElement);
function _class() {
_classCallCheck$2(this, _class);
return _possibleConstructorReturn$2(this, _WeElement.apply(this, arguments));
}
_class.prototype.render = function render$$1(props) {
return Omi.h(
'ul',
null,
props.items.map(function (item) {
return Omi.h(
'li',
{ key: item.id },
item.text
);
})
);
};
return _class;
}(WeElement));
define('todo-app', (_temp2 = _class2 = function (_WeElement2) {
_inherits$2(_class2, _WeElement2);
function _class2() {
var _temp, _this2, _ret;
_classCallCheck$2(this, _class2);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this2 = _possibleConstructorReturn$2(this, _WeElement2.call.apply(_WeElement2, [this].concat(args))), _this2), _this2.handleChange = function (e) {
_this2.data.text = e.target.value;
}, _this2.handleSubmit = function (e) {
e.preventDefault();
if (!_this2.data.text.trim().length) {
return;
}
_this2.data.items.push({
text: _this2.data.text,
id: Date.now()
});
_this2.data.text = '';
}, _temp), _possibleConstructorReturn$2(_this2, _ret);
}
_class2.prototype.install = function install() {
tick(function () {
console.log('tick');
});
tick(function () {
console.log('tick2');
});
};
_class2.prototype.beforeRender = function beforeRender() {
nextTick(function () {
console.log('nextTick');
});
// don't using tick in beforeRender
// tick(() => {
// console.log(Math.random())
// })
};
_class2.prototype.afterUpdate = function afterUpdate() {
console.log('afterUpdate');
};
_class2.prototype.installed = function installed() {
console.log('installed');
};
_class2.prototype.render = function render$$1() {
this.data.a = { c: 2 };
console.log('render');
return Omi.h(
'div',
null,
Omi.h(
'h3',
null,
'TODO',
this.data.a.c
),
Omi.h('todo-list', { items: this.data.items }),
Omi.h(
'form',
{ onSubmit: this.handleSubmit },
Omi.h('input', {
id: 'new-todo',
onChange: this.handleChange,
value: this.data.text
}),
Omi.h(
'button',
null,
'Add #',
this.data.items.length + 1
)
)
);
};
_createClass(_class2, null, [{
key: 'data',
get: function get() {
return { items: [], a: { b: 1 }, text: '' };
}
}]);
return _class2;
}(WeElement), _class2.observe = true, _temp2));
render(Omi.h('todo-app', null), 'body');
}());
//# sourceMappingURL=b.js.map
|
'use strict';
/* Controllers */
var contactControllers = angular.module('contactControllers', []);
contactControllers.controller('ContactListCtrl', ['$scope', 'Contacts',
function($scope, Contacts) {
$scope.contacts = Contacts.query();
$scope.updateData = function(){
console.log("Code for posting or update with Contacts.update({}})");
}
}]);
|
require('./tests/algolia-test')();
|
$(document).ready(function() {
var template = _.template(
'<div><audio controls>\
<source src="sounds/<%= filename %>" type="audio/wav">\
</audio></div>');
$.get('/sounds', function(d) {
_.each(d.sounds, function(arg) {
$('.container').append(template({filename: arg}));
});
});
});
|
var Map = $.extend(true, {}, Map, {
Model: {
Column: function () {
var self = this;
self.Name = ko.observable(null);
}
}
});
|
"use strict";
// external modules
var md5 = require("blueimp-md5");
var Sequelize = require("sequelize");
// core
var logger = require("../logger.js");
module.exports = function (sequelize, DataTypes) {
var User = sequelize.define("User", {
id: {
type: DataTypes.UUID,
primaryKey: true,
defaultValue: Sequelize.UUIDV4
},
profileid: {
type: DataTypes.STRING,
unique: true
},
profile: {
type: DataTypes.TEXT
},
history: {
type: DataTypes.TEXT
}
}, {
classMethods: {
associate: function (models) {
User.hasMany(models.Note, {
foreignKey: "ownerId",
constraints: false
});
User.hasMany(models.Note, {
foreignKey: "lastchangeuserId",
constraints: false
});
},
parseProfile: function (profile) {
try {
var profile = JSON.parse(profile);
} catch (err) {
logger.error(err);
profile = null;
}
if (profile) {
profile = {
name: profile.displayName || profile.username,
photo: User.parsePhotoByProfile(profile)
}
}
return profile;
},
parsePhotoByProfile: function (profile) {
var photo = null;
switch (profile.provider) {
case "facebook":
photo = 'https://graph.facebook.com/' + profile.id + '/picture';
break;
case "twitter":
photo = profile.photos[0].value;
break;
case "github":
photo = 'https://avatars.githubusercontent.com/u/' + profile.id + '?s=48';
break;
case "dropbox":
//no image api provided, use gravatar
photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0].value);
break;
}
return photo;
}
}
});
return User;
};
|
import Entity from './Entity';
import { Body } from 'matter-js';
export default class Ship extends Entity {
constructor(app) {
super(app);
this.accelerating = false;
this.turningLeft = false;
this.turningRight = false;
this.app.physics.createBody(this, 'circle', this.x, this.y, 65, {
frictionAir: 0.03
});
}
turnLeft() {
this.turningLeft = true;
Body.rotate(this.physicsBody, -(Math.PI / 20));
}
turnRight() {
this.turningRight = true;
Body.rotate(this.physicsBody, Math.PI / 20);
}
accelerate() {
this.accelerating = true;
Body.applyForce(this.physicsBody, {
x: this.x,
y: this.y
}, {
x: Math.cos(this.angle) * 0.003,
y: Math.sin(this.angle) * 0.003
});
}
update() {
super.update();
this.accelerating = false;
this.turningLeft = false;
this.turningRight = false;
}
}
|
var indexSectionsWithContent =
{
0: "abcdefghijklmnopqrstuvwxyz~",
1: "cefikmnpsuv",
2: "l",
3: "cefikmnpsuv",
4: "abcdefghiklmnoprsuv~",
5: "ehimotw",
6: "c",
7: "ckmv",
8: "abcdefghijklmnopqrstuvwxyz",
9: "m",
10: "dgms"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "files",
4: "functions",
5: "variables",
6: "typedefs",
7: "enums",
8: "enumvalues",
9: "related",
10: "defines"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Files",
4: "Functions",
5: "Variables",
6: "Typedefs",
7: "Enumerations",
8: "Enumerator",
9: "Friends",
10: "Macros"
};
|
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['bho_IN'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%z%c%T%s%b%e%r",
"country_name": null,
"country_post": null,
"country_ab2": "IN",
"country_ab3": "IND",
"country_num": 356,
"country_car": "IND",
"country_isbn": null,
"lang_name": "\u092d\u094b\u091c\u092a\u0941\u0930\u0940",
"lang_ab": null,
"lang_term": "bho",
"lang_lib": "bho"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1yY\u0939]",
"noexpr": "^[-0nN\u0928]",
"yesstr": "\u0939\u093e\u0901",
"nostr": "\u0928\u0939\u0940\u0902"
},
"LC_MONETARY": {
"currency_symbol": "\u20b9",
"mon_decimal_point": ".",
"mon_thousands_sep": ",",
"mon_grouping": [
3,
2
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 0,
"n_cs_precedes": 1,
"n_sep_by_space": 0,
"p_sign_posn": 1,
"n_sign_posn": 1,
"int_curr_symbol": "INR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%p%t%f%t%g",
"name_gen": "",
"name_mr": "\u0936\u094d\u0930\u0940",
"name_mrs": "\u0936\u094d\u0930\u0940\u092e\u0924\u0940",
"name_miss": "\u0915\u0941\u092e\u093e\u0930\u0940",
"name_ms": "\u0915\u0941\u092e\u093e\u0930"
},
"LC_NUMERIC": {
"decimal_point": ".",
"thousands_sep": ",",
"grouping": 3
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": [
"+%c ",
0,
0
],
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "91"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"\u0930\u0935\u093f",
"\u0938\u094b\u092e",
"\u092e\u0902\u0917\u0932",
"\u092c\u0941\u0927",
"\u0917\u0941\u0930\u0941",
"\u0936\u0941\u0915\u094d\u0930",
"\u0936\u0928\u093f"
],
"day": [
"\u0930\u0935\u093f\u0935\u093e\u0930",
"\u0938\u094b\u092e\u0935\u093e\u0930",
"\u092e\u0902\u0917\u0932\u0935\u093e\u0930",
"\u092c\u0941\u0927\u0935\u093e\u0930",
"\u0917\u0941\u0930\u0941\u0935\u093e\u0930",
"\u0936\u0941\u0915\u094d\u0930\u0935\u093e\u0930",
"\u0936\u0928\u093f\u0935\u093e\u0930"
],
"week": [
7,
19971130,
1
],
"abmon": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u091f\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930\"%"
],
"mon": [
"\u091c\u0928\u0935\u0930\u0940",
"\u092b\u0930\u0935\u0930\u0940",
"\u092e\u093e\u0930\u094d\u091a",
"\u0905\u092a\u094d\u0930\u0948\u0932",
"\u092e\u0908",
"\u091c\u0942\u0928",
"\u091c\u0941\u0932\u093e\u0908",
"\u0905\u0917\u0938\u094d\u0924",
"\u0938\u093f\u0924\u092e\u094d\u092c\u0930",
"\u0905\u0915\u094d\u091f\u0942\u092c\u0930",
"\u0928\u0935\u092e\u094d\u092c\u0930",
"\u0926\u093f\u0938\u092e\u094d\u092c\u0930\"%"
],
"d_t_fmt": "%A %d %b %Y %I:%M:%S %p %Z",
"d_fmt": "%-d\/\/%-m\/\/%y",
"t_fmt": "%I:%M:%S %p %Z",
"am_pm": [
"\u092a\u0942\u0930\u094d\u0935\u093e\u0939\u094d\u0928",
"\u0905\u092a\u0930\u093e\u0939\u094d\u0928"
],
"t_fmt_ampm": "%I:%M:%S %p %Z",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": null,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
|
import LatLng from './latlng'
import Point from './point'
const {min, max, sin, log, PI, atan, exp} = Math
class SphericalMercator {
constructor() {
this.R = 6378137
this.MAX_LATITUDE = 85.0511287798
}
// @method project(latlng: LatLng): Point
// converts latlng to Point (meters)
project(latlng) {
//convert [lng, lat] to meters
const d = Math.PI / 180
const R = this.R
const maxLat = this.MAX_LATITUDE
const lat = max(min(maxLat, latlng.lat), -maxLat)
const sinA = sin(lat * d)
return new Point(
R * latlng.lng * d,
R * log((1 + sinA) / (1 - sinA)) / 2
)
}
// @method unproject(point: Point): LatLng
// converts point (in meters) to LatLng
unproject(point) {
const d = 180 / Math.PI
const R = this.R
return new LatLng(
(2 * atan(exp(point.y / R)) - (PI / 2)) * d,
point.x * d / R);
}
/*
TODO
bounds: (function () {
var d = 6378137 * Math.PI;
return L.bounds([-d, -d], [d, d]);
})()*/
}
module.exports = SphericalMercator
|
import { uuid } from 'utils/utils';
export const defaultState = {
id: null,
condition: '',
name: '',
description: '',
finalMember: '',
initialMember: '',
};
export const defaultForm = {
condition: '',
name: '',
description: '',
initialMember: '',
finalMember: '',
};
export function formToState(form) {
const { condition, name, description, finalMember, initialMember } = form;
const id = form.id || uuid();
return {
id,
condition,
name,
description,
finalMember,
initialMember,
};
}
export function formToStore(form) {
const { filterNested } = form;
return filterNested.reduce((acc, cv) => {
const state = formToState(cv);
return {
...acc,
[state.id]: state,
};
}, {});
}
// export function storeToForm(currentStore) {
// const calculatedVariables = [];
// Object.keys(currentStore).forEach(key => {
// const {
// id,
// label,
// name,
// formula,
// type,
// scope,
// [type]: simpleState,
// } = currentStore[key];
// calculatedVariables.push({
// id,
// label,
// name,
// formula,
// type,
// scope,
// [type]: {
// ...simpleState,
// },
// });
// });
// return {
// ...defaultForm,
// calculatedVariables,
// };
// }
// const Factory = (currentStore = {}) => {
// return {
// formToStore: form => {
// if (form) currentStore = formToStore(form);
// return currentStore;
// },
// storeToForm: () => {
// return storeToForm(currentStore);
// },
// getStore: () => {
// return currentStore;
// },
// };
// };
// export default Factory;
|
jui.define("chart.widget.topologyctrl", [ "util.base" ], function(_) {
/**
* @class chart.widget.topologyctrl
* @extends chart.widget.core
*/
var TopologyControlWidget = function(chart, axis, widget) {
var self = this;
var targetKey, startX, startY;
var renderWait = false;
var scale = 1, boxX = 0, boxY = 0;
function initDragEvent() {
self.on("chart.mousemove", function(e) {
if(!_.typeCheck("string", targetKey)) return;
var xy = axis.c(targetKey);
xy.setX(startX + (e.chartX - startX));
xy.setY(startY + (e.chartY - startY));
if(renderWait === false) {
setTimeout(function () {
chart.render();
setBrushEvent();
renderWait = false;
}, 70);
renderWait = true;
}
});
self.on("chart.mouseup", endDragAction);
self.on("bg.mouseup", endDragAction);
self.on("bg.mouseout", endDragAction);
function endDragAction(e) {
if(!_.typeCheck("string", targetKey)) return;
targetKey = null;
}
}
function initZoomEvent() {
$(chart.root).bind("mousewheel DOMMouseScroll", function(e){
if(e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0) {
if(scale < 2) {
scale += 0.1;
}
} else {
if(scale > 0.5) {
scale -= 0.1;
}
}
chart.scale(scale);
return false;
});
}
function initMoveEvent() {
var startX = null, startY = null;
self.on("chart.mousedown", function(e) {
if(_.typeCheck("string", targetKey)) return;
if(startX != null || startY != null) return;
startX = boxX + e.x;
startY = boxY + e.y;
});
self.on("chart.mousemove", function(e) {
if(startX == null || startY == null) return;
var xy = chart.view(startX - e.x, startY - e.y);
boxX = xy.x;
boxY = xy.y;
});
self.on("chart.mouseup", endMoveAction);
self.on("bg.mouseup", endMoveAction);
self.on("bg.mouseout", endMoveAction);
function endMoveAction(e) {
if(startX == null || startY == null) return;
startX = null;
startY = null;
}
}
function setBrushEvent() {
chart.svg.root.get(0).each(function(i, brush) {
var cls = brush.attr("class");
if(cls && cls.indexOf("topologynode") != -1) {
brush.each(function(i, node) {
var index = parseInt(node.attr("index"));
if(!isNaN(index)) {
var data = axis.data[index];
(function (key) {
node.on("mousedown", function(e) {
if (_.typeCheck("string", targetKey)) return;
var xy = axis.c(key);
targetKey = key;
startX = xy.x;
startY = xy.y;
// 선택한 노드 맨 마지막으로 이동
xy.moveLast();
});
})(self.axis.getValue(data, "key"));
}
});
}
});
}
this.draw = function() {
if(widget.zoom) {
initZoomEvent();
}
if(widget.move) {
initMoveEvent();
chart.svg.root.attr({ cursor: "move" });
}
initDragEvent();
setBrushEvent();
return chart.svg.group();
}
}
TopologyControlWidget.setup = function() {
return {
/** @cfg {Boolean} [move=false] Set to be moved to see the point of view of the topology map. */
move: false,
/** @cfg {Boolean} [zoom=false] Set the zoom-in / zoom-out features of the topology map. */
zoom: false
}
}
return TopologyControlWidget;
}, "chart.widget.core");
|
'use babel'
/* eslint-env jasmine */
import path from 'path'
import fs from 'fs-extra'
import {lifecycle} from './../spec-helpers'
describe('gorename', () => {
let gorename = null
let editor = null
let gopath = null
let source = null
let target = null
beforeEach(() => {
runs(() => {
lifecycle.setup()
gopath = fs.realpathSync(lifecycle.temp.mkdirSync('gopath-'))
process.env.GOPATH = gopath
})
waitsForPromise(() => {
return lifecycle.activatePackage()
})
runs(() => {
const { mainModule } = lifecycle
mainModule.provideGoConfig()
mainModule.provideGoGet()
mainModule.loadGorename()
})
waitsFor(() => {
gorename = lifecycle.mainModule.gorename
return gorename
})
})
afterEach(() => {
lifecycle.teardown()
})
describe('when a simple file is open', () => {
beforeEach(() => {
runs(() => {
source = path.join(__dirname, '..', 'fixtures', 'gorename')
target = path.join(gopath, 'src', 'basic')
fs.copySync(source, target)
})
waitsForPromise(() => {
return atom.workspace.open(path.join(target, 'main.go')).then((e) => {
editor = e
})
})
})
it('renames a single token', () => {
editor.setCursorBufferPosition([4, 5])
let info = gorename.wordAndOffset(editor)
expect(info.word).toBe('foo')
expect(info.offset).toBe(33)
let file = editor.getBuffer().getPath()
let cwd = path.dirname(file)
let r = false
let cmd
waitsFor(() => {
if (lifecycle.mainModule.provideGoConfig()) {
return true
}
return false
}, '', 750)
waitsForPromise(() => {
return lifecycle.mainModule.provideGoConfig().locator.findTool('gorename').then((c) => {
expect(c).toBeTruthy()
cmd = c
})
})
waitsForPromise(() => {
return gorename.runGorename(file, info.offset, cwd, 'bar', cmd).then((result) => {
r = result
})
})
runs(() => {
expect(r).toBeTruthy()
expect(r.success).toBe(true)
expect(r.result.stdout.trim()).toBe('Renamed 2 occurrences in 1 file in 1 package.')
editor.destroy()
})
waitsForPromise(() => {
return atom.workspace.open(path.join(target, 'main.go')).then((e) => {
editor = e
})
})
runs(() => {
let expected = fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'gorename', 'expected'), 'utf8')
let actual = editor.getText()
expect(actual).toBe(expected)
})
})
})
})
|
var class_tempo_1_1_current_thread =
[
[ "AnyCurrentScope", "class_tempo_1_1_current_thread.html#a48a61021d19eb06b0d64b346a78a0b1f", null ],
[ "ConstructScope", "class_tempo_1_1_current_thread.html#a7fec7793c297c5a6823c0776d3e7e4d3", null ],
[ "ConstructScope< TResult >", "class_tempo_1_1_current_thread.html#a6019427cc75db3c7a85625e2f3f894c4", null ],
[ "CurrentContinuousScope", "class_tempo_1_1_current_thread.html#a9f7c85eb75843b598bfd5295a837d1d8", null ],
[ "CurrentSequentialScope", "class_tempo_1_1_current_thread.html#a505c20046e5cd375cc9cc87351df44f6", null ],
[ "Init", "class_tempo_1_1_current_thread.html#a5295b9b27175bf83b78097bc4c3c08cf", null ],
[ "ResetThread", "class_tempo_1_1_current_thread.html#a169d7ef533f5fc7fc717769bede4eaf7", null ],
[ "RunSequentialBlock", "class_tempo_1_1_current_thread.html#aabc6947d1e3369f0c9aa1cc6e2a8d9d4", null ]
];
|
/**
* nengine
* https://nuintun.github.io/nengine
*
* Licensed under the MIT license
* https://github.com/Nuintun/nengine/blob/master/LICENSE
*/
'use strict';
// external lib
var path = require('path'); // nodejs libs
var nopt = require('nopt'); // external libs
// variable declaration
var parsed;
var known = {};
var aliases = {};
var optlist = cli.optlist = {
root: {
short: 'r',
info: 'Set server root directory',
type: path
},
port: {
short: 'p',
info: 'Set server port',
type: Number
},
configfile: {
short: 'c',
info: 'Set nengine config file path',
type: path
},
help: {
short: 'h',
info: 'Display nengine help text',
type: Boolean
},
version: {
short: 'V',
info: 'Print nengine version',
type: Boolean
},
verbose: {
short: 'v',
info: 'Verbose mode, a lot more information output',
type: Boolean
}
};
// default command
cli.cmdlist = {
run: {
info: 'Run nengine server'
}
};
// initialize nopt params
Object.keys(optlist).forEach(function(key) {
var short = optlist[key].short;
if (short) {
aliases[short] = '--' + key;
}
known[key] = optlist[key].type;
});
// get command line params
parsed = nopt(known, aliases, process.argv, 2);
// set cli cmd and options
cli.cmd = parsed.argv.remain;
cli.options = parsed;
// clean cli.options
delete parsed.argv;
/**
* this is only executed when run via command line
*/
function cli() {
// run command
return require('../index').exec(cli.cmd, cli.options);
}
// exports cli
module.exports = cli;
|
'use strict';
var tester = require('./_lib/tester');
exports.examples = tester([
{
rules: 'not',
value: 33,
error: 'RNOT1'
},
{
rules: 'not hello',
value: 33,
error: 'R8'
},
{
rules: 'not format ^3$',
value: 33,
expect: true
},
{
rules: 'not format ^3$',
value: 3,
verr: {
rule: 'not',
params: [ { format: '^3$' } ],
index: null
}
},
{
rules: 'not type string',
value: '',
verr: {
rule: 'not',
params: [ { type: 'string' } ],
index: null
}
},
{
rules: 'not type string',
value: null,
expect: true
},
{
rules: 'not exact_length 3',
value: '',
expect: true
},
{
rules: 'not exact_length 3',
value: '111',
verr: {
rule: 'not',
params: [ { exact_length: 3 } ],
index: null
}
}
]);
|
'use strict';
const Promise = require('promise')
const chai = require('chai')
const { assert } = chai
const rzpInstance = require('../razorpay');
const mocker = require('../mocker')
const equal = require('deep-equal')
const { getDateInSecs,
normalizeDate,
normalizeNotes
} = require('../../dist/utils/razorpay-utils');
const { runCallbackCheckTest,
runParamsCheckTest,
runURLCheckTest,
runCommonTests } = require("../../dist/utils/predefined-tests.js");
const SUB_PATH = "/subscriptions",
FULL_PATH = `/v1${SUB_PATH}`,
TEST_SUBSCRIPTION_ID = "sub_sometestid",
TEST_OFFER_ID = "offer_sometestid",
apiObj = rzpInstance.subscriptions;
const runIDRequiredTest = (params) => {
let {apiObj, methodName, methodArgs, mockerParams} = params;
mocker.mock(mockerParams);
it (`method ${methodName} checks for Subscription ID as param`,
(done) => {
apiObj[methodName](...methodArgs).then(() => {
done(new Error(`method ${methodName} does not`+
` check for Subscription ID`));
},(err) => {
done();
});
});
}
describe("SUBSCRIPTIONS", () => {
describe("Create Subscription", () => {
let expectedUrl = `${FULL_PATH}`,
params = {
param1: "something",
param2: "something else",
notes: {"something": "something else"}
},
expectedParams = {
param1: params.param1,
param2: params.param2,
...(normalizeNotes(params.notes))
},
methodArgs = [params],
methodName = "create",
mockerParams = {
url: `${SUB_PATH}`,
method: "POST"
};
runCommonTests({
apiObj,
methodName,
methodArgs,
expectedUrl,
expectedParams,
mockerParams
});
});
describe("Update Subscription", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}`,
methodName = "update",
params = {
"plan_id":"plan_00000000000002",
"quantity": 1,
"remaining_count": 5,
"schedule_change_at": "now"
},
expectedParams = {
...params
},
methodArgs = [TEST_SUBSCRIPTION_ID, params],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}`,
method: "PATCH"
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}`,
method: "PATCH"
}
});
runParamsCheckTest({
apiObj,
methodName,
methodArgs: [TEST_SUBSCRIPTION_ID, params],
mockerParams,
expectedParams,
testTitle: "Check params is being sent or not"
});
runCommonTests({
apiObj,
methodName,
methodArgs,
expectedUrl,
mockerParams
});
});
describe('Delete Offer', () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/${TEST_OFFER_ID}`,
methodName = "deleteOffer",
methodArgs = [TEST_SUBSCRIPTION_ID, TEST_OFFER_ID],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/${TEST_OFFER_ID}`,
method: "DELETE"
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined, undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}/${undefined}`,
method: "DELETE"
}
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Fetch Subscription", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}`,
methodName = "fetch",
methodArgs = [TEST_SUBSCRIPTION_ID],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}`
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}`
}
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Fetch All Subscriptions", () => {
let methodName = "all",
params = {
"param1": "something",
"skip": 10,
"count": 10
},
methodArgs = [params],
expectedParams = {
...params
},
expectedUrl = FULL_PATH,
mockerParams = {
url: SUB_PATH
};
runParamsCheckTest({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedParams,
testTitle: "Check if all params passed are being sent"
});
params = {};
methodArgs = [params];
expectedParams = {"skip": 0, "count": 10};
runParamsCheckTest({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedParams,
testTitle: "Check if skip and count are automatically populated"
});
params = {"from": 'Aug 25, 2016', "to": 'Aug 30, 2016'};
methodArgs = [params];
expectedParams = {"from": getDateInSecs(params.from),
"to": getDateInSecs(params.to),
"count": "10",
"skip": "0"};
runParamsCheckTest({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedParams,
testTitle: "Check if dates are converted to ms"
});
methodArgs = [{}];
runCallbackCheckTest({
apiObj,
methodName,
mockerParams,
methodArgs
});
});
describe("Fetch Pending Updates", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/retrieve_scheduled_changes`,
methodName = "pendingUpdate",
methodArgs = [TEST_SUBSCRIPTION_ID],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/retrieve_scheduled_changes`
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}/retrieve_scheduled_changes`
}
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Cancel Update", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/cancel_scheduled_changes`,
methodName = "cancelScheduledChanges",
methodArgs = [TEST_SUBSCRIPTION_ID],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/cancel_scheduled_changes`,
method : 'POST'
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}/cancel_scheduled_changes`,
method : 'POST'
}
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Pause Subscription", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/pause`,
methodName = "pause",
params = {
"pause_at": "now"
},
methodArgs = [TEST_SUBSCRIPTION_ID, params],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/pause`,
method : 'POST'
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}/pause`,
method : 'POST'
}
});
let expectedParams = {pause_at: 'now'};
runParamsCheckTest({
apiObj,
methodName,
methodArgs: [TEST_SUBSCRIPTION_ID, params],
mockerParams,
expectedParams,
testTitle: "Check if pause at is being sent or not"
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Resume Subscription", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/resume`,
methodName = "resume",
params = {
"resume_at": "now"
},
methodArgs = [TEST_SUBSCRIPTION_ID, params],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/resume`,
method : 'POST'
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined],
mockerParams: {
url: `${SUB_PATH}/${undefined}/resume`,
method : 'POST'
}
});
let expectedParams = {resume_at: 'now'};
runParamsCheckTest({
apiObj,
methodName,
methodArgs: [TEST_SUBSCRIPTION_ID, params],
mockerParams,
expectedParams,
testTitle: "Check if resume at is being sent or not"
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Cancel Subscription", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/cancel`,
methodName = "cancel",
methodArgs = [TEST_SUBSCRIPTION_ID, false],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/cancel`,
method: "POST"
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined, false],
mockerParams: {
url: `${SUB_PATH}/${undefined}`,
method: "POST"
}
});
it("Checks for type of arguments", (done) => {
apiObj.cancel(TEST_SUBSCRIPTION_ID, null).then(() => {
done(new Error("Datatype is not checked for the arguments"));
}, () => {
done();
});
});
let expectedParams = {cancel_at_cycle_end: 1};
runParamsCheckTest({
apiObj,
methodName,
methodArgs: [TEST_SUBSCRIPTION_ID, true],
mockerParams,
expectedParams,
testTitle: "Check if cancel at end of cycle is being sent or not"
});
runCommonTests({
apiObj,
methodName,
methodArgs,
mockerParams,
expectedUrl
});
});
describe("Create Addon", () => {
let expectedUrl = `${FULL_PATH}/${TEST_SUBSCRIPTION_ID}/addons`,
methodName = "createAddon",
params = {
"item": {
"name": "Extra Chair",
"amount": "30000",
"currency": "INR"
},
"quantity": "2"
},
expectedParams = {...params},
methodArgs = [TEST_SUBSCRIPTION_ID, params],
mockerParams = {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/addons`,
method: "POST"
};
runIDRequiredTest({
apiObj,
methodName,
methodArgs: [undefined, params],
mockerParams: {
url: `${SUB_PATH}/${TEST_SUBSCRIPTION_ID}/addons`,
method: "POST"
}
});
runURLCheckTest({
apiObj,
methodName,
methodArgs,
expectedUrl,
mockerParams
});
});
describe("Create Registration Link", () => {
let expectedUrl = `/v1/subscription_registration/auth_links`,
params = {
param1: "something",
param2: "something else",
notes: {"something": "something else"}
},
expectedParams = {
param1: params.param1,
param2: params.param2,
...(normalizeNotes(params.notes))
},
methodArgs = [params],
methodName = "createRegistrationLink",
mockerParams = {
url: `/subscription_registration/auth_links`,
method: "POST"
};
runParamsCheckTest({
apiObj,
methodName,
methodArgs: [params],
mockerParams,
expectedParams,
testTitle: "Check if params is being sent or not"
})
runCommonTests({
apiObj,
methodName,
methodArgs,
expectedUrl,
expectedParams,
mockerParams
});
});
});
|
//Welcome to the annotated source code of the interpreter for [𝔼𝕊𝕄𝕚𝕟 3](https://github.com/molarmanful/ESMin), a wonderful JavaScript ES6 golfing language created by [@molarmanful](https://github.com/molarmanful)!
//This will serve as documentation for those who want to learn the language.
//
//---
//
//Let's get started!
//---
//put the numbers.js library in the math object
math.import(numbers,{wrap:true,silent:true});
//- improved replace function
String.prototype.ireplace=function(x,y=''){return this.replace(x,y)};
//- recursive replace
String.prototype.rreplace=function(r,o='',t){t=this.replace(r,o);return t!=this?t.rreplace(r,o):t};
//- global replace
String.prototype.greplace=function(x,y='',f=''){return this.replace(RegExp(x,'g'+f),y)};
//- string reverse
String.prototype.reverse=function(){return[...this].reverse().join``};
//- matrix split
String.prototype.msplit=function(r='\n',c=''){return this.split(r).map(x=>x.split(c))};
//- matrix join
Array.prototype.mjoin=function(r='',c='\n'){return this.map(x=>x.join(r)).join(c)};
//- transliterate (dictionary replace)
String.prototype.treplace=function(x,y=x.reverse(),a=Math.max(x.length,y.length),b=Math.min(x.length,y.length),i=0,t=this){for(;i<a;i++)t=t.replace(RegExp(x[i],"g"),y[i%b]);return t};
//- square
Number.prototype.square=function(){return math.pow(+this,2)};
//- cube
Number.prototype.cube=function(){return math.pow(+this,3)};
//- equation solver!
Math.solve=(x,y='x')=>new algebra.Equation(algebra.parse(x.split`=`[0]),algebra.parse(x.split`=`[1])).solveFor(y).toString();
//- parsing
Math.parse=(x)=>algebra.parse(x).toString();
//- inclusive range
Array.irange=(x,y)=>_.range(y!=[]._?x:0,(y!=[]._?y:x)+1);
//- combinatorics
Math.pwst=x=>Combinatorics.power(x).toArray();
Math.comb=(x,y=x.length)=>Combinatorics.combination(x,y).toArray();
Math.perm=(x,y=x.length)=>Combinatorics.permutation(x,y).toArray();
Math.peco=(i,...x)=>Combinatorics.permutationCombination(i,...x).toArray();
Math.cp=(i,...x)=>Combinatorics.cartesianProduct(i,...x).toArray();
Math.bn=(x,y=x.length)=>Combinatorics.baseN(x,y).toArray();
//prototype-based function aliasing
[String,Array,Number,RegExp,Date,_,Function,Pen,numeral,jQuery].map(v=>Object.getOwnPropertyNames(v.prototype).map((x,y)=>x!='caller'&&x!='arguments'&&(v.prototype[String.fromCharCode(y+248)]=v.prototype[x])));
//object-based function aliasing
[math,Math,String,Array,Number,Object,JSON,RegExp,Date,_,window,Function,numeral,jQuery].map(v=>Object.getOwnPropertyNames(v).map((x,y)=>v[String.fromCharCode(y+248)]=v[x]));
//function alias helper: use as `alias(Array,METHOD_NAME_STRING)`
var alias=(v,w)=>Object.getOwnPropertyNames(v).map((x,y)=>v[String.fromCharCode(y+248)]==v[w]?String.fromCharCode(y+248):0).join``.replace(/0/g,'');
//char palette helper
var chpal=`InOut: ï î í ì ᴉ ô
Zeros: Ⅹ ℍ 𝕜 𝕄 𝔾 𝕋 ℙ 𝔼 ℤ 𝕐
Stack: Ξ ᵖ ᵍ ʳ ᶜ
Const: ị ʉ ℇ ɸ π τ ⊨ ⊭ ᕠ
Built: ש М ɱ Ϛ Ѧ Ѩ Ꞩ П ɲ Ø ʝ ɟ ɼ ᶂ ᶁ ß Ꝉ ε ë Ɱ Յ փ ᵴ ᶐ ᶛ ʗ ℹ ɖ Ꝓ ɐ
Basic: ⊕ ¤ ₙ ᶉ … ⍪
Paren: ⸩ ⁽ ⎛ ⎝ ⎞ ⟨ ⟦ ⟬ ⁅ ⦌ “ ” ‘ ’ ⍘ ⍞ ⬮ ⬯ ⬭ ⬬ ⦃ ⦄
Block: ɘ э Э ⏖ ⏜ ⏝ ⟮ ⟯ Ⅰ Ⅱ Ⅲ ᶈ Ꞓ
Funcs: ⓑ ⓧ Ⓒ ⒞ ⨭ ⨴ ⸮ ⁇ ⁉ ⩤ ⩥ ⓜ ⒨ Ⓐ ⓢ ⓕ ⒡ Ⓕ F Ⓘ ⒤ ⓡ ⒭ ⓔ ⒠ Ⓢ ⒮ ⨝ ⌊ ⌙ ⌈ ᴙ ᴚ D ² ³ ⁿ √ ∛ ¡
Arrow: ⇏ ↛ ↪ ⤤ ⇝ ⇀ →
Regex: ⩄ ﹩ ❛ ❜ ⑴ ⑵ ⑶ ⊙ ⎖ α 𝚨 𐄫 ᶌ  ␉ ⑊ ⌿ ⍀
Opers: ˖ ⧺ ˗ ‡ × ÷ ٪ « ≪ » ≫ ⫸ ⋙ ˜ ⍜ ⇔
Logic: ‼ ≔ ≠ ≤ ≥ ⅋ ∧ ⋎ ∨ ⊻
Loops: ↺ ↻
Num's: ¼ ½ ¾ ⅐ ⅑ ⅒ ⅓ ⅔ ⅕ ⅖ ⅗ ⅘ ⅙ ⅚ ⅛ ⅜ ⅝ ⅞ ᶀ ᶍ`,
//all the chars
ɕ=`ïîíìᴉôⅩℍ𝕜𝕄𝔾𝕋ℙ𝔼ℤ𝕐Ξᵖᵍʳᶜịʉℇɸπτ⊨⊭ᕠשМϚѦѨПɲØʝɼᶂᶁßꝈᵭᶑεëⱮՅփᵴᶐᶛʗℹ⊕¤ₙᶉ…⸩⁽⎛⎝⎞⦃⦄ ⟨⟦⟬⁅⦌“”‘’⍘⬮⬯⬭⬬ɘэЭ⏖⏜⏝⟮⟯ⅠⅡⅢᶈⓑⓧⒸ⒞⨭⨴⸮⁇⁉⩥ⓜ⒨Ⓐⓢⓕ⒡ⒻFⒾ⒤ⓡ⒭ⓔ⒠Ⓢ⒮⨝⌊⌙⌈ᴙᴚD⇏↛↪⤤⇝⇀→⩄﹩❛❜⑴⑵⑶⊙⎖α𝚨𐄫ᶌ␉⑊⌿⍀˖⧺˗‡×÷٪«≪»≫⫸⋙˜⍜⇔‼≔≠≤≥⅋∧⋎∨⊻↺↻²³ⁿ√∛¼½¾⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞ᶀᶍɟ¡⍪ɖꞒꝒᵮ⩤⍞ɱ`,
ᵮ=`øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ`
;
//Custom encoding thanks to @Dennis! This encoding can hold up to 1024 chars by storing each character in 1.25 bytes, or 10 bits.
var charTable=`\t\n !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_\`abcdefghijklmnopqrstuvwxyz{|}~¡¤«²³»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɕɖɘɟɱɲɸɼʉʗʝʳʾ˖˗˜ΞΣαεπτϚМПЭэѦѨՅփש٪ᕠᴉᴙᴚᵍᵖᵭᵮᵴᶀᶁᶂᶈᶉᶌᶍᶐᶑᶛᶜḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙẛẜẝẞẟẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹỺỻỼỽỾỿ‘’“”‡…‼⁅⁇⁉⁽ⁿₙℇℍℙℤℹ⅋⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞ⅠⅡⅢⅩ→↛↪↺↻⇀⇏⇔⇝√∛∧∨≔≠≤≥≪≫⊕⊙⊨⊭⊻⋎⋙⌈⌊⌙⌿⍀⍘⍜⍞⍪⎖⎛⎝⎞⏖⏜⏝␉⑊⑴⑵⑶⒞⒠⒡⒤⒨⒭⒮ⒶⒸⒻⒾⓈⓑⓔⓕⓜⓡⓢⓧ❛❜⟦⟨⟬⟮⟯⤤⦃⦄⦌⧺⨝⨭⨴⩄⩤⩥⫸⬬⬭⬮⬯Ɱ⸩⸮ꝈꝒꞒ𐄫𝔼𝔾𝕄𝕋𝕐𝕜𝚨﹩DFꞨ`
function encode(string) {
return string.replace(/[\s\S]{1,4}/g, function(chunk){
var asNumber = 0;
var encoded = '';
for(var i = 0; i < chunk.length; i++)
asNumber = 1024 * asNumber + charTable.indexOf(chunk[i]);
for(var i = 0; i < 5; i++) {
encoded = String.fromCharCode(asNumber % 256) + encoded;
asNumber = Math.floor(asNumber / 256);
}
return encoded.slice(4 - chunk.length);
});
}
function decode(string) {
return string.replace(/[\s\S]{1,5}/g, function(chunk){
var asNumber = 0;
var decoded = '';
for(var i = 0; i < chunk.length; i++)
asNumber = 256 * asNumber + chunk.charCodeAt(i);
for(var i = 0; i < 4; i++) {
decoded = charTable[asNumber % 1024] + decoded;
asNumber = Math.floor(asNumber / 1024);
}
return decoded.slice(5 - chunk.length);
});
}
//stack representation
var Ξ=[],
//I/O FUNCTIONS
//---
//*not shown: `ï = input, î = ï[0], í = ï[1], ì = ï[2], ᴉ = [...ï]`*
//-output
ô=i=>o.value+=i!=[]._?i:Ξ.join`\n`,
//---
//get source code
ℹ=(i=0,j=c.value.length)=>[c.value.slice(i,j),Ξ.push(i)][0],
//STACK FUNCTIONS
//---
//- push
ᵖ=(i=0,...r)=>{Ξ.push(i,...r)},
//- get
ᵍ=i=>i!=[]._?Ξ[i<0?Ξ.length+i:i]:Ξ[Ξ.length-1],
//- remove
ʳ=(i=Ξ.length-1)=>Ξ.splice(i,1),
//- clear
ᶜ=i=>Ξ=[],
//MORE ALIASES
//---
//
//CONSTANTS
ᶖ=Infinity,
ʉ=[]._,
ℇ=math.e,
ε=Number.EPSILON,
ɸ=(1+math.sqrt(5))/2,
π=math.pi,
τ=math.pi*2,
//BUILT-IN OBJECTS
М=math,
ɱ=Math,
Ϛ=String,
Ѧ=Array,
Ѩ=_,
П=Number,
Ø=Object,
ʝ=JSON,
ɼ=RegExp,
ᶁ=Date,
ש=window,
ᶂ=Function,
ɲ=numeral,
ɟ=jQuery,
Ꞩ=Set,
//FUNCTIONS
ß='toString',
Ꝉ='length',
//- general-purpose map
Ɱ=(i,f,s='',j='')=>typeof i=='object'?i.map(f):typeof i=='string'?i.split(s).map(f).join(j):eval((''+i).split(s).map(f).join(j)),
ë=eval,
ᵴ='',
Յ='0b',
փ='0x',
//ALPHABETS
ᶐ='ABCDEFGHIJKLMNOPQRSTUVWXYZ',
ᶛ='abcdefghijklmnopqrstuvwxyz',
//CANVAS
ʗ=new Pen('cv'),
//storage for copy-paste blocks
ᶈ=[],
Ꝓ=parseInt,
ɐ=-1,
//NUMBERS
//aliases for 0-256; get number alias using `nchars[NUMBER]`
nchars=`ḀḁḂḃḄḅḆḇḈḉḊḋḌḍḎḏḐḑḒḓḔḕḖḗḘḙḚḛḜḝḞḟḠḡḢḣḤḥḦḧḨḩḪḫḬḭḮḯḰḱḲḳḴḵḶḷḸḹḺḻḼḽḾḿṀṁṂṃṄṅṆṇṈṉṊṋṌṍṎṏṐṑṒṓṔṕṖṗṘṙṚṛṜṝṞṟṠṡṢṣṤṥṦṧṨṩṪṫṬṭṮṯṰṱṲṳṴṵṶṷṸṹṺṻṼṽṾṿẀẁẂẃẄẅẆẇẈẉẊẋẌẍẎẏẐẑẒẓẔẕẖẗẘẙaʾẛẜẝẞẟẠạẢảẤấẦầẨẩẪẫẬậẮắẰằẲẳẴẵẶặẸẹẺẻẼẽẾếỀềỂểỄễỆệỈỉỊịỌọỎỏỐốỒồỔổỖỗỘộỚớỜờỞởỠỡỢợỤụỦủỨứỪừỬửỮữỰựỲỳỴỵỶỷỸỹỺỻỼỽỾỿ`
;jQuery.noConflict();
//dictionary stuff
var client=new XMLHttpRequest();client.open('GET','scrabbledict.txt');client.onreadystatechange=_=>(ɖ=client.responseText.split`\n`,ᶑ=ɖ.map(x=>x.toLowerCase()),ᵭ=ɖ.map(a=>a[0]+a.slice(1).toLowerCase()));client.send();
//---
//fix parentheses functions
var fix=i=>{
var c=[''],I=[];
[...i].map((x,y)=>{
I.push(x)
!c[c.length-1].match`["'\`]`?
I[I.length-1].match`["'\`]`?c.push(I[I.length-1]):
I[I.length-1]=='('?c.push(`)`):
I[I.length-1]=='['?c.push(`]`):
I[I.length-1]=='{'?c.push(`}`):
I[I.length-1].match`;`?(I.splice(-1,0,...c.reverse()),c=['']):
I[I.length-1].match`[)\\]}]`&&~c.lastIndexOf(I[I.length-1])&&I.splice(-1,1,...c.splice(c.lastIndexOf(I[I.length-1])).reverse())
:I[I.length-1].match(c[c.length-1])&&I[I.length-2]!='\\'&&I[I.length-3]!='\\'&&c.pop()
})
I.push(...c.reverse())
return I.join``
},
Fix=i=>{
var c=[''],I=[];
[...i].reverse().map((x,y)=>{
I.push(x)
!c[c.length-1].match`["'\`]`?
I[I.length-1].match`["'\`]`?c.push(I[I.length-1]):
I[I.length-1]==')'?c.push(`(`):
I[I.length-1]==']'?c.push(`[`):
I[I.length-1]=='}'?c.push(`{`):
I[I.length-1].match`;`?(I.splice(-1,0,...c.reverse()),c=['']):
I[I.length-1].match`[([{]`&&I.splice(-1,1,...c.splice(c.lastIndexOf(I[I.length-1])).reverse())
:I[I.length-1].match(c[c.length-1])&&I[I.length-2]!='\\'&&I[I.length-3]!='\\'&&c.pop()
})
I.push(...c.reverse())
return I.reverse().join``
}
//---
//compression functions
shoco.c=i=>Array.prototype.map.call(shoco.compress(i),x=>charTable[x]).join``;
shoco.d=i=>shoco.decompress(new Uint8Array((i.constructor==Array?i[0]:i).split``.map(x=>charTable.indexOf(x[0]))));
var compress=i=>LZString.compress(shoco.c(i));
//TIME TO INTERPRET!
//---
var Σ=c=>{
var
//- functions
r='ᵖᵍʳôℹΣɘϚѦПØѨɼᶁɲɟⱮëßꝒꞨ\\u00f8-\\u024f',
//- these don't need surrounding parens
n='A-Za-z$_ãïîíìΞᴉɕᶖʉℇεɸπτᶐɖᵭᶑᵴᶛɐ¼½¾⅐⅑⅒⅓⅔⅕⅖⅗⅘⅙⅚⅛⅜⅝⅞ᶀᶍ\\u1e00-\\u1eff',
//- real numbers regex
d='-?\\d+(?:\\.\\d*)?(?:e[+\\-]?\\d+)?';
//TRANSPILE 𝔼𝕊𝕄𝕚𝕟 => ES6
//
//fix parentheses after 1st-stage transpilation
c=Fix(fix(c
//copy block; copies code, then pastes elsewhere when called
.rreplace(/⟮([^⟮⟯]*)⟯?/g,(x,y)=>(ᶈ.push(y),y))
//paste copy block 1
.replace(/Ⅰ/g,ᶈ[0])
//paste copy block 2
.replace(/Ⅱ/g,ᶈ[1])
//paste copy block 3
.replace(/Ⅲ/g,ᶈ[2])
//COMPRESSION
.replace(/ɘ([^#]+)#?/g,(x,y)=>shoco.d(LZString.decompress(y)))
.replace(/э([^#]+)#?/gm,(x,y)=>shoco.d(y))
.replace(/Э([^#]+)#?/g,(x,y)=>LZString.decompress(y))
//eval-paste block; evaluates code, then pastes result directly in place of block
.replace(eval(`/⏖([${n}]+)/g`),'⏜$1⏝')
.rreplace(/⏜([^⏜⏝]*)⏝?/g,(x,y)=>Σ(y))
//charcode block
.replace(/Ꞓ(.)/g,(x,y)=>y.codePointAt())
//implicit input
.replace(/^(\\u00f8-\\u024f)/,'ï$1')
.replace(/^(\\u00f8-\\u024f)?$/,'ï$1')
//alias for 10; can be used with zeroes series
.replace(/Ⅹ/g,'10')
//ZEROES
.replace(/ℍ/g,'00')
.replace(/𝕜/g,'000')
.replace(/𝕄/g,'000000')
.replace(/𝔾/g,'000000000')
.replace(/𝕋/g,'000000000000')
.replace(/ℙ/g,'000000000000000')
.replace(/𝔼/g,'000000000000000000')
.replace(/ℤ/g,'000000000000000000000')
.replace(/𝕐/g,'000000000000000000000000')
//`('')+` - good for string coercion
.replace(/⊕/g,'⬯+')
.replace(/Ꞩ/g,'ₙꞨ')
//`.join('')`
.replace(/⨝/g,alias(Array.prototype,'join')[0]+'⬯')
//`.toString(2)`
.replace(/ⓑ/g,'ß2')
//`.toString(16)`
.replace(/ⓧ/g,'ß16')
//`String.fromCharCode`
.replace(/Ⓒ/g,'Ϛ'+alias(String,'fromCharCode')[0])
//`.charCodeAt()`
.replace(/⒞/g,alias(String.prototype,'charCodeAt')[0]+'⬮')
//`.filter(($,_,ã)=>`
.replace(/ⓕ/g,alias(Array.prototype,'filter')[0]+'⇀')
.replace(/⒡/g,alias(Array.prototype,'filter')[0]+'⇀$')
//`.map(($,_,ã)=>`
.replace(/ⓜ/g,alias(Array.prototype,'map')[0]+'⇀')
.replace(/⒨/g,alias(Array.prototype,'map')[0]+'⇀$')
//`.reduce(($,_,ã)=>`
.replace(/ⓡ/g,alias(Array.prototype,'reduce')[0]+'⇀')
.replace(/⒭/g,alias(Array.prototype,'reduce')[0]+'⇀$')
//`.every(($,_,ã)=>`
.replace(/ⓔ/g,alias(Array.prototype,'every')[0]+'⇀')
.replace(/⒠/g,alias(Array.prototype,'every')[0]+'⇀$')
//`.some(($,_,ã)=>`
.replace(/Ⓢ/g,alias(Array.prototype,'some')[0]+'⇀')
.replace(/⒮/g,alias(Array.prototype,'some')[0]+'⇀$')
//`.find(($,_,ã)=>`
.replace(/Ⓕ/g,alias(Array.prototype,'find')[0]+'⇀')
.replace(/F/g,alias(Array.prototype,'find')[0]+'⇀$')
//`.findIndex(($,_,ã)=>`
.replace(/Ⓘ/g,alias(Array.prototype,'findIndex')[0]+'⇀')
.replace(/⒤/g,alias(Array.prototype,'findIndex')[0]+'⇀$')
//`.split('')`
.replace(/ⓢ/g,alias(String.prototype,'split')[0]+'⬯')
//`[...Array(n)]`
.replace(eval(`/Ⓐ(([${n}]|\\d)+)/g`),'⟦Ѧ($1)]')
//`.reverse()` (string)
.replace(/ᴙ/g,alias(String.prototype,'reverse')[0]+'⬮')
//`.reverse()` (array)
.replace(/ᴚ/g,alias(Array.prototype,'reverse')[0]+'⬮')
//`math.sum`
.replace(/⨭/g,'М'+alias(math,'sum')[0])
//`math.prod`
.replace(/⨴/g,'М'+alias(math,'prod')[0])
//`_.range`
.replace(/⩥/g,'Ѩ'+alias(_,'range')[0])
//`_.irange`
.replace(/⩤/g,'Ѧ'+alias(Array,'irange')[0])
//`math.random`
.replace(/⸮/g,'М'+alias(math,'random')[0])
//`math.randomInt`
.replace(/⁇/g,'М'+alias(math,'randomInt')[0])
//`math.pickRandom`
.replace(/⁉/g,'М'+alias(math,'pickRandom')[0])
//`math.floor`
.replace(/⌊/g,'М'+alias(math,'floor')[0])
//`math.round`
.replace(/⌙/g,'М'+alias(math,'round')[0])
//`math.ceil`
.replace(/⌈/g,'М'+alias(math,'ceil')[0])
//`math.sqrt`
.replace(/√/g,'М'+alias(math,'sqrt')[0])
//`math.cbrt`
.replace(/∛/g,'М'+alias(math,'cbrt')[0])
//`math.pow`
.replace(/ⁿ/g,'М'+alias(math,'pow')[0])
//`.square()`
.replace(/²/g,alias(Number.prototype,'square')[0]+'⬮')
//`.cube()`
.replace(/³/g,alias(Number.prototype,'cube')[0]+'⬮')
//`math.factorial`
.replace(/¡/g,'М'+alias(math,'factorial')[0])
//`new Date`
.replace(/D/g,'ₙᶁ')
//function argument aliases
.replace(/⬮/g,'()')
.replace(/⬯/g,'(``)')
.replace(/⬭/g,'(` `)')
.replace(/⬬/g,'(`\n`)')
.replace(/⍪/g,'`,`')
//whitespace aliases - also useful for regex
.replace(//g,'\\n')
.replace(/␉/g,'\\t')
.replace(/␠/g,'\\s')
//one-char string; can be used as function argument
.replace(/⍘(.)/g,'(`$1`)')
.replace(/⍞(..)/g,'(`$1`)')
//PARENTHETICAL ARROW FUNCTIONS
.replace(/⇝/g,'((a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
.replace(/⇀/g,'(($,_,ã)=>')
//ARGUMENT PARSER: turns `⁽abc` into `(a,b,c)`.
.replace(/⎝/g,`=⁽`)
//PARENTHETICAL ARGUMENT PARSER
.replace(/⎛/g,'(⁽')
.replace(eval(`/⁽(([${n}]|\\d)+)/g`),(x,y)=>`(${y.split(/\s|/g)})`)
//AUTO-ADD PARENTHESES
.replace(/^([\u00f8-\u0236ßꝈ])/,'ï$1')
.replace(eval(`/([${r}])(([${n}]|${d})+)/g`),'$1($2)')
.replace(eval(`/([${r}])([^(\u00f8-\u0236ßꝈ¤])/g`),'$1($2')
//prevents object from turning into a function
.replace(/¤/g,'')
//AUTO-ADD BRACKETS
.replace(eval(`/⎖(([${n}]|\\d)+)/g`),'[$1]')
.replace(eval(`/([ïîíìᴉᶈɕɖᶑᵭΞᵮ])(([${n}]|\\d)+)/g`),'$1[$2]')
//MORE ARROW FUNCTIONS
.replace(/⇏/g,'(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
.replace(/↛/g,'=(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z)=>')
.replace(/↪/g,'($,_,ã)=>')
.replace(/⤤/g,'=($,_,ã)=>')
.replace(/→/g,'=>')
//array shorthand
.replace(eval(`/⟨(([${n}]|\\d)+)/g`),(x,y)=>`[${y.split(/\s|/g)}]`)
//PARENTHESES
.replace(/“/g,'(`')
.replace(/”/g,'`)')
.replace(/‘/g,'\\`')
.replace(/’/g,'\\`)')
.replace(/⸩/g,'))')
.replace(/⎞/g,'/)')
.replace(/⦌/g,'])')
//template-string-ish stuff
.replace(/⦃/g,'`+(')
.replace(/⦄/g,')+`')
//SPREAD OPERATORS
.replace(/…/g,'...')
.replace(eval(`/⟬([${n}]+)/g`),'[...$1]')
.replace(/⟦/g,'[...')
//ASSIGNMENT OPERATORS
.replace(/˖/g,'+=')
.replace(/⧺/g,'++')
.replace(/˗/g,'-=')
.replace(/‡/g,'--')
.replace(/×/g,'*=')
.replace(/÷/g,'/=')
.replace(/٪/g,'%=')
.replace(/≪/g,'<<=')
.replace(/≫/g,'>>=')
.replace(/⋙/g,'>>>=')
.replace(/∧/g,'&=')
.replace(/⊻/g,'^=')
.replace(/∨/g,'|=')
.replace(eval(`/([${n}])⇔/g`),'$1=$1')
//LOGIC
.replace(/‼/g,'!!')
.replace(/≔/g,'==')
.replace(/≠/g,'!=')
.replace(/≤/g,'<=')
.replace(/≥/g,'>=')
.replace(/⅋/g,'&&')
.replace(/⋎/g,'||')
//more keywords
.replace(/ᶉ/g,'return ')
.replace(/ₙ/g,'new ')
.replace(/ᕠ/g,'this')
//EXPONENTS/ROOTS
.replace(eval(`/(⦅.+|(([${n}]|${d})+))²/g`),'math.pow($1,2)')
.replace(eval(`/(⦅.+|(([${n}]|${d})+))³/g`),'math.pow($1,3)')
//FRACTIONS
.replace(/½/g,'.5')
.replace(/¼/g,'.25')
.replace(/¾/g,'.75')
.replace(/⅐/g,'(1/7)')
.replace(/⅑/g,'(1/9)')
.replace(/⅒/g,'.1')
.replace(/⅓/g,'(1/3)')
.replace(/⅔/g,'(2/3)')
.replace(/⅕/g,'.2')
.replace(/⅖/g,'.4')
.replace(/⅗/g,'.6')
.replace(/⅘/g,'.8')
.replace(/⅙/g,'(1/6)')
.replace(/⅚/g,'(5/6)')
.replace(/⅛/g,'.125')
.replace(/⅜/g,'.375')
.replace(/⅝/g,'.625')
.replace(/⅞/g,'.875')
//BINARY/HEX PREFIXES
.replace(/ᶀ/g,'0b')
.replace(/ᶍ/g,'0x')
//AUTO-FORMAT FUNCTION NAMES
.replace(/([^.])([\u00f8-\u0236])/g,'$1["$2"]')
.replace(/[ßꝈ]/g,'[$&]')
//REGEX
.replace(/⩄/g,'$$&')
.replace(/﹩/g,'$$$')
.replace(/❛/g,'$$`')
.replace(/❜/g,"$$'")
.replace(/⑴/g,'$1')
.replace(/⑵/g,'$2')
.replace(/⑶/g,'$3')
.replace(/⊙/g,'(.)')
.replace(/⁅/g,'[^')
.replace(/α/g,'a-z')
.replace(/𝚨/g,'A-Z')
.replace(/𐄫/g,'0-9')
.replace(/ᶌ/g,'aeiou')
.replace(/⌿/g,'/g')
.replace(/⍀/g,'/ig')
.replace(/⑊/g,'\\\\')
//some more keywords
.replace(/⊨/g,'true')
.replace(/⊭/g,'false')
.replace(/␀/g,'null')
//BITSHIFTS
.replace(/«/g,'<<')
.replace(/»/g,'>>')
.replace(/⫸/g,'>>>')
//bitwise rounding
.replace(/˜/g,'0|')
.replace(/⍜/g,'|0')
//WHILE LOOP
.replace(/↻/g,'while(')
))
//FOR LOOP (@ = end parentheses)
.replace(/↺/g,'for(')
.replace(/([^\\])@/g,'$1)');
//OUTPUT
//---
//- implicit (stack) output
if(!c.match(/ô/g)&&c.match(/ᵖ/g)){c+=';ô()',console.log(c),eval(c);}
//- implicit output
else if(!c.match(/ô/g)){console.log(c),o.value=eval(c);}
//- explicit output
else console.log(c),eval(c);
return eval(c);
}
|
const url = require('url');
const log = require('gutil-color-log');
const path = require('path');
const types = require('./mimetype').types;
// const routes = require('../router').routes;
function route(req, routes) {
let indexPath;
let pathname = url.parse(req.url).pathname;
// let route = routes[pathname];
// if (route && typeof route === 'string') {
// pathname = route;
// }
// if (route && typeof route === 'function') {
// pathname = route;
// }
let ext = path.extname(pathname)
if (ext) {
ext = ext.slice(1)
} else {
ext = '';
pathname += 'index.html';
}
const type = types[ext];
switch (type) {
case "text/html":
indexPath = './views' + pathname;
break;
case 'application/json':
indexPath = './data' + pathname;
break;
default:
indexPath = './assets' + pathname;
break;
}
log('green', 'url:' + indexPath);
return indexPath
}
module.exports = route;
|
var unirest = require('unirest');
var secrets = require('../secrets');
/*
Requests an access token from the Lufthansa API.
An access token is valid for 1.5 day, so don't keep your server running for more than 1.5 day ;-)
*/
exports.register = function (server, options, next) {
var postData = {
client_id: secrets.lufthansa.client_id,
client_secret: secrets.lufthansa.client_secret,
grant_type: 'client_credentials'
};
unirest.post('https://api.lufthansa.com/v1/oauth/token')
.header('Accept', 'application/json')
.send(postData)
.end(function (response) {
server.expose('access_token', response.body.access_token);
next();
});
};
exports.register.attributes = {
name: 'init',
version: '0.0.1'
};
|
export default {
key: 'D',
suffix: 'mmaj9',
positions: [
{
frets: 'x53650',
fingers: '021430'
},
{
frets: 'x70665',
fingers: '040231'
},
{
frets: 'x809a9',
fingers: '010243'
},
{
frets: 'acbaac',
fingers: '132114',
barres: 10,
capo: true
}
]
};
|
/*
Create a function that:
* **Takes** a collection of books
* Each book has propeties `title` and `author`
** `author` is an object that has properties `firstName` and `lastName`
* **finds** the most popular author (the author with biggest number of books)
* **prints** the author to the console
* if there is more than one author print them all sorted in ascending order by fullname
* fullname is the concatenation of `firstName`, ' ' (empty space) and `lastName`
* **Use underscore.js for all operations**
*/
function solve() {
var validator = {
validateIfUndefined: function (val, name) {
name = name || 'Value';
if (val === undefined) {
throw new Error(name + ' cannot be undefined');
}
},
validateIfObject: function (val, name) {
name = name || 'Value';
if (typeof val !== 'object') {
throw new Error(name + ' must be an object');
}
},
validateIfNumber: function (val, name) {
name = name || 'Value';
if (typeof val !== 'number') {
throw new Error(name + ' must be a number');
}
},
validateString: function (val, minLength, maxLength, name) {
name = name || 'Value';
this.validateIfUndefined(val, name);
if (typeof val !== 'string') {
throw new Error(name + ' must be a string');
}
if (val.length < minLength || maxLength < val.length) {
throw new Error(name + ' must be between ' + minLength + ' and ' + maxLength + ' symbols');
}
},
validatePositiveNumber: function (val, name) {
name = name || 'Value';
this.validateIfUndefined(val, name);
this.validateIfNumber(val, name);
if (val <= 0) {
throw new Error(name + ' must be positive number');
}
},
validateIfArray: function (val, name) {
name = name || 'Value';
this.validateIfUndefined(val, name);
this.validateIfObject(val, name);
if (!Array.isArray(val)) {
throw new Error(name + ' must be array');
}
}
};
return function (books) {
var result, sortedByAuthorBooksCount, maxBooksCount;
validator.validateIfArray(books, 'Books');
_.each(books, function (book) {
validator.validateIfUndefined(book, 'Book');
validator.validateIfUndefined(book.author, 'Book author');
validator.validateString(book.title, 0, Number.MAX_VALUE, 'Book title');
validator.validateString(book.author.firstName, 0, Number.MAX_VALUE, 'Author first name');
validator.validateString(book.author.lastName, 0, Number.MAX_VALUE, 'Author last name');
});
sortedByAuthorBooksCount = _.chain(books)
.groupBy(function (book) {
return book.author.firstName + ' ' + book.author.lastName;
})
.map(function (authorBooks) {
var group = {
authorName: authorBooks[0].author.firstName + ' ' + authorBooks[0].author.lastName,
books: authorBooks
};
return group;
})
.sortBy(function (author) {
return -1 * author.books.length;
}).value();
maxBooksCount = sortedByAuthorBooksCount[0].books.length;
_.chain(sortedByAuthorBooksCount)
.filter(function (author) {
return author.books.length === maxBooksCount;
})
.sortBy('authorName')
.each(function (author) {
console.log(author.authorName)
});
};
}
module.exports = solve;
|
/**
* Using Rails-like standard naming convention for endpoints.
* GET /things -> index
* POST /things -> create
* GET /things/:id -> show
* PUT /things/:id -> update
* DELETE /things/:id -> destroy
*/
var mongoose = require('mongoose'),
User = require('./user.model');
exports.index = function*() {
this.body = yield User.find({});
};
exports.show = function*(id) {
var user = yield User.findById(id);
if (!user) {
return this.throw('User not found!', 404);
}
this.body = user;
};
|
// Generated by CoffeeScript 1.10.0
import config from 'travis/config/environment';
var GAInitializer, initialize;
initialize = function(application) {
var ga, s;
if (config.gaCode) {
window._gaq = [];
_gaq.push(['_setAccount', config.gaCode]);
ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = 'https://ssl.google-analytics.com/ga.js';
s = document.getElementsByTagName('script')[0];
return s.parentNode.insertBefore(ga, s);
}
};
GAInitializer = {
name: 'google-analytics',
initialize: initialize
};
export {initialize};
export default GAInitializer;
|
import { combineReducers } from 'redux-immutable';
import webrtcReducer from 'containers/Webrtc/reducer';
import { SET_ROOM_NAME } from './constants';
function roomName(state = '', { type, payload }) {
switch (type) {
case SET_ROOM_NAME:
return payload;
default:
return state;
}
}
export default combineReducers({
roomName,
webrtc: webrtcReducer,
});
|
// @flow
import React from 'react'
import { Route } from 'react-router-dom'
import WorkCard from '../work/WorkCard'
import { Header, Article, Page } from '../ui'
import selector from '../../store/selector'
import style from './style.scss'
import type { Store } from '../../store/entities'
type Props = {
store: Store,
}
const WorkList = ({ store }) => {
const work = selector.findMostRecentWork(store)
return (
<Page>
<Header
title="Work | Chris Aubert"
description="Check out what I've been working on"
/>
<header className={style.header}>
<h1 className={style.title}>Work</h1>
</header>
<main>
<section>
<div className="card_container">
{work.map(work => (
<WorkCard
key={work.slug}
{...work}
/>
))}
</div>
</section>
</main>
</Page>
)
}
const WorkArticle = ({ store, match }) => {
const work = selector.findWorkBySlug(store, match.params.slug)
return (
<Article
title={work.title}
description={work.blurb}
content={work.content}
/>
)
}
const Router = (props: Props) => {
return (
<div>
<Route
exact
path="/work"
render={({ location }) => (<WorkList {...props} location={location} />)}
/>
<Route
path="/work/:slug"
render={({ match }) => (<WorkArticle {...props} match={match} />)}
/>
</div>
)}
export default Router
|
(() => {
"use strict";
class KwcDateFormat {
beforeRegister() {
this.is = "kwc-date-format";
this.properties = {
date: {
type: String,
value: null
},
inputFormat: {
type: String,
value: null
},
format: {
type: String,
value: null
},
locale: {
type: String,
value: null
},
_i18nLocale: {
type: String,
readOnly: true,
value: null
},
output: {
type: String,
reflectToAttribute: true,
readOnly: true,
notify: true,
computed: "_computeOutput(date, inputFormat, format, locale, _i18nLocale)"
}
};
}
attached() {
const that = this;
const i18next = window.i18next;
if (i18next) {
that._set_i18nLocale(i18next.language);
i18next.on("initialized", () => that._set_i18nLocale(i18next.language));
i18next.on("loaded", () => that._set_i18nLocale(i18next.language));
i18next.on("languageChanged", () => that._set_i18nLocale(i18next.language));
}
}
_computeOutput(date, inputFormat, format, locale, _i18nLocale) {
var datetime;
if (date) {
if (inputFormat) {
datetime = moment(date, inputFormat);
} else {
datetime = moment(date);
}
} else {
datetime = moment();
}
if (locale) {
datetime.locale(locale);
} else if (_i18nLocale) {
datetime.locale(_i18nLocale);
}
return datetime.format(format);
}
}
Polymer(KwcDateFormat);
})();
|
import {almostEquals, distanceBetweenPoints, sign} from './helpers.math';
import {_isPointInArea} from './helpers.canvas';
const EPSILON = Number.EPSILON || 1e-14;
const getPoint = (points, i) => i < points.length && !points[i].skip && points[i];
const getValueAxis = (indexAxis) => indexAxis === 'x' ? 'y' : 'x';
export function splineCurve(firstPoint, middlePoint, afterPoint, t) {
// Props to Rob Spencer at scaled innovation for his post on splining between points
// http://scaledinnovation.com/analytics/splines/aboutSplines.html
// This function must also respect "skipped" points
const previous = firstPoint.skip ? middlePoint : firstPoint;
const current = middlePoint;
const next = afterPoint.skip ? middlePoint : afterPoint;
const d01 = distanceBetweenPoints(current, previous);
const d12 = distanceBetweenPoints(next, current);
let s01 = d01 / (d01 + d12);
let s12 = d12 / (d01 + d12);
// If all points are the same, s01 & s02 will be inf
s01 = isNaN(s01) ? 0 : s01;
s12 = isNaN(s12) ? 0 : s12;
const fa = t * s01; // scaling factor for triangle Ta
const fb = t * s12;
return {
previous: {
x: current.x - fa * (next.x - previous.x),
y: current.y - fa * (next.y - previous.y)
},
next: {
x: current.x + fb * (next.x - previous.x),
y: current.y + fb * (next.y - previous.y)
}
};
}
/**
* Adjust tangents to ensure monotonic properties
*/
function monotoneAdjust(points, deltaK, mK) {
const pointsLen = points.length;
let alphaK, betaK, tauK, squaredMagnitude, pointCurrent;
let pointAfter = getPoint(points, 0);
for (let i = 0; i < pointsLen - 1; ++i) {
pointCurrent = pointAfter;
pointAfter = getPoint(points, i + 1);
if (!pointCurrent || !pointAfter) {
continue;
}
if (almostEquals(deltaK[i], 0, EPSILON)) {
mK[i] = mK[i + 1] = 0;
continue;
}
alphaK = mK[i] / deltaK[i];
betaK = mK[i + 1] / deltaK[i];
squaredMagnitude = Math.pow(alphaK, 2) + Math.pow(betaK, 2);
if (squaredMagnitude <= 9) {
continue;
}
tauK = 3 / Math.sqrt(squaredMagnitude);
mK[i] = alphaK * tauK * deltaK[i];
mK[i + 1] = betaK * tauK * deltaK[i];
}
}
function monotoneCompute(points, mK, indexAxis = 'x') {
const valueAxis = getValueAxis(indexAxis);
const pointsLen = points.length;
let delta, pointBefore, pointCurrent;
let pointAfter = getPoint(points, 0);
for (let i = 0; i < pointsLen; ++i) {
pointBefore = pointCurrent;
pointCurrent = pointAfter;
pointAfter = getPoint(points, i + 1);
if (!pointCurrent) {
continue;
}
const iPixel = pointCurrent[indexAxis];
const vPixel = pointCurrent[valueAxis];
if (pointBefore) {
delta = (iPixel - pointBefore[indexAxis]) / 3;
pointCurrent[`cp1${indexAxis}`] = iPixel - delta;
pointCurrent[`cp1${valueAxis}`] = vPixel - delta * mK[i];
}
if (pointAfter) {
delta = (pointAfter[indexAxis] - iPixel) / 3;
pointCurrent[`cp2${indexAxis}`] = iPixel + delta;
pointCurrent[`cp2${valueAxis}`] = vPixel + delta * mK[i];
}
}
}
/**
* This function calculates Bézier control points in a similar way than |splineCurve|,
* but preserves monotonicity of the provided data and ensures no local extremums are added
* between the dataset discrete points due to the interpolation.
* See : https://en.wikipedia.org/wiki/Monotone_cubic_interpolation
*
* @param {{
* x: number,
* y: number,
* skip?: boolean,
* cp1x?: number,
* cp1y?: number,
* cp2x?: number,
* cp2y?: number,
* }[]} points
* @param {string} indexAxis
*/
export function splineCurveMonotone(points, indexAxis = 'x') {
const valueAxis = getValueAxis(indexAxis);
const pointsLen = points.length;
const deltaK = Array(pointsLen).fill(0);
const mK = Array(pointsLen);
// Calculate slopes (deltaK) and initialize tangents (mK)
let i, pointBefore, pointCurrent;
let pointAfter = getPoint(points, 0);
for (i = 0; i < pointsLen; ++i) {
pointBefore = pointCurrent;
pointCurrent = pointAfter;
pointAfter = getPoint(points, i + 1);
if (!pointCurrent) {
continue;
}
if (pointAfter) {
const slopeDelta = pointAfter[indexAxis] - pointCurrent[indexAxis];
// In the case of two points that appear at the same x pixel, slopeDeltaX is 0
deltaK[i] = slopeDelta !== 0 ? (pointAfter[valueAxis] - pointCurrent[valueAxis]) / slopeDelta : 0;
}
mK[i] = !pointBefore ? deltaK[i]
: !pointAfter ? deltaK[i - 1]
: (sign(deltaK[i - 1]) !== sign(deltaK[i])) ? 0
: (deltaK[i - 1] + deltaK[i]) / 2;
}
monotoneAdjust(points, deltaK, mK);
monotoneCompute(points, mK, indexAxis);
}
function capControlPoint(pt, min, max) {
return Math.max(Math.min(pt, max), min);
}
function capBezierPoints(points, area) {
let i, ilen, point, inArea, inAreaPrev;
let inAreaNext = _isPointInArea(points[0], area);
for (i = 0, ilen = points.length; i < ilen; ++i) {
inAreaPrev = inArea;
inArea = inAreaNext;
inAreaNext = i < ilen - 1 && _isPointInArea(points[i + 1], area);
if (!inArea) {
continue;
}
point = points[i];
if (inAreaPrev) {
point.cp1x = capControlPoint(point.cp1x, area.left, area.right);
point.cp1y = capControlPoint(point.cp1y, area.top, area.bottom);
}
if (inAreaNext) {
point.cp2x = capControlPoint(point.cp2x, area.left, area.right);
point.cp2y = capControlPoint(point.cp2y, area.top, area.bottom);
}
}
}
/**
* @private
*/
export function _updateBezierControlPoints(points, options, area, loop, indexAxis) {
let i, ilen, point, controlPoints;
// Only consider points that are drawn in case the spanGaps option is used
if (options.spanGaps) {
points = points.filter((pt) => !pt.skip);
}
if (options.cubicInterpolationMode === 'monotone') {
splineCurveMonotone(points, indexAxis);
} else {
let prev = loop ? points[points.length - 1] : points[0];
for (i = 0, ilen = points.length; i < ilen; ++i) {
point = points[i];
controlPoints = splineCurve(
prev,
point,
points[Math.min(i + 1, ilen - (loop ? 0 : 1)) % ilen],
options.tension
);
point.cp1x = controlPoints.previous.x;
point.cp1y = controlPoints.previous.y;
point.cp2x = controlPoints.next.x;
point.cp2y = controlPoints.next.y;
prev = point;
}
}
if (options.capBezierPoints) {
capBezierPoints(points, area);
}
}
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['angular', 'objectpath', 'tv4'], factory);
} else if (typeof exports === 'object') {
module.exports = factory(require('angular'), require('objectpath'), require('tv4'));
} else {
root.schemaForm = factory(root.angular, root.objectpath, root.tv4);
}
}(this, function(angular, objectpath, tv4) {
// Deps is sort of a problem for us, maybe in the future we will ask the user to depend
// on modules for add-ons
var deps = [];
try {
//This throws an expection if module does not exist.
angular.module('ngSanitize');
deps.push('ngSanitize');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('ui.sortable');
deps.push('ui.sortable');
} catch (e) {}
try {
//This throws an expection if module does not exist.
angular.module('angularSpectrumColorpicker');
deps.push('angularSpectrumColorpicker');
} catch (e) {}
var schemaForm = angular.module('schemaForm', deps);
angular.module('schemaForm').provider('sfPath',
[function() {
// When building with browserify ObjectPath is available as `objectpath` but othwerwise
// it's called `ObjectPath`.
var ObjectPath = window.ObjectPath || objectpath;
var sfPath = {parse: ObjectPath.parse};
// if we're on Angular 1.2.x, we need to continue using dot notation
if (angular.version.major === 1 && angular.version.minor < 3) {
sfPath.stringify = function(arr) {
return Array.isArray(arr) ? arr.join('.') : arr.toString();
};
} else {
sfPath.stringify = ObjectPath.stringify;
}
// We want this to use whichever stringify method is defined above,
// so we have to copy the code here.
sfPath.normalize = function(data, quote) {
return sfPath.stringify(Array.isArray(data) ? data : sfPath.parse(data), quote);
};
// expose the methods in sfPathProvider
this.parse = sfPath.parse;
this.stringify = sfPath.stringify;
this.normalize = sfPath.normalize;
this.$get = function() {
return sfPath;
};
}]);
/**
* @ngdoc service
* @name sfSelect
* @kind function
*
*/
angular.module('schemaForm').factory('sfSelect', ['sfPath', function(sfPath) {
var numRe = /^\d+$/;
/**
* @description
* Utility method to access deep properties without
* throwing errors when things are not defined.
* Can also set a value in a deep structure, creating objects when missing
* ex.
* var foo = Select('address.contact.name',obj)
* Select('address.contact.name',obj,'Leeroy')
*
* @param {string} projection A dot path to the property you want to get/set
* @param {object} obj (optional) The object to project on, defaults to 'this'
* @param {Any} valueToSet (opional) The value to set, if parts of the path of
* the projection is missing empty objects will be created.
* @returns {Any|undefined} returns the value at the end of the projection path
* or undefined if there is none.
*/
return function(projection, obj, valueToSet) {
if (!obj) {
obj = this;
}
//Support [] array syntax
var parts = typeof projection === 'string' ? sfPath.parse(projection) : projection;
if (typeof valueToSet !== 'undefined' && parts.length === 1) {
//special case, just setting one variable
obj[parts[0]] = valueToSet;
return obj;
}
if (typeof valueToSet !== 'undefined' &&
typeof obj[parts[0]] === 'undefined') {
// We need to look ahead to check if array is appropriate
obj[parts[0]] = parts.length > 2 && numRe.test(parts[1]) ? [] : {};
}
var value = obj[parts[0]];
for (var i = 1; i < parts.length; i++) {
// Special case: We allow JSON Form syntax for arrays using empty brackets
// These will of course not work here so we exit if they are found.
if (parts[i] === '') {
return undefined;
}
if (typeof valueToSet !== 'undefined') {
if (i === parts.length - 1) {
//last step. Let's set the value
value[parts[i]] = valueToSet;
return valueToSet;
} else {
// Make sure to create new objects on the way if they are not there.
// We need to look ahead to check if array is appropriate
var tmp = value[parts[i]];
if (typeof tmp === 'undefined' || tmp === null) {
tmp = numRe.test(parts[i + 1]) ? [] : {};
value[parts[i]] = tmp;
}
value = tmp;
}
} else if (value) {
//Just get nex value.
value = value[parts[i]];
}
}
return value;
};
}]);
// FIXME: type template (using custom builder)
angular.module('schemaForm').provider('sfBuilder', ['sfPathProvider', function(sfPathProvider) {
var SNAKE_CASE_REGEXP = /[A-Z]/g;
var snakeCase = function(name, separator) {
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
};
var builders = {
ngModel: function(args) {
if (!args.form.key) {
return;
}
var key = args.form.key;
// Redact part of the key, used in arrays
// KISS keyRedaction is a number.
if (args.state.keyRedaction) {
key = key.slice(args.state.keyRedaction);
}
// Stringify key.
var modelValue;
if (!args.state.modelValue) {
var strKey = sfPathProvider.stringify(key).replace(/"/g, '"');
modelValue = (args.state.modelName || 'model');
if (strKey) { // Sometimes, like with arrays directly in arrays strKey is nothing.
modelValue += (strKey[0] !== '[' ? '.' : '') + strKey;
}
} else {
// Another builder, i.e. array has overriden the modelValue
modelValue = args.state.modelValue;
}
// Find all sf-field-value attributes.
// No value means a add a ng-model.
// sf-field-value="replaceAll", loop over attributes and replace $$value$$ in each.
// sf-field-value="attrName", replace or set value of that attribute.
var nodes = args.fieldFrag.querySelectorAll('[sf-field-model]');
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
var conf = n.getAttribute('sf-field-model');
if (!conf || conf === '') {
n.setAttribute('ng-model', modelValue);
} else if (conf === 'replaceAll') {
var attributes = n.attributes;
for (var j = 0; attributes.length; j++) {
if (attributes[j].value && attributes[j].value.indexOf('$$value') !== -1) {
attributes[j].value = attributes[j].value.replace(/\$\$value\$\$/g, modelValue);
}
}
} else {
var val = n.getAttribute(conf);
if (val && val.indexOf('$$value$$')) {
n.setAttribute(conf, val.replace(/\$\$value\$\$/g, modelValue));
} else {
n.setAttribute(conf, modelValue);
}
}
}
},
simpleTransclusion: function(args) {
var children = args.build(args.form.items, args.path + '.items', args.state);
args.fieldFrag.firstChild.appendChild(children);
},
// Patch on ngModelOptions, since it doesn't like waiting for its value.
ngModelOptions: function(args) {
if (args.form.ngModelOptions && Object.keys(args.form.ngModelOptions).length > 0) {
args.fieldFrag.firstChild.setAttribute('ng-model-options', JSON.stringify(args.form.ngModelOptions));
}
},
transclusion: function(args) {
var transclusions = args.fieldFrag.querySelectorAll('[sf-field-transclude]');
if (transclusions.length) {
for (var i = 0; i < transclusions.length; i++) {
var n = transclusions[i];
// The sf-transclude attribute is not a directive, but has the name of what we're supposed to
// traverse.
var sub = args.form[n.getAttribute('sf-field-transclude')];
if (sub) {
sub = Array.isArray(sub) ? sub : [sub];
var childFrag = args.build(sub, args.path + '.' + sub, args.state);
n.appendChild(childFrag);
}
}
}
}
};
this.builders = builders;
this.$get = ['$templateCache', 'schemaFormDecorators', 'sfPath', function($templateCache, schemaFormDecorators, sfPath) {
var checkForSlot = function(form, slots) {
// Finally append this field to the frag.
// Check for slots
if (form.key) {
var slot = slots[sfPath.stringify(form.key)];
if (slot) {
while (slot.firstChild) {
slot.removeChild(slot.firstChild);
}
return slot;
}
}
};
var build = function(items, decorator, templateFn, slots, path, state) {
state = state || {};
path = path || 'schemaForm.form';
var container = document.createDocumentFragment();
items.reduce(function(frag, f, index) {
// Sanity check.
if (!f.type) {
return;
}
var field = decorator[f.type] || decorator['default'];
if (!field.replace) {
// Backwards compatability build
var n = document.createElement(snakeCase(decorator.__name, '-'));
n.setAttribute('form', path + '[' + index + ']');
(checkForSlot(f, slots) || frag).appendChild(n);
} else {
var tmpl;
// TODO: Create a couple fo testcases, small and large and
// measure optmization. A good start is probably a cache of DOM nodes for a particular
// template that can be cloned instead of using innerHTML
var div = document.createElement('div');
var template = templateFn(field.template) || templateFn([decorator['default'].template]);
div.innerHTML = template;
// Move node to a document fragment, we don't want the div.
tmpl = document.createDocumentFragment();
while (div.childNodes.length > 0) {
tmpl.appendChild(div.childNodes[0]);
}
tmpl.firstChild.setAttribute('sf-field',path + '[' + index + ']');
// Possible builder, often a noop
var args = {
fieldFrag: tmpl,
form: f,
state: state,
path: path + '[' + index + ']',
// Recursive build fn
build: function(items, path, state) {
return build(items, decorator, templateFn, slots, path, state);
},
};
// Builders are either a function or a list of functions.
if (typeof field.builder === 'function') {
field.builder(args);
} else {
field.builder.forEach(function(fn) { fn(args); });
}
// Append
(checkForSlot(f, slots) || frag).appendChild(tmpl);
}
return frag;
}, container);
return container;
};
return {
/**
* Builds a form from a canonical form definition
*/
build: function(form, decorator, slots) {
return build(form, decorator, function(url) {
return $templateCache.get(url);
}, slots);
},
builder: builders,
internalBuild: build
};
}];
}]);
angular.module('schemaForm').provider('schemaFormDecorators',
['$compileProvider', 'sfPathProvider', function($compileProvider, sfPathProvider) {
var defaultDecorator = '';
var decorators = {};
// Map template after decorator and type.
var templateUrl = function(name, form) {
//schemaDecorator is alias for whatever is set as default
if (name === 'sfDecorator') {
name = defaultDecorator;
}
var decorator = decorators[name];
if (decorator[form.type]) {
return decorator[form.type].template;
}
//try default
return decorator['default'].template;
};
var createDirective = function(name) {
$compileProvider.directive(name,
['$parse', '$compile', '$http', '$templateCache', '$interpolate', '$q', 'sfErrorMessage',
'sfPath','sfSelect',
function($parse, $compile, $http, $templateCache, $interpolate, $q, sfErrorMessage,
sfPath, sfSelect) {
return {
restrict: 'AE',
replace: false,
transclude: false,
scope: true,
require: '?^sfSchema',
link: function(scope, element, attrs, sfSchema) {
//The ngModelController is used in some templates and
//is needed for error messages,
scope.$on('schemaFormPropagateNgModelController', function(event, ngModel) {
event.stopPropagation();
event.preventDefault();
scope.ngModel = ngModel;
});
//Keep error prone logic from the template
scope.showTitle = function() {
return scope.form && scope.form.notitle !== true && scope.form.title;
};
scope.listToCheckboxValues = function(list) {
var values = {};
angular.forEach(list, function(v) {
values[v] = true;
});
return values;
};
scope.checkboxValuesToList = function(values) {
var lst = [];
angular.forEach(values, function(v, k) {
if (v) {
lst.push(k);
}
});
return lst;
};
scope.buttonClick = function($event, form) {
if (angular.isFunction(form.onClick)) {
form.onClick($event, form);
} else if (angular.isString(form.onClick)) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
sfSchema.evalInParentScope(form.onClick, {'$event': $event, form: form});
} else {
scope.$eval(form.onClick, {'$event': $event, form: form});
}
}
};
/**
* Evaluate an expression, i.e. scope.$eval
* but do it in sfSchemas parent scope sf-schema directive is used
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalExpr = function(expression, locals) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
return sfSchema.evalInParentScope(expression, locals);
}
return scope.$eval(expression, locals);
};
/**
* Evaluate an expression, i.e. scope.$eval
* in this decorators scope
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalInScope = function(expression, locals) {
if (expression) {
return scope.$eval(expression, locals);
}
};
/**
* Interpolate the expression.
* Similar to `evalExpr()` and `evalInScope()`
* but will not fail if the expression is
* text that contains spaces.
*
* Use the Angular `{{ interpolation }}`
* braces to access properties on `locals`.
*
* @param {string} content The string to interpolate.
* @param {Object} locals (optional) Properties that may be accessed in the
* `expression` string.
* @return {Any} The result of the expression or `undefined`.
*/
scope.interp = function(expression, locals) {
return (expression && $interpolate(expression)(locals));
};
//This works since we ot the ngModel from the array or the schema-validate directive.
scope.hasSuccess = function() {
if (!scope.ngModel) {
return false;
}
return scope.ngModel.$valid &&
(!scope.ngModel.$pristine || !scope.ngModel.$isEmpty(scope.ngModel.$modelValue));
};
scope.hasError = function() {
if (!scope.ngModel) {
return false;
}
return scope.ngModel.$invalid && !scope.ngModel.$pristine;
};
/**
* DEPRECATED: use sf-messages instead.
* Error message handler
* An error can either be a schema validation message or a angular js validtion
* error (i.e. required)
*/
scope.errorMessage = function(schemaError) {
return sfErrorMessage.interpolate(
(schemaError && schemaError.code + '') || 'default',
(scope.ngModel && scope.ngModel.$modelValue) || '',
(scope.ngModel && scope.ngModel.$viewValue) || '',
scope.form,
scope.options && scope.options.validationMessage
);
};
// Rebind our part of the form to the scope.
var once = scope.$watch(attrs.form, function(form) {
if (form) {
// Workaround for 'updateOn' error from ngModelOptions
// see https://github.com/Textalk/angular-schema-form/issues/255
// and https://github.com/Textalk/angular-schema-form/issues/206
form.ngModelOptions = form.ngModelOptions || {};
scope.form = form;
//ok let's replace that template!
//We do this manually since we need to bind ng-model properly and also
//for fieldsets to recurse properly.
var templatePromise;
// type: "template" is a special case. It can contain a template inline or an url.
// otherwise we find out the url to the template and load them.
if (form.type === 'template' && form.template) {
templatePromise = $q.when(form.template);
} else {
var url = form.type === 'template' ? form.templateUrl : templateUrl(name, form);
templatePromise = $http.get(url, {cache: $templateCache}).then(function(res) {
return res.data;
});
}
templatePromise.then(function(template) {
if (form.key) {
var key = form.key ?
sfPathProvider.stringify(form.key).replace(/"/g, '"') : '';
template = template.replace(
/\$\$value\$\$/g,
'model' + (key[0] !== '[' ? '.' : '') + key
);
}
element.html(template);
// Do we have a condition? Then we slap on an ng-if on all children,
// but be nice to existing ng-if.
if (form.condition) {
var evalExpr = 'evalExpr(form.condition,{ model: model, "arrayIndex": arrayIndex})';
if (form.key) {
evalExpr = 'evalExpr(form.condition,{ model: model, "arrayIndex": arrayIndex, "modelValue": model' + sfPath.stringify(form.key) + '})';
}
angular.forEach(element.children(), function(child) {
var ngIf = child.getAttribute('ng-if');
child.setAttribute(
'ng-if',
ngIf ?
'(' + ngIf +
') || (' + evalExpr +')'
: evalExpr
);
});
}
$compile(element.contents())(scope);
});
// Where there is a key there is probably a ngModel
if (form.key) {
// It looks better with dot notation.
scope.$on(
'schemaForm.error.' + form.key.join('.'),
function(event, error, validationMessage, validity) {
if (validationMessage === true || validationMessage === false) {
validity = validationMessage;
validationMessage = undefined;
}
if (scope.ngModel && error) {
if (scope.ngModel.$setDirty) {
scope.ngModel.$setDirty();
} else {
// FIXME: Check that this actually works on 1.2
scope.ngModel.$dirty = true;
scope.ngModel.$pristine = false;
}
// Set the new validation message if one is supplied
// Does not work when validationMessage is just a string.
if (validationMessage) {
if (!form.validationMessage) {
form.validationMessage = {};
}
form.validationMessage[error] = validationMessage;
}
scope.ngModel.$setValidity(error, validity === true);
if (validity === true && !scope.ngModel.$valid) {
+ // Previous the model maybe invalid, then the model value is undefined.
+ // To make the validation to the tv4 works, we need also re-trigger validators
+ scope.ngModel.$validate();
// Setting or removing a validity can change the field to believe its valid
// but its not. So lets trigger its validation as well.
scope.$broadcast('schemaFormValidate');
}
}
});
// Clean up the model when the corresponding form field is $destroy-ed.
// Default behavior can be supplied as a globalOption, and behavior can be overridden in the form definition.
scope.$on('$destroy', function() {
// If the entire schema form is destroyed we don't touch the model
if (!scope.externalDestructionInProgress) {
var destroyStrategy = form.destroyStrategy ||
(scope.options && scope.options.destroyStrategy) || 'remove';
// No key no model, and we might have strategy 'retain'
if (form.key && destroyStrategy !== 'retain') {
// Get the object that has the property we wan't to clear.
var obj = scope.model;
if (form.key.length > 1) {
obj = sfSelect(form.key.slice(0, form.key.length - 1), obj);
}
// We can get undefined here if the form hasn't been filled out entirely
if (obj === undefined) {
return;
}
// Type can also be a list in JSON Schema
var type = (form.schema && form.schema.type) || '';
// Empty means '',{} and [] for appropriate types and undefined for the rest
if (destroyStrategy === 'empty' && type.indexOf('string') !== -1) {
obj[form.key.slice(-1)] = '';
} else if (destroyStrategy === 'empty' && type.indexOf('object') !== -1) {
obj[form.key.slice(-1)] = {};
} else if (destroyStrategy === 'empty' && type.indexOf('array') !== -1) {
obj[form.key.slice(-1)] = [];
} else if (destroyStrategy === 'null') {
obj[form.key.slice(-1)] = null;
} else {
delete obj[form.key.slice(-1)];
}
}
}
});
}
once();
}
});
}
};
}
]);
};
var createManualDirective = function(type, templateUrl, transclude) {
transclude = angular.isDefined(transclude) ? transclude : false;
$compileProvider.directive('sf' + angular.uppercase(type[0]) + type.substr(1), function() {
return {
restrict: 'EAC',
scope: true,
replace: true,
transclude: transclude,
template: '<sf-decorator form="form"></sf-decorator>',
link: function(scope, element, attrs) {
var watchThis = {
'items': 'c',
'titleMap': 'c',
'schema': 'c'
};
var form = {type: type};
var once = true;
angular.forEach(attrs, function(value, name) {
if (name[0] !== '$' && name.indexOf('ng') !== 0 && name !== 'sfField') {
var updateForm = function(val) {
if (angular.isDefined(val) && val !== form[name]) {
form[name] = val;
//when we have type, and if specified key we apply it on scope.
if (once && form.type && (form.key || angular.isUndefined(attrs.key))) {
scope.form = form;
once = false;
}
}
};
if (name === 'model') {
//"model" is bound to scope under the name "model" since this is what the decorators
//know and love.
scope.$watch(value, function(val) {
if (val && scope.model !== val) {
scope.model = val;
}
});
} else if (watchThis[name] === 'c') {
//watch collection
scope.$watchCollection(value, updateForm);
} else {
//$observe
attrs.$observe(name, updateForm);
}
}
});
}
};
});
};
/**
* DEPRECATED: use defineDecorator instead.
* Create a decorator directive and its sibling "manual" use decorators.
* The directive can be used to create form fields or other form entities.
* It can be used in conjunction with <schema-form> directive in which case the decorator is
* given it's configuration via a the "form" attribute.
*
* ex. Basic usage
* <sf-decorator form="myform"></sf-decorator>
**
* @param {string} name directive name (CamelCased)
* @param {Object} templates, an object that maps "type" => "templateUrl"
*/
this.createDecorator = function(name, templates) {
//console.warn('schemaFormDecorators.createDecorator is DEPRECATED, use defineDecorator instead.');
decorators[name] = {'__name': name};
angular.forEach(templates, function(url, type) {
decorators[name][type] = {template: url, replace: false, builder: []};
});
if (!decorators[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* Create a decorator directive and its sibling "manual" use decorators.
* The directive can be used to create form fields or other form entities.
* It can be used in conjunction with <schema-form> directive in which case the decorator is
* given it's configuration via a the "form" attribute.
*
* ex. Basic usage
* <sf-decorator form="myform"></sf-decorator>
**
* @param {string} name directive name (CamelCased)
* @param {Object} fields, an object that maps "type" => `{ template, builder, replace}`.
attributes `builder` and `replace` are optional, and replace defaults to true.
*/
this.defineDecorator = function(name, fields) {
decorators[name] = {'__name': name}; // TODO: this feels like a hack, come up with a better way.
angular.forEach(fields, function(field, type) {
field.builder = field.builder || [];
field.replace = angular.isDefined(field.replace) ? field.replace : true;
decorators[name][type] = field;
});
if (!decorators[defaultDecorator]) {
defaultDecorator = name;
}
createDirective(name);
};
/**
* Creates a directive of a decorator
* Usable when you want to use the decorators without using <schema-form> directive.
* Specifically when you need to reuse styling.
*
* ex. createDirective('text','...')
* <sf-text title="foobar" model="person" key="name" schema="schema"></sf-text>
*
* @param {string} type The type of the directive, resulting directive will have sf- prefixed
* @param {string} templateUrl
* @param {boolean} transclude (optional) sets transclude option of directive, defaults to false.
*/
this.createDirective = createManualDirective;
/**
* Same as createDirective, but takes an object where key is 'type' and value is 'templateUrl'
* Useful for batching.
* @param {Object} templates
*/
this.createDirectives = function(templates) {
angular.forEach(templates, function(url, type) {
createManualDirective(type, url);
});
};
/**
* Getter for decorator settings
* @param {string} name (optional) defaults to defaultDecorator
* @return {Object} rules and templates { rules: [],templates: {}}
*/
this.decorator = function(name) {
name = name || defaultDecorator;
return decorators[name];
};
/**
* Adds a mapping to an existing decorator.
* @param {String} name Decorator name
* @param {String} type Form type for the mapping
* @param {String} url The template url
* @param {Function} builder (optional) builder function
* @param {boolean} replace (optional) defaults to false. Replace decorator directive with template.
*/
this.addMapping = function(name, type, url, builder, replace) {
if (decorators[name]) {
decorators[name][type] = {
template: url,
builder: builder,
replace: !!replace
};
}
};
//Service is just a getter for directive templates and rules
this.$get = function() {
return {
decorator: function(name) {
return decorators[name] || decorators[defaultDecorator];
},
defaultDecorator: defaultDecorator
};
};
//Create a default directive
createDirective('sfDecorator');
}]);
angular.module('schemaForm').provider('sfErrorMessage', function() {
// The codes are tv4 error codes.
// Not all of these can actually happen in a field, but for
// we never know when one might pop up so it's best to cover them all.
// TODO: Humanize these.
var defaultMessages = {
'default': 'Field does not validate',
0: 'Invalid type, expected {{schema.type}}',
1: 'No enum match for: {{viewValue}}',
10: 'Data does not match any schemas from "anyOf"',
11: 'Data does not match any schemas from "oneOf"',
12: 'Data is valid against more than one schema from "oneOf"',
13: 'Data matches schema from "not"',
// Numeric errors
100: 'Value is not a multiple of {{schema.divisibleBy}}',
101: '{{viewValue}} is less than the allowed minimum of {{schema.minimum}}',
102: '{{viewValue}} is equal to the exclusive minimum {{schema.minimum}}',
103: '{{viewValue}} is greater than the allowed maximum of {{schema.maximum}}',
104: '{{viewValue}} is equal to the exclusive maximum {{schema.maximum}}',
105: 'Value is not a valid number',
// String errors
200: 'String is too short ({{viewValue.length}} chars), minimum {{schema.minLength}}',
201: 'String is too long ({{viewValue.length}} chars), maximum {{schema.maxLength}}',
202: 'String does not match pattern: {{schema.pattern}}',
// Object errors
300: 'Too few properties defined, minimum {{schema.minProperties}}',
301: 'Too many properties defined, maximum {{schema.maxProperties}}',
302: 'Required',
303: 'Additional properties not allowed',
304: 'Dependency failed - key must exist',
// Array errors
400: 'Array is too short ({{value.length}}), minimum {{schema.minItems}}',
401: 'Array is too long ({{value.length}}), maximum {{schema.maxItems}}',
402: 'Array items are not unique',
403: 'Additional items not allowed',
// Format errors
500: 'Format validation failed',
501: 'Keyword failed: "{{title}}"',
// Schema structure
600: 'Circular $refs',
// Non-standard validation options
1000: 'Unknown property (not in schema)'
};
// In some cases we get hit with an angular validation error
defaultMessages.number = defaultMessages[105];
defaultMessages.required = defaultMessages[302];
defaultMessages.min = defaultMessages[101];
defaultMessages.max = defaultMessages[103];
defaultMessages.maxlength = defaultMessages[201];
defaultMessages.minlength = defaultMessages[200];
defaultMessages.pattern = defaultMessages[202];
this.setDefaultMessages = function(messages) {
defaultMessages = messages;
};
this.getDefaultMessages = function() {
return defaultMessages;
};
this.setDefaultMessage = function(error, msg) {
defaultMessages[error] = msg;
};
this.$get = ['$interpolate', function($interpolate) {
var service = {};
service.defaultMessages = defaultMessages;
/**
* Interpolate and return proper error for an eror code.
* Validation message on form trumps global error messages.
* and if the message is a function instead of a string that function will be called instead.
* @param {string} error the error code, i.e. tv4-xxx for tv4 errors, otherwise it's whats on
* ngModel.$error for custom errors.
* @param {Any} value the actual model value.
* @param {Any} viewValue the viewValue
* @param {Object} form a form definition object for this field
* @param {Object} global the global validation messages object (even though its called global
* its actually just shared in one instance of sf-schema)
* @return {string} The error message.
*/
service.interpolate = function(error, value, viewValue, form, global) {
global = global || {};
var validationMessage = form.validationMessage || {};
// Drop tv4 prefix so only the code is left.
if (error.indexOf('tv4-') === 0) {
error = error.substring(4);
}
// First find apropriate message or function
var message = validationMessage['default'] || global['default'] || '';
[validationMessage, global, defaultMessages].some(function(val) {
if (angular.isString(val) || angular.isFunction(val)) {
message = val;
return true;
}
if (val && val[error]) {
message = val[error];
return true;
}
});
var context = {
error: error,
value: value,
viewValue: viewValue,
form: form,
schema: form.schema,
title: form.title || (form.schema && form.schema.title)
};
if (angular.isFunction(message)) {
return message(context);
} else {
return $interpolate(message)(context);
}
};
return service;
}];
});
/**
* Schema form service.
* This service is not that useful outside of schema form directive
* but makes the code more testable.
*/
angular.module('schemaForm').provider('schemaForm',
['sfPathProvider', function(sfPathProvider) {
var stripNullType = function(type) {
if (Array.isArray(type) && type.length == 2) {
if (type[0] === 'null')
return type[1];
if (type[1] === 'null')
return type[0];
}
return type;
}
//Creates an default titleMap list from an enum, i.e. a list of strings.
var enumToTitleMap = function(enm) {
var titleMap = []; //canonical titleMap format is a list.
enm.forEach(function(name) {
titleMap.push({name: name, value: name});
});
return titleMap;
};
// Takes a titleMap in either object or list format and returns one in
// in the list format.
var canonicalTitleMap = function(titleMap, originalEnum) {
if (!angular.isArray(titleMap)) {
var canonical = [];
if (originalEnum) {
angular.forEach(originalEnum, function(value, index) {
canonical.push({name: titleMap[value], value: value});
});
} else {
angular.forEach(titleMap, function(name, value) {
canonical.push({name: name, value: value});
});
}
return canonical;
}
return titleMap;
};
var defaultFormDefinition = function(name, schema, options) {
var rules = defaults[stripNullType(schema.type)];
if (rules) {
var def;
for (var i = 0; i < rules.length; i++) {
def = rules[i](name, schema, options);
//first handler in list that actually returns something is our handler!
if (def) {
// Do we have form defaults in the schema under the x-schema-form-attribute?
if (def.schema['x-schema-form'] && angular.isObject(def.schema['x-schema-form'])) {
def = angular.extend(def, def.schema['x-schema-form']);
}
return def;
}
}
}
};
//Creates a form object with all common properties
var stdFormObj = function(name, schema, options) {
options = options || {};
var f = options.global && options.global.formDefaults ?
angular.copy(options.global.formDefaults) : {};
if (options.global && options.global.supressPropertyTitles === true) {
f.title = schema.title;
} else {
f.title = schema.title || name;
}
if (schema.description) { f.description = schema.description; }
if (options.required === true || schema.required === true) { f.required = true; }
if (schema.maxLength) { f.maxlength = schema.maxLength; }
if (schema.minLength) { f.minlength = schema.maxLength; }
if (schema.readOnly || schema.readonly) { f.readonly = true; }
if (schema.minimum) { f.minimum = schema.minimum + (schema.exclusiveMinimum ? 1 : 0); }
if (schema.maximum) { f.maximum = schema.maximum - (schema.exclusiveMaximum ? 1 : 0); }
// Non standard attributes (DONT USE DEPRECATED)
// If you must set stuff like this in the schema use the x-schema-form attribute
if (schema.validationMessage) { f.validationMessage = schema.validationMessage; }
if (schema.enumNames) { f.titleMap = canonicalTitleMap(schema.enumNames, schema['enum']); }
f.schema = schema;
// Ng model options doesn't play nice with undefined, might be defined
// globally though
f.ngModelOptions = f.ngModelOptions || {};
return f;
};
var text = function(name, schema, options) {
if (stripNullType(schema.type) === 'string' && !schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'text';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
//default in json form for number and integer is a text field
//input type="number" would be more suitable don't ya think?
var number = function(name, schema, options) {
if (stripNullType(schema.type) === 'number') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var integer = function(name, schema, options) {
if (stripNullType(schema.type) === 'integer') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'number';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkbox = function(name, schema, options) {
if (stripNullType(schema.type) === 'boolean') {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkbox';
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var select = function(name, schema, options) {
if (stripNullType(schema.type) === 'string' && schema['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'select';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var checkboxes = function(name, schema, options) {
if (stripNullType(schema.type) === 'array' && schema.items && schema.items['enum']) {
var f = stdFormObj(name, schema, options);
f.key = options.path;
f.type = 'checkboxes';
if (!f.titleMap) {
f.titleMap = enumToTitleMap(schema.items['enum']);
}
options.lookup[sfPathProvider.stringify(options.path)] = f;
return f;
}
};
var fieldset = function(name, schema, options) {
if (stripNullType(schema.type) === 'object') {
var f = stdFormObj(name, schema, options);
f.type = 'fieldset';
f.items = [];
options.lookup[sfPathProvider.stringify(options.path)] = f;
//recurse down into properties
angular.forEach(schema.properties, function(v, k) {
var path = options.path.slice();
path.push(k);
if (options.ignore[sfPathProvider.stringify(path)] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: path,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
});
if (def) {
f.items.push(def);
}
}
});
return f;
}
};
var array = function(name, schema, options) {
if (stripNullType(schema.type) === 'array') {
var f = stdFormObj(name, schema, options);
f.type = 'array';
f.key = options.path;
options.lookup[sfPathProvider.stringify(options.path)] = f;
var required = schema.required &&
schema.required.indexOf(options.path[options.path.length - 1]) !== -1;
// The default is to always just create one child. This works since if the
// schemas items declaration is of type: "object" then we get a fieldset.
// We also follow json form notatation, adding empty brackets "[]" to
// signify arrays.
var arrPath = options.path.slice();
arrPath.push('');
f.items = [defaultFormDefinition(name, schema.items, {
path: arrPath,
required: required || false,
lookup: options.lookup,
ignore: options.ignore,
global: options.global
})];
return f;
}
};
//First sorted by schema type then a list.
//Order has importance. First handler returning an form snippet will be used.
var defaults = {
string: [select, text],
object: [fieldset],
number: [number],
integer: [integer],
boolean: [checkbox],
array: [checkboxes, array]
};
var postProcessFn = function(form) { return form; };
/**
* Provider API
*/
this.defaults = defaults;
this.stdFormObj = stdFormObj;
this.defaultFormDefinition = defaultFormDefinition;
/**
* Register a post process function.
* This function is called with the fully merged
* form definition (i.e. after merging with schema)
* and whatever it returns is used as form.
*/
this.postProcess = function(fn) {
postProcessFn = fn;
};
/**
* Append default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.appendRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].push(rule);
};
/**
* Prepend default form rule
* @param {string} type json schema type
* @param {Function} rule a function(propertyName,propertySchema,options) that returns a form
* definition or undefined
*/
this.prependRule = function(type, rule) {
if (!defaults[type]) {
defaults[type] = [];
}
defaults[type].unshift(rule);
};
/**
* Utility function to create a standard form object.
* This does *not* set the type of the form but rather all shared attributes.
* You probably want to start your rule with creating the form with this method
* then setting type and any other values you need.
* @param {Object} schema
* @param {Object} options
* @return {Object} a form field defintion
*/
this.createStandardForm = stdFormObj;
/* End Provider API */
this.$get = function() {
var service = {};
service.merge = function(schema, form, ignore, options, readonly) {
form = form || ['*'];
options = options || {};
// Get readonly from root object
readonly = readonly || schema.readonly || schema.readOnly;
var stdForm = service.defaults(schema, ignore, options);
//simple case, we have a "*", just put the stdForm there
var idx = form.indexOf('*');
if (idx !== -1) {
form = form.slice(0, idx)
.concat(stdForm.form)
.concat(form.slice(idx + 1));
}
//ok let's merge!
//We look at the supplied form and extend it with schema standards
var lookup = stdForm.lookup;
return postProcessFn(form.map(function(obj) {
//handle the shortcut with just a name
if (typeof obj === 'string') {
obj = {key: obj};
}
if (obj.key) {
if (typeof obj.key === 'string') {
obj.key = sfPathProvider.parse(obj.key);
}
}
//If it has a titleMap make sure it's a list
if (obj.titleMap) {
obj.titleMap = canonicalTitleMap(obj.titleMap);
}
//
if (obj.itemForm) {
obj.items = [];
var str = sfPathProvider.stringify(obj.key);
var stdForm = lookup[str];
angular.forEach(stdForm.items, function(item) {
var o = angular.copy(obj.itemForm);
o.key = item.key;
obj.items.push(o);
});
}
//extend with std form from schema.
if (obj.key) {
var strid = sfPathProvider.stringify(obj.key);
if (lookup[strid]) {
var schemaDefaults = lookup[strid];
angular.forEach(schemaDefaults, function(value, attr) {
if (obj[attr] === undefined) {
obj[attr] = schemaDefaults[attr];
}
});
}
}
// Are we inheriting readonly?
if (readonly === true) { // Inheriting false is not cool.
obj.readonly = true;
}
//if it's a type with items, merge 'em!
if (obj.items) {
obj.items = service.merge(schema, obj.items, ignore, options, obj.readonly);
}
//if its has tabs, merge them also!
if (obj.tabs) {
angular.forEach(obj.tabs, function(tab) {
tab.items = service.merge(schema, tab.items, ignore, options, obj.readonly);
});
}
// Special case: checkbox
// Since have to ternary state we need a default
if (obj.type === 'checkbox' && angular.isUndefined(obj.schema['default'])) {
obj.schema['default'] = false;
}
return obj;
}));
};
/**
* Create form defaults from schema
*/
service.defaults = function(schema, ignore, globalOptions) {
var form = [];
var lookup = {}; //Map path => form obj for fast lookup in merging
ignore = ignore || {};
globalOptions = globalOptions || {};
if (stripNullType(schema.type) === 'object') {
angular.forEach(schema.properties, function(v, k) {
if (ignore[k] !== true) {
var required = schema.required && schema.required.indexOf(k) !== -1;
var def = defaultFormDefinition(k, v, {
path: [k], // Path to this property in bracket notation.
lookup: lookup, // Extra map to register with. Optimization for merger.
ignore: ignore, // The ignore list of paths (sans root level name)
required: required, // Is it required? (v4 json schema style)
global: globalOptions // Global options, including form defaults
});
if (def) {
form.push(def);
}
}
});
} else {
throw new Error('Not implemented. Only type "object" allowed at root level of schema.');
}
return {form: form, lookup: lookup};
};
//Utility functions
/**
* Traverse a schema, applying a function(schema,path) on every sub schema
* i.e. every property of an object.
*/
service.traverseSchema = function(schema, fn, path, ignoreArrays) {
ignoreArrays = angular.isDefined(ignoreArrays) ? ignoreArrays : true;
path = path || [];
var traverse = function(schema, fn, path) {
fn(schema, path);
angular.forEach(schema.properties, function(prop, name) {
var currentPath = path.slice();
currentPath.push(name);
traverse(prop, fn, currentPath);
});
//Only support type "array" which have a schema as "items".
if (!ignoreArrays && schema.items) {
var arrPath = path.slice(); arrPath.push('');
traverse(schema.items, fn, arrPath);
}
};
traverse(schema, fn, path || []);
};
service.traverseForm = function(form, fn) {
fn(form);
angular.forEach(form.items, function(f) {
service.traverseForm(f, fn);
});
if (form.tabs) {
angular.forEach(form.tabs, function(tab) {
angular.forEach(tab.items, function(f) {
service.traverseForm(f, fn);
});
});
}
};
return service;
};
}]);
/* Common code for validating a value against its form and schema definition */
/* global tv4 */
angular.module('schemaForm').factory('sfValidator', [function() {
var validator = {};
/**
* Validate a value against its form definition and schema.
* The value should either be of proper type or a string, some type
* coercion is applied.
*
* @param {Object} form A merged form definition, i.e. one with a schema.
* @param {Any} value the value to validate.
* @return a tv4js result object.
*/
validator.validate = function(form, value) {
if (!form) {
return {valid: true};
}
var schema = form.schema;
if (!schema) {
return {valid: true};
}
// Input of type text and textareas will give us a viewValue of ''
// when empty, this is a valid value in a schema and does not count as something
// that breaks validation of 'required'. But for our own sanity an empty field should
// not validate if it's required.
if (value === '') {
value = undefined;
}
// Numbers fields will give a null value, which also means empty field
if (form.type === 'number' && value === null) {
value = undefined;
}
// Version 4 of JSON Schema has the required property not on the
// property itself but on the wrapping object. Since we like to test
// only this property we wrap it in a fake object.
var wrap = {type: 'object', 'properties': {}};
var propName = form.key[form.key.length - 1];
wrap.properties[propName] = schema;
if (form.required) {
wrap.required = [propName];
}
var valueWrap = {};
if (angular.isDefined(value)) {
valueWrap[propName] = value;
}
return tv4.validateResult(valueWrap, wrap);
};
return validator;
}]);
/**
* Directive that handles the model arrays
*/
angular.module('schemaForm').directive('sfArray', ['sfSelect', 'schemaForm', 'sfValidator', 'sfPath',
function(sfSelect, schemaForm, sfValidator, sfPath) {
var setIndex = function(index) {
return function(form) {
if (form.key) {
form.key[form.key.indexOf('')] = index;
}
};
};
return {
restrict: 'A',
scope: true,
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
var formDefCache = {};
scope.validateArray = angular.noop;
if (ngModel) {
// We need the ngModelController on several places,
// most notably for errors.
// So we emit it up to the decorator directive so it can put it on scope.
scope.$emit('schemaFormPropagateNgModelController', ngModel);
}
// Watch for the form definition and then rewrite it.
// It's the (first) array part of the key, '[]' that needs a number
// corresponding to an index of the form.
var once = scope.$watch(attrs.sfArray, function(form) {
if (!form) {
return;
}
// An array model always needs a key so we know what part of the model
// to look at. This makes us a bit incompatible with JSON Form, on the
// other hand it enables two way binding.
var list = sfSelect(form.key, scope.model);
// We only modify the same array instance but someone might change the array from
// the outside so let's watch for that. We use an ordinary watch since the only case
// we're really interested in is if its a new instance.
var key = sfPath.normalize(form.key);
scope.$watch('model' + (key[0] !== '[' ? '.' : '') + key, function(value) {
list = scope.modelArray = value;
});
// Since ng-model happily creates objects in a deep path when setting a
// a value but not arrays we need to create the array.
if (angular.isUndefined(list)) {
list = [];
sfSelect(form.key, scope.model, list);
}
scope.modelArray = list;
// Arrays with titleMaps, i.e. checkboxes doesn't have items.
if (form.items) {
// To be more compatible with JSON Form we support an array of items
// in the form definition of "array" (the schema just a value).
// for the subforms code to work this means we wrap everything in a
// section. Unless there is just one.
var subForm = form.items[0];
if (form.items.length > 1) {
subForm = {
type: 'section',
items: form.items.map(function(item) {
item.ngModelOptions = form.ngModelOptions;
if (angular.isUndefined(item.readonly)) {
item.readonly = form.readonly;
}
return item;
})
};
}
}
// We ceate copies of the form on demand, caching them for
// later requests
scope.copyWithIndex = function(index) {
if (!formDefCache[index]) {
if (subForm) {
var copy = angular.copy(subForm);
copy.arrayIndex = index;
schemaForm.traverseForm(copy, setIndex(index));
formDefCache[index] = copy;
}
}
return formDefCache[index];
};
scope.appendToArray = function() {
var len = list.length;
var copy = scope.copyWithIndex(len);
schemaForm.traverseForm(copy, function(part) {
if (part.key) {
var def;
if (angular.isDefined(part['default'])) {
def = part['default'];
}
if (angular.isDefined(part.schema) &&
angular.isDefined(part.schema['default'])) {
def = part.schema['default'];
}
if (angular.isDefined(def)) {
sfSelect(part.key, scope.model, def);
}
}
});
// If there are no defaults nothing is added so we need to initialize
// the array. undefined for basic values, {} or [] for the others.
if (len === list.length) {
var type = sfSelect('schema.items.type', form);
var dflt;
if (type === 'object') {
dflt = {};
} else if (type === 'array') {
dflt = [];
}
list.push(dflt);
}
// Trigger validation.
scope.validateArray();
return list;
};
scope.deleteFromArray = function(index) {
list.splice(index, 1);
// Trigger validation.
scope.validateArray();
// Angular 1.2 lacks setDirty
if (ngModel && ngModel.$setDirty) {
ngModel.$setDirty();
}
return list;
};
// Always start with one empty form unless configured otherwise.
// Special case: don't do it if form has a titleMap
if (!form.titleMap && form.startEmpty !== true && list.length === 0) {
scope.appendToArray();
}
// Title Map handling
// If form has a titleMap configured we'd like to enable looping over
// titleMap instead of modelArray, this is used for intance in
// checkboxes. So instead of variable number of things we like to create
// a array value from a subset of values in the titleMap.
// The problem here is that ng-model on a checkbox doesn't really map to
// a list of values. This is here to fix that.
if (form.titleMap && form.titleMap.length > 0) {
scope.titleMapValues = [];
// We watch the model for changes and the titleMapValues to reflect
// the modelArray
var updateTitleMapValues = function(arr) {
scope.titleMapValues = [];
arr = arr || [];
form.titleMap.forEach(function(item) {
scope.titleMapValues.push(arr.indexOf(item.value) !== -1);
});
};
//Catch default values
updateTitleMapValues(scope.modelArray);
scope.$watchCollection('modelArray', updateTitleMapValues);
//To get two way binding we also watch our titleMapValues
scope.$watchCollection('titleMapValues', function(vals, old) {
if (vals && vals !== old) {
var arr = scope.modelArray;
// Apparently the fastest way to clear an array, readable too.
// http://jsperf.com/array-destroy/32
while (arr.length > 0) {
arr.pop();
}
form.titleMap.forEach(function(item, index) {
if (vals[index]) {
arr.push(item.value);
}
});
// Time to validate the rebuilt array.
scope.validateArray();
}
});
}
// If there is a ngModel present we need to validate when asked.
if (ngModel) {
var error;
scope.validateArray = function() {
// The actual content of the array is validated by each field
// so we settle for checking validations specific to arrays
// Since we prefill with empty arrays we can get the funny situation
// where the array is required but empty in the gui but still validates.
// Thats why we check the length.
var result = sfValidator.validate(
form,
scope.modelArray.length > 0 ? scope.modelArray : undefined
);
// TODO: DRY this up, it has a lot of similarities with schema-validate
// Since we might have different tv4 errors we must clear all
// errors that start with tv4-
Object.keys(ngModel.$error)
.filter(function(k) { return k.indexOf('tv4-') === 0; })
.forEach(function(k) { ngModel.$setValidity(k, true); });
if (result.valid === false &&
result.error &&
(result.error.dataPath === '' ||
result.error.dataPath === '/' + form.key[form.key.length - 1])) {
// Set viewValue to trigger $dirty on field. If someone knows a
// a better way to do it please tell.
ngModel.$setViewValue(scope.modelArray);
error = result.error;
ngModel.$setValidity('tv4-' + result.error.code, false);
}
};
scope.$on('schemaFormValidate', scope.validateArray);
scope.hasSuccess = function() {
return ngModel.$valid && !ngModel.$pristine;
};
scope.hasError = function() {
return ngModel.$invalid;
};
scope.schemaError = function() {
return error;
};
}
once();
});
}
};
}
]);
/**
* A version of ng-changed that only listens if
* there is actually a onChange defined on the form
*
* Takes the form definition as argument.
* If the form definition has a "onChange" defined as either a function or
*/
angular.module('schemaForm').directive('sfChanged', function() {
return {
require: 'ngModel',
restrict: 'AC',
scope: false,
link: function(scope, element, attrs, ctrl) {
var form = scope.$eval(attrs.sfChanged);
//"form" is really guaranteed to be here since the decorator directive
//waits for it. But best be sure.
if (form && form.onChange) {
ctrl.$viewChangeListeners.push(function() {
if (angular.isFunction(form.onChange)) {
form.onChange(ctrl.$modelValue, form);
} else {
scope.evalExpr(form.onChange, {'modelValue': ctrl.$modelValue, form: form});
}
});
}
}
};
});
angular.module('schemaForm').directive('sfField',
['$parse', '$compile', '$http', '$templateCache', '$interpolate', '$q', 'sfErrorMessage',
'sfPath','sfSelect',
function($parse, $compile, $http, $templateCache, $interpolate, $q, sfErrorMessage,
sfPath, sfSelect) {
return {
restrict: 'AE',
replace: false,
transclude: false,
scope: true,
require: '?^sfSchema',
link: {
pre: function(scope) {
//The ngModelController is used in some templates and
//is needed for error messages,
scope.$on('schemaFormPropagateNgModelController', function(event, ngModel) {
event.stopPropagation();
event.preventDefault();
scope.ngModel = ngModel;
});
//make sure to overwrite form here so that we don't inherit it by accident
scope.form = null;
},
post: function(scope, element, attrs, sfSchema) {
//Keep error prone logic from the template
scope.showTitle = function() {
return scope.form && scope.form.notitle !== true && scope.form.title;
};
scope.listToCheckboxValues = function(list) {
var values = {};
angular.forEach(list, function(v) {
values[v] = true;
});
return values;
};
scope.checkboxValuesToList = function(values) {
var lst = [];
angular.forEach(values, function(v, k) {
if (v) {
lst.push(k);
}
});
return lst;
};
scope.buttonClick = function($event, form) {
if (angular.isFunction(form.onClick)) {
form.onClick($event, form);
} else if (angular.isString(form.onClick)) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
sfSchema.evalInParentScope(form.onClick, {'$event': $event, form: form});
} else {
scope.$eval(form.onClick, {'$event': $event, form: form});
}
}
};
/**
* Evaluate an expression, i.e. scope.$eval
* but do it in sfSchemas parent scope sf-schema directive is used
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalExpr = function(expression, locals) {
if (sfSchema) {
//evaluating in scope outside of sfSchemas isolated scope
return sfSchema.evalInParentScope(expression, locals);
}
return scope.$eval(expression, locals);
};
/**
* Evaluate an expression, i.e. scope.$eval
* in this decorators scope
* @param {string} expression
* @param {Object} locals (optional)
* @return {Any} the result of the expression
*/
scope.evalInScope = function(expression, locals) {
if (expression) {
return scope.$eval(expression, locals);
}
};
/**
* Interpolate the expression.
* Similar to `evalExpr()` and `evalInScope()`
* but will not fail if the expression is
* text that contains spaces.
*
* Use the Angular `{{ interpolation }}`
* braces to access properties on `locals`.
*
* @param {string} content The string to interpolate.
* @param {Object} locals (optional) Properties that may be accessed in the
* `expression` string.
* @return {Any} The result of the expression or `undefined`.
*/
scope.interp = function(expression, locals) {
return (expression && $interpolate(expression)(locals));
};
//This works since we ot the ngModel from the array or the schema-validate directive.
scope.hasSuccess = function() {
if (!scope.ngModel) {
return false;
}
return scope.ngModel.$valid &&
(!scope.ngModel.$pristine || !scope.ngModel.$isEmpty(scope.ngModel.$modelValue));
};
scope.hasError = function() {
if (!scope.ngModel) {
return false;
}
return scope.ngModel.$invalid && !scope.ngModel.$pristine;
};
/**
* DEPRECATED: use sf-messages instead.
* Error message handler
* An error can either be a schema validation message or a angular js validtion
* error (i.e. required)
*/
scope.errorMessage = function(schemaError) {
return sfErrorMessage.interpolate(
(schemaError && schemaError.code + '') || 'default',
(scope.ngModel && scope.ngModel.$modelValue) || '',
(scope.ngModel && scope.ngModel.$viewValue) || '',
scope.form,
scope.options && scope.options.validationMessage
);
};
// Rebind our part of the form to the scope.
var once = scope.$watch(attrs.sfField, function(form) {
if (form) {
// Workaround for 'updateOn' error from ngModelOptions
// see https://github.com/Textalk/angular-schema-form/issues/255
// and https://github.com/Textalk/angular-schema-form/issues/206
form.ngModelOptions = form.ngModelOptions || {};
scope.form = form;
// Where there is a key there is probably a ngModel
if (form.key) {
// It looks better with dot notation.
scope.$on(
'schemaForm.error.' + form.key.join('.'),
function(event, error, validationMessage, validity) {
if (validationMessage === true || validationMessage === false) {
validity = validationMessage;
validationMessage = undefined;
}
if (scope.ngModel && error) {
if (scope.ngModel.$setDirty) {
scope.ngModel.$setDirty();
} else {
// FIXME: Check that this actually works on 1.2
scope.ngModel.$dirty = true;
scope.ngModel.$pristine = false;
}
// Set the new validation message if one is supplied
// Does not work when validationMessage is just a string.
if (validationMessage) {
if (!form.validationMessage) {
form.validationMessage = {};
}
form.validationMessage[error] = validationMessage;
}
scope.ngModel.$setValidity(error, validity === true);
if (validity === true) {
// Setting or removing a validity can change the field to believe its valid
// but its not. So lets trigger its validation as well.
scope.$broadcast('schemaFormValidate');
}
}
});
// Clean up the model when the corresponding form field is $destroy-ed.
// Default behavior can be supplied as a globalOption, and behavior can be overridden in the form definition.
scope.$on('$destroy', function() {
// If the entire schema form is destroyed we don't touch the model
if (!scope.externalDestructionInProgress) {
var destroyStrategy = form.destroyStrategy ||
(scope.options && scope.options.destroyStrategy) || 'remove';
// No key no model, and we might have strategy 'retain'
if (form.key && destroyStrategy !== 'retain') {
// Get the object that has the property we wan't to clear.
var obj = scope.model;
if (form.key.length > 1) {
obj = sfSelect(form.key.slice(0, form.key.length - 1), obj);
}
// We can get undefined here if the form hasn't been filled out entirely
if (obj === undefined) {
return;
}
// Type can also be a list in JSON Schema
var type = (form.schema && form.schema.type) || '';
// Empty means '',{} and [] for appropriate types and undefined for the rest
//console.log('destroy', destroyStrategy, form.key, type, obj);
if (destroyStrategy === 'empty' && type.indexOf('string') !== -1) {
obj[form.key.slice(-1)] = '';
} else if (destroyStrategy === 'empty' && type.indexOf('object') !== -1) {
obj[form.key.slice(-1)] = {};
} else if (destroyStrategy === 'empty' && type.indexOf('array') !== -1) {
obj[form.key.slice(-1)] = [];
} else if (destroyStrategy === 'null') {
obj[form.key.slice(-1)] = null;
} else {
delete obj[form.key.slice(-1)];
}
}
}
});
}
once();
}
});
}
}
};
}
]);
angular.module('schemaForm').directive('sfMessage',
['$injector', 'sfErrorMessage', function($injector, sfErrorMessage) {
return {
scope: false,
restrict: 'EA',
link: function(scope, element, attrs) {
//Inject sanitizer if it exists
var $sanitize = $injector.has('$sanitize') ?
$injector.get('$sanitize') : function(html) { return html; };
var message = '';
if (attrs.sfMessage) {
scope.$watch(attrs.sfMessage, function(msg) {
if (msg) {
message = $sanitize(msg);
if (scope.ngModel) {
update(scope.ngModel.$valid);
} else {
update();
}
}
});
}
var update = function(valid) {
if (valid && !scope.hasError()) {
element.html(message);
} else {
var errors = [];
angular.forEach(((scope.ngModel && scope.ngModel.$error) || {}), function(status, code) {
if (status) {
// if true then there is an error
// Angular 1.3 removes properties, so we will always just have errors.
// Angular 1.2 sets them to false.
errors.push(code);
}
});
// In Angular 1.3 we use one $validator to stop the model value from getting updated.
// this means that we always end up with a 'schemaForm' error.
errors = errors.filter(function(e) { return e !== 'schemaForm'; });
// We only show one error.
// TODO: Make that optional
var error = errors[0];
if (error) {
element.html(sfErrorMessage.interpolate(
error,
scope.ngModel.$modelValue,
scope.ngModel.$viewValue,
scope.form,
scope.options && scope.options.validationMessage
));
} else {
element.html(message);
}
}
};
update();
scope.$watchCollection('ngModel.$error', function() {
if (scope.ngModel) {
update(scope.ngModel.$valid);
}
});
}
};
}]);
/*
FIXME: real documentation
<form sf-form="form" sf-schema="schema" sf-decorator="foobar"></form>
*/
angular.module('schemaForm')
.directive('sfSchema',
['$compile', 'schemaForm', 'schemaFormDecorators', 'sfSelect', 'sfPath', 'sfBuilder',
function($compile, schemaForm, schemaFormDecorators, sfSelect, sfPath, sfBuilder) {
return {
scope: {
schema: '=sfSchema',
initialForm: '=sfForm',
model: '=sfModel',
options: '=sfOptions'
},
controller: ['$scope', function($scope) {
this.evalInParentScope = function(expr, locals) {
return $scope.$parent.$eval(expr, locals);
};
}],
replace: false,
restrict: 'A',
transclude: true,
require: '?form',
link: function(scope, element, attrs, formCtrl, transclude) {
//expose form controller on scope so that we don't force authors to use name on form
scope.formCtrl = formCtrl;
//We'd like to handle existing markup,
//besides using it in our template we also
//check for ng-model and add that to an ignore list
//i.e. even if form has a definition for it or form is ["*"]
//we don't generate it.
var ignore = {};
transclude(scope, function(clone) {
clone.addClass('schema-form-ignore');
element.prepend(clone);
if (element[0].querySelectorAll) {
var models = element[0].querySelectorAll('[ng-model]');
if (models) {
for (var i = 0; i < models.length; i++) {
var key = models[i].getAttribute('ng-model');
//skip first part before .
ignore[key.substring(key.indexOf('.') + 1)] = true;
}
}
}
});
var lastDigest = {};
var childScope;
// Common renderer function, can either be triggered by a watch or by an event.
var render = function(schema, form) {
var merged = schemaForm.merge(schema, form, ignore, scope.options);
// Create a new form and destroy the old one.
// Not doing keeps old form elements hanging around after
// they have been removed from the DOM
// https://github.com/Textalk/angular-schema-form/issues/200
if (childScope) {
// Destroy strategy should not be acted upon
scope.externalDestructionInProgress = true;
childScope.$destroy();
scope.externalDestructionInProgress = false;
}
childScope = scope.$new();
//make the form available to decorators
childScope.schemaForm = {form: merged, schema: schema};
//clean all but pre existing html.
element.children(':not(.schema-form-ignore)').remove();
// Find all slots.
var slots = {};
var slotsFound = element[0].querySelectorAll('*[sf-insert-field]');
for (var i = 0; i < slotsFound.length; i++) {
slots[slotsFound[i].getAttribute('sf-insert-field')] = slotsFound[i];
}
// if sfUseDecorator is undefined the default decorator is used.
var decorator = schemaFormDecorators.decorator(attrs.sfUseDecorator);
// Use the builder to build it and append the result
element[0].appendChild( sfBuilder.build(merged, decorator, slots) );
//compile only children
$compile(element.children())(childScope);
//ok, now that that is done let's set any defaults
if (!scope.options || scope.options.setSchemaDefaults !== false) {
schemaForm.traverseSchema(schema, function(prop, path) {
if (angular.isDefined(prop['default'])) {
var val = sfSelect(path, scope.model);
if (angular.isUndefined(val)) {
sfSelect(path, scope.model, prop['default']);
}
}
});
}
scope.$emit('sf-render-finished', element);
};
//Since we are dependant on up to three
//attributes we'll do a common watch
scope.$watch(function() {
var schema = scope.schema;
var form = scope.initialForm || ['*'];
//The check for schema.type is to ensure that schema is not {}
if (form && schema && schema.type &&
(lastDigest.form !== form || lastDigest.schema !== schema) &&
Object.keys(schema.properties).length > 0) {
lastDigest.schema = schema;
lastDigest.form = form;
render(schema, form);
}
});
// We also listen to the event schemaFormRedraw so you can manually trigger a change if
// part of the form or schema is chnaged without it being a new instance.
scope.$on('schemaFormRedraw', function() {
var schema = scope.schema;
var form = scope.initialForm || ['*'];
if (schema) {
render(schema, form);
}
});
scope.$on('$destroy', function() {
// Each field listens to the $destroy event so that it can remove any value
// from the model if that field is removed from the form. This is the default
// destroy strategy. But if the entire form (or at least the part we're on)
// gets removed, like when routing away to another page, then we definetly want to
// keep the model intact. So therefore we set a flag to tell the others it's time to just
// let it be.
scope.externalDestructionInProgress = true;
});
}
};
}
]);
angular.module('schemaForm').directive('schemaValidate', ['sfValidator', '$parse', 'sfSelect',
function(sfValidator, $parse, sfSelect) {
return {
restrict: 'A',
scope: false,
// We want the link function to be *after* the input directives link function so we get access
// the parsed value, ex. a number instead of a string
priority: 500,
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
// We need the ngModelController on several places,
// most notably for errors.
// So we emit it up to the decorator directive so it can put it on scope.
scope.$emit('schemaFormPropagateNgModelController', ngModel);
var error = null;
// When using the new builder we might not have form just yet
var once = scope.$watch(attrs.schemaValidate, function(form) {
if (!form) {
return;
}
if (form.copyValueTo) {
ngModel.$viewChangeListeners.push(function() {
var paths = form.copyValueTo;
angular.forEach(paths, function(path) {
sfSelect(path, scope.model, ngModel.$modelValue);
});
});
}
// Validate against the schema.
var validate = function(viewValue) {
//Still might be undefined
if (!form) {
return viewValue;
}
// Omit TV4 validation
if (scope.options && scope.options.tv4Validation === false) {
return viewValue;
}
var result = sfValidator.validate(form, viewValue);
// Since we might have different tv4 errors we must clear all
// errors that start with tv4-
Object.keys(ngModel.$error)
.filter(function(k) { return k.indexOf('tv4-') === 0; })
.forEach(function(k) { ngModel.$setValidity(k, true); });
if (!result.valid) {
// it is invalid, return undefined (no model update)
ngModel.$setValidity('tv4-' + result.error.code, false);
error = result.error;
// In Angular 1.3+ return the viewValue, otherwise we inadvertenly
// will trigger a 'parse' error.
// we will stop the model value from updating with our own $validator
// later.
if (ngModel.$validators) {
return viewValue;
}
// Angular 1.2 on the other hand lacks $validators and don't add a 'parse' error.
return undefined;
}
return viewValue;
};
// Custom validators, parsers, formatters etc
if (typeof form.ngModel === 'function') {
form.ngModel(ngModel);
}
['$parsers', '$viewChangeListeners', '$formatters'].forEach(function(attr) {
if (form[attr] && ngModel[attr]) {
form[attr].forEach(function(fn) {
ngModel[attr].push(fn);
});
}
});
['$validators', '$asyncValidators'].forEach(function(attr) {
// Check if our version of angular has validators, i.e. 1.3+
if (form[attr] && ngModel[attr]) {
angular.forEach(form[attr], function(fn, name) {
ngModel[attr][name] = fn;
});
}
});
// Get in last of the parses so the parsed value has the correct type.
// We don't use $validators since we like to set different errors depending tv4 error codes
ngModel.$parsers.push(validate);
// But we do use one custom validator in the case of Angular 1.3 to stop the model from
// updating if we've found an error.
if (ngModel.$validators) {
ngModel.$validators.schemaForm = function() {
// Any error and we're out of here!
return !Object.keys(ngModel.$error).some(function(e) { return e !== 'schemaForm'});
}
}
// Listen to an event so we can validate the input on request
scope.$on('schemaFormValidate', function() {
// We set the viewValue to trigger parsers,
// since modelValue might be empty and validating just that
// might change an existing error to a "required" error message.
if (ngModel.$setDirty) {
// Angular 1.3+
ngModel.$setDirty();
ngModel.$setViewValue(ngModel.$viewValue);
ngModel.$commitViewValue();
// In Angular 1.3 setting undefined as a viewValue does not trigger parsers
// so we need to do a special required check. Fortunately we have $isEmpty
if (form.required && ngModel.$isEmpty(ngModel.$modelValue)) {
ngModel.$setValidity('tv4-302', false);
}
} else {
// Angular 1.2
// In angular 1.2 setting a viewValue of undefined will trigger the parser.
// hence required works.
ngModel.$setViewValue(ngModel.$viewValue);
}
});
scope.schemaError = function() {
return error;
};
// Just watch once.
once();
});
}
};
}]);
return schemaForm;
}));
|
module.exports = {
'/':{
fields: ['apply-uk', 'application-country'],
controller: require('../../../controllers/go-overseas'),
backLink: '/../prototype_oix_171004/startpage',
next: '/../intro', /* if Yes is selected */
nextAlt: 'what-do-you-want-to-do-overseas', /* if they are from Germany/France */
nextAltAlt:'what-do-you-want-to-do-overseas',/* if they are from Afganistan */
nextAltAltAlt:'what-do-you-want-to-do-overseas', /* if they are from Spain - first hidden as renewal */
nextAltAltAltAlt:'../overseas-not-available' /* if they are from Syria - not available */
},
'/what-do-you-want-to-do': {
fields: ['what-to-do'],
backLink: './',
next: '/dob'
},
'/what-do-you-want-to-do-overseas': {
controller: require('../../../controllers/go-overseas'),
fields: ['what-to-do-overseas'],
backLink: './',
next: '/dob',
nextAlt: 'dob-overseas', /* if they are from Germany/France */
nextAltAlt: 'dob-overseas', /* if they are from Afganistan */
nextAltAltAlt: '../overseas-first' /* if they are from Spain - first hidden as renewal */
},
'/dob-overseas': {
fields: ['age-day', 'age-year', 'age-month'],
controller: require('../../../controllers/go-overseas'),
backLink: './',
next: '/../filter', /* if they are from the UK */
nextAlt: '../overseas', /* if they are from Germany/France */
nextAltAlt:'../overseas-not-eligible', /* if they are from Afganistan */
},
'/dob': {
fields: ['age-day', 'age-year', 'age-month'],
controller: require('../../../controllers/go-overseas'),
backLink: './',
next: '/../filter', /* if they are from the UK */
}
};
|
import * as schemas from "../lib/onvif_schemas";
import { curryCMD, getKey } from './utils';
import onvifCMD from './onvifCMD';
/** User's Level **/
const UserLevel = {
0: 'Administrator',
1: 'Operator',
2: 'User',
//3: 'Anonymous',
//4: 'Extended'
}
/**
* GetUsers()
*
* @export
* @returns array [{key, user_name, user_level}]
*/
export const GetUsers =
curryCMD( 'GetUsers', async () => {
let res = await onvifCMD( 'device', 'GetUsers' );
let users = res.User.v;
let datas = [];
users.forEach((user, index) => {
let u = {
key: index,
user_name: user.Username.v,
user_level: getKey( user.UserLevel )
}
datas.push(u);
});
return datas;
});
/**
* CreateUsers()
*
* @export
* @param {key, user_name, user_level} user
*/
export const CreateUsers =
curryCMD( 'CreateUsers', async (arg) => {
let user = arg[0];
let _user = new schemas.tt_User();
_user.Username.v = user.name;
_user.Password.v = user.password;
_user.UserLevel.v = Object.values( UserLevel ).findIndex( (v) => v === user.level );
await onvifCMD( 'device', 'CreateUsers', _user );
});
/**
* SetUser()
*
* @export
* @param {key, user_name, user_level} user
*/
export const SetUser =
curryCMD( 'SetUser', async (arg) => {
let user = arg[0];
let _user = new schemas.tt_User();
_user.Username.v = user.name;
_user.Password.v = user.password;
_user.UserLevel.v = Object.values( UserLevel ).findIndex( (v) => user.level === v );
await onvifCMD( 'device', 'SetUser', _user );
});
/**
* DeleteUsers() by pass user's name.
*
* @export
* @param string userName
*/
export const DeleteUsers =
curryCMD( 'DeleteUsers', async (arg) => {
let userName = new schemas.xsd_string();
userName.v = arg[0];
await onvifCMD( 'device', 'DeleteUsers', userName );
});
/**
* GetDeviceInformation()
*
* @export
* @return object {Model, FirmwareVersion, Manufacturer, SerialNumber, HardwareId}
*/
export const GetDeviceInformation =
curryCMD( 'GetDeviceInformation', async (arg) => {
let res = await onvifCMD( 'device', 'GetDeviceInformation' );
let info = {
Model: res.Model.v,
FirmwareVersion: res.FirmwareVersion.v,
Manufacturer: res.Manufacturer.v,
SerialNumber: res.SerialNumber.v,
HardwareId: res.HardwareId.v
};
return info;
});
/**
* GetHostname()
*
* @export
* @return string hostname
*/
export const GetHostname =
curryCMD( 'GetHostname', async (arg) => {
let res = await onvifCMD( 'device', 'GetHostname' );
let hostname = res.HostnameInformation.Name.v;
return hostname;
});
/**
* SetHostname()
*
* @export
* @param string hostname
*/
export const SetHostname =
curryCMD( 'SetHostname', async (arg) => {
let hostname = arg[0];
await onvifCMD( 'device', 'SetHostname', hostname );
});
/**
* SystemReboot()
*
* @export
*/
export const SystemReboot =
curryCMD( 'SystemReboot', async (arg) => {
await onvifCMD( 'device', 'SystemReboot' );
});
/**
* GetNetworkInterfaces()
*
* @export
* @return object networkinterface
*/
export const GetNetworkInterfaces =
curryCMD( 'GetNetworkInterfaces', async (arg) => {
let res = await onvifCMD( 'device', 'GetNetworkInterfaces' );
let networkinterface = res.NetworkInterfaces.v;
return networkinterface;
});
/**
* GetDiscoveryMode()
*
* @export
* @returns boolean
*/
export const GetDiscoveryMode =
curryCMD( 'GetDiscoveryMode', async (arg) => {
let res = await onvifCMD( 'device', 'GetDiscoveryMode' );
let discoveryMode = res.DiscoveryMode.v;
return discoveryMode === 0 ? true : false;
});
/**
* GetNTP()
*
* @export
* @returns array
*/
export const GetNTP =
curryCMD( 'GetNTP', async (arg) => {
let res = await onvifCMD( 'device', 'GetNTP' );
let ntp = res.NTPInformation;
let info = [];
if ( ntp.FromDHCP.v )
ntp.NTPFromDHCP.v.forEach( (n) => info.push(n) );
else
ntp.NTPManual.v.forEach( (n) => info.push(n) );
return info;
});
/**
* GetDNS()
*
* @export
* @returns array
*/
export const GetDNS =
curryCMD( 'GetDNS', async (arg) => {
let res = await onvifCMD( 'device', 'GetDNS' );
let dns = res.DNSInformation;
let ip_address = [];
if ( dns.FromDHCP.v )
dns.DNSFromDHCP.v.forEach( (d) => ip_address.push(d));
else
dns.DNSManual.v.forEach( (d) => ip_address.push(d));
return ip_address;
});
/**
* GetNetworkProtocols()
*
* @export
* @returns object {[name]: {enable, port[]}}
*/
export const GetNetworkProtocols =
curryCMD( 'GetNetworkProtocols', async (arg) => {
let res = await onvifCMD( 'device', 'GetNetworkProtocols' );
let protocols = {};
res.NetworkProtocols.v.forEach((p) => {
let name = getKey(p.Name);
let ports = [];
p.Port.v.forEach((port) => ports.push(port.v));
protocols[name] = {
enable: p.Enabled.v,
port: ports[0]
};
});
return protocols;
});
/**
* GetSystemDateAndTime()
*
* @export
* @returns object sdt
*/
export const GetSystemDateAndTime =
curryCMD( 'GetSystemDateAndTime', async (arg) => {
let res = await onvifCMD( 'device', 'GetSystemDateAndTime' );
let dt = res.SystemDateAndTime;
let sdt = {
sync_type: getKey(dt.DateTimeType),
daylightSavings: dt.DaylightSavings.v,
tz: dt.TimeZone.TZ.v,
local: new Date(
dt.LocalDateTime.Date.Year.v, // year
dt.LocalDateTime.Date.Month.v, // month
dt.LocalDateTime.Date.Day.v, // day
dt.LocalDateTime.Time.Hour.v, // hour
dt.LocalDateTime.Time.Minute.v, // minute
dt.LocalDateTime.Time.Second.v, // second
),
utc: new Date(
dt.UTCDateTime.Date.Year.v, // year
dt.UTCDateTime.Date.Month.v, // month
dt.UTCDateTime.Date.Day.v, // day
dt.UTCDateTime.Time.Hour.v, // hour
dt.UTCDateTime.Time.Minute.v, // minute
dt.UTCDateTime.Time.Second.v, // second
)
};
return sdt;
});
|
'use strict';
const firstDay = new Date('1900-01-01').getTime();
async function getData(config, callback, meta) {
const { latestDate } = meta;
if (latestDate.getTime() === firstDay) {
return callback([
{
id: 'a'.repeat(2000),
commonID: 'b'.repeat(2000),
modificationDate: new Date(0),
data: { x: 42 }
}
]);
}
return null;
}
module.exports = getData;
|
/* 作者: dailc
* 时间: 2017-06-31
* 描述: Number-of-Digit-One
*
* 来自: https://leetcode.com/problems/number-of-digit-one
*/
(function(exports) {
/**
* @param {number} n
* @return {number}
*/
var countDigitOne = function(n) {
var count = 0;
for (var m = 1; m <= n; m *= 10) {
var divisor = ~~(n / m);
var remainder = n % m;
count += ~~((divisor + 8) / 10) * m;
if (divisor % 10 == 1) {
count += remainder + 1;
}
}
return count;
};
LeetCode.countDigitOne = countDigitOne;
})(window.LeetCode = window.LeetCode || {});
|
'use strict'
module.exports = function (RED) {
// var deviceFW = require('node-red-device-framework')
// var coreHelper = deviceFW.deviceFWHelper
// var Device = coreHelper.Device
// var coreTypes = coreHelper.getDeviceTypesConfig(RED)
// const path = require('path')
// Initialize HTTP Configs
var DNController = require('./deviceNodeController')(RED)
DNController.initHttpRequests()
function DeviceNode (n) {
try {
RED.nodes.createNode(this, n)
var node = this
node.device = null
node.config = n
} catch (e) {
console.log(e)
} finally {
}
node.on('close', function () {
node.device.close()
})
}
RED.nodes.registerType('deviceNode', DeviceNode)
}
|
require([
'app/router',
'dojo/hash'
], function (
router,
hash
) {
describe('app/router', function () {
afterEach(function () {
hash('');
});
describe('setHash', function () {
it('sets the correct URL parameters', function () {
router.setHash({id: 1});
expect(hash()).toContain('id=1');
router.setHash({id: [1, 2, 3]});
expect(hash()).toContain('id=1&id=2&id=3');
});
});
describe('onHashChange', function () {
beforeEach(function () {
spyOn(router, 'onIdsChange');
});
it('updates the properties of the router', function () {
router.onHashChange('id=1');
expect(router.projectIds).toEqual(['1']);
router.onHashChange('id=1&id=2&id=3');
expect(router.projectIds).toEqual(['1', '2', '3']);
router.onHashChange('test=1');
expect(router.projectIds).toEqual([]);
});
it('calls update functions if new values', function () {
router.projectIds = [];
router.onHashChange('id=1');
router.onHashChange('id=1&id=2');
router.onHashChange('id=1');
expect(router.onIdsChange.calls.count()).toBe(3);
});
it('doesn\'t call update if not new values', function () {
router.projectIds = ['1'];
router.onHashChange('id=1');
router.projectIds = ['1', '2'];
router.onHashChange('id=2&id=1');
expect(router.onIdsChange).not.toHaveBeenCalled();
});
});
describe('getProjectIdWhereClause', function () {
it('handles no project id', function () {
router.projectIds = null;
expect(router.getProjectsWhereClause()).toEqual('1=1');
router.projectIds = [];
expect(router.getProjectsWhereClause()).toEqual('1=1');
});
it('handles bad project id', function () {
router.projectIds = 'abcde';
expect(router.getProjectsWhereClause()).toEqual('1=1');
router.projectIds = ['abcde'];
expect(router.getProjectsWhereClause()).toEqual('1=1');
});
it('handles single project id', function () {
router.projectIds = [1];
expect(router.getProjectsWhereClause()).toEqual('Project_ID IN(1)');
});
it('handles multiple project ids', function () {
router.projectIds = [1, 2];
expect(router.getProjectsWhereClause()).toEqual('Project_ID IN(1,2)');
});
it('handles single project id with negate arg', function () {
router.projectIds = [1];
expect(router.getProjectsWhereClause({
negate: false
})).toEqual('Project_ID IN(1)');
});
it('handles multiple project ids with negate arg', function () {
router.projectIds = [1, 2];
expect(router.getProjectsWhereClause({
negate: false
})).toEqual('Project_ID IN(1,2)');
});
it('can negate no project id', function () {
router.projectIds = null;
expect(router.getProjectsWhereClause({
negate: true
})).toEqual('1=1');
});
it('can negate single project id', function () {
router.projectIds = [1];
expect(router.getProjectsWhereClause({
negate: true
})).toEqual('Project_ID NOT IN(1)');
});
it('can negate multiple project ids', function () {
router.projectIds = [1, 2];
expect(router.getProjectsWhereClause({
negate: true
})).toEqual('Project_ID NOT IN(1,2)');
});
});
describe('getProjectId', function () {
it('returns the current project id', function () {
router.projectIds = [2];
expect(router.getProjectId()).toBe(2);
});
it('throws an error if there are multiple or no ids', function () {
router.projectIds = [1, 2];
expect(router.getProjectId.bind(router)).toThrow();
router.projectIds = [];
expect(router.getProjectId.bind(router)).toThrow();
});
});
});
});
|
// Run a batch operation against the Word object model.
Word.run(function (context) {
var ooxmlText = "<w:p xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'>" +
"<w:r><w:rPr><w:b/><w:b-cs/><w:color w:val='FF0000'/><w:sz w:val='28'/><w:sz-cs w:val='28'/>" +
"</w:rPr><w:t>Hello world (this should be bold, red, size 14).</w:t></w:r></w:p>";
// Create a range proxy object for the current selection.
var range = context.document.getSelection();
// Queue a commmand to insert OOXML at the end of the selection.
range.insertOoxml(ooxmlText, Word.InsertLocation.end);
// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('Inserted the OOXML at the end of the selection.');
});
})
.catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
|
import * as angular from 'angular'
import services from '../../../services/services.js'
import * as angularUiRouter from 'angular-ui-router'
const name = 'profile'
angular.module(name, [services, 'ui.router'])
.component(name, {
templateUrl: 'lib/components/user/' + name + '/' + name + '.html',
controller: profileController
})
.config(stateConfig)
function stateConfig($stateProvider) {
$stateProvider
.state(name, {
url: '/' + name,
template: '<' + name + '></' + name + '>'
});
}
function profileController(usersDataService, officesDataService, $state) {
let _this = this
this.offices = officesDataService.gettingOffices()
let init = () => {
usersDataService.gettingUser()
.then(function (user) {
_this.user = user;
})
}
init();
this.selectDelegation = function (safeName) {
this.user.officeSafeName = safeName
console.log(this.user)
}
this.submit = function () {
usersDataService.updatingUser(this.user);
}
}
export default name
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*
* 首页 - 问答
*
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
ScrollView,
Image,
Dimensions,
TouchableOpacity
} from 'react-native';
const { width, height } = Dimensions.get('window');
// cell上部分的高度
var cellTopViewHeight = width/375*200;
// cell下部分的高度
var cellBottomViewHeight = 153;
var localData_hom_hot = require('../LocalData/LocalData_home_hot.json');
import CellItem from '../Component/JYHomeNewCellItem';
// 攻略详情
import StrategyDetails from '../Pages/JYStrategyDetails'
var JYHomeStroll = React.createClass({
getDefaultProps() {
return {
url_api: 'http://api.mglife.me/v2/home/2?offset=0&limit=20',
key_world: 'home_list'
}
},
getInitialState() {
return {
// 下面的列表数据
dataSource: new ListView.DataSource({
rowHasChanged:(row1, row2) => row1 !== row2
}),
}
},
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this._renderRow}
/>
);
},
componentDidMount() {
this._loadDataFromNet();
},
// 获取网络数据
_loadDataFromNet() {
fetch(this.props.url_api)
.then((response) => response.json())
.then(responseData => {
var jsonData = responseData['data'];
this._detailWithData(jsonData);
})
.catch((error) => {
if (error) {
console.log('错误信息:' + error);
var jsonData = localData_hom_hot['data'];
this._detailWithData(jsonData);
}
})
},
// 数据转换
_detailWithData(jsonData) {
// 临时 list列表数据
var tempListDataArr = [];
// 获取首页中的数据
var homeListData = jsonData[this.props.key_world];
// 进行遍历,重组数据
for (var i = 0; i < homeListData.length; i++) {
// 单独的数据
var cellData = homeListData[i];
// 由于请求回来的数据过多这里进行了过滤
if (i > 20) {
break;
}
// 列表数据
tempListDataArr.push(cellData);
}
// 刷新状态
this.setState({
dataSource:this.state.dataSource.cloneWithRows(tempListDataArr)
})
},
// 渲染listVie的单行
_renderRow(rowData) {
var cellPostData = rowData['post'];
console.log(cellPostData);
return (
<View style={styles.cellStyle}>
<TouchableOpacity
style = {styles.cellTopViewStyle}
activeOpacity={0.8}
onPress={()=>{
const { navigator } = this.props;
if(navigator) {
navigator.push({
name: 'StrategyDetails',
component: StrategyDetails,
params: {
id:cellPostData.id
}
})
}
}}
>
{/*cell的上部分背景图*/}
<Image
style={styles.cellTopViewBackImgStyle}
source={{uri:cellPostData.new_cover_image_url}}
/>
{/*cell的上部分背景图上面的文字*/}
<View style={styles.cellTopViewContentStyle}>
{/*channel_icon*/}
<Image
style={{width:27, height:27, bottom:10}}
source={{uri:cellPostData.channel_icon}}
/>
{/*title*/}
<View style={{borderTopWidth:0.5, borderTopColor:'white', borderBottomWidth:0.5, borderBottomColor:'white', padding:5}}>
<Text
style={{color:'white', fontSize:19}}
>{cellPostData.title}</Text>
</View>
<Text
style={{color:'white', fontSize:19, paddingTop:5}}
>[{cellPostData.channel_title}]</Text>
</View>
{/*cell右上角的喜欢数量*/}
<View style={styles.cellLikeCountViewStyle}>
{/*上面的指纹图片*/}
<Image source={require('../Images/Home/icon_post_favorite_21x21_.png')} style={{width:21, height: 21}} />
{/*下面的喜欢数*/}
<Text style={{fontSize:10, color:'white'}}>{cellPostData.likes_count}</Text>
</View>
</TouchableOpacity>
{/*cell下半部分的横向滚动列表*/}
<View style={styles.cellBottomViewStyle}>
<ScrollView
style={{flex:1}}
horizontal={true}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingHorizontal:5}}
>
{this._renderCellBotItems(cellPostData.post_items)}
</ScrollView>
</View>
</View>
)
},
// 渲染cell下半部分的横向滚动
_renderCellBotItems(dataArr){
var cellBotItems = [];
for (var i = 0; i < dataArr.length; i++) {
var itemData = dataArr[i];
cellBotItems.push(
// 自定义的一个item组件
<CellItem
key={i}
topImageSource={itemData.cover_image_url}
title={itemData.name}
priceTitle={itemData.price}
topImageStyle={{height:88, width: 88, borderRadius:10}}
style={{padding: 5}}
navigator={this.props.navigator}
/>
)
}
return cellBotItems;
},
})
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
// cell的样式
cellStyle:{
// backgroundColor:'pink',
borderTopWidth:15,
borderTopColor:'#f5f5f5'
},
// cell的topView
cellTopViewStyle:{
height:cellTopViewHeight,
width:width,
},
// cell的bottomView
cellBottomViewStyle:{
height:cellBottomViewHeight,
width:width,
},
// cell的topView的背景图
cellTopViewBackImgStyle:{
flex:1,
height:cellTopViewHeight,
},
// cell右上角的喜欢数量view
cellLikeCountViewStyle:{
position:'absolute',
alignItems: 'center',
width:35,
height:40,
right:10,
paddingTop:5,
backgroundColor:'rgba(0,0,0,.2)',
borderBottomLeftRadius:5,
borderBottomRightRadius:5,
},
// cell上半部分的背景图上的黑色蒙层及文字信息
cellTopViewContentStyle:{
position:'absolute',
alignItems:'center',
height:cellTopViewHeight,
width:width,
top:0,
left:0,
backgroundColor:'rgba(0,0,0,.2)',
justifyContent:'center'
},
});
module.exports = JYHomeStroll;
|
$.Class('core.Options', function (that) {
var isOpened = false;
var closedElement;
var openedElement;
that.__container = $.Load('$.Dom.Body');
that.__id = 'options';
that.__class = 'closed';
this.__construct = function () {
this.parentCall("__construct", "div");
initClosedElement();
initOpenedElement();
};
this.toggle = function() {
isOpened ? this.close() : this.open();
return this;
};
this.close = function() {
isOpened = false;
closedElement.addStyle('display', null);
openedElement.addStyle('display', 'none');
this.removeClass('opened').addClass('closed');
};
this.open = function() {
isOpened = true;
closedElement.addStyle('display', 'none');
openedElement.addStyle('display', null);
this.removeClass('closed').addClass('opened');
};
var initClosedElement = (function() {
closedElement = $.Load('$.Dom.Element', 'a');
closedElement.text('options');
closedElement.addEvent('click', this.open, this);
this.appendChild(closedElement);
}).bind(this);
var initOpenedElement = (function() {
openedElement = $.Load('$.Dom.Element', 'div');
openedElement.addStyle('display', 'none');
var closeButton = $.Load('$.Dom.Element', 'a');
closeButton.text('Close options');
closeButton.addEvent('click', this.close, this);
openedElement.appendChild(closeButton);
openedElement.appendChild($.Load('core.Options.ToggleSoldiers'));
this.appendChild(openedElement);
}).bind(this);
}).Extend('$.Dom.Element');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.