code stringlengths 2 1.05M |
|---|
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('personas'); |
'use strict';
var namespace = 'main';
var angular = require('angular');
var app = angular.module(namespace, [
// inject:modules start
require('./layouts')(namespace).name
// inject:modules end
]);
var runDeps = [];
var run = function() {
};
run.$inject = runDeps;
app.run(run);
module.exports = app; |
/* globals createPatchedLoad, normalizePath */
describe('adapter requirejs', function () {
var load
var originalLoadSpy
var karma
beforeEach(function () {
spyOn(console, 'error')
karma = {
files: {
'/base/some/file.js': '12345'
},
config: {}
}
originalLoadSpy = jasmine.createSpy('requirejs.load')
load = createPatchedLoad(karma, originalLoadSpy, '/')
})
it('should add timestamp', function () {
load('context', 'module', '/base/some/file.js')
expect(originalLoadSpy).toHaveBeenCalled()
expect(originalLoadSpy.calls.mostRecent().args[2]).toBe('/base/some/file.js?12345')
})
it('should not append timestamp if not found', function () {
load('context', 'module', '/base/other/file.js')
expect(originalLoadSpy).toHaveBeenCalled()
expect(originalLoadSpy.calls.mostRecent().args[2]).toBe('/base/other/file.js')
})
it('should not append timestamp when running in debug mode', function () {
load = createPatchedLoad(karma, originalLoadSpy, '/debug.html')
load(null, null, '/base/some/file.js')
expect(originalLoadSpy).toHaveBeenCalled()
expect(originalLoadSpy.calls.mostRecent().args[2]).toBe('/base/some/file.js')
})
it('should ignore when config.requireJsShowNoTimestampsError is a RegExp string and does not match', function () {
karma.config.requireJsShowNoTimestampsError = '^(?!.*/base/other/file\\.js)'
load = createPatchedLoad(karma, originalLoadSpy, '/')
load('context', 'module', '/base/other/file.js')
expect(console.error).not.toHaveBeenCalled()
})
it('should ignore when config.requireJsShowNoTimestampsError exists and is falsy', function () {
karma.config.requireJsShowNoTimestampsError = false
load = createPatchedLoad(karma, originalLoadSpy, '/')
load('context', 'module', '/base/other/file.js')
expect(console.error).not.toHaveBeenCalled()
})
it('should ignore absolute paths with domains', function () {
load('context', 'module', 'http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js')
expect(console.error).not.toHaveBeenCalled()
})
it('should log errors when the file is not found', function () {
load('context', 'module', '/base/other/file.js')
expect(console.error).toHaveBeenCalled()
expect(console.error.calls.mostRecent().args[0]).toMatch(/^There is no timestamp for /)
})
describe('normalizePath', function () {
it('should normalize . and .. in the path', function () {
expect(normalizePath('/base/a/../b/./../x.js')).toBe('/base/x.js')
})
it('should log errors when the file is not found', function () {
load('context', 'module', '/base/other/file.js')
expect(console.error).toHaveBeenCalled()
expect(console.error.calls.mostRecent().args[0]).toMatch(/^There is no timestamp for /)
})
describe('normalizePath', function () {
it('should normalize . and .. in the path', function () {
expect(normalizePath('/base/a/../b/./../x.js')).toBe('/base/x.js')
})
it('should preserve .. in the beginning of the path', function () {
expect(normalizePath('../../a/file.js')).toBe('../../a/file.js')
})
it('should remove query parameters', function () {
expect(normalizePath('/base/a/../b/./../x.js?noext=1')).toBe('/base/x.js')
expect(normalizePath('../../a/file.js?noext=1')).toBe('../../a/file.js')
expect(normalizePath('/base/a.js?noext=1')).toEqual('/base/a.js')
})
})
})
})
|
"use strict";
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
var System = require("pid-system");
module.exports.main = function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee() {
var _ref2, _ref3, db, otherDb, options, returnPid, error, doc;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return System.receive(this);
case 2:
_ref2 = _context.sent;
_ref3 = _slicedToArray(_ref2, 4);
db = _ref3[0];
otherDb = _ref3[1];
options = _ref3[2];
returnPid = _ref3[3];
error = null;
_context.next = 11;
return db.fullyReplicateFrom(otherDb, options).catch(function (err) {
error = err;
});
case 11:
doc = _context.sent;
if (doc) {
System.send(returnPid, ["OK", doc]);
} else if (error) {
System.send(returnPid, ["ERR", error.name, error.message]);
}
case 13:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function main() {
return _ref.apply(this, arguments);
}
return main;
}(); |
'use strict';
angular.module('module.core').filter('inDuration', function () {
function isNumeric(str) {
return !isNaN(str);
}
function pad(num) {
if (isNumeric(num)) {
num = parseInt(num);
if (num < 10) {
num = "0" + num;
}
}
return num;
}
return function (input) {
var ms, seconds, minutes, hours;
ms = seconds = minutes = hours = 0;
ms = input;
if (ms > 1000) {
seconds = Math.floor(ms / 1000);
ms -= (seconds * 1000);
}
if (seconds > 60) {
minutes = Math.floor(seconds / 60);
seconds -= (minutes * 60);
}
if (minutes > 60) {
hours = Math.floor(minutes / 60);
minutes -= (hours * 60);
}
return "00:" + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + ":" + pad(String(parseInt(ms)).substr(0, 2));
};
});
|
import { Dispatcher } from 'flux'
const instance = new Dispatcher()
export default instance
export const dispatch = instance.dispatch.bind(instance)
|
const Yoga = require('../src/dist/entry-browser');
describe('Absloute position', () => {
test('absolute layout width height start to', () => {
const root = Yoga.Node.create();
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_START, 10);
child.setPosition(Yoga.EDGE_TOP, 10);
child.setWidth(10);
child.setHeight(10);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
});
test('absolute layout width height end bottom', () => {
const root = Yoga.Node.create();
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_END, 10);
child.setPosition(Yoga.EDGE_BOTTOM, 10);
child.setWidth(10);
child.setHeight(10);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(80);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(80);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
});
test('absolute layout start top end bottom', () => {
const root = Yoga.Node.create();
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_START, 10);
child.setPosition(Yoga.EDGE_TOP, 10);
child.setPosition(Yoga.EDGE_END, 10);
child.setPosition(Yoga.EDGE_BOTTOM, 10);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(80);
expect(child.getComputedLayout().height).toEqual(80);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(80);
expect(child.getComputedLayout().height).toEqual(80);
});
test('absolute layout width height start top end bottom', () => {
const root = Yoga.Node.create();
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_START, 10);
child.setPosition(Yoga.EDGE_TOP, 10);
child.setPosition(Yoga.EDGE_END, 10);
child.setPosition(Yoga.EDGE_BOTTOM, 10);
child.setWidth(10);
child.setHeight(10);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
});
test('do not clamp height of absolute node to height of its overflow hidden parent', () => {
const root = Yoga.Node.create();
root.setFlexDirection(Yoga.FLEX_DIRECTION_ROW);
root.setOverflow(Yoga.OVERFLOW_HIDDEN);
root.setWidth(50);
root.setHeight(50);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_START, 0);
child.setPosition(Yoga.EDGE_TOP, 0);
root.insertChild(child, 0);
const childChild = Yoga.Node.create();
childChild.setWidth(100);
childChild.setHeight(100);
child.insertChild(childChild, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(50);
expect(root.getComputedLayout().height).toEqual(50);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(100);
expect(child.getComputedLayout().height).toEqual(100);
expect(childChild.getComputedLayout().left).toEqual(0);
expect(childChild.getComputedLayout().top).toEqual(0);
expect(childChild.getComputedLayout().width).toEqual(100);
expect(childChild.getComputedLayout().height).toEqual(100);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(50);
expect(root.getComputedLayout().height).toEqual(50);
expect(child.getComputedLayout().left).toEqual(-50);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(100);
expect(child.getComputedLayout().height).toEqual(100);
expect(childChild.getComputedLayout().left).toEqual(0);
expect(childChild.getComputedLayout().top).toEqual(0);
expect(childChild.getComputedLayout().width).toEqual(100);
expect(childChild.getComputedLayout().height).toEqual(100);
});
test('absolute layout within border', () => {
const root = Yoga.Node.create();
root.setMargin(Yoga.EDGE_LEFT, 10);
root.setMargin(Yoga.EDGE_TOP, 10);
root.setMargin(Yoga.EDGE_RIGHT, 10);
root.setMargin(Yoga.EDGE_BOTTOM, 10);
root.setPadding(Yoga.EDGE_LEFT, 10);
root.setPadding(Yoga.EDGE_TOP, 10);
root.setPadding(Yoga.EDGE_RIGHT, 10);
root.setPadding(Yoga.EDGE_BOTTOM, 10);
root.setBorder(Yoga.EDGE_LEFT, 10);
root.setBorder(Yoga.EDGE_TOP, 10);
root.setBorder(Yoga.EDGE_RIGHT, 10);
root.setBorder(Yoga.EDGE_BOTTOM, 10);
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_LEFT, 0);
child.setPosition(Yoga.EDGE_TOP, 0);
child.setWidth(50);
child.setHeight(50);
root.insertChild(child, 0);
const child2 = Yoga.Node.create();
child2.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child2.setPosition(Yoga.EDGE_RIGHT, 0);
child2.setPosition(Yoga.EDGE_BOTTOM, 0);
child2.setWidth(50);
child2.setHeight(50);
root.insertChild(child2, 1);
const child3 = Yoga.Node.create();
child3.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child3.setPosition(Yoga.EDGE_LEFT, 0);
child3.setPosition(Yoga.EDGE_TOP, 0);
child3.setMargin(Yoga.EDGE_LEFT, 10);
child3.setMargin(Yoga.EDGE_TOP, 10);
child3.setMargin(Yoga.EDGE_RIGHT, 10);
child3.setMargin(Yoga.EDGE_BOTTOM, 10);
child3.setWidth(50);
child3.setHeight(50);
root.insertChild(child3, 2);
const child4 = Yoga.Node.create();
child4.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child4.setPosition(Yoga.EDGE_RIGHT, 0);
child4.setPosition(Yoga.EDGE_BOTTOM, 0);
child4.setMargin(Yoga.EDGE_LEFT, 10);
child4.setMargin(Yoga.EDGE_TOP, 10);
child4.setMargin(Yoga.EDGE_RIGHT, 10);
child4.setMargin(Yoga.EDGE_BOTTOM, 10);
child4.setWidth(50);
child4.setHeight(50);
root.insertChild(child4, 3);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(10);
expect(root.getComputedLayout().top).toEqual(10);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(50);
expect(child.getComputedLayout().height).toEqual(50);
expect(child2.getComputedLayout().left).toEqual(40);
expect(child2.getComputedLayout().top).toEqual(40);
expect(child2.getComputedLayout().width).toEqual(50);
expect(child2.getComputedLayout().height).toEqual(50);
expect(child3.getComputedLayout().left).toEqual(20);
expect(child3.getComputedLayout().top).toEqual(20);
expect(child3.getComputedLayout().width).toEqual(50);
expect(child3.getComputedLayout().height).toEqual(50);
expect(child4.getComputedLayout().left).toEqual(30);
expect(child4.getComputedLayout().top).toEqual(30);
expect(child4.getComputedLayout().width).toEqual(50);
expect(child4.getComputedLayout().height).toEqual(50);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(10);
expect(root.getComputedLayout().top).toEqual(10);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(10);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(50);
expect(child.getComputedLayout().height).toEqual(50);
expect(child2.getComputedLayout().left).toEqual(40);
expect(child2.getComputedLayout().top).toEqual(40);
expect(child2.getComputedLayout().width).toEqual(50);
expect(child2.getComputedLayout().height).toEqual(50);
expect(child3.getComputedLayout().left).toEqual(20);
expect(child3.getComputedLayout().top).toEqual(20);
expect(child3.getComputedLayout().width).toEqual(50);
expect(child3.getComputedLayout().height).toEqual(50);
expect(child4.getComputedLayout().left).toEqual(30);
expect(child4.getComputedLayout().top).toEqual(30);
expect(child4.getComputedLayout().width).toEqual(50);
expect(child4.getComputedLayout().height).toEqual(50);
});
test('absolute layout align items and justify content center', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items and justify content flex end', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_FLEX_END);
root.setAlignItems(Yoga.ALIGN_FLEX_END);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(50);
expect(child.getComputedLayout().top).toEqual(60);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(60);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout justify content center', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(50);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items center', () => {
const root = Yoga.Node.create();
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items center on child only', () => {
const root = Yoga.Node.create();
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setAlignSelf(Yoga.ALIGN_CENTER);
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items and justify content center and top position', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_TOP, 10);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(10);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items and justify content center and bottom position', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_BOTTOM, 10);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(50);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(25);
expect(child.getComputedLayout().top).toEqual(50);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items and justify content center and left position', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_LEFT, 5);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(5);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(5);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('absolute layout align items and justify content center and right position', () => {
const root = Yoga.Node.create();
root.setJustifyContent(Yoga.JUSTIFY_CENTER);
root.setAlignItems(Yoga.ALIGN_CENTER);
root.setFlexGrow(1);
root.setWidth(110);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPosition(Yoga.EDGE_RIGHT, 5);
child.setWidth(60);
child.setHeight(40);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(45);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(110);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(45);
expect(child.getComputedLayout().top).toEqual(30);
expect(child.getComputedLayout().width).toEqual(60);
expect(child.getComputedLayout().height).toEqual(40);
});
test('position root with rtl should position withoutdirection', () => {
const root = Yoga.Node.create();
root.setPosition(Yoga.EDGE_LEFT, 72);
root.setWidth(52);
root.setHeight(52);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(72);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(52);
expect(root.getComputedLayout().height).toEqual(52);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(72);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(52);
expect(root.getComputedLayout().height).toEqual(52);
});
test('absolute layout percentage bottom based on parent height', () => {
const root = Yoga.Node.create();
root.setWidth(100);
root.setHeight(200);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setPositionPercent(Yoga.EDGE_TOP, 50);
child.setWidth(10);
child.setHeight(10);
root.insertChild(child, 0);
const child2 = Yoga.Node.create();
child2.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child2.setPositionPercent(Yoga.EDGE_BOTTOM, 50);
child2.setWidth(10);
child2.setHeight(10);
root.insertChild(child2, 1);
const child3 = Yoga.Node.create();
child3.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child3.setPositionPercent(Yoga.EDGE_TOP, 10);
child3.setPositionPercent(Yoga.EDGE_BOTTOM, 10);
child3.setWidth(10);
root.insertChild(child3, 2);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(200);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(100);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
expect(child2.getComputedLayout().left).toEqual(0);
expect(child2.getComputedLayout().top).toEqual(90);
expect(child2.getComputedLayout().width).toEqual(10);
expect(child2.getComputedLayout().height).toEqual(10);
expect(child3.getComputedLayout().left).toEqual(0);
expect(child3.getComputedLayout().top).toEqual(20);
expect(child3.getComputedLayout().width).toEqual(10);
expect(child3.getComputedLayout().height).toEqual(160);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(200);
expect(child.getComputedLayout().left).toEqual(90);
expect(child.getComputedLayout().top).toEqual(100);
expect(child.getComputedLayout().width).toEqual(10);
expect(child.getComputedLayout().height).toEqual(10);
expect(child2.getComputedLayout().left).toEqual(90);
expect(child2.getComputedLayout().top).toEqual(90);
expect(child2.getComputedLayout().width).toEqual(10);
expect(child2.getComputedLayout().height).toEqual(10);
expect(child3.getComputedLayout().left).toEqual(90);
expect(child3.getComputedLayout().top).toEqual(20);
expect(child3.getComputedLayout().width).toEqual(10);
expect(child3.getComputedLayout().height).toEqual(160);
});
test('absolute layout in wrap reverse column container', () => {
const root = Yoga.Node.create();
root.setFlexWrap(Yoga.WRAP_WRAP_REVERSE);
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(20);
child.setHeight(20);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
});
test('absolute layout in wrap reverse row container', () => {
const root = Yoga.Node.create();
root.setFlexDirection(Yoga.FLEX_DIRECTION_ROW);
root.setFlexWrap(Yoga.WRAP_WRAP_REVERSE);
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(20);
child.setHeight(20);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(80);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(80);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
});
test('absolute layout in wrap reverse column container flex end', () => {
const root = Yoga.Node.create();
root.setFlexWrap(Yoga.WRAP_WRAP_REVERSE);
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setAlignSelf(Yoga.ALIGN_FLEX_END);
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(20);
child.setHeight(20);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
});
test('absolute layout in wrap reverse row container flex end', () => {
const root = Yoga.Node.create();
root.setFlexDirection(Yoga.FLEX_DIRECTION_ROW);
root.setFlexWrap(Yoga.WRAP_WRAP_REVERSE);
root.setWidth(100);
root.setHeight(100);
const child = Yoga.Node.create();
child.setAlignSelf(Yoga.ALIGN_FLEX_END);
child.setPositionType(Yoga.POSITION_TYPE_ABSOLUTE);
child.setWidth(20);
child.setHeight(20);
root.insertChild(child, 0);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_LTR);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(0);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
root.calculateLayout(undefined, undefined, Yoga.DIRECTION_RTL);
expect(root.getComputedLayout().left).toEqual(0);
expect(root.getComputedLayout().top).toEqual(0);
expect(root.getComputedLayout().width).toEqual(100);
expect(root.getComputedLayout().height).toEqual(100);
expect(child.getComputedLayout().left).toEqual(80);
expect(child.getComputedLayout().top).toEqual(0);
expect(child.getComputedLayout().width).toEqual(20);
expect(child.getComputedLayout().height).toEqual(20);
});
});
|
import React from 'react'
import styled from 'styled-components'
const Row = styled.div`
display: flex;
flex-direction: row;
border-bottom: 1px solid #ccc;
padding-bottom: 2.5em;
margin-bottom: 3em;
`
const Left = styled.div`
width: 66%;
`
const Right = styled.div`
display: flex;
flex-direction: column;
`
const Name = styled.h1`
font-size: 48px;
text-transform: uppercase;
letter-spacing: 3px;
font-weight: 500;
`
const Title = styled.h2`
text-transform: uppercase;
letter-spacing: 2px;
font-style: italic;
margin-top: 10px;
`
const Item = styled.span`
line-height: 1.3em;
font-size: 16px;
letter-spacing: 1px;
`
function About() {
return (
<Row>
<Left>
<Name>Robson Gian Perassoli</Name>
<Title>Software Engineer</Title>
</Left>
<Right>
<Item>
<a href='mailto:robsonperassoli@gmail.com'>robsonperassoli@gmail.com</a>
</Item>
<Item>+55 (49) 98853-5294</Item>
<br/>
<Item>
<a href='http://robsonperassoli.com.br'>robsonperassoli.com.br</a>
</Item>
<Item>
<a href='https://github.com/robsonperassoli'>github.com/robsonperassoli</a>
</Item>
<Item>
<a href='https://www.linkedin.com/in/robsonperassoli/'>linkedin.com/in/robsonperassoli</a>
</Item>
</Right>
</Row>
)
}
export default About
|
import styled from 'styled-components';
import {Link} from 'react-router'
const StyledLink = styled(Link)`
text-decoration: none;
color: #666;
font-size:1.2em;
margin-left:0.5em;
margin-right:0.5em;
@media all and (max-width: 800px) {
text-align: center;
padding: 10px;
}
`;
export default StyledLink; |
import React from 'react'
import { LinkContainer } from 'react-router-bootstrap'
import {Button} from 'react-bootstrap'
export default class AboutPage extends React.Component {
render() {
return (
<div className="container">
<img className="img-responsive pull-right" alt="Joachim Schirrmacher" src="/img/team/Joachim-Schirrmacher.jpg"/>
<h2>Joachim Schirrmacher</h2>
<p>
Eine Begegnung mit Freunden brachte mich auf den Gedanken, etwas tun zu müssen. Als wir über
das Thema Flüchtlinge sprachen, war mir klar, dass die Behauptungen, die ich hörte, nicht stimmen
konnten. Ohne stichhaltige Belege fühlte ich mich mit meinen Gegenargumenten zu schwach.
</p>
<p>
Als Software-Entwickler bin ich eher rational, das Post-Faktische ist mir total fremdartig, auch
wenn ich jetzt immer wieder damit konfrontiert werde. Aber mit meinen Fähigkeiten kann ich dennoch
einen Unterschied machen. Wenn ich eine Möglichkeit schaffe, Menschen wie mir einen Rückhalt zu
geben, eine leicht erreichbare Hilfestellung, dann wäre das ein Unterschied.
</p>
<p>
Daher reifte die Idee einer Smartphone-App, mit der ich jederzeit eine Aussage prüfen kann,
Belege und Quellen finde. Das hilft mir in der Diskussion und bringt sie vom Post-Faktischen
in die Realität zurück.
</p>
<p>
Gut, dass es Menschen gibt, die mich dabei unterstützen.
</p>
<LinkContainer to="/apply" className="pull-right">
<Button bsSize="large" bsStyle="primary">Mitmachen</Button>
</LinkContainer>
</div>
)
}
}
|
import '../components/common/Header.jsx';
import '../components/common/Layout.jsx';
import '../components/pics/PicsDetails.jsx';
import '../components/pics/PicsEditForm.jsx';
import '../components/pics/PicsHome.jsx';
import '../components/pics/PicsItem.jsx';
import '../components/pics/PicsList.jsx';
import '../components/pics/PicsNewForm.jsx';
|
import {delay} from './delay'
import {ifElseAsync} from './ifElseAsync'
test('arity of 1 - condition is async', async () => {
const condition = async x => {
await delay(100)
return x > 4
}
const whenTrue = x => x + 1
const whenFalse = x => x + 10
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(5), fn(1)])
expect(result).toEqual([6, 11])
})
test('arity of 1 - condition is sync', async () => {
const condition = x => x > 4
const whenTrue = async x => {
await delay(100)
return x + 1
}
const whenFalse = async x => {
await delay(100)
return x + 10
}
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(5), fn(1)])
expect(result).toEqual([6, 11])
})
test('arity of 1 - all inputs are async', async () => {
const condition = async x => {
await delay(100)
return x > 4
}
const whenTrue = async x => {
await delay(100)
return x + 1
}
const whenFalse = async x => {
await delay(100)
return x + 10
}
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(5), fn(1)])
expect(result).toEqual([6, 11])
})
test('arity of 2 - condition is async', async () => {
const condition = async (x, y) => {
await delay(100)
return x + y > 4
}
const whenTrue = (x, y) => x + y + 1
const whenFalse = (x, y) => x + y + 10
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(14, 20), fn(1, 3)])
expect(result).toEqual([35, 14])
})
test('arity of 2 - condition is sync', async () => {
const condition = (x, y) => x + y > 4
const whenTrue = async (x, y) => {
await delay(100)
return x + y + 1
}
const whenFalse = async (x, y) => {
await delay(100)
return x + y + 10
}
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(14, 20), fn(1, 3)])
expect(result).toEqual([35, 14])
})
test('arity of 2 - all inputs are async', async () => {
const condition = async (x, y) => {
await delay(100)
return x + y > 4
}
const whenTrue = async (x, y) => {
await delay(100)
return x + y + 1
}
const whenFalse = async (x, y) => {
await delay(100)
return x + y + 10
}
const fn = ifElseAsync(condition, whenTrue, whenFalse)
const result = await Promise.all([fn(14, 20), fn(1, 3)])
expect(result).toEqual([35, 14])
})
|
export default function factory($) {
return function task(done) {
return $.git.push('origin', null, { args: '--tags' }, (err) => {
done(err);
});
};
}
|
// Built-in modifiers
import CountModifiers from './CountModifier';
import GenderModifier from './GenderModifier';
import IfModifier from './IfModifier';
import PluralModifier from './PluralModifier';
import DateModifier from './DateModifier';
import DateTimeModifier from './DateTimeModifier';
import TimeModifier from './TimeModifier';
import NumberModifier from './NumberModifier';
import PriceModifier from './PriceModifier';
export default [
new CountModifiers(),
new GenderModifier(),
new IfModifier(),
new PluralModifier(),
new DateModifier(),
new DateTimeModifier(),
new TimeModifier(),
new NumberModifier(),
new PriceModifier()
]; |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateDocs = void 0;
const fs_1 = require("fs");
const path = require("path");
const markdown_pipeline_1 = require("markdown-pipeline");
const DeclarationFileParser_1 = require("./DeclarationFileParser");
const MiscContent_1 = require("./MiscContent");
const PageGenerator_1 = require("./PageGenerator");
/** Helper function to compress search content using a very simple string-based algorithm */
function compressContent(content) {
let words = [];
let ref = Object.create(null);
let str = content.join("+").replace(/\w+/g, (word) => {
if (word in ref) {
// if seen: move word to the front of the stack, insert old position
let idx = ref[word];
words.unshift(words.splice(idx, 1)[0]);
for (let i = idx; i >= 0; i--)
ref[words[i]] = i;
return idx;
}
else {
// add new word to the front of the stack, insert word itself
words.unshift(word);
for (let w in ref)
ref[w]++;
ref[word] = 0;
return word;
}
});
// replace most common patterns with single chars
str = str
.replace(/\|3\#0\:3\:3\+2\.2/g, "*")
.replace(/\|2\#0\:2\+1/g, "?")
.replace(/\|2\#0\:2\+/g, "!")
.replace(/\|1\+/g, "=");
return str;
// Decompression algorithm is the reverse:
// let inflate = (str: string) => {
// let w2: string[] = [];
// return str
// .replace(/\=/g, "|1+")
// .replace(/\!/g, "|2#0:2+")
// .replace(/\?/g, "|2#0:2+1")
// .replace(/\*/g, "|3#0:3:3+2.2")
// .replace(/(\d+)|\w+/g, (w, n) => {
// if (n) w = w2.splice(n, 1)[0];
// w2.unshift(w);
// return w;
// });
// }
// console.log(inflate(str).split("+").join("\n"));
}
/** Process given source and add documentation pages to the pipeline */
function generateDocs(pipeline, config) {
let packagePath = path.join(__dirname, "../../node_modules", config.module);
let packageJSON = fs_1.readFileSync(path.join(packagePath, "package.json")).toString();
let packageInfo = JSON.parse(packageJSON);
// read declaration files and parse their types/JSDoc
let parser = new DeclarationFileParser_1.DeclarationFileParser(path.join(packagePath, packageInfo.typings));
// generate a plain list of IDs, types, and links
let index = parser.getPageData();
let content = [];
for (let node of index) {
for (let c of node.content) {
if (c.spec.deprecated)
continue;
if (c.id.endsWith(".") || c.spec.inherited)
continue;
let path = node.id.replace(/\W/g, "_") +
(c.id.indexOf(".") < 0 ? "" : "#" + c.id.replace(/[\.\@\[\]]/g, ":"));
content.push(c.id + "|" + c.spec.type + "|" + path);
}
}
content.sort((a, b) => (a === b ? 0 : a > b ? 1 : -1));
let jsonItem = new markdown_pipeline_1.Pipeline.Item("@symbols");
jsonItem.output.push({
path: config.json_out,
data: JSON.stringify({
version: packageInfo.version,
content: compressContent(content),
}),
});
pipeline.add(jsonItem);
// parse miscellaneous content and generate all content pages
let misc = new MiscContent_1.MiscContent();
misc.readDir(config.misc_path);
for (let page of index) {
let pg = new PageGenerator_1.PageGenerator(page, parser, misc, config.template, config.base_url);
let content = pg.generate();
let id = page.id.replace(/\W/g, "_");
if (content.length) {
if (pg.data.alias) {
pg.data.alias = path.join(config.out, pg.data.alias + ".html");
}
pipeline.add(new markdown_pipeline_1.Pipeline.Item(path.join(config.out, id), content, pg.data));
}
}
}
exports.generateDocs = generateDocs;
|
'use strict';
/**
* test whether the given variable is a plain object
* @param {Object} obj - variable to be checked
* @returns {Boolean}
*/
function isPlainObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]' &&
Object.getPrototypeOf(obj) === Object.prototype;
}
module.exports = isPlainObject; |
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.0.6 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
* Available via the MIT or new BSD license.
* see: http://github.com/jrburke/requirejs for details
*/
//Not using strict: uneven strict support in browsers, #392, and causes
//problems with requirejs.exec()/transpiler plugins that may not be strict.
/*jslint regexp: true, nomen: true, sloppy: true */
/*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.0.6',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
ap = Array.prototype,
aps = ap.slice,
apsp = ap.splice,
isBrowser = !!(typeof window !== 'undefined' && navigator && document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
* This is not robust in IE for transferring methods that match
* Object.prototype names, but the uses of mixin here seem unlikely to
* trigger a problem related to that.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value !== 'string') {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
//Allow getting a global that expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
function makeContextModuleFunc(func, relMap, enableBuildCallback) {
return function () {
//A version of a require function that passes a moduleName
//value for items that may need to
//look up paths relative to the moduleName
var args = aps.call(arguments, 0), lastArg;
if (enableBuildCallback &&
isFunction((lastArg = args[args.length - 1]))) {
lastArg.__requireJsBuild = true;
}
args.push(relMap);
return func.apply(null, args);
};
}
function addRequireMethods(req, context, relMap) {
each([
['toUrl'],
['undef'],
['defined', 'requireDefined'],
['specified', 'requireSpecified']
], function (item) {
var prop = item[1] || item[0];
req[item[0]] = context ? makeContextModuleFunc(context[prop], relMap) :
//If no context, then use default context. Reference from
//contexts instead of early binding to default context, so
//that during builds, the latest instance of the default
//context with its config gets used.
function () {
var ctx = contexts[defContextName];
return ctx[prop].apply(ctx, arguments);
};
});
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite and existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
waitSeconds: 7,
baseUrl: './',
paths: {},
pkgs: {},
shim: {}
},
registry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
requireCounter = 1,
unnormalizedCounter = 1,
//Used to track the order in which modules
//should be executed, by the order they
//load. Important for consistent cycle resolution
//behavior.
waitAry = [];
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; ary[i]; i += 1) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts,
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
if (config.pkgs[baseName]) {
//If the baseName is a package name, then just treat it as one
//name to concat the name with.
normalizedBaseParts = baseParts = [baseName];
} else {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
}
name = normalizedBaseParts.concat(name.split('/'));
trimDots(name);
//Some use of packages may use a . path to reference the
//'main' module name, so normalize for that.
pkgConfig = config.pkgs[(pkgName = name[0])];
name = name.join('/');
if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
name = pkgName;
}
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if (applyMap && (baseParts || starMap) && map) {
nameParts = name.split('/');
for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = map[baseParts.slice(0, j).join('/')];
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = mapValue[nameSegment];
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break;
}
}
}
}
if (foundMap) {
break;
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && starMap[nameSegment]) {
foundStarMap = starMap[nameSegment];
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
return name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = config.paths[id];
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
removeScript(id);
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.undef(id);
context.require([id]);
return true;
}
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix,
index = name ? name.indexOf('!') : -1,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
if (index !== -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = defined[prefix];
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
normalizedName = normalize(name, parentName, applyMap);
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = registry[id];
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = registry[id];
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
getModule(depMap).on(name, fn);
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = registry[id];
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length - 1, 0].concat(globalDefQueue));
globalDefQueue = [];
}
}
/**
* Helper function that creates a require function object to give to
* modules that ask for it as a dependency. It needs to be specific
* per module because of the implication of path mappings that may
* need to be relative to the module name.
*/
function makeRequire(mod, enableBuildCallback, altRequire) {
var relMap = mod && mod.map,
modRequire = makeContextModuleFunc(altRequire || context.require,
relMap,
enableBuildCallback);
addRequireMethods(modRequire, context, relMap);
modRequire.isBrowser = isBrowser;
return modRequire;
}
handlers = {
'require': function (mod) {
return makeRequire(mod);
},
'exports': function (mod) {
mod.usingExports = |
(() => {
'use strict';
angular
.module('app')
.controller('ApproveUserUpdateModalController', ApproveUserUpdateModalController);
function ApproveUserUpdateModalController (originalUser, modifiedUser, NotificationService, $uibModalInstance, UserFactory, PublicInfoFactory, $routeSegment, Ranks, Constants) {
const vm = this;
const confirmDeleteModal = '#ConfirmDelete';
vm.originalUser = {};
vm.tempUser = angular.copy(modifiedUser);
vm.modifiedUser = angular.copy(modifiedUser);
vm.changeCountry = changeCountry;
vm.changeRegion = changeRegion;
vm.changeCity = changeCity;
vm.changePlatoon = changePlatoon;
vm.setSections = setSections;
vm.approveUser = approveUser;
vm.declineUser = declineUser;
vm.showConfirmDecline = showConfirmDecline;
vm.close = close;
activate();
///
function activate() {
if (originalUser && originalUser.success) {
vm.originalUser = originalUser.data;
vm.originalUser.stringGender = Constants.GENDER[originalUser.data.gender];
vm.originalUser.stringRank = Ranks[originalUser.data.userRank];
}
setCountries();
setRegions(vm.modifiedUser.country.id);
setCities(vm.modifiedUser.region.id);
setPlatoons(vm.modifiedUser.city.id);
setSections(vm.modifiedUser.platoon.id);
setRanks();
}
function approveUser() {
NotificationService.info('Користувач ' + vm.modifiedUser.firstName + ' ' +
vm.modifiedUser.lastName + ' підтверджується...');
let valuesToSend = {
firstName: vm.modifiedUser.firstName,
lastName: vm.modifiedUser.lastName,
gender: vm.modifiedUser.gender,
userAgeGroup: vm.modifiedUser.userAgeGroup,
telephoneNumber: vm.modifiedUser.telephoneNumber,
birthDate: +moment(vm.modifiedUser.birthDate),
countryId: vm.modifiedUser && vm.modifiedUser.country.id,
regionId: vm.modifiedUser && vm.modifiedUser.region.id,
cityId: vm.modifiedUser && vm.modifiedUser.city.id,
platoonId: vm.modifiedUser && vm.modifiedUser.platoon.id,
sectionId: vm.modifiedUser && vm.modifiedUser.section.id,
userRank: vm.modifiedUser.userRank
};
UserFactory.approveUpdateUser({temp_userId: vm.modifiedUser.id}, valuesToSend, (res) => {
if (res.success) {
close();
NotificationService.info('Користувач '+vm.modifiedUser.firstName+' '+vm.modifiedUser.lastName+' підтверджений');
$routeSegment.reload()
} else {
NotificationService.error('Помилка:' + res.data.message);
}
});
}
function declineUser() {
NotificationService.info('Користувач ' + vm.originalUser.firstName + ' ' +
vm.originalUser.lastName + ' видаляється...');
UserFactory.rejectUpdateUser({tempUserId: vm.modifiedUser.id}, null ,(res) => {
if (res.success) {
close();
NotificationService.info('Користувач ' + vm.originalUser.firstName + ' ' +
vm.originalUser.lastName + ' видалений зі списку');
$routeSegment.reload()
} else {
NotificationService.error('Помилка:' + res.data.message);
}
});
}
//This additional function needed just to create another modal with 'confirm decline user'
function showConfirmDecline() {
$(confirmDeleteModal).modal();
}
function setCountries() {
PublicInfoFactory.countries().$promise.then((res) => {
if (res.success) {
vm.countries = res.data;
}
});
}
function setRegions(countryId) {
if (countryId === null) return [];
PublicInfoFactory.region({countryId: countryId}).$promise.then((res) => {
if (res.success) {
vm.regions = res.data;
}
});
}
function setCities(regionId) {
if (regionId === null) return [];
PublicInfoFactory.city({regionId: regionId}).$promise.then((res) => {
if (res.success) {
vm.cities = res.data;
}
});
}
function setPlatoons(cityId) {
if (cityId === null) return [];
PublicInfoFactory.platoon({cityId: cityId}).$promise.then((res) => {
if (res.success) {
vm.platoons = res.data;
}
});
}
function setSections(platoonId) {
if (platoonId === null) return [];
PublicInfoFactory.section({platoonId: platoonId}).$promise.then((res) => {
if (res.success) {
vm.sections = res.data;
}
});
}
function setRanks() {
PublicInfoFactory.rank().$promise.then((res) => {
if (res.success) {
vm.ranks = res.data.reduce((ranks, rank) => {
ranks.push({
value: rank,
name: Ranks[rank]
});
return ranks;
}, []);
}
});
}
//Special function for view to correct change country
function changeCountry() {
setRegions(vm.modifiedUser.country.id);
vm.modifiedUser.region = {};
vm.modifiedUser.city = {};
vm.modifiedUser.platoon = {};
}
//Special function for view to correct change region
function changeRegion() {
setCities(vm.modifiedUser.region.id);
vm.modifiedUser.city = {};
vm.modifiedUser.platoon = {};
}
//Same, but to correct change city
function changeCity() {
setPlatoons(vm.modifiedUser.city.id);
vm.modifiedUser.platoon = {};
}
//Same, but to correct change platoon
function changePlatoon() {
setSections(vm.modifiedUser.platoon.id);
}
function close(data) {
$uibModalInstance.close(data);
$(confirmDeleteModal).modal('hide');
}
}
})();
|
'use strict';
angular.module('stavkaPopisa',[])
.controller('stavkaPopisaNewCtrl', function ($scope, $modal, $modalInstance) {
$scope.sacuvaj = function() {
$modalInstance.close({'selectedStavka':$scope.selectedStavka,
'action':'save'});
}
$scope.zatvaranje = function() {
$modalInstance.dismiss('cancel');
}
$scope.selektujArtikal = function () {
var modalInstance = $modal.open({
templateUrl: 'views/artikli-modal.html',
controller: 'artikliModalCtrl',
scope: $scope
});
modalInstance.result.then(function (data) {
var selectedArtikal = data.selectedArtikal;
if( data.action==='save') {
$scope.selectedStavka.artikal = selectedArtikal;
}
},
function (response) {
if (response.status === 500) {
$scope.greska = "greska";
}
$route.reload();
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
}
});
|
var Piece = require('./Piece');
function Flag () {
super('Flag', -1);
}
Flag.prototype = Piece;
Flag.prototype.constructor = Flag;
module.exports = Flag;
|
module.exports = function exports() {
'use strict';
return {
p1k1: {a: 1, b: 'overwritten'},
p1k3: {e: 5, f: 6},
p1k4: {g: 7, h: 8}
};
};
|
export default class AutoCompleteSubjects {
initialize() {
$( function() {
$('#mandatory-autocomplete-input').materialize_autocomplete({
multiple: {
enable: false
},
dropdown: {
el: '#singleDropdownMandatory',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>'
},
getData: function (value, callback) {
$.ajax({
url: "/admin/studyplans/json/availableSubjects",
data: { query: value, id: $('#studyPlanId').val() },
type: 'GET',
success: function (data) {
callback(value, data);
}
});
},
onSelect: function (item) {
$('#mandatorySubjectId').val(item.id);
}
});
$('#optional-autocomplete-input').materialize_autocomplete({
multiple: {
enable: false
},
dropdown: {
el: '#singleDropdownOptional',
itemTemplate: '<li class="ac-item" data-id="<%= item.id %>" data-text=\'<%= item.name %>\'><a href="javascript:void(0)"><%= item.name %></a></li>'
},
getData: function (value, callback) {
$.ajax({
url: "/admin/studyplans/json/availableSubjects",
data: { query: value, id: $('#studyPlanId').val() },
type: 'GET',
success: function (data) {
callback(value, data);
}
});
},
onSelect: function (item) {
$('#optionalSubjectId').val(item.id);
}
});
});
}
} |
import useAllMarkdownRemark from './use-allmarkdown'
const useSortedMarkdown = () => {
let pages = useAllMarkdownRemark()
let sortedByCategory = {}
pages.forEach(page => {
let { category } = page.node.frontmatter
// If we find a first instance, create a new array for the category
if (!sortedByCategory[category]) {
sortedByCategory[category] = []
}
// Push the page to its category array
sortedByCategory[category].push(page)
})
return sortedByCategory
}
export default useSortedMarkdown
|
'use strict';
var config = require('./config');
var controllers = require('./controllers');
var logger = require('./logger');
const apiEndpoints = [
// Authentication
{ method: 'POST', path: '/register', config: controllers.authentication.register },
{ method: 'POST', path: '/login', config: controllers.authentication.login },
{ method: 'POST', path: '/logout', config: controllers.authentication.logout },
// Agents
{ method: 'GET', path: '/agents', config: controllers.agent.getAll },
{ method: 'GET', path: '/agents/{id}', config: controllers.agent.getById },
// Adds
{ method: 'GET', path: '/adds', config: controllers.add.getAll },
{ method: 'GET', path: '/adds/{id}', config: controllers.add.getById },
// Appointments
{ method: 'GET', path: '/appointments', config: controllers.appointment.getAll },
{ method: 'GET', path: '/appointments/{id}', config: controllers.appointment.getById },
{ method: 'POST', path: '/appointments', config: controllers.appointment.create },
{ method: 'DELETE', path: '/appointments/{id}', config: controllers.appointment.deleteById },
{ method: 'PUT', path: '/appointments/{id}', config: controllers.appointment.updateById },
// Reviews
{ method: 'POST', path: '/reviews/{id}', config: controllers.review.addReview }
].map(function(endpoint) { // add api url prefix to each route path
endpoint.path = `${config.application.apiUrl}${endpoint.path}`
return endpoint
});
const clientEndpoints = [
// Public
// images
{ method: "GET", path: `${config.application.imageUrl}/{filename}`, config: controllers.static.getImage },
];
const endpoints = clientEndpoints.concat(apiEndpoints);
// Notify
logger.logHeader("Registered endpoints:", config.logger.tags.SYSTEM)
endpoints.forEach(function(endpoint) {
logger.log(`[${endpoint.method}] ${endpoint.path}`, config.logger.tags.SYSTEM)
});
module.exports = {
endpoints
};
|
describe("Ext.layout.container.VBox", function(){
var ct, c, makeCt;
afterEach(function(){
Ext.destroy(ct, c);
ct = c = makeCt = null;
});
describe("defaults", function(){
var counter = 0,
proto = Ext.layout.container.VBox.prototype;
beforeEach(function() {
// We only need to create a layout instance once to wire up configs
if (!counter) {
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
layout: 'vbox',
width: 100,
height: 100
});
counter++;
}
});
it("should have align: begin", function() {
expect(proto.align).toBe('begin');
});
it("should have constrainAlign: false", function() {
expect(proto.constrainAlign).toBe(false);
});
it("should have enableSplitters: true", function() {
expect(proto.enableSplitters).toBe(true);
});
it("should have no padding", function() {
expect(proto.padding).toBe(0);
});
it("should have pack start", function() {
expect(proto.pack).toBe('start');
});
});
describe("removing items", function(){
it("should clear the top on an item when removing and using in another container", function(){
c = new Ext.Component({
height: 50
});
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
layout: 'vbox',
width: 100,
height: 100,
items: [{
height: 50
}, c]
});
var other = new Ext.container.Container({
renderTo: Ext.getBody(),
layout: 'fit',
width: 100,
height: 100
});
ct.remove(c, false);
other.add(c);
var top = c.getEl().getStyle('top');
// Normalize top value
if (top === 'auto') {
top = '';
} else if (top == '0px') {
top = '';
}
expect(top).toBe('');
other.destroy();
});
it("should remove an item when the item is not rendered and the item is not destroying", function() {
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
collapsed: true,
layout: 'vbox',
width: 100,
height: 100
});
// When adding the item to the collapsed panel, it won't render
c = ct.add({});
expect(function() {
ct.remove(0, false);
}).not.toThrow();
});
});
describe("padding", function(){
beforeEach(function(){
makeCt = function(pad){
c = new Ext.Component({
flex: 1
});
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
width: 80,
height: 100,
layout: {
type: 'vbox',
align: 'stretch',
padding: pad
},
items: c
});
};
});
it("should not add any padding by default", function(){
makeCt(0);
expect(c.getWidth()).toBe(80);
expect(c.getHeight()).toBe(100);
});
it("should read a padding number", function(){
makeCt(5);
expect(c.getWidth()).toBe(70);
expect(c.getHeight()).toBe(90);
});
it("should read a padding string", function(){
makeCt('1 2 3 4');
expect(c.getWidth()).toBe(74);
expect(c.getHeight()).toBe(96);
});
});
describe("padding and shrinkwrap", function(){
beforeEach(function() {
makeCt = function(childMargins) {
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
width: 80,
padding: 100, // innerCt stretches *inside* this.
layout: {
type: 'vbox',
align: 'stretch'
},
defaults: {
xtype: 'component',
height: 50,
margin: childMargins
},
items: [{},{}]
});
};
});
it("should not add any padding by default", function(){
makeCt(0);
expect(ct.layout.innerCt.getHeight()).toBe(100);
});
it("should read a padding number", function(){
makeCt(5);
expect(ct.layout.innerCt.getHeight()).toBe(120);
});
it("should read a padding string", function(){
makeCt('1 2 3 4');
expect(ct.layout.innerCt.getHeight()).toBe(108);
});
});
it("should apply margin to components", function(){
ct = new Ext.container.Container({
width: 200,
height: 200,
renderTo: Ext.getBody(),
defaultType: 'component',
layout: {
type: 'vbox',
align: 'stretch'
},
defaults: {
flex: 1,
margin: 5
},
items: [{}, {}]
});
expect(ct.items.first().getY()).toBe(5);
expect(ct.items.first().getX()).toBe(5);
expect(ct.items.last().getY()).toBe(105);
expect(ct.items.last().getX()).toBe(5);
});
describe("pack", function(){
var getY;
beforeEach(function(){
makeCt = function(pack){
ct = new Ext.container.Container({
defaultType: 'component',
renderTo: Ext.getBody(),
width: 600,
height: 600,
layout: {
type: 'vbox',
pack: pack
},
items: [{
height: 30
}, {
height: 40
}, {
height: 20
}]
});
};
getY = function(index){
return ct.items.getAt(index).el.getY();
};
});
afterEach(function(){
getY = null;
});
it("should pack at the top with pack: start", function(){
makeCt('start');
expect(getY(0)).toBe(0);
expect(getY(1)).toBe(30);
expect(getY(2)).toBe(70);
});
it("should pack in the middle with pack: center", function(){
makeCt('center');
expect(getY(0)).toBe(255);
expect(getY(1)).toBe(285);
expect(getY(2)).toBe(325);
});
it("should pack at the bottom with pack: cend", function(){
makeCt('end');
expect(getY(0)).toBe(510);
expect(getY(1)).toBe(540);
expect(getY(2)).toBe(580);
});
});
describe("align", function(){
var getX, getY, getWidth, getHeight;
beforeEach(function(){
makeCt = function(align, items, options) {
options = options || {};
ct = new Ext.container.Container({
defaultType: 'component',
renderTo: Ext.getBody(),
width: 600,
height: 600,
autoScroll: !!options.autoScroll,
layout: {
type: 'vbox',
align: align,
constrainAlign: !!options.constrainAlign
},
items: items
});
};
getX = function(index){
return ct.items.getAt(index).getEl().getX();
};
getY = function(index){
return ct.items.getAt(index).getEl().getY();
};
getWidth = function(index) {
return ct.items.getAt(index).getWidth();
};
getHeight = function(index) {
return ct.items.getAt(index).getHeight();
};
});
afterEach(function(){
getX = getY = getWidth = getHeight = null;
});
describe("left/center/right", function() {
it("should keep items at the left when using align: left", function(){
makeCt('left', [{
html: 'a'
}, {
html: 'b'
}]);
expect(getX(0)).toBe(0);
expect(getX(1)).toBe(0);
});
it("should align items in the middle when using align: center", function(){
makeCt('center', [{
width: 100
}, {
width: 300
}]);
expect(getX(0)).toBe(250);
expect(getX(1)).toBe(150);
});
it("should keep items to the right when using align: right", function(){
makeCt('right', [{
html: 'a'
}, {
html: 'b'
}]);
expect(getX(0)).toBe(600 - getWidth(0));
expect(getX(1)).toBe(600 - getWidth(1));
});
describe("constrainAlign", function(){
var makeLongString = function(c, len) {
var out = [],
i = 0;
for (; i < len; ++i) {
out.push(c);
}
return out.join(' ');
};
it("should constrain a shrink wrapped item with align: left", function(){
makeCt('left', [{
html: makeLongString('A', 100)
}], {
constrainAlign: true
});
expect(getWidth(0)).toBe(600);
expect(getX(0)).toBe(0);
});
it("should constrain a shrink wrapped item with align: center", function(){
makeCt('center', [{
html: makeLongString('A', 100)
}], {
constrainAlign: true
});
expect(getWidth(0)).toBe(600);
expect(getX(0)).toBe(0);
});
it("should constrain a shrink wrapped item with align: right", function(){
makeCt('center', [{
html: makeLongString('A', 100)
}], {
constrainAlign: true
});
expect(getWidth(0)).toBe(600);
expect(getX(0)).toBe(0);
});
it("should not constrain a fixed width item", function(){
makeCt('left', [{
html: 'A',
width: 1000
}], {
constrainAlign: false
});
expect(getWidth(0)).toBe(1000);
});
it("should recalculate the top positions", function(){
makeCt('left', [{
html: makeLongString('A', 100)
}, {
html: 'B'
}], {
constrainAlign: true
});
expect(getY(0)).toBe(0);
expect(getY(1)).toBe(getHeight(0));
});
});
});
describe("stretchmax", function() {
it("should stretch all items to the size of the largest when using align: stretchmax", function(){
makeCt('stretchmax', [{
html: 'foo'
}, {
html: 'foo bar baz'
}, {
html: 'foo'
}]);
c = new Ext.Component({
renderTo: Ext.getBody(),
html: 'foo bar baz',
floating: true
});
var expected = c.getWidth();
c.destroy();
expect(getWidth(0)).toBe(expected);
expect(getWidth(1)).toBe(expected);
expect(getWidth(2)).toBe(expected);
});
it("should always use a stretchmax over a fixed width", function(){
makeCt('stretchmax', [{
width: 30
}, {
html: 'foo bar baz blah long text'
}, {
html: 'foo'
}]);
c = new Ext.Component({
renderTo: Ext.getBody(),
html: 'foo bar baz blah long text',
floating: true
});
var expected = c.getWidth();
c.destroy();
expect(getWidth(0)).toBe(expected);
expect(getWidth(1)).toBe(expected);
expect(getWidth(2)).toBe(expected);
});
describe("minWidth", function() {
it("should stretch an item with a minWidth", function(){
makeCt('stretchmax', [{
width: 30
}, {
minWidth: 5
}]);
expect(getWidth(0)).toBe(30);
expect(getWidth(1)).toBe(30);
});
it("should stretch to the item with the largest minWidth", function(){
makeCt('stretchmax', [{
minWidth: 30
}, {
minWidth: 50
}]);
expect(getWidth(0)).toBe(50);
expect(getWidth(1)).toBe(50);
});
it("should stretch a single item outside the bounds of the container", function(){
makeCt('stretchmax', [{
xtype: 'panel',
title: 'Title',
minWidth: 1000,
shrinkWrap: true,
shrinkWrapDock: true,
html: 'Content...'
}], {
autoScroll: true
});
expect(getWidth(0)).toBe(1000);
});
});
it("should respect a maxWidth", function(){
makeCt('stretchmax', [{
width: 30
}, {
maxWidth: 20
}]);
expect(getWidth(0)).toBe(30);
expect(getWidth(1)).toBe(20);
});
});
it("should stretch all items to the container width", function(){
makeCt('stretch', [{
}, {
}]);
expect(getWidth(0)).toBe(600);
expect(getWidth(1)).toBe(600);
});
});
describe("height", function(){
var getHeight;
beforeEach(function(){
makeCt = function(items){
ct = new Ext.container.Container({
renderTo: Ext.getBody(),
width: 100,
height: 600,
defaultType: 'component',
layout: {
type: 'vbox',
align: 'stretch'
},
items: items
});
};
getHeight = function(index) {
return ct.items.getAt(index).getHeight();
};
});
afterEach(function(){
getHeight = null;
});
describe("flex only", function(){
it("should stretch a single flex item to the height of the container", function(){
makeCt({
flex: 1
});
expect(getHeight(0)).toBe(600);
});
it("should stretch 3 equally flexed items equally", function(){
makeCt([{
flex: 1
}, {
flex: 1
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(200);
expect(getHeight(1)).toBe(200);
expect(getHeight(2)).toBe(200);
});
it("should flex 2 items according to ratio", function(){
makeCt([{
flex: 3
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(450);
expect(getHeight(1)).toBe(150);
});
it("should flex 4 items according to ratio", function(){
makeCt([{
flex: 3
}, {
flex: 1
}, {
flex: 3
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(225);
expect(getHeight(1)).toBe(75);
expect(getHeight(2)).toBe(225);
expect(getHeight(3)).toBe(75);
});
it("should use flex as a ratio", function(){
makeCt([{
flex: 5000000
}, {
flex: 1000000
}]);
expect(getHeight(0)).toBe(500);
expect(getHeight(1)).toBe(100);
});
});
describe("fixed height only", function(){
it("should set the height of a single item", function(){
makeCt({
height: 200
});
expect(getHeight(0)).toBe(200);
});
it("should set the height of multiple items", function(){
makeCt([{
height: 500
}, {
height: 50
}]);
expect(getHeight(0)).toBe(500);
expect(getHeight(1)).toBe(50);
});
it("should allow a single item to exceed the container height", function(){
makeCt({
height: 900
});
expect(getHeight(0)).toBe(900);
});
it("should allow multiple items to exceed the container height", function(){
makeCt([{
height: 400
}, {
height: 400
}]);
expect(getHeight(0)).toBe(400);
expect(getHeight(1)).toBe(400);
});
});
describe("mixed", function(){
it("should give any remaining space to a single flexed item", function(){
makeCt([{
height: 200
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(200);
expect(getHeight(1)).toBe(400);
});
it("should flex a single item with 2 fixed", function(){
makeCt([{
height: 100
}, {
flex: 1
}, {
height: 300
}]);
expect(getHeight(0)).toBe(100);
expect(getHeight(1)).toBe(200);
expect(getHeight(2)).toBe(300);
});
it("should flex 2 items with 1 fixed", function(){
makeCt([{
flex: 2
}, {
height: 300
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(200);
expect(getHeight(1)).toBe(300);
expect(getHeight(2)).toBe(100);
});
it("should give priority to flex over a fixed height", function(){
makeCt([{
flex: 1,
height: 200
}, {
flex: 1
}]);
expect(getHeight(0)).toBe(300);
expect(getHeight(1)).toBe(300);
});
});
describe("min/max", function(){
it("should assign a 0 height if there is no more flex height", function(){
makeCt([{
flex: 1,
style: 'line-height:0'
}, {
height: 700
}]);
expect(getHeight(0)).toBe(0);
expect(getHeight(1)).toBe(700);
});
it("should respect a minWidth on a flex even if there is no more flex width", function(){
makeCt([{
flex: 1,
minHeight: 50
}, {
height: 700
}]);
expect(getHeight(0)).toBe(50);
expect(getHeight(1)).toBe(700);
});
it("should respect a minWidth on a flex even if there is no excess flex width", function(){
makeCt([{
flex: 1,
maxHeight: 100
}, {
height: 300
}]);
expect(getHeight(0)).toBe(100);
expect(getHeight(1)).toBe(300);
});
it("should update flex values based on min constraint", function(){
var c1 = new Ext.Component({
flex: 1,
minHeight: 500
}), c2 = new Ext.Component({
flex: 1
});
makeCt([c1, c2]);
expect(c1.getHeight()).toBe(500);
expect(c2.getHeight()).toBe(100);
});
it("should handle multiple min constraints", function(){
var c1 = new Ext.Component({
flex: 1,
minHeight: 250
}), c2 = new Ext.Component({
flex: 1,
minHeight: 250
}), c3 = new Ext.Component({
flex: 1
});
makeCt([c1, c2, c3]);
expect(c1.getHeight()).toBe(250);
expect(c2.getHeight()).toBe(250);
expect(c3.getHeight()).toBe(100);
});
it("should update flex values based on max constraint", function(){
var c1 = new Ext.Component({
flex: 1,
maxHeight: 100
}), c2 = new Ext.Component({
flex: 1
});
makeCt([c1, c2]);
expect(c1.getHeight()).toBe(100);
expect(c2.getHeight()).toBe(500);
});
it("should update flex values based on multiple max constraints", function(){
var c1 = new Ext.Component({
flex: 1,
maxHeight: 100
}), c2 = new Ext.Component({
flex: 1,
maxHeight: 100
}), c3 = new Ext.Component({
flex: 1
});
makeCt([c1, c2, c3]);
expect(c1.getHeight()).toBe(100);
expect(c2.getHeight()).toBe(100);
expect(c3.getHeight()).toBe(400);
});
it("should give precedence to min constraints over flex when the min is the same", function() {
var c1 = new Ext.Component({
flex: 1,
minHeight: 200
}), c2 = new Ext.Component({
flex: 3,
minHeight: 200
}), c3 = new Ext.Component({
flex: 1,
minHeight: 200
});
makeCt([c1, c2, c3]);
expect(c1.getHeight()).toBe(200);
expect(c2.getHeight()).toBe(200);
expect(c3.getHeight()).toBe(200);
});
it("should give precedence to max constraints over flex when the max is the same", function() {
var c1 = new Ext.Component({
flex: 1,
maxHeight: 100
}), c2 = new Ext.Component({
flex: 3,
maxHeight: 100
}), c3 = new Ext.Component({
flex: 1,
maxHeight: 100
});
makeCt([c1, c2, c3]);
expect(c1.getHeight()).toBe(100);
expect(c2.getHeight()).toBe(100);
expect(c3.getHeight()).toBe(100);
});
});
});
// Taken from extjs/test/issues/issue.html?id=5497
it("should align:center when box layouts are nested", function() {
// create a temporary component to measure the width of the text when
// rendered directly to the body by itself
var txtEl = Ext.widget({
xtype: 'component',
autoEl: 'span',
html: 'Some informative title',
renderTo: document.body
}),
twidth = txtEl.el.getWidth(),
// the target width for the spec below will be the measured width here
w = Ext.isIE9 ? twidth + 1 : twidth,
h = 20,
y = 0,
x = [90, 92];
txtEl.destroy();
ct = Ext.create('Ext.container.Container', {
renderTo: document.body,
style: 'background-color:yellow',
width: 300,
height: 200,
layout: {
type: 'vbox',
align: 'stretch'
},
items: {
id: 'l1',
xtype: 'container',
style: 'background-color:red',
layout: {
type: 'vbox',
align: 'center'
},
items: {
id: 'l2',
style: 'background-color:blue;color:white',
xtype: 'component', html: 'Some informative title', height: 20
}
}
});
expect(ct).toHaveLayout({
"el": {
"xywh": "0 0 300 200"
},
"items": {
"l1": {
"el": {
"xywh": "0 0 300 20"
},
"items": {
"l2": {
"el": {
x : x,
y : y,
w : [w-1,w+1],
h : [h-1,h+1]
}
}
}
}
}
});
});
// Taken from extjs/test/issues/5562.html
// Shrinkwrapping VBox should add height for any horizontal scrollbar if any of the boxes overflowed the Container width.
// So ct1's published shrinkwrap width shoiuld be the height of the two children cmp1 and cmp2 plus scrollbart height.
it("should include horizontal scroller in reported shrinkwrap height", function() {
ct = Ext.create('Ext.container.Container', {
renderTo: document.body,
width: 200,
style: 'border: 1px solid black',
layout: 'hbox',
items: [{
itemId: 'ct1',
defaultType: 'component',
style: 'background-color:yellow',
xtype: 'container',
layout: 'vbox',
flex: 1,
overflowX: 'auto',
items: [{
itemId: 'cmp1',
width: 500,
style: 'background-color:red',
html: 'child 1 content asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf asdf',
margin: '0 3 0 0'
}, {
itemId: 'cmp2',
style: 'background-color:blue',
html: 'child 2 content',
margin: '0 0 0 2'
}]
}]
});
var ct1 = ct.child('#ct1'),
cmp1 = ct1.child('#cmp1'),
cmp2 = ct1.child('#cmp2'),
cmp1Height = cmp1.getHeight(),
cmp2Height = cmp2.getHeight();
// cmp1 should have wrapped to two lines of text, cmp2 only one.
expect(cmp1Height).toBeGreaterThanOrEqual((cmp2Height * 2) - 1);
expect(cmp1Height).toBeLessThanOrEqual((cmp2Height * 2) + 1);
// ct1 should contain a scrollbar as well as the two stacked up Components.
// So the container which contains those two should be cmp1Height + cmp2Height + <scrollbarHeight> high
expect(ct1.el.getHeight()).toEqual(cmp1Height + cmp2Height + Ext.getScrollbarSize().height);
// ct just has border:1px solid black, so should be 2px higher
expect(ct.el.getHeight()).toEqual(cmp1Height + cmp2Height + Ext.getScrollbarSize().height + 2);
});
it("should size correctly with docked items & a configured parallel size & shrinkWrap perpendicular size", function() {
ct = new Ext.panel.Panel({
floating: true,
shadow: false,
autoShow: true,
border: false,
layout: 'vbox',
height: 150,
dockedItems: [{
dock: 'top',
xtype: 'component',
html: 'X'
}],
items: [{
xtype: 'component',
html: '<div style="width: 50px;"></div>'
}]
});
expect(ct.getWidth()).toBe(50);
expect(ct.getHeight()).toBe(150);
});
describe("scrolling", function() {
var scrollSize = 20,
defaultSize = 600,
origScroll;
function makeCt (cfg, layoutOptions) {
cfg = cfg || {};
if (cfg.items) {
Ext.Array.forEach(cfg.items, function(item, index) {
if (!item.html) {
item.html = index + 1;
}
});
}
ct = new Ext.container.Container(Ext.apply({
renderTo: Ext.getBody(),
layout: Ext.apply({
type: 'vbox'
}, layoutOptions)
}, cfg));
}
function makeShrinkWrapItem(h, w) {
return {
html: makeShrinkWrapHtml(h, w)
};
}
function makeShrinkWrapHtml(h, w) {
h = h || 10;
w = w || 10;
return Ext.String.format('<div style="height: {0}px; width: {1}px;"></div>', h, w);
}
function expectScroll(vertical, horizontal) {
var el = ct.getEl(),
dom = el.dom;
expectScrollDimension(vertical, el, dom, el.getStyle('overflow-y'), dom.scrollHeight, dom.clientHeight);
expectScrollDimension(horizontal, el, dom, el.getStyle('overflow-x'), dom.scrollWidth, dom.clientWidth);
}
function expectScrollDimension(value, el, dom, style, scrollSize, clientSize) {
if (value !== undefined) {
if (value) {
expect(style).not.toBe('hidden');
expect(scrollSize).toBeGreaterThan(clientSize);
} else {
if (style === 'hidden') {
expect(style).toBe('hidden');
} else {
expect(scrollSize).toBeLessThanOrEqual(clientSize);
}
}
}
}
function expectWidths(widths) {
expectSizes(widths, 'getWidth');
}
function expectHeights(heights) {
expectSizes(heights, 'getHeight');
}
function expectSizes(list, method) {
Ext.Array.forEach(list, function(size, index) {
expect(ct.items.getAt(index)[method]()).toBe(size);
});
}
// IE9 adds an extra space when shrink wrapping, see:
// http://social.msdn.microsoft.com/Forums/da-DK/iewebdevelopment/thread/47c5148f-a142-4a99-9542-5f230c78cb3b
function expectCtWidth(width) {
var shrinkWrap = ct.getSizeModel().width.shrinkWrap,
el = ct.getEl(),
dom = el.dom,
overflowOther = el.getStyle('overflow-y') !== 'hidden' && dom.scrollHeight > dom.clientHeight;
if (Ext.isIE9 && shrinkWrap && overflowOther) {
width += 4;
}
expect(ct.getWidth()).toBe(width);
}
function expectInnerCtWidth(width) {
expectInnerSize(width, 'getWidth');
}
// IE9 adds an extra space when shrink wrapping, see:
// http://social.msdn.microsoft.com/Forums/da-DK/iewebdevelopment/thread/47c5148f-a142-4a99-9542-5f230c78cb3b
function expectCtHeight(height) {
var shrinkWrap = ct.getSizeModel().height.shrinkWrap,
el = ct.getEl(),
dom = el.dom,
overflowOther = el.getStyle('overflow-x') !== 'hidden' && dom.scrollWidth > dom.clientWidth;
if (Ext.isIE9 && shrinkWrap && overflowOther) {
height += 4;
}
expect(ct.getHeight()).toBe(height);
}
function expectInnerCtHeight(height) {
expectInnerSize(height, 'getHeight');
}
function expectInnerSize(size, method) {
expect(ct.getLayout().innerCt[method]()).toBe(size);
}
beforeEach(function() {
origScroll = Ext.getScrollbarSize;
Ext.getScrollbarSize = function() {
return {
width: scrollSize,
height: scrollSize
}
};
});
afterEach(function() {
Ext.getScrollbarSize = origScroll;
});
describe("limited scrolling", function() {
describe("with no scroller", function() {
it("should limit the innerCt height to the container height", function() {
makeCt({
width: defaultSize,
height: defaultSize,
defaultType: 'component',
items: [{
height: 400
}, {
height: 400
}]
});
expectInnerCtHeight(defaultSize);
});
});
describe("user scrolling disabled", function() {
it("should limit the innerCt height to the container height", function() {
makeCt({
width: defaultSize,
height: defaultSize,
defaultType: 'component',
scrollable: {
x: false
},
items: [{
height: 400
}, {
height: 400
}]
});
expectInnerCtHeight(800);
});
});
});
describe("fixed size", function() {
function makeFixedCt(items, scrollable, layoutOptions) {
makeCt({
width: defaultSize,
height: defaultSize,
defaultType: 'component',
items: items,
scrollable: scrollable !== undefined ? scrollable : true
}, layoutOptions);
}
describe("vertical scrolling", function() {
it("should not show a scrollbar when configured to not scroll vertically", function() {
makeFixedCt([{
height: 400
}, {
height: 400
}], {
y: false
});
expectScroll(false, false);
expectInnerCtHeight(800);
});
describe("with no horizontal scrollbar", function() {
describe("configured", function() {
it("should not show a scrollbar when the total height does not overflow", function() {
makeFixedCt([{
height: 100
}, {
height: 100
}]);
expectScroll(false, false);
expectHeights([100, 100]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the total height overflows", function() {
makeFixedCt([{
height: 400
}, {
height: 400
}]);
expectScroll(true, false);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
});
describe("calculated", function() {
it("should not show a scrollbar when using only flex", function() {
makeFixedCt([{
flex: 1
}, {
flex: 2
}]);
expectScroll(false, false);
expectHeights([200, 400]);
expectInnerCtHeight(defaultSize);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minHeight does not cause an overflow", function() {
makeFixedCt([{
flex: 1
}, {
flex: 1,
minHeight: 300
}, {
flex: 1
}, {
flex: 1
}]);
expectScroll(false, false);
expectHeights([100, 300, 100, 100]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
flex: 1,
minHeight: 400
}, {
flex: 1,
minHeight: 400
}]);
expectScroll(true, false);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
});
});
describe("shrinkWrap", function() {
it("should not show a scrollbar when the total height does not overflow", function() {
makeFixedCt([makeShrinkWrapItem(50), makeShrinkWrapItem(50)]);
expectScroll(false, false);
expectHeights([50, 50]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the total width overflows", function() {
makeFixedCt([makeShrinkWrapItem(400), makeShrinkWrapItem(400)]);
expectScroll(true, false);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minHeight does not cause an overflow", function() {
makeFixedCt([{
minHeight: 200,
html: makeShrinkWrapHtml(100)
}, {
minHeight: 300,
html: makeShrinkWrapHtml(50)
}]);
expectScroll(false, false);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
minHeight: 400,
html: makeShrinkWrapHtml(100)
}, {
minHeight: 500,
html: makeShrinkWrapHtml(50)
}]);
expectScroll(true, false);
expectHeights([400, 500]);
expectInnerCtHeight(900);
});
});
});
describe("configured + calculated", function() {
it("should not show a scrollbar when the configured height does not overflow", function() {
makeFixedCt([{
height: 300
}, {
flex: 1
}]);
expectScroll(false, false);
expectHeights([300, 300]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the configured height overflows", function() {
makeFixedCt([{
height: 700
}, {
flex: 1
}]);
expectScroll(true, false);
expectHeights([700, 0]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minHeight does not cause an overflow", function() {
makeFixedCt([{
height: 300
}, {
flex: 1,
minHeight: 200
}]);
expectScroll(false, false);
expectHeights([300, 300]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 300
}, {
flex: 1,
minHeight: 500
}]);
expectScroll(true, false);
expectHeights([300, 500]);
expectInnerCtHeight(800);
});
});
});
describe("configured + shrinkWrap", function() {
it("should not show a scrollbar when the total height does not overflow", function() {
makeFixedCt([{
height: 300
}, makeShrinkWrapItem(200)]);
expectScroll(false, false);
expectHeights([300, 200]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the total height overflows", function() {
makeFixedCt([{
height: 400
}, makeShrinkWrapItem(400)]);
expectScroll(true, false);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minHeight does not cause an overflow", function() {
makeFixedCt([{
height: 300
}, {
html: makeShrinkWrapHtml(100),
minHeight: 200
}]);
expectScroll(false, false);
expectHeights([300, 200]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 300
}, {
html: makeShrinkWrapHtml(200),
minHeight: 500
}]);
expectScroll(true, false);
expectHeights([300, 500]);
expectInnerCtHeight(800);
});
});
});
describe("calculated + shrinkWrap", function() {
it("should not show a scrollbar when the shrinkWrap height does not overflow", function() {
makeFixedCt([makeShrinkWrapItem(500), {
flex: 1
}]);
expectScroll(false, false);
expectHeights([500, 100]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the shrinkWrap height overflows", function() {
makeFixedCt([makeShrinkWrapItem(700), {
flex: 1
}]);
expectScroll(true, false);
expectHeights([700, 0]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minHeight does not cause an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100),
minHeight: 200
}, {
flex: 1,
minHeight: 300
}]);
expectScroll(false, false);
expectHeights([200, 400]);
expectInnerCtHeight(defaultSize);
});
it("should show a scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100),
minHeight: 350
}, {
flex: 1,
minHeight: 350
}]);
expectScroll(true, false);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
});
});
});
describe("with a horizontal scrollbar", function() {
var big = 1000;
describe("where the horizontal scroll can be inferred before the first pass", function() {
describe("configured", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 100,
width: big
}, {
height: 100
}]);
expectScroll(false, true);
expectHeights([100, 100]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 400,
width: big
}, {
height: 400
}]);
expectScroll(true, true);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
});
describe("calculated", function() {
// There will never be overflow when using only calculated
it("should account for the horizontal scrollbar", function() {
makeFixedCt([{
flex: 1,
width: big
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([290, 290]);
expectInnerCtHeight(defaultSize - scrollSize);
});
describe("minWidth", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
flex: 1,
minHeight: 400,
width: big
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([400, 180]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
flex: 1,
minHeight: 350,
width: big
}, {
flex: 1,
minHeight: 350
}]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
});
});
describe("shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(200),
width: big
}, {
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
width: big
}, {
html: makeShrinkWrapHtml(400)
}]);
expectScroll(true, true);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100),
minHeight: 200,
width: big
}, {
html: makeShrinkWrapHtml(100),
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100),
minHeight: 350,
width: big
}, {
html: makeShrinkWrapHtml(200),
minHeight: 350
}]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
});
});
describe("configured + calculated", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 150,
width: big
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([150, 430]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 800,
width: big
}, {
flex: 1
}]);
expectScroll(true, true);
expectHeights([800, 0]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
height: 200,
width: big
}, {
flex: 1,
minHeight: 200
}]);
expectScroll(false, true);
expectHeights([200, 380]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 200,
width: big
}, {
flex: 1,
minHeight: 500
}]);
expectScroll(true, true);
expectHeights([200, 500]);
expectInnerCtHeight(700);
});
});
});
describe("configured + shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 150,
width: big
}, makeShrinkWrapItem(300)]);
expectScroll(false, true);
expectHeights([150, 300]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 350,
width: big
}, makeShrinkWrapItem(350)]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
height: 200,
width: big
}, {
html: makeShrinkWrapHtml(100),
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 200,
width: big
}, {
html: makeShrinkWrapHtml(200),
minHeight: 550
}]);
expectScroll(true, true);
expectHeights([200, 550]);
expectInnerCtHeight(750);
});
});
});
describe("calculated + shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(300),
width: big
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([300, 280]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
html: makeShrinkWrapItem(700),
width: big
}, {
flex: 1
}]);
expectScroll(true, true);
expectHeights([700, 0]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(200),
width: big
}, {
flex: 1,
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 380]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
width: big
}, {
flex: 1,
minHeight: 500
}]);
expectScroll(true, true);
expectHeights([400, 500]);
expectInnerCtHeight(900);
});
});
});
});
describe("when the horizontal scroll needs to be calculated", function() {
describe("configured", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 100,
html: makeShrinkWrapHtml(10, big)
}, {
height: 100
}]);
expectScroll(false, true);
expectHeights([100, 100]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 400,
html: makeShrinkWrapHtml(10, big)
}, {
height: 400
}]);
expectScroll(true, true);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
});
describe("calculated", function() {
// There will never be overflow when using only calculated
it("should account for the horizontal scrollbar", function() {
makeFixedCt([{
flex: 1,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([290, 290]);
expectInnerCtHeight(defaultSize - scrollSize);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
flex: 1,
minHeight: 400,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([400, 180]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
flex: 1,
minHeight: 350,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1,
minHeight: 350
}]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
});
});
describe("shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(200, big)
}, {
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400, big)
}, {
html: makeShrinkWrapHtml(400)
}]);
expectScroll(true, true);
expectHeights([400, 400]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100, big),
minHeight: 200
}, {
html: makeShrinkWrapHtml(100),
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(100, big),
minHeight: 350
}, {
html: makeShrinkWrapHtml(200),
minHeight: 350
}]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
});
});
describe("configured + calculated", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 150,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([150, 430]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 800,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1
}]);
expectScroll(true, true);
expectHeights([800, 0]);
expectInnerCtHeight(800);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
height: 200,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1,
minHeight: 200
}]);
expectScroll(false, true);
expectHeights([200, 380]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 200,
html: makeShrinkWrapHtml(10, big)
}, {
flex: 1,
minHeight: 500
}]);
expectScroll(true, true);
expectHeights([200, 500]);
expectInnerCtHeight(700);
});
});
});
describe("configured + shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
height: 150,
html: makeShrinkWrapHtml(10, big)
}, makeShrinkWrapItem(300)]);
expectScroll(false, true);
expectHeights([150, 300]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
height: 350,
html: makeShrinkWrapHtml(10, big)
}, makeShrinkWrapItem(350)]);
expectScroll(true, true);
expectHeights([350, 350]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
height: 200,
html: makeShrinkWrapHtml(10, big)
}, {
html: makeShrinkWrapHtml(100),
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 300]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
height: 200,
html: makeShrinkWrapHtml(10, big)
}, {
html: makeShrinkWrapHtml(200),
minHeight: 550
}]);
expectScroll(true, true);
expectHeights([200, 550]);
expectInnerCtHeight(750);
});
});
});
describe("calculated + shrinkWrap", function() {
it("should account for the horizontal scrollbar when there is no overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(300, big)
}, {
flex: 1
}]);
expectScroll(false, true);
expectHeights([300, 280]);
expectInnerCtHeight(defaultSize - scrollSize);
});
it("should account for the horizontal scrollbar when there is overflow", function() {
makeFixedCt([{
html: makeShrinkWrapItem(700, big)
}, {
flex: 1
}]);
expectScroll(true, true);
expectHeights([700, 0]);
expectInnerCtHeight(700);
});
describe("with constraint", function() {
it("should account for the horizontal scrollbar when the minHeight does not cause overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(200, big)
}, {
flex: 1,
minHeight: 300
}]);
expectScroll(false, true);
expectHeights([200, 380]);
expectInnerCtHeight(defaultSize - scrollSize)
});
it("should account for the horizontal scrollbar when the minHeight causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400, big)
}, {
flex: 1,
minHeight: 500
}]);
expectScroll(true, true);
expectHeights([400, 500]);
expectInnerCtHeight(900);
});
});
});
});
describe("when the horizontal scrollbar triggers a vertical scrollbar", function() {
var scrollTakesSize = Ext.getScrollbarSize().height > 0;
describe("configured", function() {
it("should account for the horizontal scrollbar", function() {
makeFixedCt([{
height: 295,
html: makeShrinkWrapHtml(10, big)
}, {
height: 295
}]);
expectScroll(scrollTakesSize, true);
expectHeights([295, 295]);
expectInnerCtHeight(590);
});
});
describe("shrinkWrap", function() {
it("should account for the horizontal scrollbar", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(295, big)
}, makeShrinkWrapItem(295)]);
expectScroll(scrollTakesSize, true);
expectHeights([295, 295]);
expectInnerCtHeight(590);
});
});
describe("configured + shrinkWrap", function() {
it("should account for the horizontal scrollbar", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(295, big)
}, {
height: 295
}]);
expectScroll(scrollTakesSize, true);
expectHeights([295, 295]);
expectInnerCtHeight(590);
});
});
});
});
});
describe("horizontal scrolling", function() {
it("should not show a scrollbar when configured to not scroll horizontally", function() {
makeFixedCt([{
height: 100,
width: 900
}, {
height: 100
}], {
x: false
});
expectScroll(false, false);
});
describe("with no vertical scrollbar", function() {
describe("configured width", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([{
height: 100,
width: 300
}, {
height: 100,
width: 400
}]);
expectScroll(false, false);
expectWidths([300, 400]);
expectInnerCtWidth(400);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([{
height: 100,
width: 700
}, {
height: 200,
width: 800
}]);
expectScroll(false, true);
expectWidths([700, 800]);
expectInnerCtWidth(800);
});
});
describe("align stretch", function() {
it("should not show a scrollbar by default", function() {
makeFixedCt([{
height: 100
}, {
height: 100
}], true, {align: 'stretch'});
expectScroll(false, false);
expectWidths([600, 600]);
expectInnerCtWidth(defaultSize);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
height: 100,
minWidth: 400
}, {
height: 100
}], true, {align: 'stretch'});
expectScroll(false, false);
expectWidths([600, 600]);
expectInnerCtWidth(defaultSize);
});
it("should show a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
height: 100,
minWidth: 800
}, {
height: 100
}], true, {align: 'stretch'});
expectScroll(false, true);
expectWidths([800, 600]);
expectInnerCtWidth(800);
});
});
});
describe("shrinkWrap width", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([makeShrinkWrapItem(10, 300), makeShrinkWrapItem(10, 200)]);
expectScroll(false, false);
expectWidths([300, 200]);
expectInnerCtWidth(300);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([makeShrinkWrapItem(10, 500), makeShrinkWrapItem(10, 750)]);
expectScroll(false, true);
expectWidths([500, 750]);
expectInnerCtWidth(750);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
height: 100,
minWidth: 400,
html: makeShrinkWrapHtml(10, 10)
}, {
height: 100,
minWidth: 500,
html: makeShrinkWrapHtml(10, 10)
}]);
expectScroll(false, false);
expectWidths([400, 500]);
expectInnerCtWidth(500);
});
it("should show a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
height: 100,
minWidth: 650,
html: makeShrinkWrapHtml(10, 50)
}, {
height: 100,
minWidth: 750,
html: makeShrinkWrapHtml(10, 50)
}]);
expectScroll(false, true);
expectWidths([650, 750]);
expectInnerCtWidth(750);
});
});
});
});
describe("with a vertical scrollbar", function() {
describe("where the vertical scroll can be inferred before the first pass", function() {
describe("configured width", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([{
height: 400,
width: 300
}, {
height: 400,
width: 400
}]);
expectScroll(true, false);
expectWidths([300, 400]);
expectInnerCtWidth(400);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([{
height: 400,
width: 700
}, {
height: 400,
width: 800
}]);
expectScroll(true, true);
expectWidths([700, 800]);
expectInnerCtWidth(800);
});
});
describe("align stretch", function() {
it("should not show a scrollbar by default", function() {
makeFixedCt([{
height: 400
}, {
height: 400
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([580, 580]);
expectInnerCtWidth(defaultSize - scrollSize);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
height: 400,
minWidth: 400
}, {
height: 400
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([580, 580]);
expectInnerCtWidth(defaultSize - scrollSize);
});
it("should should a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
height: 400,
minWidth: 800
}, {
height: 400
}], true, {align: 'stretch'});
expectScroll(true, true);
expectWidths([800, 580]);
expectInnerCtWidth(800);
});
});
});
describe("shrinkWrap width", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([{
height: 400,
html: makeShrinkWrapHtml(10, 300)
}, {
height: 400,
html: makeShrinkWrapHtml(10, 200)
}]);
expectScroll(true, false);
expectWidths([300, 200]);
expectInnerCtWidth(300);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([{
height: 400,
html: makeShrinkWrapHtml(10, 500)
}, {
height: 400,
html: makeShrinkWrapHtml(10, 750)
}]);
expectScroll(true, true);
expectWidths([500, 750]);
expectInnerCtWidth(750);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
height: 400,
minWidth: 400,
html: makeShrinkWrapHtml(10, 10)
}, {
height: 400,
minWidth: 500,
html: makeShrinkWrapHtml(10, 10)
}]);
expectScroll(true, false);
expectWidths([400, 500]);
expectInnerCtWidth(500);
});
it("should should a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
height: 400,
minWidth: 650,
html: makeShrinkWrapHtml(10, 50)
}, {
height: 400,
minWidth: 750,
html: makeShrinkWrapHtml(10, 50)
}]);
expectScroll(true, true);
expectWidths([650, 750]);
expectInnerCtWidth(750);
});
});
});
});
describe("when the horizontal scroll needs to be calculated", function() {
describe("configured width", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
width: 300
}, {
html: makeShrinkWrapHtml(400),
width: 400
}]);
expectScroll(true, false);
expectWidths([300, 400]);
expectInnerCtWidth(400);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
width: 700
}, {
html: makeShrinkWrapHtml(400),
width: 800
}]);
expectScroll(true, true);
expectWidths([700, 800]);
expectInnerCtWidth(800);
});
});
describe("align stretch", function() {
it("should not show a scrollbar by default", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400)
}, {
html: makeShrinkWrapHtml(400)
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([580, 580]);
expectInnerCtWidth(defaultSize - scrollSize);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
minWidth: 400
}, {
html: makeShrinkWrapHtml(400)
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([580, 580]);
expectInnerCtWidth(defaultSize - scrollSize);
});
it("should show a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
html: makeShrinkWrapHtml(400),
minWidth: 800
}, {
html: makeShrinkWrapHtml(400)
}], true, {align: 'stretch'});
expectScroll(true, true);
expectWidths([800, 580]);
expectInnerCtWidth(800);
});
});
});
describe("shrinkWrap height", function() {
it("should not show a scrollbar when the largest width does not overflow", function() {
makeFixedCt([makeShrinkWrapItem(400, 300), makeShrinkWrapItem(400, 200)]);
expectScroll(true, false);
expectWidths([300, 200]);
expectInnerCtWidth(300);
});
it("should show a scrollbar when the largest width overflows", function() {
makeFixedCt([makeShrinkWrapItem(400, 500), makeShrinkWrapItem(400, 750)]);
expectScroll(true, true);
expectWidths([500, 750]);
expectInnerCtWidth(750);
});
describe("with constraint", function() {
it("should not show a scrollbar when the minWidth does not cause an overflow", function() {
makeFixedCt([{
minWidth: 400,
html: makeShrinkWrapHtml(400, 10)
}, {
minWidth: 500,
html: makeShrinkWrapHtml(400, 10)
}]);
expectScroll(true, false);
expectWidths([400, 500]);
expectInnerCtWidth(500);
});
it("should show a scrollbar when the minWidth causes an overflow", function() {
makeFixedCt([{
minWidth: 650,
html: makeShrinkWrapHtml(400, 50)
}, {
minWidth: 750,
html: makeShrinkWrapHtml(400, 50)
}]);
expectScroll(true, true);
expectWidths([650, 750]);
expectInnerCtWidth(750);
});
});
});
});
});
});
});
describe("shrinkWrap width", function() {
function makeShrinkWrapCt(items, scrollable, layoutOptions) {
// Float to prevent stretching
makeCt({
floating: true,
height: defaultSize,
defaultType: 'component',
items: items,
scrollable: scrollable !== undefined ? scrollable : true
}, layoutOptions);
}
// Not testing vertical scroll here because it's never visible
describe("with no vertical scrollbar", function() {
describe("configured", function() {
it("should publish the largest width", function() {
makeShrinkWrapCt([{
height: 100,
width: 400
}, {
height: 100,
width: 500
}]);
expectScroll(false, false);
expectWidths([400, 500]);
expectCtWidth(500);
});
});
describe("shrinkWrap", function() {
it("should publish the largest width", function() {
makeShrinkWrapCt([{
height: 100,
html: makeShrinkWrapHtml(10, 250)
}, {
height: 100,
html: makeShrinkWrapHtml(10, 300)
}]);
expectScroll(false, false);
expectWidths([250, 300]);
expectCtWidth(300);
});
describe("with constraint", function() {
it("should publish the largest constrained width", function() {
makeShrinkWrapCt([{
height: 100,
html: makeShrinkWrapHtml(10, 150),
minWidth: 300
}, {
height: 100,
html: makeShrinkWrapHtml(10, 100),
minWidth: 350
}]);
expectScroll(false, false);
expectWidths([300, 350]);
expectCtWidth(350);
});
});
});
describe("align: stretch", function() {
it("should stretch items & publish the largest width", function() {
makeShrinkWrapCt([{
height: 100,
html: makeShrinkWrapHtml(10, 200)
}, {
height: 100,
html: makeShrinkWrapHtml(10, 300)
}], true, {align: 'stretch'});
expectScroll(false, false);
expectWidths([300, 300]);
expectCtWidth(300);
});
describe("with constraint", function() {
it("should stretch items and publish the largest constrained width", function() {
makeShrinkWrapCt([{
height: 100,
minWidth: 400
}, {
height: 100,
minWidth: 550
}], true, {align: 'stretch'});
expectScroll(false, false);
expectWidths([550, 550]);
expectCtWidth(550);
});
});
});
});
describe("with a vertical scrollbar", function() {
var big = 1000;
describe("where the vertical scroll can be inferred before the first pass", function() {
describe("configured", function() {
it("should account for the scrollbar in the total width", function() {
makeShrinkWrapCt([{
height: big,
width: 400
}, {
width: 500
}]);
expectScroll(true, false);
expectWidths([400, 500]);
expectCtWidth(520);
});
});
describe("shrinkWrap", function() {
it("should account for the scrollbar in the total width", function() {
makeShrinkWrapCt([{
height: big,
html: makeShrinkWrapHtml(10, 250)
}, {
html: makeShrinkWrapHtml(10, 300)
}]);
expectScroll(true, false);
expectWidths([250, 300]);
expectCtWidth(320);
});
describe("with constraint", function() {
it("should publish the largest constrained width", function() {
makeShrinkWrapCt([{
height: big,
html: makeShrinkWrapHtml(10, 150),
minWidth: 300
}, {
html: makeShrinkWrapHtml(10, 100),
minWidth: 350
}]);
expectScroll(true, false);
expectWidths([300, 350]);
expectCtWidth(370);
});
});
});
describe("align: stretch", function() {
it("should stretch items & publish the largest width", function() {
makeShrinkWrapCt([{
height: big,
html: makeShrinkWrapHtml(10, 200)
}, {
height: 100,
html: makeShrinkWrapHtml(10, 300)
}]);
expectScroll(true, false);
expectWidths([200, 300]);
expectCtWidth(320);
});
describe("with constraint", function() {
it("should stretch items and publish the largest constrained width", function() {
makeShrinkWrapCt([{
height: big,
minWidth: 400
}, {
height: 100,
minWidth: 550
}]);
expectScroll(true, false);
expectWidths([400, 550]);
expectCtWidth(570);
});
});
});
});
describe("when the vertical scroll needs to be calculated", function() {
describe("configured", function() {
it("should account for the scrollbar in the total width", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(big, 400)
}, {
html: makeShrinkWrapHtml(10, 500)
}]);
expectScroll(true, false);
expectWidths([400, 500]);
expectCtWidth(520);
});
});
describe("shrinkWrap", function() {
it("should account for the scrollbar in the total width", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(big, 250)
}, {
html: makeShrinkWrapHtml(10, 300)
}]);
expectScroll(true, false);
expectWidths([250, 300]);
expectCtWidth(320);
});
describe("with constraint", function() {
it("should publish the largest constrained width", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(big, 150),
minWidth: 300
}, {
html: makeShrinkWrapHtml(10, 100),
minWidth: 350
}]);
expectScroll(true, false);
expectWidths([300, 350]);
expectCtWidth(370);
});
});
});
describe("align: stretch", function() {
it("should stretch items & publish the largest width", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(big, 200)
}, {
height: 100,
html: makeShrinkWrapHtml(10, 300)
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([300, 300]);
expectCtWidth(320);
});
describe("with constraint", function() {
it("should stretch items and publish the largest constrained width", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(big, 10),
minWidth: 400
}, {
minWidth: 550
}], true, {align: 'stretch'});
expectScroll(true, false);
expectWidths([550, 550]);
expectCtWidth(570);
});
});
});
});
});
});
describe("shrinkWrap height", function() {
function makeShrinkWrapCt(items, scrollable, layoutOptions) {
makeCt({
// Float to prevent stretching
floating: true,
width: defaultSize,
defaultType: 'component',
items: items,
scrollable: scrollable !== undefined ? scrollable : true
}, layoutOptions);
}
// Not testing vertical scroll here because it's never visible
// Flex items become shrinkWrap when shrink wrapping the height, so we won't bother
// with those
describe("with no horizontal scrollbar", function() {
describe("configured", function() {
it("should publish the total height", function() {
makeShrinkWrapCt([{
height: 400
}, {
height: 400
}]);
expectScroll(false, false);
expectHeights([400, 400]);
expectCtHeight(800);
});
});
describe("shrinkWrap", function() {
it("should publish the total height", function() {
makeShrinkWrapCt([makeShrinkWrapItem(400), makeShrinkWrapItem(400)]);
expectScroll(false, false);
expectHeights([400, 400]);
expectCtHeight(800);
});
describe("with constraint", function() {
it("should publish the total height", function() {
makeShrinkWrapCt([{
minHeight: 350,
html: makeShrinkWrapHtml(200)
}, {
minHeight: 400,
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, false);
expectHeights([350, 400]);
expectCtHeight(750);
});
});
});
describe("configured + shrinkWrap", function() {
it("should publish the total height", function() {
makeShrinkWrapCt([{
height: 400
}, makeShrinkWrapItem(400)]);
expectScroll(false, false);
expectHeights([400, 400]);
expectCtHeight(800);
});
describe("with constraint", function() {
it("should publish the total height", function() {
makeShrinkWrapCt([{
height: 350
}, {
minHeight: 400,
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, false);
expectHeights([350, 400]);
expectCtHeight(750);
});
});
});
});
describe("with a horizontal scrollbar", function() {
var big = 1000;
describe("where the horizontal scroll can be inferred before the first pass", function() {
describe("configured", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 400,
width: big
}, {
height: 400
}]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
});
describe("shrinkWrap", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(400),
width: big
}, makeShrinkWrapItem(400)]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
describe("with constraint", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
minHeight: 350,
html: makeShrinkWrapHtml(200),
width: big
}, {
minHeight: 400,
html: makeShrinkWrapHtml(100)
}]);
expectScroll(false, true);
expectHeights([350, 400]);
expectCtHeight(770);
});
});
});
describe("configured + shrinkWrap", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 400,
width: big
}, makeShrinkWrapItem(400)]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
describe("with constraint", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 350,
width: big
}, {
minHeight: 400,
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, true);
expectHeights([350, 400]);
expectCtHeight(770);
});
});
});
});
describe("when the horizontal scroll needs to be calculated", function() {
describe("configured", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 400,
html: makeShrinkWrapHtml(10, big)
}, {
height: 400
}]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
});
describe("shrinkWrap", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
html: makeShrinkWrapHtml(400, big)
}, makeShrinkWrapItem(400)]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
describe("with constraint", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
minHeight: 350,
html: makeShrinkWrapHtml(200, big)
}, {
minHeight: 400,
html: makeShrinkWrapHtml(100)
}]);
expectScroll(false, true);
expectHeights([350, 400]);
expectCtHeight(770);
});
});
});
describe("configured + shrinkWrap", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 400,
html: makeShrinkWrapHtml(10, big)
}, makeShrinkWrapItem(400)]);
expectScroll(false, true);
expectHeights([400, 400]);
expectCtHeight(820);
});
describe("with constraint", function() {
it("should account for the scrollbar in the total height", function() {
makeShrinkWrapCt([{
height: 350,
html: makeShrinkWrapHtml(10, big)
}, {
minHeight: 400,
html: makeShrinkWrapHtml(300)
}]);
expectScroll(false, true);
expectHeights([350, 400]);
expectCtHeight(770);
});
});
});
});
});
});
describe("preserving scroll state", function() {
var endSpy;
beforeEach(function() {
endSpy = jasmine.createSpy();
});
afterEach(function() {
endSpy = null;
});
it("should restore the horizontal/vertical scroll position with user scrolling", function() {
makeCt({
height: 400,
width: 400,
scrollable: true,
items: [{
height: 300,
width: 500
}, {
height: 300,
width: 500
}]
});
var scrollable = ct.getScrollable();
scrollable.on('scrollend', endSpy);
scrollable.scrollTo(30, 50);
waitsFor(function() {
return endSpy.callCount > 0;
});
runs(function() {
ct.setSize(401, 401);
});
waitsFor(function() {
var pos = scrollable.getPosition();
return pos.x > 0 && pos.y > 0;
});
runs(function() {
var pos = scrollable.getPosition();
expect(pos).toEqual({
x: 30,
y: 50
});
});
});
it("should restore the horizontal/vertical scroll position with programmatic scrolling", function() {
// Allows for only programmatic scrolling, but the scrollbars aren't visible
makeCt({
height: 400,
width: 400,
scrollable: {
y: false,
x: false
},
items: [{
height: 300,
width: 500
}, {
height: 300,
width: 500
}]
});
var scrollable = ct.getScrollable();
scrollable.on('scrollend', endSpy);
scrollable.scrollTo(30, 50);
waitsFor(function() {
return endSpy.callCount > 0;
});
runs(function() {
ct.setSize(401, 401);
});
waitsFor(function() {
var pos = scrollable.getPosition();
return pos.x > 0 && pos.y > 0;
});
runs(function() {
var pos = scrollable.getPosition();
expect(pos).toEqual({
x: 30,
y: 50
});
});
});
});
});
function createOverflowSuite(options) {
describe("parent type: " + options.parentXtype +
", child type: " + options.childXtype +
", parent layout: " + options.parentLayout,
function() {
function makeContainer(overflowDim) {
var nonOverflowDim = overflowDim === 'width' ? 'height' : 'width',
scrollbarSize = Ext.getScrollbarSize(),
component = {
xtype: 'component',
style: 'margin: 3px; background-color: green;'
},
childCt = {
xtype: options.childXtype,
autoScroll: true,
layout: 'vbox',
items: [component]
},
parentCt = {
xtype: options.parentXtype,
floating: true,
shadow: false,
layout: options.parentLayout,
items: [childCt]
};
component[overflowDim] = 500;
component[nonOverflowDim] = 90 - scrollbarSize[nonOverflowDim];
childCt[overflowDim] = 98;
if (options.parentXtype === 'container') {
parentCt.style = 'border: 1px solid black';
}
if (options.childXtype === 'container') {
childCt.style = 'border: 1px solid black';
}
ct = Ext.widget(parentCt);
ct.show();
}
describe("horizontal overflow with shrink wrap height", function() {
beforeEach(function() {
makeContainer('width');
});
it("should include scrollbar size in the height", function() {
expect(ct.getHeight()).toBe(100);
});
});
describe("vertical overflow with shrink wrap width", function() {
beforeEach(function() {
makeContainer('height');
});
it("should include scrollbar size in the width", function() {
expect(ct.getWidth()).toBe(100);
});
});
});
}
createOverflowSuite({
parentXtype: 'container',
childXtype: 'container',
parentLayout: 'auto'
});
createOverflowSuite({
parentXtype: 'container',
childXtype: 'container',
parentLayout: 'vbox'
});
createOverflowSuite({
parentXtype: 'panel',
childXtype: 'container',
parentLayout: 'auto'
});
createOverflowSuite({
parentXtype: 'panel',
childXtype: 'container',
parentLayout: 'vbox'
});
createOverflowSuite({
parentXtype: 'container',
childXtype: 'panel',
parentLayout: 'auto'
});
createOverflowSuite({
parentXtype: 'container',
childXtype: 'panel',
parentLayout: 'vbox'
});
createOverflowSuite({
parentXtype: 'panel',
childXtype: 'panel',
parentLayout: 'auto'
});
createOverflowSuite({
parentXtype: 'panel',
childXtype: 'panel',
parentLayout: 'vbox'
});
describe("misc overflow", function() {
it("should layout with autoScroll + align: stretch + A shrink wrapped parallel item", function() {
expect(function() {
ct = new Ext.container.Container({
autoScroll: true,
layout: {
align: 'stretch',
type: 'vbox'
},
renderTo: Ext.getBody(),
width: 600,
height: 200,
items: [{
xtype: 'component',
height: 200,
html: 'Item'
}, {
xtype: 'component',
html: 'Component'
}]
});
}).not.toThrow();
});
});
});
|
const mongoose = require('mongoose');
let articleShema = mongoose.Schema({
title: {type: String, required: true},
content: {type: String, required: true},
author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
date: {type: Date, default: Date.now()}
});
const Article = mongoose.model('Article', articleShema);
module.exports = Article; |
'use strict'
var api = require('../api/pressure')
var def = require('../definition/pressure/kilonewton-per-square-meter')
var unit = 'kilonewton-per-square-meter'
api.augment(unit, def)
module.exports = api.get(unit)
|
var path = require('path');
var pkg = require('./package.json');
var fs = require('fs');
var browserify = require('browserify');
var boot = require('loopback-boot');
module.exports = function buildBrowserBundle(env, callback) {
var b = browserify({ basedir: __dirname });
b.require('./' + pkg.main, { expose: 'lbclient' });
try {
boot.compileToBrowserify({
appRootDir: __dirname,
env: env
}, b);
} catch(err) {
return callback(err);
}
var bundlePath = path.resolve(__dirname, 'browser.bundle.js');
var out = fs.createWriteStream(bundlePath);
var isDevEnv = ~['debug', 'development', 'test'].indexOf(env);
b.bundle()
.on('error', callback)
.pipe(out);
out.on('error', callback);
out.on('close', callback);
}; |
"use strict";
const _ = require('lodash'),
co = require('co'),
path = require('path'),
moment = require('moment'),
Q = require('bluebird');
const test = require(path.join(process.cwd(), 'test', '_base'))(module);
const waigo = global.waigo;
test['action tokens'] = {
beforeEach: function*() {
this.createAppModules({
'support/actionTokens': 'module.exports = { init: function*() { return Array.from(arguments).concat(1); } }; '
});
yield this.initApp();
yield this.startApp({
startupSteps: [],
shutdownSteps: [],
actionTokens: {
dummy: true,
},
});
this.setup = waigo.load('support/startup/actionTokens');
},
afterEach: function*() {
yield this.shutdownApp();
},
'init action tokens': function*() {
yield this.setup(this.App);
this.App.actionTokens.should.eql([this.App, { dummy: true }, 1]);
},
};
|
import React from 'react'
import { Message } from 'semantic-ui-react'
const MessageErrorExample = () => (
<Message
error
header='There was some errors with your submission'
list={[
'You must include both a upper and lower case letters in your password.',
'You need to select your home country.',
]}
/>
)
export default MessageErrorExample
|
/** Created by hhj on 3/22/16. */
/* eslint-disable no-unused-expressions */
import { expect } from 'chai'
import myErrorHandler from '../myErrorHandler'
describe('lib myErrorHandler', () => {
it('should handle string error', () => {
expect(myErrorHandler('test error message')).to.be.undefined
})
it('should handle object error', () => {
expect(myErrorHandler({ message: 'test error message' })).to.be.undefined
})
})
|
(function () {
'use strict';
const filesToCache = [
'.',
'style/app.css',
'index.html',
'favicon.ico',
'pages/404.html',
'pages/offline.html',
'style/font/HmnHiRzvcnQr8CjBje6GQvesZW2xOQ-xsNqO47m55DA.woff2',
'images/touch/icon-192x192.png'
];
const staticCacheName = 'pages-cache-v1';
const notToCache = 'https://api.github.com';
self.addEventListener('install', event => {
console.log('Attempting to install service worker and cache static assets');
//self.skipWaiting();
event.waitUntil(
caches.open(staticCacheName)
.then(cache => {
return cache.addAll(filesToCache);
})
);
});
self.addEventListener('activate', event => {
console.log('Service worker activating...');
let cacheWhitelist = [staticCacheName];
event.waitUntil(
caches.keys()
.then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
self.addEventListener('fetch', event => {
console.log(`Fetching: ${event.request.url}`);
if (event.request.url.startsWith(notToCache)) { return event.request; }
event.respondWith(
caches.match(event.request)
.then(response => {
if (response) { console.log(`Found ${event.request.url} in cache`); }
return response || fetchAndCache(event.request);
})
);
});
function fetchAndCache(url) {
console.log(`Network request for ${url.url}`);
return fetch(url)
.then(response => {
if (!response.ok) {
if (response.status === 404) {
return caches.match('pages/404.html');
}
throw Error(response.statusText);
}
return caches.open(staticCacheName)
.then(cache => {
cache.put(url, response.clone());
return response;
});
})
.catch(error => {
console.log(`Request failed: ${error}`);
return caches.match('pages/offline.html');
})
}
})();
|
export default {
data: {
questionnaire: {
id: "1",
title: "Test",
description: "",
surveyId: "",
theme: "default",
legalBasis: "StatisticsOfTradeAct",
navigation: false,
summary: false,
__typename: "Questionnaire",
sections: [
{
id: "1",
title: "Section 1",
position: 0,
alias: "",
displayName: "Section 1",
pages: [
{
id: "1",
title: "",
alias: "",
displayName: "",
position: 0,
confirmation: null,
__typename: "QuestionPage"
}
],
questionnaire: {
id: "1",
questionnaireInfo: {
totalSectionCount: 1,
__typename: "QuestionnaireInfo"
},
__typename: "Questionnaire"
},
__typename: "Section"
}
]
}
}
};
|
import { getNodeScope } from '../../node'
test('Returns node for valid elements', () => {
const o = document.createElement('div')
expect(getNodeScope(o)).toBe(o)
expect(getNodeScope(document)).toBe(document)
})
test('Returns document for invalid arguments', () => {
expect(getNodeScope()).toBe(document)
expect(getNodeScope(true)).toBe(document)
expect(getNodeScope('div')).toBe(document)
expect(getNodeScope({})).toBe(document)
})
test('Returns window for window', () => {
expect(getNodeScope(window)).toBe(window)
})
|
/*
服务端应该导入本模块。用于索引当前系统中的页面components
key为ejs模板的文件名
value为components模块
TODO: 使用bash扫描component文件夹直接生成本文件
*/
import React, { PropTypes } from 'react'
import { Home } from '../home.jsx'
import { Shot } from '../shot.jsx'
import { Sample } from '../sample.jsx'
import { Pringles } from '../pringles.jsx'
import { Suite } from '../suite.jsx'
import { Hotel } from '../hotel.jsx'
import { HotelRequire } from '../hotel-require.jsx'
import { Scheme } from '../scheme.jsx'
import { Cases } from '../cases.jsx'
import { WeddingPat } from '../wedding-pat.jsx'
import { WeddingVideo } from '../wedding-video.jsx'
import { WeddingMV } from '../wedding-mv.jsx'
import { SchemeRequire } from '../scheme-require.jsx'
import { Adv } from '../adv.jsx'
import { Dress } from '../dress.jsx'
import { DressDetails } from '../dress-details.jsx'
import { Movie } from '../movie.jsx'
import { Supply } from '../supply.jsx'
import { Car } from '../car.jsx'
const ComponentsIndex = {
'home': <Home />,
'shot': <Shot />,
'sample': <Sample />,
'pringles': <Pringles />,
'suite': <Suite />,
'hotel': <Hotel />,
'hotel-require': <HotelRequire />,
'scheme': <Scheme />,
'cases': <Cases />,
'wedding-pat': <WeddingPat />,
'wedding-video': <WeddingVideo />,
'wedding-mv': <WeddingMV />,
'scheme-require': <SchemeRequire />,
'adv': <Adv />,
'dress': <Dress />,
'dress-details': <DressDetails />,
'movie': <Movie />,
'supply': <Supply />,
'car': <Car />
}
export {
ComponentsIndex
}
|
import { defaultDispatch, dispatchToAPI } from './common';
import { USERS } from '../reducers/index';
const defaultDispatchUsers = (payload, reducer) =>
defaultDispatch(USERS, payload, reducer);
/* Action creators */
const usersRequested = () =>
defaultDispatchUsers({
isFetching: true,
error: null
});
const usersReceived = ({ response }) => {
const users = response.data.users;
return defaultDispatchUsers({
isFetching: false,
users
});
};
const usersError = error =>
defaultDispatchUsers({
isFetching: false,
error
});
/* Thunks */
// access users endpoint
export const usersApi = config => {
config = {
method: 'GET',
...config
};
return dispatchToAPI({
endpoint: '/users',
config,
authenticated: true,
actions: [usersRequested, usersReceived, usersError]
});
};
|
// @flow
import React, { Component } from 'react';
import { Button, Classes } from '@blueprintjs/core';
import DocumentTitle from 'react-document-title';
import Login from 'components/Login';
import './Welcome.scss';
type PropsType = {
isInstalled: boolean,
isOutdated: boolean,
handleConnect: () => void,
}
export default class Welcome extends Component {
state = {
isButtonVisible: true,
}
props: PropsType;
handleInstall = () => {
this.setState({ isButtonVisible: false });
window.open('/assets/tind3r.zip');
}
renderButton() {
const isChrome = window.chrome;
if (isChrome) {
if (this.props.isInstalled) {
if (this.props.isOutdated) {
return (
<div>
<h3 className={Classes.HEADING}>...but you need update firstly, click below to get latest version od Chrome Extension</h3>
<Button onClick={this.handleInstall}>Get .crx file</Button>
<div className="welcome__update-explanation">
Note: after download complete, extract zip file, go to url: <i>chrome://extensions/</i>, then toggle on developer mode
and just Drag&Drop .crx file. <br/><br/> After that reload the page!
</div>
</div>
);
}
return (
<Login onClick={this.props.handleConnect} />
);
}
if (this.state.isButtonVisible) {
return (
<Button
onClick={this.handleInstall}
text="Get the extension file"
/>
);
}
return (
<div className="welcome__update-explanation">
Note: after download complete, extract zip file, go to url: <i>chrome://extensions/</i>, then toggle on developer mode
and click "Load unpacked" at the top left and seleft unziped folder. <br/><br/> After that reload the page!
</div>
);
}
return (
<span className="welcome__chrome">
Only on Google Chrome <img alt="Chrome" src="/assets/img/chrome.png" />
</span>
);
}
render() {
return (
<DocumentTitle title="Tind3r.com - Unofficial Tinder client">
<div className="welcome">
<div className="welcome__left">
<div className="welcome__name">
tind<b>3</b>r.com
<div className="welcome__slogan">unofficial Tinder web client</div>
</div>
<div className="welcome__image" />
</div>
<div className="welcome__right">
<div className="welcome__info">
<div className="welcome__cell">
<h1>Great things <br /> are coming</h1>
{this.renderButton()}
</div>
</div>
</div>
</div>
</DocumentTitle>
);
}
}
|
var WinReg = require('winreg');
var startOnBoot = {
enableAutoStart: function(name, file, callback){
var key = getKey();
key.set(name, WinReg.REG_SZ, file, callback || noop);
},
disableAutoStart: function(name, callback){
var key = getKey();
key.remove(name, callback || noop);
},
getAutoStartValue: function(name, callback){
var key = getKey();
key.get(name, function(error, result){
if(result){
callback(result.value);
}
else{
callback(null, error);
}
});
}
};
var RUN_LOCATION = '\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
function getKey(){
return new WinReg({
hive: WinReg.HKCU, //CurrentUser,
key: RUN_LOCATION
});
}
function noop(){}
module.exports = startOnBoot; |
angular.module('LocalChat')
.factory('Location', function(Auth, Socket) {
var L = {};
L.locationSet = false;
L.currentLocation = 'Unknown Location';
var settingLocation = false;
L.setLocation = function () {
if (settingLocation) return;
settingLocation = true;
var options = {};
var watch = navigator.geolocation.watchPosition(success, failure, options);
function success(position) {
navigator.geolocation.clearWatch(watch);
Auth.onSession('setLocation', {
coords: {
latitude : position.coords.latitude,
longitude : position.coords.longitude
}
}, function(locationName) {
L.currentLocation = locationName;
L.locationSet = true;
});
settingLocation = false;
}
function failure(error) {
navigator.geolocation.clearWatch(watch);
console.log(error);
settingLocation = false;
}
};
Socket.on('connect', function() {
L.locationSet = false;
L.setLocation();
});
return L;
}); |
// Configure some input fields with the boostrap datepicker
$(function () {
$("#DateReleased").datepicker();
$("#DateRetired").datepicker();
});
|
var hash = exports;
hash.utils = require('./hash/utils');
hash.common = require('./hash/common');
hash.sha = require('./hash/sha');
hash.ripemd = require('./hash/ripemd');
hash.hmac = require('./hash/hmac');
// Proxy hash functions to the main object
hash.sha1 = hash.sha.sha1;
hash.sha256 = hash.sha.sha256;
hash.sha224 = hash.sha.sha224;
hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;
|
const pretty = require('pretty-time');
const timeManager = {
start() {
const start = process.hrtime();
return {
stop() {
const diff = process.hrtime(start);
const theDiff = diff[0] * 1e9 + diff[1];
return {
diff: theDiff,
diffFormatted: pretty(theDiff, 'ms'),
};
},
};
},
};
module.exports = timeManager;
|
/*
Copyright 2013-2015 ASIAL CORPORATION
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import util from '../../ons/util';
import autoStyle from '../../ons/autostyle';
import ModifierUtil from '../../ons/internal/modifier-util';
import AnimatorFactory from '../../ons/internal/animator-factory';
import ToastAnimator from './animator';
import FadeToastAnimator from './fade-animator';
import AscendToastAnimator from './ascend-animator';
import LiftToastAnimator from './lift-animator';
import FallToastAnimator from './fall-animator';
import platform from '../../ons/platform';
import BaseDialogElement from '../base/base-dialog';
import contentReady from '../../ons/content-ready';
const scheme = {
'.toast': 'toast--*',
'.toast__message': 'toast--*__message',
'.toast__button': 'toast--*__button'
};
const defaultClassName = 'toast';
const _animatorDict = {
'default': platform.isAndroid() ? AscendToastAnimator : LiftToastAnimator,
'fade': FadeToastAnimator,
'ascend': AscendToastAnimator,
'lift': LiftToastAnimator,
'fall': FallToastAnimator,
'none': ToastAnimator
};
/**
* @element ons-toast
* @category dialog
* @description
* [en]
* The Toast or Snackbar component is useful for displaying dismissable information or simple actions at (normally) the bottom of the page.
*
* This component does not block user input, allowing the app to continue its flow. For simple toasts, consider `ons.notification.toast` instead.
* [/en]
* [ja][/ja]
* @guide dialogs
* [en]Dialog components[/en]
* [ja]Dialog components[/ja]
* @seealso ons-alert-dialog
* [en]The `<ons-alert-dialog>` component is preferred for displaying undismissable information.[/en]
* [ja][/ja]
*/
export default class ToastElement extends BaseDialogElement {
/**
* @attribute animation
* @type {String}
* @default default
* @description
* [en]The animation used when showing and hiding the toast. Can be either `"default"`, `"ascend"` (Android), `"lift"` (iOS), `"fall"`, `"fade"` or `"none"`.[/en]
* [ja][/ja]
*/
/**
* @attribute animation-options
* @type {Expression}
* @description
* [en]Specify the animation's duration, timing and delay with an object literal. E.g. `{duration: 0.2, delay: 1, timing: 'ease-in'}`.[/en]
* [ja]アニメーション時のduration, timing, delayをオブジェクトリテラルで指定します。e.g. <code>{duration: 0.2, delay: 1, timing: 'ease-in'}</code>[/ja]
*/
constructor() {
super();
this._defaultDBB = e => e.callParentHandler();
contentReady(this, () => this._compile());
}
get _scheme() {
return scheme;
}
get _toast() {
return util.findChild(this, `.${defaultClassName}`);
}
_updateAnimatorFactory() {
// Reset position style
this._toast && (this._toast.style.top = this._toast.style.bottom = '');
return new AnimatorFactory({
animators: _animatorDict,
baseClass: ToastAnimator,
baseClassName: 'ToastAnimator',
defaultAnimation: this.getAttribute('animation')
});
}
/**
* @property onDeviceBackButton
* @type {Object}
* @description
* [en]Back-button handler.[/en]
* [ja]バックボタンハンドラ。[/ja]
*/
_compile() {
autoStyle.prepare(this);
this.style.display = 'none';
this.style.zIndex = 10000; // Lower than dialogs
const messageClassName = 'toast__message';
const buttonClassName = 'toast__button';
let toast = util.findChild(this, `.${defaultClassName}`);
if (!toast) {
toast = document.createElement('div');
toast.classList.add(defaultClassName);
while (this.childNodes[0]) {
toast.appendChild(this.childNodes[0]);
}
}
let button = util.findChild(toast, `.${buttonClassName}`);
if (!button) {
button = util.findChild(toast, e => util.match(e, '.button') || util.match(e, 'button'));
if (button) {
button.classList.remove('button');
button.classList.add(buttonClassName);
toast.appendChild(button);
}
}
if (!util.findChild(toast, `.${messageClassName}`)) {
let message = util.findChild(toast, '.message');
if (!message) {
message = document.createElement('div');
for (let i = toast.childNodes.length - 1; i >= 0; i--) {
if (toast.childNodes[i] !== button) {
message.insertBefore(toast.childNodes[i], message.firstChild);
}
}
}
message.classList.add(messageClassName);
toast.insertBefore(message, toast.firstChild);
}
if (toast.parentNode !== this) {
this.appendChild(toast);
}
ModifierUtil.initModifier(this, this._scheme);
}
/**
* @property visible
* @readonly
* @type {Boolean}
* @description
* [en]Whether the element is visible or not.[/en]
* [ja]要素が見える場合に`true`。[/ja]
*/
/**
* @method show
* @signature show([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are `"default"`, `"ascend"` (Android), `"lift"` (iOS), `"fall"`, `"fade"` or `"none"`.[/en]
* [ja][/ja]
* @param {String} [options.animationOptions]
* [en]Specify the animation's duration, delay and timing. E.g. `{duration: 0.2, delay: 0.4, timing: 'ease-in'}`.[/en]
* [ja]アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: 'ease-in'}[/ja]
* @description
* [en]Show the element.[/en]
* [ja][/ja]
* @return {Promise}
* [en]Resolves to the displayed element[/en]
* [ja][/ja]
*/
/**
* @method toggle
* @signature toggle([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are `"default"`, `"ascend"` (Android), `"lift"` (iOS), `"fall"`, `"fade"` or `"none"`.[/en]
* [ja][/ja]
* @param {String} [options.animationOptions]
* [en]Specify the animation's duration, delay and timing. E.g. `{duration: 0.2, delay: 0.4, timing: 'ease-in'}`.[/en]
* [ja]アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: 'ease-in'}[/ja]
* @description
* [en]Toggle toast visibility.[/en]
* [ja][/ja]
*/
/**
* @method hide
* @signature hide([options])
* @param {Object} [options]
* [en]Parameter object.[/en]
* [ja]オプションを指定するオブジェクト。[/ja]
* @param {String} [options.animation]
* [en]Animation name. Available animations are `"default"`, `"ascend"` (Android), `"lift"` (iOS), `"fall"`, `"fade"` or `"none"`.[/en]
* [ja][/ja]
* @param {String} [options.animationOptions]
* [en]Specify the animation's duration, delay and timing. E.g. `{duration: 0.2, delay: 0.4, timing: 'ease-in'}`.[/en]
* [ja]アニメーション時のduration, delay, timingを指定します。e.g. {duration: 0.2, delay: 0.4, timing: 'ease-in'}[/ja]
* @description
* [en]Hide toast.[/en]
* [ja][/ja]
* @return {Promise}
* [en]Resolves to the hidden element[/en]
* [ja][/ja]
*/
/**
* @param {String} name
* @param {Function} Animator
*/
static registerAnimator(name, Animator) {
if (!(Animator.prototype instanceof ToastAnimator)) {
throw new Error('"Animator" param must inherit OnsToastElement.ToastAnimator');
}
_animatorDict[name] = Animator;
}
static get animators() {
return _animatorDict;
}
static get ToastAnimator() {
return ToastAnimator;
}
}
customElements.define('ons-toast', ToastElement);
|
/**
* Created by mankind on 10/02/15.
*/
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
// Define schema for Comments
var CommentSchema = new Schema({
text : String,
article : {
type : String,
ref : "Article"
},
author: {
type : String,
ref : "User"
}
});
mongoose.model('Comment', CommentSchema); |
angular.module('jwt-prototype')
.controller('dashboard', function ($scope, $location) {
$scope.user = JSON.parse(localStorage.getItem('user'))
if(!$scope.user) {
$location.path('/')
}
console.log("User from dashboard: ", $scope.user);
$scope.name = $scope.user.username
})
|
import Ember from 'ember';
import {
module,
test
} from 'qunit';
import Pretender from 'pretender';
import startApp from 'dummy/tests/helpers/start-app';
var application;
var store;
var server;
var posts = [
{
id: 1,
post_title: 'post title 1',
body: 'post body 1',
comments: []
},
{
id: 2,
post_title: 'post title 2',
body: 'post body 2',
comments: []
},
{
id: 3,
post_title: 'post title 3',
body: 'post body 3',
comments: []
}
];
module('Acceptance: CRUD Success', {
beforeEach: function() {
application = startApp();
store = application.__container__.lookup('store:main');
server = new Pretender(function() {
// Retrieve list of non-paginated records
this.get('/test-api/posts/', function(request) {
if (request.queryParams.post_title === 'post title 2') {
return [200, {'Content-Type': 'application/json'}, JSON.stringify([posts[1]])];
} else {
return [200, {'Content-Type': 'application/json'}, JSON.stringify(posts)];
}
});
// Retrieve single record
this.get('/test-api/posts/1/', function(request) {
return [200, {'Content-Type': 'application/json'}, JSON.stringify(posts[0])];
});
// Create record
this.post('/test-api/posts/', function(request) {
var data = Ember.$.parseJSON(request.requestBody);
data['id'] = 4;
return [201, {'Content-Type': 'application/json'}, JSON.stringify(data)];
});
// Update record
this.put('/test-api/posts/1/', function(request) {
var data = Ember.merge(posts[0], Ember.$.parseJSON(request.requestBody));
return [200, {'Content-Type': 'application/json'}, JSON.stringify(data)];
});
// Delete record
this.delete('/test-api/posts/1/', function(request) {
return [204];
});
});
},
afterEach: function() {
Ember.run(application, 'destroy');
server.shutdown();
}
});
test('Retrieve list of non-paginated records', function(assert) {
assert.expect(4);
return store.findAll('post').then(function(posts) {
assert.ok(posts);
assert.equal(posts.get('length'), 3);
var post = posts.objectAt(2);
assert.equal(post.get('postTitle'), 'post title 3');
assert.equal(post.get('body'), 'post body 3');
});
});
test('Retrieve single record', function(assert) {
assert.expect(3);
return Ember.run(function() {
return store.findRecord('post', 1).then(function(post) {
assert.ok(post);
assert.equal(post.get('postTitle'), 'post title 1');
assert.equal(post.get('body'), 'post body 1');
});
});
});
test('Retrieve via query', function(assert) {
assert.expect(3);
return Ember.run(function() {
return store.query('post', {post_title: 'post title 2'}).then(function(post) {
assert.ok(post);
post = post.objectAt(0);
assert.equal(post.get('postTitle'), 'post title 2');
assert.equal(post.get('body'), 'post body 2');
});
});
});
test('Create record', function(assert) {
assert.expect(4);
return Ember.run(function() {
var post = store.createRecord('post', {
postTitle: 'my new post title',
body: 'my new post body'
});
return post.save().then(function(post) {
assert.ok(post);
assert.equal(post.get('id'), 4);
assert.equal(post.get('postTitle'), 'my new post title');
assert.equal(post.get('body'), 'my new post body');
});
});
});
test('Update record', function(assert) {
assert.expect(7);
return Ember.run(function() {
return store.findRecord('post', 1).then(function(post) {
assert.ok(post);
assert.equal(post.get('isDirty'), false);
return Ember.run(function() {
post.set('postTitle', 'new post title');
post.set('body', 'new post body');
assert.equal(post.get('isDirty'), true);
return post.save().then(function(post) {
assert.ok(post);
assert.equal(post.get('isDirty'), false);
assert.equal(post.get('postTitle'), 'new post title');
assert.equal(post.get('body'), 'new post body');
});
});
});
});
});
test('Delete record', function(assert) {
assert.expect(2);
return Ember.run(function() {
return store.findRecord('post', 1).then(function(post) {
assert.ok(post);
return post.destroyRecord().then(function(post) {
assert.ok(post);
});
});
});
});
|
var tape = require('tape')
var G = require('../')
tape('get', function (t) {
var g = G.random(10, 30)
// G.each(g, function (key, node) {
// t.equal(node, G.get(g, key))
// })
//
G.eachEdge(g, function (src, dst, v) {
console.log(src, dst)
t.equal(G.get(g, src, dst), v)
})
t.end()
})
//RANDOMLY generate a graph and then check that it
//has some reasonable properties.
tape('hops', function (t) {
//a is subset of b
function subset(a, b) {
for(var k in a) {
t.equal(b[k], a[k])
}
}
var g = G.random(100, 300)
var reachable = G.hops(g, '#0', 0, 3) //{start: '#0'})
var reachable2 = G.hops(g, '#0', 0, 2) //G.traverse(g, {start: '#0', hops: 2})
// var reachable3 = G G.traverse(g, {start: '#0', max: 20})
//var reachable4 = G.traverse(g, {start: '#0', hops: 2, max: 20})
t.ok(Object.keys(reachable).length)
console.log('reachable2 is subset of reachable')
subset(reachable2, reachable)
console.log('reachable3 is subset of reachable')
// subset(reachable3, reachable)
//if the random graph happened not to have 20 nodes within 2 hops
//then reachable3 will be larger than reachable2.
// if(Object.keys(reachable2).length > 20) {
// console.log('reachable3 is subset of reachable2')
// subset(reachable3, reachable2)
// } else {
// console.log('reachable2 is subset of reachable3')
// subset(reachable2, reachable3)
// }
//
// //since reachable4 is either 2 hops or 20 nodes
// //it's always the subset of either 2 or 3.
//
// subset(reachable4, reachable3)
// subset(reachable4, reachable2)
t.end()
})
//make sure the empty graph does not throw
tape('empty graph', function (t) {
var g = G.random(0,0)
var o = G.hops(g, 'a', 0, 3) //G.traverse(g, {start:'a'})
t.deepEqual(o, {})
t.end()
})
|
var chai = require("chai");
var _ = require("underscore");
_.mixin(require('../src/underscore.catenate'));
describe("underscore.catenate", function() {
it("should catenate methods", function() {
var value = "";
var fooBar = _.catenate(function() {
return value += "foo";
}, function() {
return value += "Bar";
});
chai.expect(fooBar()).to.equal("fooBar");
});
}); |
const create = require("lodash/create")
const { observable } = require("kobs")
module.exports = (makePromise, cmp) => ctx => {
const makeCtxPromise = makePromise(ctx)
const promiseObs = observable({ status: "idle" })
const trigger = () => {
promiseObs({
status: "waiting",
})
return makeCtxPromise()
.then(result => {
promiseObs({
status: "success",
result,
})
})
.catch(result => {
promiseObs({
status: "error",
result,
})
})
}
return cmp(
create(ctx, {
command: {
status: () => promiseObs().status,
result: () => promiseObs().result,
trigger,
},
})
)
}
|
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
express: {
app: {
options: {
script: 'server.js'
}
}
},
bower: {
install: {
options: {
targetDir: 'bower_components',
copy: false,
cleanTargetDir: true
}
}
},
copy: {
app: {
files: [
{
src: 'public/favicon.ico',
dest: 'dist/favicon.ico'
},
{
src: 'public/index.html',
dest: 'build/index.html'
}
]
},
mock: {
files: [
{
src: 'bower_components/angular-mocks/angular-mocks.js',
dest: 'dist/js/angular-mocks.js'
},
{
src: 'public/index.html',
dest: 'build/index.html'
}
]
}
},
processhtml: {
app: {
files: {
'dist/index.html': 'build/index.html'
}
},
mock: {
files: {
'dist/index.html': 'build/index.html'
}
}
},
htmlmin: {
app: {
options: {
useShortDoctype: true,
collapseWhitespace: true,
collapseBooleanAttributes: true,
removeComments: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeOptionalTags: true
},
files: {
'dist/index.html': 'dist/index.html',
'dist/partials/home.html': 'lib/partials/home.html',
'dist/partials/travis-login.html': 'lib/partials/travis-login.html',
'dist/partials/wall.html': 'lib/partials/wall.html'
}
}
},
less: {
app: {
files: {
'build/app.css': 'less/app.less'
}
}
},
imageEmbed: {
app: {
src: [ 'build/app.css' ],
dest: 'build/app.css'
}
},
cssmin : {
options: {
keepSpecialComments: 0
},
app: {
src: 'build/app.css',
dest: 'dist/css/app.min.css'
}
},
ngAnnotate: {
app: {
src: [ 'lib/**/*.js' ],
dest: 'build/main.js'
}
},
concat: {
app: {
src: [
'bower_components/ev-emitter/ev-emitter.js',
'bower_components/eventEmitter/EventEmitter.js',
'bower_components/eventie/eventie.js',
'bower_components/jquery/dist/jquery.js',
'bower_components/momentjs/min/moment-with-locales.js',
'bower_components/spin.js/spin.js',
'bower_components/angular/angular.js',
'bower_components/angular-masonry/angular-masonry.js',
'bower_components/angular-moment/angular-moment.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-spinner/angular-spinner.js',
'bower_components/desandro-matches-selector/matches-selector.js',
'bower_components/fizzy-ui-utils/utils.js',
'bower_components/get-size/get-size.js',
'bower_components/imagesloaded/imagesloaded.js',
'bower_components/outlayer/item.js',
'bower_components/outlayer/outlayer.js',
'bower_components/masonry/dist/masonry.pkgd.js',
'build/main.js'
],
dest: 'build/app.js'
}
},
uglify: {
app: {
files: {
'dist/js/app.min.js': 'build/app.js'
}
}
},
clean: {
dist: [ 'dist' ],
build: [ 'build' ]
},
watch: {
img: {
files: [ 'img/**/*' ],
tasks: [ 'build' ]
},
less: {
files: [ 'less/**/*' ],
tasks: [ 'build' ]
},
lib: {
files: [ 'lib/**/*' ],
tasks: [ 'build' ]
},
public: {
files: [ 'public/**/*' ],
tasks: [ 'build' ]
}
},
jshint: {
files: [
'lib/**/*.js',
'test/**/*.js',
'*.js'
]
},
jasmine: {
app: {
src: 'dist/js/app.min.js',
options: {
specs: 'test/**/*Spec.js'
}
}
},
shell: {
webDriverManagerUpdate: {
command: 'node_modules/protractor/bin/webdriver-manager update'
}
},
karma: {
unit: {
options: {
configFile: 'karma.conf.js'
}
}
},
protractor: {
e2e: {
options: {
configFile: 'protractor.conf.js'
}
}
}
});
grunt.loadNpmTasks('grunt-express-server');
grunt.loadNpmTasks('grunt-bower-task');
grunt.loadNpmTasks('grunt-ng-annotate');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-htmlmin');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-image-embed');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-processhtml');
grunt.loadNpmTasks('grunt-shell');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-protractor-runner');
grunt.registerTask('install', [ 'bower:install' ]);
grunt.registerTask('build', [
'clean:build',
'clean:dist',
'copy:app',
'less:app',
'imageEmbed:app',
'ngAnnotate:app',
'concat:app',
'processhtml:app',
'htmlmin:app',
'cssmin:app',
'uglify:app',
'clean:build'
]);
grunt.registerTask('dist', [
'install',
'build'
]);
grunt.registerTask('serve', [
'express:app',
'watch'
]);
grunt.registerTask('dev', [
'dist',
'serve'
]);
grunt.registerTask('test:unit', [
'copy:mock',
'processhtml:mock',
'htmlmin:app',
'clean:build',
'jshint',
'karma:unit'
]);
grunt.registerTask('test:e2e', [
'copy:mock',
'processhtml:mock',
'htmlmin:app',
'clean:build',
'shell:webDriverManagerUpdate',
'express:app',
'protractor:e2e'
]);
grunt.registerTask('test', [
'test:unit',
'test:e2e'
]);
grunt.registerTask('travis', [
'dist',
'test'
]);
};
|
import React from 'react';
import Home from './home/home';
import ProjectList from './project_list/project_list';
import Contact from './contact/contact';
import Landing from './landing/landing';
import PortfolioFooter from './../footer/footer';
export default React.createClass({
render() {
return (
<section id="fullpage" className="body">
<div className="section">
<Landing />
</div>
<div className="section">
<Home {...this.props} />
</div>
<ProjectList {...this.props} />
<div className="section">
<Contact {...this.props} />
<PortfolioFooter />
</div>
</section>
);
}
});
|
/**
Copyright (c) <2015> <copyright Martin Agents, David Chong, Aaron Giroux, Geoffrey Scofield, Daniel Sullivan, >
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/* Access level constants */
USER_BANNED = 'USER_BANNED';
REGULAR = 'REGULAR';
/**
* Global functions used by the client
* @namespace GameChatClient
*/
GameChatClient = {
/* General use chat room access control functions */
// TODO Confirm this works
/**
* @function allowUserIntoChatRoom
* @memberof GameChatClient
* @desc Allows user into chat room
* @param {String} userId - ID of user
* @param {String} chatRoomId - ID of chat room
*/
allowUserIntoChatRoom: function (userId, chatRoomId) {
// First put the user into the REGULAR list
console.log(
"allowUserIntoChatRoom(): Calling setUserChatRoomAccessLevel "
+ "to grant access to userId "
+ userId
+ "for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, REGULAR, true);
// Now revoke their BANNED membership if it exists
console.log(
"allowUserIntoChatRoom(): Calling setUserChatRoomAccessLevel "
+ "to revoke any existing ban for userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, USER_BANNED, false);
},
// TODO Confirm this works
/**
* @function banUserFromChatRoom
* @memberof GameChatClient
* @desc Bans user from chat room.
* @param {String} userId - ID of user
* @param {String} chatRoomId - ID of chat room
*/
banUserFromChatRoom: function (userId, chatRoomId) {
// First ban the user
console.log(
"banUserFromChatRoom(): Calling setUserChatRoomAccessLevel to ban userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, USER_BANNED, true);
// Now revoke their REGULAR membership
console.log(
"banUserFromChatRoom(): Calling setUserChatRoomAccessLevel "
+ " to revoke REGULAR membership for userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, REGULAR, false);
},
// TODO Confirm this works
/**
* @function inviteUserToChatRoom
* @memberof GameChatClient
* @desc Invites user to existing chat room and grants them access.
* @param {String} userId - ID of user
* @param {String} chatRoomId - ID of chat room
* @param {?String} inviteMessage - Message to display in invite
* @returns {String} ID of new ChatRoomInvites doc
*/
inviteUserToChatRoom: function (userId, chatRoomId, inviteMessage) {
// First put the user into the REGULAR list
console.log(
"inviteUserToChatRoom(): Calling setUserChatRoomAccessLevel "
+ " to grant access to userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, REGULAR, true);
// Now revoke their BANNED membership if it exists
console.log(
"inviteUserToChatRoom(): Calling setUserChatRoomAccessLevel "
+ "to revoke any existing ban for userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.setUserChatRoomAccessLevel(userId, chatRoomId, USER_BANNED, false);
// Finally, send an invite to the user
console.log(
"inviteUserToChatRoom(): Calling createChatRoomInvite() to send invite to userId "
+ userId
+ " for chatRoomId "
+ chatRoomId
);
GameChatClient.createChatRoomInvite(userId, chatRoomId, inviteMessage);
},
/* Chatroom/invite creation functions */
/**
* @function createChatRoom
* @memberof GameChatClient
* @desc Creates a new chat room, sets all users in Map arg to their mapped access value
* and sends a ChatRoomInvite to those users.
* @param {String} roomname - Name of chat room
* @param {Map} users - usersAccess Map of user ID keys/access values to allow into chat room
* @param {Map} flags - Configuration options for chatroom (isPublic, etc.)
* @param {?String} gameId - ID of game document (if one is set)
* @param {?String} inviteMessage - Inviter message to invitees
* @returns {String} ID of ChatRooms doc
*/
createChatRoom: function (roomname, users, flags, gameId, inviteMessage) {
var usersArray = [];
function usersToArray(value, key, map) {
usersArray.push([key, value])
} // TODO Try putting a semicolon here at some point, looks cleaner
users.forEach(usersToArray);
var newChatRoomId;
// TODO Remove (only used for debugging)
console.log("createChatRoom(): calling Meteor.methods.insert()");
newChatRoomId = ChatRooms.insert({
adminId: Meteor.userId(),
roomname: roomname,
isPublic: flags.get('isPublic'),
gameId: gameId,
accessRegular: [],
accessBanned: [],
invited: [],
messages: [],
currentUsers: []
});
console.log("createChatRoom(): newChatRoomId=" + newChatRoomId);
console.log("createChatRoom(): Name of new ChatRooms doc: "
+ ChatRooms.findOne(newChatRoomId).roomname);
console.log("createChatRoom(): Creating access levels and invites");
// TODO Change this to also use values in Map 'users' to set user permissions
// Create chat room user access levels and invites
for (var i = 0; i < usersArray.length; i++) {
GameChatClient.setUserChatRoomAccessLevel(
usersArray[i][0],
newChatRoomId,
REGULAR,
true
);
var newInviteId
= GameChatClient
.createChatRoomInvite(
usersArray[i][0],
newChatRoomId,
inviteMessage
);
console.log("Access level for userId "
+ usersArray[i][0]
+ " has been set to "
+ REGULAR
+ " and invite with id "
+ newInviteId
+ " has been created for them"
);
}
return newChatRoomId;
},
// TODO Confirm this works
/**
* @function setUserChatRoomAccessLevel
* @memberof GameChatClient
* @desc Sets access level for user.
* Note that REGULAR and USER_BANNED are two separate lists.
* REGULAR is the access whitelist. If your room is private (isPublic: false),
* users that are not members of the room's REGULAR group will not be able to see the room,
* but they can be added later with a single call to this function.
* USER_BANNED is the access blacklist. Users that are members of USER_BANNED
* will not be able to see the room, even if it is public (isPublic: false).
* Users must be removed from USER_BANNED with a call to this function
* before they can see the room.
* Generally speaking, you should use {@link GameChatClient#banUserFromChatRoom},
* {@link GameChatClient#allowUserIntoChatRoom}
* or {@link GameChatClient#inviteUserToChatRoom}
* rather than call this function directly. Those functions will call this one
* and add/remove the users from each list as appropriate.
* @param {String} userId - ID of user
* @param {String} chatRoomId - ID of chat room
* @param {String} accessLevel - Access level of user (USE ESTABLISHED CONSTANTS)
* @param {Boolean} add - True for adding user, false for removing user
* @returns Updated ChatRoom document if set was successful, null otherwise
*/
setUserChatRoomAccessLevel: function (userId, chatRoomId, accessLevel, add) {
switch (accessLevel) {
case REGULAR:
var userRegularSet;
if(add) {
console.log(
"setUserChatRoomAccessLevel(): "
+ "Adding REGULAR membership for userId "
+ userId
);
userRegularSet = ChatRooms.update(chatRoomId, {$push:{accessRegular: userId}});
} else {
console.log(
"setUserChatRoomAccessLevel(): "
+ "Removing REGULAR membership for userId "
+ userId
);
userRegularSet = ChatRooms.update(
chatRoomId,
{$pull:{accessRegular:userId,currentUsers:userId}
});
}
return userRegularSet;
case USER_BANNED:
var userBanSet;
if(add) {
console.log(
"setUserChatRoomAccessLevel(): "
+ "Adding USER_BANNED membership for userId "
+ userId
);
userBanSet = ChatRooms.update(
chatRoomId,
{$push:{accessBanned:userId},$pull:{currentUsers:userId}
});
} else {
console.log(
"setUserChatRoomAccessLevel(): "
+ "Removing USER_BANNED membership for userId "
+ userId
);
userBanSet = ChatRooms.update(chatRoomId, {$pull:{accessBanned: userId}});
}
return userBanSet;
default:
return null;
}
},
/**
* @function createChatRoomInvite
* @memberof GameChatClient
* @desc Create chat room invite for user
* @param {String} userId - ID of user
* @param {String} chatRoomId - ID of chat room
* @param {?String} inviteMessage - Inviter message for invitee
* @returns {String} ID of new ChatRoomInvites doc
*/
createChatRoomInvite: function (userId, chatRoomId, inviteMessage) {
var inviterName = Meteor.user().username;
var inviteGameId = ChatRooms.findOne(chatRoomId).gameId;
var newInviteMessage;
// Create invite message if it hasn't already been created
if (inviteMessage == null) {
if (inviteGameId != null && Games.find({_id: inviteGameId}).count() === 1) {
newInviteMessage
= " invites you to play "
+ Games.findOne(inviteGameId).gameName;
} else {
newInviteMessage
= " has invited you to chat room "
+ ChatRooms.findOne(chatRoomId).roomname;
}
} else {
newInviteMessage = " " + inviteMessage;
}
// Make sure user is in list of invited users
if (ChatRooms.findOne(chatRoomId).invited.indexOf(userId) === -1) {
ChatRooms.update(chatRoomId, {$push:{invited:userId}});
}
return ChatRoomsInvites
.insert({
userId: userId,
chatRoomId: chatRoomId,
inviterName: inviterName,
inviteMessage: newInviteMessage
}
);
},
// TODO Hide chat rooms that the user does not have access to (not invited, banned, etc.)
/**
* @function getChatRooms
* @memberof GameChatClient
* @desc Returns a list of all chat rooms that the user can join.
* @returns {Mongo.Cursor} List of all chat rooms that the user can join
*/
getChatRooms: function () {
return ChatRooms.find({});
},
/**
* @function getChatRoomsInvites
* @memberof GameChatClient
* @desc Returns a list of all of the user's chat room invites.
* @returns {Mongo.Cursor} List of all chat room invites
*/
getChatRoomsInvites: function () {
return ChatRoomsInvites.find({});
},
/**
* @function getChatRoomsInvitesCount
* @memberof GameChatClient
* @desc Returns count of all of the user's unaccepted/undeclined invites
* @returns {Number} Number of unaccepted/undeclined invites
*/
getChatRoomsInvitesCount: function () {
return ChatRoomsInvites.find({userId: Meteor.userId()}).count();
},
/**
* @function acceptInvite
* @memberof GameChatClient
* @desc Accepts an invitation and switches to attached room
* @param inviteId - ID of chat room invite
*/
acceptInvite: function(inviteId) {
GameChatClient
.setCurrentRoomId(ChatRoomsInvites.findOne({_id: inviteId}).chatRoomId);
ChatRoomsInvites.remove(inviteId);
},
/**
* @function declineInvite
* @memberof GameChatClient
* @desc Declines an invitation
* @param inviteId - ID of chat room invite
*/
declineInvite: function(inviteId) {
ChatRoomsInvites.remove(inviteId);
},
/**
* @function getCurrentRoomId
* @memberof GameChatClient
* @desc Returns the ID of the client's currently active chat room
* @returns {String} ID of client's currently active chat room
*/
getCurrentRoomId: function () {
return Session.get("currentRoomId")
},
/**
* @function getOnlineUsers
* @memberof GameChatClient
* @desc Returns a list of all users (other than the calling one)
* that are currently online.
* NOTE: Sending identical values for both params will cancel both filters
* @param {Boolean} filterFriends - If true, remove users that are in Friends list
* @param {Boolean} filterNotFriends - If true, remove users that are NOT in Friends list
* @returns {Mongo.Cursor} List of all users that are currently online
*/
getOnlineUsers: function (filterFriends, filterNotFriends) {
if (filterFriends === filterNotFriends) {
return Meteor.users.find({"status.online": true,_id:{$ne: Meteor.userId()}});
}
if (filterFriends === true) {
return Meteor.users.find(
{
$and:
[
{"status.online":true},
{_id:{$ne:Meteor.userId()}},
{_id:{$nin:Friends.findOne({userId:Meteor.userId()}).friends}}
]
}
);
}
return Meteor.users.find(
{
$and:
[
{"status.online":true},
{_id:{$ne:Meteor.userId()}},
{_id:{$in:Friends.findOne({userId:Meteor.userId()}).friends}}
]
}
);
},
/**
* @function sendChatMessage
* @memberof GameChatClient
* @desc Sends a message from the user to a chat room.
* @param {String} roomId - Id of chat room to update with message
* @param {String} message - Contents of user's message
*/
sendChatMessage: function (roomId, message) {
Meteor.call('sendNewChatMessage', roomId, message);
},
/**
* @function setCurrentRoomId
* @memberof GameChatClient
* @desc Sets the ID of the client's currently active room
* @param {String} newCurrentRoomId - ID of the client's new currently active room
*/
setCurrentRoomId: function (newCurrentRoomId) {
var oldRoomId = GameChatClient.getCurrentRoomId();
Session.set("currentRoomId", newCurrentRoomId);
Meteor.call('leaveChatRoom', oldRoomId);
Meteor.call('joinChatRoom', newCurrentRoomId);
},
/* Game Functions */
// TODO Make these functions available to site admin only
// TODO Add game images
/**
* @function addGame
* @memberof GameChatClient
* @desc Adds game to GameChat DB
* @param {String} gameName - Name of game
* @param {String} gameDescription - Description of game
* @param {String} gameUrl - URL of game
* @returns Unique _id of document if successful
*/
addGame: function (gameName, gameDescription, gameUrl) {
return Games.insert(
{
gameName: gameName,
gameDescription: gameDescription,
gameUrl: gameUrl
}
);
},
// TODO Remove game images
/**
* @function removeGame
* @memberof GameChatClient
* @desc Removes game from GameChat DB
* @param {String} gameId - ID of game document
*/
removeGame: function (gameId) {
Games.remove(gameId);
},
// TODO Update game images
/**
* @function updateGame
* @memberof GameChatClient
* @desc Updates game document in GameChat DB
* @param {String} gameId - ID of game document
* @param {?String} gameName - Name of game
* @param {?String} gameDescription - Description of game
* @param {?String} gameUrl - URL of game
*/
updateGame: function (gameId, gameName, gameDescription, gameUrl) {
if (gameName != null) {
Games.update(gameId, {gameName: gameName});
}
if (gameDescription != null) {
Games.update(gameId, {gameDescription: gameDescription});
}
if (gameUrl != null) {
Games.update(gameId, {gameUrl : gameUrl});
}
},
/**
* @function getGames
* @memberof GameChatClient
* @desc Returns a list of all games for which a chat room can be started.
* @returns {Mongo.Cursor} List of all games that can be assigned to a chat room
*/
getGames: function () {
return Games.find({});
},
/* ===== Admin functions ===== */
/**
* @function userIsAdmin
* @memberof GameChatClient
* @desc Returns true/false if the user is/is not an admin.
* @param {String} userId - ID of user to check for admin status
* @returns {Boolean} True if user is admin, false otherwise
*/
userIsAdmin:function (userId) {
return Meteor.users.findOne(userId).isAdmin;
},
/**
* @function toggleUserAdmin
* @memberof GameChatClient
* @desc Toggles the admin status of another user. User MUST be admin.
* @param {String} userId - ID of user for whom to toggle admin status
*/
toggleUserAdmin: function (userId) {
Meteor.call('toggleUserAdmin', userId);
},
/**
* @function deleteAccount
* @desc Delete a user account
* @param {userId} - ID of user account to delete
*/
deleteAccount: function (userId) {
Meteor.call('deleteAccount', userId);
},
/* ===== Friend functions ===== */
/**
* @function sendFriendRequest
* @desc Send a friend request
* @param {String} friendUserId - ID of user to which request will be sent
*/
sendFriendRequest: function (friendUserId) {
console.log("sendFriendRequest(): now running on client");
Meteor.call('sendFriendRequest', friendUserId);
},
/**
* @function acceptFriendRequest
* @desc Accept a friend request
* @param {String} friendInviteId - ID of friend request invite
*/
acceptFriendRequest: function (friendInviteId) {
var inviterUserId
= Meteor.users
.findOne({username:ChatRoomsInvites.findOne(friendInviteId).inviterName})
._id;
ChatRoomsInvites.remove(friendInviteId);
Meteor.call('acceptFriendRequest', inviterUserId);
},
/**
* @function denyFriendRequest
* @desc Deny a friend request
* @param {String} notFriendInviteId - ID of friend request invite
*/
denyFriendRequest: function (notFriendInviteId) {
console.log("GameChatClient.denyFriendRequest(): now running");
var inviterUserId
= Meteor.users
.findOne({username:ChatRoomsInvites.findOne(notFriendInviteId).inviterName})
._id;
ChatRoomsInvites.remove(notFriendInviteId);
Meteor.call('denyFriendRequest', inviterUserId);
}
};
|
(function() {
'use strict';
angular
.module('assessoriaTorrellesApp')
.factory('Photo', Photo);
Photo.$inject = ['$resource', 'DateUtils'];
function Photo ($resource, DateUtils) {
var resourceUrl = 'api/photos/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true},
'insertPhoto':{method : 'POST', url: '/api/properties/:id/photos'}, //TODO remove hardcoded /1/ and replace with actual id
'getPhotos':{method:'GET',url:'/api/properties/:id/photos',isArray: true},
'deletePhoto':{method:'DELETE',url:'/api/properties/:id/photos'},
'makeCover':{method:'POST',url:'/api/properties/:idProperty/cover/:idPhoto'},
'get': {
method: 'GET',
transformResponse: function (data) {
if (data) {
data = angular.fromJson(data);
data.created = DateUtils.convertDateTimeFromServer(data.created);
}
return data;
}
},
'update': { method:'PUT' }
});
}
})();
|
/**
* =======================================================================================================
*
* Seezoo page_list Controller
*
* @package Seezoo Core
* @author Yoshiaki Sugimoto <neo.yoshiaki.sugimoto@gmail.com>
*
* =======================================================================================================
*/
ClassExtend('Controller', function DashboardPagesPageListController() {
var pp;
/**
* =======================================================================================================
* constructor
* =======================================================================================================
*/
this.__construct = function() {
this.load.module('ui');
this.load.model('page_model');
this.load.library(['page_operator', 'sz_calendar']);
};
/**
* =======================================================================================================
* default method
* =======================================================================================================
*/
this.index = function() {
var that = this;
// create sitemap menu
this.menu = this._createSitemapMenu();
// set up page_operator library
this.ready('page_operator', function() {
this.page_operator.init();
});
this.menu.detect('a').Cevent('click', function(ev) {
ev.preventDefault();
ev.stopPropagation();
switch (ev.target.className) {
case 'delete_page':
if (this.menu.readAttr('target_page_id') !== '1') {
this.page_operator.deleteCurrent(ev.target.href);
} else {
alert('トップページ(ページIDが1のもの)は削除できません。');
this.menu.hide();
}
break;
case 'visit':
location.href = ev.target.href;
break;
case 'sz_page_move_upper':
this.page_operator.movePageLevel(true);
break;
case 'sz_page_move_lower':
this.page_operator.movePageLevel(false);
break;
}
});
// DOM.id('with_system').event('click', function() {
// // submit and set cookie value
// this.parentNode.submit();
// });
// set event
DOM('a.sz_zoom').event('click', this.editPage, this);
};
/**
* =======================================================================================================
* _createSitemapMenu
* create sitemap control menu
* @access public
* @execute call
* @return xElement map
* =======================================================================================================
*/
this._createSitemapMenu = function() {
var map = DOM.create('div', {'class' : 'sz_sitemap_menu', 'id' : 'sz_sitemaps'})
.appendTo(window['IEFIX'] ? IEFIX.body : document.body),
links, html;
html =['<div class="sz_sitemap_menu_top"></div>',
'<div id="sz_sitemap_content">',
'<ul>',
'<li><a href="#" class="visit">訪問</a></li>',
'<li><a href="#" class="sz_zoom page_config">ページ設定</a></li>',
'<li><a href="#" class="sz_zoom create_page">子ページ作成</a></li>',
'<li><a href="#" class="sz_zoom create_external_link">外部リンク作成</a></li>',
'<li><a href="#" class="sz_zoom view_version">バージョン情報</a></li>',
'<li><a href="javascript:void(0)" class="sz_page_move_upper">ページ順を上へ</a></li>',
'<li><a href="javascript:void(0)" class="sz_page_move_lower">ページ順を下へ</a></li>',
'<li><a href="#" class="copy_page">ページを複製する</a></li>',
'<li><a href="#" class="delete_page">削除</a></li>',
'</ul>',
'</div>',
'<div class="sz_sitemap_menu_bottom"></div>'
];
return map.html(html.join('\n'));
};
this.editPage = function(ev) {
var e = DOM(ev.target), tab = true, that = this,
ttl, add, v = true;
if (e.hasClass('page_config')) {
if ( e.readAttr('href').indexOf('external') !== -1 ) {
ttl = '外部リンク設定の変更'; add = false; tab = false; v = false;
} else {
ttl = 'ページ設定の変更'; add = false;
}
} else if (e.hasClass('view_version')) {
ttl = 'バージョン情報'; add = false; tab = false;
} else if ( e.hasClass('create_external_link') ) {
ttl = '外部リンクを追加'; add = false; v = false; tab = false;
} else {
ttl = '子ページの追加'; add = true;
}
pp = Helper.createDOMWindow(ttl, '', 650, (v) ? '90%' : 300, false, true);
this.ajax.get(e.readAttr('href'), {
success : function(resp) {
pp.setContent(resp.responseText);
// pre delete caption...
pp.box.getOne('h3').remove();
if (tab) {
// set up tab
that.page_model.tabChange();
// set up calendar
that.sz_calendar.initialize({template : 'sz_calendar', yearRange : 'current-2011'});
that.sz_calendar.setUp(DOM.byName('public_ymd').get(0));
// cancel submit event and process ajax
DOM.create('input').attr({type : 'hidden', name : 'from_po', value : 1}).prependTo(DOM('p.sz_add_form_submit').get(0));
pp.box.getOne('form#sz-page_add_form').event('submit', that[add ? 'pageAddBackend' : 'editPageBackend'], that);
pp.setOnClose(function() {
if (pp.box) {
pp.box.getOne('form#sz-page_add_form').unevent('submit');
}
});
if (DOM.id('check_exists')) {
DOM.id('check_exists').event('click', function(ev) {
ev.stopPropagation();
var p = DOM.id('sz_input_page_path'),
path = p.getValue();
parentPath = that.ut.trim(p.prev().getHTML()),
pid = ev.target.rel;
if (path == '') {
return alert('ページパスを入力してください。');
}
that.page_operator.checkPagePathExists(parentPath + path, pid);
})
}
} else {
window.SZ_PAGE_ID = DOM.id('sz_sitemaps').readAttr('target_page_id');
if ( v ) {
that.page_model.pv_init(DOM.id('sz_sitemaps').readAttr('target_page_id'));
} else {
DOM.id('sz_sitemaps').hide();
pp.setOnClose(function() {
if (pp.box) {
pp.box.getOne('form#sz-page_add_form').unevent('submit');
}
});
pp.box.getOne('form#sz-page_add_form').event('submit', function(ev) {
ev.preventDefault();
var uri = DOM.id('add_external_uri').getValue(),
title = DOM.id('add_external_title').getValue(),
err = [];
if ( uri === '' ) {
err[err.length] = 'URLは必須入力です。';
} else if ( ! /^http[s]?:\/\/[\w\.\/]+([\/|\?]?[\-_.!~\*a-zA-Z0-9\/\?:;@&=+$,%#]+)?$/.test(uri) ) {
err[err.length] = 'URLの形式が正しくありません。';
}
if ( title === '' ) {
err[err.length] = 'リンクタイトルは必須入力です。';
} else if ( title.length > 255 ) {
err[err.length] = 'リンクタイトルは255文字以内で入力してください。';
}
if ( err.length > 0 ) {
alert(err.join('\n'));
return;
}
that.externalPageAddBackend(this);
});
}
}
}
});
};
/**
* =======================================================================================================
* editPageBackend
* edit page config on ajax backend
* @access public
* @execute event handler
* @param Event ev
* @return void
* =======================================================================================================
*/
this.editPageBackend = function(ev) {
ev.preventDefault();
var e = DOM(ev.target), that = this, json, pid;
// validate required values.
if (this.__validate() === false) { return;}
this.ajax.post('ajax/page_edit_process/' + this.config.siteUrl(), {
param : e.serialize(),
error : function() {alert('ページ設定の変更に失敗しました。');},
success : function(resp) {
var txtNode;
if (resp.responseText === 'editting') {
return alert('このページを編集中のユーザーがいます。編集が終わってから再度実行してください。');
}
try {
json = that.json.parse(resp.responseText);
if (json.error_message) {
return alert(json.error_message);
}
txtNode = DOM.origCSS('span[pid=' + json.page_id + ']').get(0).get();
txtNode.normalize();
txtNode.removeChild(txtNode.firstChild);
txtNode.insertBefore(document.createTextNode(json.page_title), txtNode.firstChild);
} catch(e) {
return alert((['予期しない例外が発生しました。ページを更新し、再度お試し下さい。',
'それでも問題が解決しない場合は、以下の情報を添えてサイトの管理者にお問い合わせ下さい。\n',
'レスポンス:',
resp.responseText
]).join('\n'));
}
pp.hide();
}
});
};
/**
* =======================================================================================================
* pageAddBackend
* add new page on ajax backend
* @access public
* @execute event handler
* @param Event ev
* @return void
* =======================================================================================================
*/
this.pageAddBackend = function(ev) {
ev.preventDefault();
var e = DOM(ev.target), that = this, json, pid, spn;
// validate required values.
if (this.__validate() === false) { return;}
this.ajax.post('ajax/page_add_process/' + this.config.item('sz_token'), {
param : e.serialize(),
error : function() {alert('ページの追加に失敗しました。');},
success : function(resp) {
if (resp.responseText === 'editting') {
alert('このページを編集中のユーザーがいます。編集が終わってから再度実行してください。');
} else {
try {
json = that.json.parse(resp.responseText);
if (json.page_id == 1) {
that.page_operator._makeChild(DOM.id('page_' + json.page_id));
} else {
that.page_operator._makeChild(DOM.origCSS('span[pid=' + json.page_id + ']').get(0).parent(4));
}
} catch(e) {}
}
pp.hide();
}
});
};
/**
* =======================================================================================================
* externalPageAddBackend
* add new external linked page on ajax backend
* @access public
* @execute call
* @param xElement form
* @return void
* =======================================================================================================
*/
this.externalPageAddBackend = function(form) {
var that = this, json, pid, spn;
this.ajax.post('ajax/page_add_process/' + this.config.item('sz_token'), {
param : DOM(form).serialize(),
error : function() {
alert('外部リンクの追加に失敗しました。');
},
success : function(resp) {
if (resp.responseText === 'editting') {
alert('このページを編集中のユーザーがいます。編集が終わってから再度実行してください。');
} else {
try {
json = that.json.parse(resp.responseText);
if (json.page_id == 1) {
that.page_operator._makeChild(DOM.id('page_' + json.page_id));
} else {
that.page_operator._makeChild(DOM.origCSS('span[pid=' + json.page_id + ']').get(0).parent(4));
}
} catch(e) {}
}
pp.hide();
}
});
};
/**
* =======================================================================================================
* __validate
* validate value simply.
* @access private
* @execute call
* @return bool
* =======================================================================================================
*/
this.__validate = function() {
var ttl = DOM.id('sz_input_page_title'),
path = DOM.id('sz_input_page_path'),
err = [];
if (ttl && ttl.getValue() === '') {
err.push('ページタイトルは必須入力です。');
}
if (path) {
if (path.getValue() === '') {
err.push('ページパスは必須入力です。');
} else if (path.getValue().indexOf('/') !== -1) {
err.push('ページパスに / は使用できません。');
}
}
if (err.length > 0) {
alert(err.join('\n'));
return false;
}
return true;
};
});
|
module.exports = require('async')(function *(resolve, reject, module, processor, config) {
"use strict";
let Finder = require('finder');
let error = require('./error.js')(module);
if (typeof config === 'string') {
config = {'files': [config]};
}
if (config instanceof Array) {
config = {'files': config};
}
if (typeof config !== 'object') {
reject(error('invalid processor "' + processor + '" configuration'));
return;
}
let files = (typeof config.files === 'string') ? [config.files] : config.files;
if (!(files instanceof Array)) {
reject(error('invalid files specification on processor "' + processor + '" configuration'));
return;
}
let path = (config.path) ? config.path : './';
path = require('path').join(module.dirname, path);
let finder = new Finder(path, {'list': files, 'usekey': 'relative.file'});
try {
yield finder.process();
}
catch (exc) {
reject(error(exc.message));
return;
}
files = [];
for (let key in finder.items) {
files.push(finder.items[key]);
}
resolve(files);
});
|
gulp.task(mts('images'), function () {
return gulp.src([
// Returns 'src/**/*.gif' and so on....
build.src('/**/*.gif'),
build.src('/**/*.ico'),
build.src('/**/*.jpg'),
build.src('/**/*.png')
])
.pipe(gulpif(gzipOn, gzip(gzipOpt)))
.pipe(gulp.dest(build.destLocale()));
});
|
define('util', function () {
var _formatJson_cache = {};
/**
* [object2param 转换对象为url参数]
* @param {[type]} o [要转换的对象]
* @param {[type]} [transVal] [值编码函数]
* @return {[type]} [description]
*/
function object2param(o, transVal) {
var r = [],
transVal = transVal || function (v) {
return encodeURIComponent(v);
};
for (var k in o) {
r.push(k + '=' + transVal(o[k]));
}
return r.join('&');
}
/**
* [getCookie 获取cookie]
* @param {[type]} name [cookie名]
* @return {[type]} [description]
*/
function getCookie(name) {
var reg = new RegExp("(^| )" + name + "(?:=([^;]*))?(;|$)"),
val = document.cookie.match(reg);
return val ? (val[2] ? decodeURIComponent(val[2]) : "") : null;
}
/**
* [setCookie 设置cookie]
* @param {[type]} name [cookie名]
* @param {[type]} value [值]
* @param {[type]} expires [过期时间,单位分钟]
* @param {[type]} path [路径]
* @param {[type]} domain [域]
* @param {[type]} secure [是否是安全cookie]
*/
function setCookie(name, value, expires, path, domain, secure) {
var exp = new Date(),
expires = arguments[2] || null,
path = arguments[3] || "/",
domain = arguments[4] || null,
secure = arguments[5] || false;
expires ? exp.setMinutes(exp.getMinutes() + parseInt(expires)) : "";
document.cookie = name + '=' + encodeURIComponent(value) + (expires ? ';expires=' + exp.toGMTString() : '') + (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : '');
}
/**
* [delCookie 删除cookie]
* @param {[type]} name [cookie名]
* @param {[type]} path [路径]
* @param {[type]} domain [域]
* @param {[type]} secure [是否安全cookie]
* @return {[type]} [description]
*/
function delCookie(name, path, domain, secure) {
var value = getCookie(name);
if (value != null) {
var exp = new Date();
exp.setMinutes(exp.getMinutes() - 1000);
path = path || "/";
document.cookie = name + '=;expires=' + exp.toGMTString() + (path ? ';path=' + path : '') + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : '');
}
}
/**
* [formatJson 模板解析]
* @param {[type]} str [模板串]
* @param {[type]} data [数据]
* @return {[type]} [解析后的字符串]
*/
function formatJson(str, data) {
var fn = !/\W/.test(str) ? _formatJson_cache[str] = _formatJson_cache[str] || formatJson(document.getElementById(str).innerHTML) : new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + "with(obj){p.push('" + str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g, "$1\r").replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'") + "');}return p.join('');");
return data ? fn(data) : fn;
}
/**
* 模板解析,解析{}包裹的数据
* @param tpl 模板
* @param data 数据
* @returns {XML|string|void}
*/
function format(tpl, data) {
return tpl.replace(/{([^\}]+)}/g, function (v, v1) {
return data.hasOwnProperty(v1) ? data[v1] : v || '';
});
}
/**
* [loadJsonp 加载jsonp数据]
* @param {[type]} url [url地址]
* @param {[type]} opt [配置参数]
* @return {[type]} [description]
*/
function loadJsonp(url, opt) {
var option = {
onLoad: null,
onError: null,
onTimeout: null,
timeout: 8000,
charset: "utf-8"
};
var timer;
if (arguments.length == 1) {
if (typeof arguments[0] == "object") {
opt = arguments[0];
url = opt.url;
} else {
opt = {};
}
}
if (typeof(opt.data) == 'object') {
var param = [];
for (var k in opt.data) {
param.push(k + '=' + opt.data[k])
}
if (param.length > 0) {
param = param.join('&');
url += (url.indexOf('?') > 0 ? '&' : '?') + param;
}
}
for (var i in opt) {
if (opt.hasOwnProperty(i)) {
option[i] = opt[i];
}
}
var el = document.createElement("script");
el.charset = option.charset || "utf-8";
el.onload = el.onreadystatechange = function () {
if (/loaded|complete/i.test(this.readyState) || navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
option.onLoad && option.onLoad();
clear();
}
};
el.onerror = function () {
option.onError && option.onError();
clear();
};
el.src = url;
document.getElementsByTagName('head')[0].appendChild(el);
if (typeof option.onTimeout == "function") {
timer = setTimeout(function () {
option.onTimeout();
}, option.timeout);
}
;
var clear = function () {
if (!el) {
return;
}
timer && clearTimeout(timer);
el.onload = el.onreadystatechange = el.onerror = null;
el.parentNode && (el.parentNode.removeChild(el));
el = null;
}
}
/**
* [setHash 设置hash值]
* @param {[type]} val [description]
*/
function setHash(val) {
setTimeout(function () {
location.hash = val;
}, 0);
}
/**
* [getHash 获取hash值]
* @param {[type]} url [取值的url]
* @return {[type]} [hash值]
*/
function getHash(url) {
var u = url || location.hash;
return u ? u.replace(/.*#/, "") : "";
}
/**
* [getHashParam 获取hash值]
* @param {[type]} name [hash名]
* @return {[type]} [hash值]
*/
function getHashParam(name) {
var result = this.getHash().match(new RegExp("(^|&)" + name + "=([^&]*)(&|$)"));
return result != null ? result[2] : "";
}
/**
* [getUrlParam 获取url参数值]
* @param {[type]} name [url参数名]
* @param {[type]} url [url地址,默认当前host]
* @return {[type]} [url参数值]
*/
function getUrlParam(name, url) {
var u = arguments[1] || window.location.search,
reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
r = u.substr(u.indexOf("\?") + 1).match(reg);
return r != null ? r[2] : "";
}
/**
* [getParams 获取所有的参数]
* @return {[type]} [参数数组]
*/
function getParams() {
var param = [],
hash = this.getHash();
paramArr = hash ? hash.split("&") : [];
for (var i = 1, l = paramArr.length; i < l; i++) {
param.push(paramArr[i]);
}
return param;
}
/**
* [decodeUrl 解码url地址]
* @param {[type]} url [url地址]
* @return {[type]} [description]
*/
function decodeUrl(url) {
url = decodeURIComponent(url);
var urlObj = parseUrl(url),
decodedParam = [];
if (urlObj && urlObj.params) {
var value;
for (var key in urlObj.params) {
value = decodeURIComponent(urlObj.params[key]);
decodedParam.push(key + "=" + value);
}
}
var urlPrefix = url.split("?")[0];
return urlPrefix + "?" + decodedParam.join("&");
}
/**
* [parseUrl 处理url地址]
* @param {[type]} url [url地址]
* @return {[type]} [description]
*/
function parseUrl(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':', ''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function () {
var ret = {},
seg = a.search.replace(/^\?/, '').split('&'),
len = seg.length,
i = 0,
s;
for (; i < len; i++) {
if (!seg[i]) {
continue;
}
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/([^\/?#]+)$/i) || [, ''])[1],
hash: a.hash.replace('#', ''),
path: a.pathname.replace(/^([^\/])/, '/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
segments: a.pathname.replace(/^\//, '').split('/')
};
}
/**
* [replaceParam 替换url参数值]
* @param {[type]} param [参数名]
* @param {[type]} value [参数值]
* @param {[type]} url [url地址]
* @param {[type]} forceReplace [强制地图换]
* @return {[type]} [结果值]
*/
function replaceParam(param, value, url, forceReplace) {
url = url || location.href;
var reg = new RegExp("([\\?&]" + param + "=)[^&#]*");
if (!url.match(reg)) {
return (url.indexOf("?") == -1) ? (url + "?" + param + "=" + value) : (url + "&" + param + "=" + value);
}
if (forceReplace) {
return url.replace(reg, "$1" + value);
}
return url;
}
/**
* [isDate 检查数据是否是日期类型]
* @param {[String]} d [要检查的字符串]
* @return {Boolean} [返回值]
*/
function isDate(d) {
var r;
try {
r = !!Date.parse(d.replace(/-/g, '/'));
} catch (e) {
r = false;
}
return r;
}
/**
* [once 执行一次的函数]
* @param {Function} fn [要执行的函数]
* @return {[function]} [返回无论条用多少次都执行一次的函数]
*/
function once(fn) {
var run = false;
return function () {
!run && (run = !run, fn.apply(arguments[0] || null, Array.prototype.slice.call(arguments, 1)));
}
}
/**
* [getTodayStr 获取日期的今天年月日表示法]
* @param {Date|String} [date] [要获取的日期对象或日期对象字符串]
* @return {[String]} [年月日字符串]
*/
function getTodayStr(date) {
var d = date || new Date();
d = 'string' === typeof d ? new Date(d) : d;
return d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate();
}
/**
* 日志输出
* @param msg
*/
function log(msg) {
window.console && console.log(msg);
}
/**
* html转码
* @param value
*/
function htmlEncode(value) {
var d = document.createElement('div');
d.innerText = value;
return d.innerHTML;
}
/**
* html 代码还原
* @param value
*/
function htmlDecode(value) {
var d = document.createElement('div');
d.innerHTML = value;
return d.innerText;
}
function is(type, target) {
return Object.prototype.toString.call(target) === '[object ' + type + ']';
}
function deepClone(source, target) {
if (target) {
for (var k in target) {
if (target.hasOwnProperty(k)) {
var v = target[k];
if (is('Object', v)) {
source[k] = {};
deepClone(source[k], v);
}
else if (is('Array', v)) {
source[k] = [];
for (var i = 0, l = v.length; i < l; i++) {
source[k][i] = v[i];
deepClone(source[k][i], v[i]);
}
}
else {
source[k] = target[k];
}
}
}
}
return source;
}
function EventBase() {
this._events = {}
}
EventBase.prototype = {
on: function (name, fn) {
var evt = this._events[name] || (this._events[name] = []);
typeof fn === 'function' && evt.push(fn);
return this;
},
trigger: function (name) {
var evt = this._events[name];
if (evt && evt.length) {
for (var i = 0; i < evt.length; i++) {
evt[i].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
},
off: function (name, fn) {
if (name) {
var evt = this._events[name];
if (fn) {
for (var i = 0; i < evt.length; i++) {
if (fn === evt[i]) {
evt.splice(i--, 1);
}
}
}
else {
this._events[name] = [];
}
}
else {
this._events = {};
}
return this;
}
};
function TouchListen(opt) {
this.agile = opt && opt.agile || 50; // 灵敏度, 单位毫秒
this._events = {};
}
TouchListen.prototype = {
init: function () {
var self = this;
document.addEventListener('touchstart', function (e) {
self.startPoint = e.targetTouches[0];
self.time = e.timeStamp;
});
document.addEventListener('touchmove', function (e) {
var t = e.timeStamp, endPoint;
if (t - self.time > self.agile) {
self.time = t;
endPoint = e.targetTouches[0];
if (endPoint.screenX - self.startPoint.screenX > 0) {
self.trigger('swipeRight', e);
}
if (endPoint.screenX - self.startPoint.screenX < 0) {
self.trigger('swipeLeft', e);
}
if (endPoint.screenY - self.startPoint.screenY > 0) {
self.trigger('swipeDown', e);
}
if (endPoint.screenY - self.startPoint.screenY < 0) {
self.trigger('swipeUp', e);
}
}
});
}
};
deepClone(TouchListen.prototype, EventBase.prototype);
/**
* 清除空格
* @param str
*/
function trim(str) {
return str ? str.replace(/^\s*|\s*$/g, '') : str;
}
/**
* 清除左侧空格
* @param str
*/
function ltrim(str) {
return str ? str.replace(/^\s*/g, '') : str;
}
/**
* 清除右侧空格
* @param str
* @returns {XML|string|void}
*/
function rtrim(str) {
return str ? str.replace(/\s*$/g, '') : str;
}
/**
* 延迟执行
* @param fn 函数
* @returns {*} 线程id
*/
function delay(fn) {
return (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (callback) {
window.setTimeout(callback, 1000 / 60);
})(fn);
}
/**
* 取消延迟执行
* @param id 线程id
*/
function unDelay(id) {
(window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function (id) {
window.clearTimeout(id);
})(id);
}
/**
* 灰度测试
* @param fn 灰度检测函数
*/
function grayDebug(fn) {
var test = grayTest(fn);
return function (msg) {
test(window.alert, msg);
}
}
/**
* 灰度测试
* @param fn 灰度检测函数
*/
function grayTest(fn) {
var f = typeof fn === 'function' ? fn : function (members) {
var user = localStorage.username || getCookie('username');
if (user && members.indexOf(user) > -1) {
return true;
}
return false;
};
return function (factory, args, context) {
var factory = typeof factory === 'function' ? factory : window.alert, args = is('Array', args) ? args : args ? [args] : []
if (is('Array', fn)) {
if (f(fn)) {
factory.apply(context || window, args);
}
}
else if (f()) {
factory.apply(context || window, args);
}
}
}
return {
object2param: object2param,
cookie: {
get: getCookie,
set: setCookie,
del: delCookie
},
url: {
setHash: setHash,
getHash: getHash,
getHashParam: getHashParam,
getUrlParam: getUrlParam,
getParams: getParams,
decodeUrl: decodeUrl,
parseUrl: parseUrl,
replaceParam: replaceParam
},
formatJson: formatJson,
format: format,
loadJsonp: loadJsonp,
date: {
isDate: isDate,
getTodayStr: getTodayStr
},
htmlEncode: htmlEncode,
htmlDecode: htmlDecode,
once: once,
is: is,
deepClone: deepClone,
EventBase: EventBase,
TouchListen: TouchListen,
trim: trim,
ltrim: ltrim,
rtrim: rtrim,
log: log,
delay: delay,
unDelay: unDelay,
grayDebug: grayDebug,
grayTest: grayTest
};
})
; |
/*
Copyright 2014, KISSY v5.0.0
MIT Licensed
build time: Aug 26 16:05
*/
/*
combined modules:
component/plugin/drag
*/
KISSY.add('component/plugin/drag', ['dd'], function (S, require, exports, module) {
/**
* @ignore
* drag plugin for kissy component
* @author yiminghe@gmail.com
*/
var DD = require('dd');
function onDragEnd() {
var component = this.component;
var offset = component.$el.offset();
component.setInternal('xy', [
offset.left,
offset.top
]);
} /**
* drag plugin for kissy component
*
* @example
* KISY.use('overlay,component/plugin/drag,dd/plugin/proxy',
* function(S,Overlay,DragPlugin,ProxyPlugin){
* var o =new Overlay.Dialog({
* plugins:[
* new DragPlugin({
* handles: [function(){ return o.get('header'); }],
* plugins: [ProxyPlugin]
* })
* ]
* })
* // or
* o.plug(new DragPlugin({
* handles:[function(){ return o.get('header'); }]
* });
* });
*
*
* @class KISSY.Component.Plugin.Drag
* @extends KISSY.DD.Draggable
*/
/**
* drag plugin for kissy component
*
* @example
* KISY.use('overlay,component/plugin/drag,dd/plugin/proxy',
* function(S,Overlay,DragPlugin,ProxyPlugin){
* var o =new Overlay.Dialog({
* plugins:[
* new DragPlugin({
* handles: [function(){ return o.get('header'); }],
* plugins: [ProxyPlugin]
* })
* ]
* })
* // or
* o.plug(new DragPlugin({
* handles:[function(){ return o.get('header'); }]
* });
* });
*
*
* @class KISSY.Component.Plugin.Drag
* @extends KISSY.DD.Draggable
*/
module.exports = DD.Draggable.extend({
pluginId: 'component/plugin/drag',
pluginBindUI: function (component) {
this.set('node', component.$el);
this.start();
this.component = component;
this.on('dragend', onDragEnd);
},
pluginDestructor: function () {
this.destroy();
}
}, {
ATTRS: {
move: { value: 1 },
groups: { value: false }
}
});
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The production QuantifierPrefix :: { DecimalDigits , DecimalDigits }
evaluates as ...
es5id: 15.10.2.7_A1_T10
description: Execute /b{0,93}c/.exec("aaabbbbcccddeeeefffff") and check results
---*/
__executed = /b{0,93}c/.exec("aaabbbbcccddeeeefffff");
__expected = ["bbbbc"];
__expected.index = 3;
__expected.input = "aaabbbbcccddeeeefffff";
//CHECK#1
if (__executed.length !== __expected.length) {
$ERROR('#1: __executed = /b{0,93}c/.exec("aaabbbbcccddeeeefffff"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length);
}
//CHECK#2
if (__executed.index !== __expected.index) {
$ERROR('#2: __executed = /b{0,93}c/.exec("aaabbbbcccddeeeefffff"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index);
}
//CHECK#3
if (__executed.input !== __expected.input) {
$ERROR('#3: __executed = /b{0,93}c/.exec("aaabbbbcccddeeeefffff"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input);
}
//CHECK#4
for(var index=0; index<__expected.length; index++) {
if (__executed[index] !== __expected[index]) {
$ERROR('#4: __executed = /b{0,93}c/.exec("aaabbbbcccddeeeefffff"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]);
}
}
|
'use strict';
const fs = require('fs');
const path = require("path");
const Sequelize = require('sequelize');
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
const sequelize = new Sequelize(config.database, config.username, config.password, config);
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf(".") !== 0) && (file !== "index.js");
})
.forEach((file) => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
|
/**
Digg data collection
@class DiggCollection
@constructor
@return {Object} instantiated DiggCollection
**/
define(['jquery', 'backbone', 'DiggModel'], function ($, Backbone, DiggModel) {
var DiggCollection = Backbone.Collection.extend({
/**
Constructor
@method initialize
**/
initialize: function () {
var self = this;
},
/**
Fetch the collection data from server
@method getData
**/
getData: function () {
var self = this;
self.fetch({
data: {},
success: function (models) {
log(models);
},
error: function () {
log('error fetch collection');
}
});
},
model: DiggModel,
url: 'https://secure.digitalsignage.com/Digg'
});
return DiggCollection;
}); |
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2018 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
var CircumferencePoint = require('./CircumferencePoint');
var FromPercent = require('../../math/FromPercent');
var MATH_CONST = require('../../math/const');
var Point = require('../point/Point');
/**
* Returns a Point object containing the coordinates of a point on the circumference of the Circle
* based on the given angle normalized to the range 0 to 1. I.e. a value of 0.5 will give the point
* at 180 degrees around the circle.
*
* @function Phaser.Geom.Circle.GetPoint
* @since 3.0.0
*
* @generic {Phaser.Geom.Point} O - [out,$return]
*
* @param {Phaser.Geom.Circle} circle - The Circle to get the circumference point on.
* @param {number} position - A value between 0 and 1, where 0 equals 0 degrees, 0.5 equals 180 degrees and 1 equals 360 around the circle.
* @param {(Phaser.Geom.Point|object)} [out] - An object to store the return values in. If not given a Point object will be created.
*
* @return {(Phaser.Geom.Point|object)} A Point, or point-like object, containing the coordinates of the point around the circle.
*/
var GetPoint = function (circle, position, out)
{
if (out === undefined) { out = new Point(); }
var angle = FromPercent(position, 0, MATH_CONST.PI2);
return CircumferencePoint(circle, angle, out);
};
module.exports = GetPoint;
|
import _ from 'lodash';
function getPersistedValue() {
return _.get(global, 'localStorage.hideIntro', false);
}
function setPersistedValue(value) {
if(!global.localStorage) return;
if(!value) {
delete global.localStorage.hideIntro;
}
else {
global.localStorage.hideIntro = value;
}
}
export function shouldShowIntro() {
return !getPersistedValue();
}
export function setIntroVisibility(visible) {
setPersistedValue(!visible);
} |
/**
* Враппер для потомков и врапперов {@link croc.ui.form.field.AbstractTextField}
*/
croc.Mixin.define('croc.ui.form.field.MAbstractTextFieldWrapper', {
options: {
/**
* Добавить ячейки в конец поля
* @type {string|Array.<string>|croc.ui.Widget|Array.<Widget>}
*/
cellsAfter: {},
/**
* Добавить ячейки после ячейки с input
* @type {string|Array.<string>|croc.ui.Widget|Array.<Widget>}
*/
cellsAfterInput: {},
/**
* Добавить ячейки в начало поля
* @type {string|Array.<string>|croc.ui.Widget|Array.<Widget>}
*/
cellsBefore: {}
},
construct: function(options) {
this._addExtendingWrapperOptions('cellsAfter', 'cellsAfterInput', 'cellsBefore');
}
});
|
var mongoose,
Song;
mongoose = require('mongoose');
Song = mongoose.model('song');
//GET - Return all songs in the DB
exports.findAllSongs = function( req, res ) {
Song.find(function( err, songs ) {
if ( err ) {
res.send( 500, err.message );
}
console.log('GET /songs')
res.status( 200 ).jsonp( songs );
});
};
//GET - Return a song with specified ID
exports.findById = function( req, res ) {
Song.findById( req.params.id, function( err, song ) {
if ( err) {
return res.send( 500, err.message );
}
console.log( 'GET /song/' + req.params.id );
res.status( 200 ).jsonp( song );
});
};
//POST - Insert a new song in the DB
exports.addSong = function( req, res ) {
var song;
console.log('POST');
console.log( req.body );
song = new Song({
title: req.body.title,
album: req.body.album,
year: req.body.year,
artist: req.body.artist,
ranking: req.body.ranking,
rating: req.body.rating,
genre: req.body.genre,
summary: req.body.summary
});
song.save(function( err, song ) {
if ( err ) {
return res.send( 500, err.message );
}
res.status( 200 ).jsonp( song );
});
};
//PUT - Update a register that already exists
exports.updateSong = function( req, res ) {
Song.findById( req.params.id, function( err, song ) {
song.title = req.body.title;
song.album = req.body.album;
song.year = req.body.year;
song.artist = req.body.artist;
song.ranking = req.body.ranking;
song.rating = req.body.rating;
song.genre = req.body.genre;
song.summary = req.body.summary;
song.save(function( err ) {
if ( err ) {
return res.send( 500, err.message );
}
res.status( 200 ).jsonp( song );
});
});
};
//DELETE - Delete a song with specified ID
exports.deleteSong = function( req, res ) {
Song.findById( req.params.id, function( err, song ) {
song.remove(function( err ) {
if ( err ) {
return res.send( 500, err.message );
}
res.status( 200 );
})
});
}; |
import './flow-logic/index';
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {authActions} from 'modules/auth';
import {Link} from 'react-router-dom';
import inject from 'react-jss';
import {FlexBox, FlexItem} from 'components/Flex';
import Input from 'components/Input';
import Button from 'components/Button';
import styles from './styles';
import { localize } from 'modules/i18n';
import collection from './messages';
@localize({
collections: collection,
messageIds: {
emailPlaceholder: 'Login.emailPlaceholder',
passwordPlaceholder: 'Login.passwordPlaceholder',
withEmailPassword: 'Login.withEmailPassword',
or: 'Login.or',
withGoogle: 'Login.withGoogle',
signupCTA: 'Login.signupCTA',
signupLink: 'Login.signupLink'
}
})
@connect(
null,
dispatch => ({
loginEmail: (user, pw, redirect) => dispatch(authActions.loginEmail(user, pw, redirect)),
loginGoogle: (redirect) => dispatch(authActions.loginGoogle(redirect))
})
)
@inject(styles)
export default class Login extends Component {
state = {
email: "",
password: ""
}
handleFormChange = (e) => {
let {name, value} = e.target;
this.setState({[name]:value})
}
handleLogin = () => {
let {email, password} = this.state;
let {location, loginEmail} = this.props
let redirect;
if (location.state && location.state.from) redirect = location.state.from.pathname
loginEmail(email, password, redirect);
}
handleLoginGoogle = () => {
let {location, loginGoogle} = this.props
let redirect;
if (location.state && location.state.from) redirect = location.state.from.pathname
loginGoogle(redirect);
}
render() {
let {
classes,
emailPlaceholder,
passwordPlaceholder,
withEmailPassword,
or,
withGoogle,
signupCTA,
signupLink
} = this.props;
let {email, password} = this.state;
return (
<FlexBox className={classes.formContainer}>
<FlexItem fixed className={classes.inputItem}>
<Input
placeholder={emailPlaceholder.format()}
name="email"
value={email}
onChange={this.handleFormChange}
/>
</FlexItem>
<FlexItem fixed className={classes.inputItem}>
<Input
type='password'
placeholder={passwordPlaceholder.format()}
value={password}
name="password"
onChange={this.handleFormChange}
/>
</FlexItem>
<FlexItem fixed className={classes.buttonItem}>
<Button
primary
className={classes.button}
onClick={this.handleLogin}
>
{withEmailPassword.format()}
</Button>
</FlexItem>
<FlexItem fixed className={classes.orLabel}>
{or.format()}
</FlexItem>
<FlexItem fixed className={classes.buttonItem}>
<Button
className={classes.button}
onClick={this.handleLoginGoogle}
>
{withGoogle.format()}
</Button>
</FlexItem>
<FlexItem fixed className={classes.smallLabel}>
{signupCTA.format()}
<Link to='/signup'>
{signupLink.format()}
</Link>
</FlexItem>
</FlexBox>
)
}
}
|
'use strict';
const baAsn1 = require('../asn1');
module.exports.encode = (buffer, errorClass, errorCode) => {
baAsn1.encodeApplicationEnumerated(buffer, errorClass);
baAsn1.encodeApplicationEnumerated(buffer, errorCode);
};
module.exports.decode = (buffer, offset) => {
const orgOffset = offset;
let result;
result = baAsn1.decodeTagNumberAndValue(buffer, offset);
offset += result.len;
const errorClass = baAsn1.decodeEnumerated(buffer, offset, result.value);
offset += errorClass.len;
result = baAsn1.decodeTagNumberAndValue(buffer, offset);
offset += result.len;
const errorCode = baAsn1.decodeEnumerated(buffer, offset, result.value);
offset += errorClass.len;
return {
len: offset - orgOffset,
class: errorClass.value,
code: errorCode.value
};
};
|
/* ==========================================================
* gulpfile.js
* List of Gulp.js task to build and run the project
*
* Author: Yann Gouffon, yann@antistatique.net
* Date: 2014-04-29 17:53:14
*
* Copyright 2014 Federal Chancellery of Switzerland
* Licensed under MIT
*
* Last Modified by: Toni Fisler
* Last Modified time: 2014-04-30 14:33:12
========================================================== */
'use strict';
/**
* Import plugins
*/
var gulp = require('gulp'),
$ = require('gulp-load-plugins')(),
browserSync = require('browser-sync'),
reload = browserSync.reload,
runSequence = require('run-sequence'),
argv = require('yargs').argv,
del = require('del');
/**
* Build vendors dependencies
*/
gulp.task('vendors', function() {
// DEPRECATED, to be removed in 3.0.0
gulp.src([
'bower_components/jquery.socialshareprivacy/socialshareprivacy/images/*'
])
.pipe(gulp.dest('build/css/images'));
/**
* CSS VENDORS
*/
gulp.src([
'bower_components/yamm3/yamm/yamm.css',
'bower_components/jquery.socialshareprivacy/socialshareprivacy/socialshareprivacy.css',
'bower_components/bootstrapaccessibilityplugin/plugins/css/bootstrap-accessibility.css',
'bower_components/blueimp-gallery/css/blueimp-gallery.min.css',
'bower_components/blueimp-bootstrap-image-gallery/css/bootstrap-image-gallery.min.css',
'node_modules/pikaday/css/pikaday.css'
])
.pipe($.concat('vendors.css'))
.pipe($.minifyCss())
.pipe(gulp.dest('build/css'));
/**
* JS VENDORS
* (with jQuery and Bootstrap dependencies first)
*/
gulp.src([
'bower_components/jquery/jquery.js',
'bower_components/jquery.tablesorter/js/jquery.tablesorter.js',
'bower_components/chosen_v1.1.0/chosen.jquery.min.js',
'bower_components/typeahead.js/dist/typeahead.bundle.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/affix.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/alert.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/button.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/carousel.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/collapse.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/dropdown.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/modal.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tooltip.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/popover.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/scrollspy.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/tab.js',
'bower_components/bootstrap-sass-official/assets/javascripts/bootstrap/transition.js',
'bower_components/bootstrapaccessibilityplugin/plugins/js/bootstrap-accessibility.js',
'bower_components/jquery.tablesorter/js/jquery.tablesorter.js',
'bower_components/jquery.socialshareprivacy/jquery.socialshareprivacy.min.js',
'bower_components/jquery-drilldown/jquery.drilldown.min.js',
'bower_components/placeholdr/placeholdr.js',
'bower_components/blueimp-gallery/js/jquery.blueimp-gallery.min.js',
'bower_components/blueimp-bootstrap-image-gallery/js/bootstrap-image-gallery.min.js',
'node_modules/moment/moment.js',
'node_modules/pikaday/pikaday.js'
])
.pipe($.concat('vendors.min.js'))
.pipe($.uglify())
.pipe(gulp.dest('build/js'));
/**
* FONTS SOURCES
* Important to add the bootstrap fonts to avoid issues with the fonts include path
*/
gulp.src([
'bower_components/bootstrap-sass-official/assets/fonts/bootstrap/*',
'assets/fonts/*'
])
.pipe(gulp.dest('build/fonts'));
});
gulp.task('polyfills', function() {
return gulp.src([
'bower_components/html5shiv/dist/html5shiv.min.js',
'bower_components/html5shiv/dist/html5shiv-printshiv.min.js',
'bower_components/respond/dest/respond.min.js'
])
.pipe($.concat('polyfills.min.js'))
.pipe($.uglify())
.pipe(gulp.dest('build/js'));
});
/**
* Build styles from SCSS files
* With error reporting on compiling (so that there's no crash)
*/
gulp.task('styles', function() {
if (!argv.dev) { console.log('[styles] Outputting minified styles.' ); }
else { console.log('[styles] Processing styles for dev env. No minifying here, for sourcemaps!') }
return gulp.src('assets/sass/admin.scss')
.pipe($.sass({
errLogToConsole: true
}))
.pipe($.if(argv.dev, $.sourcemaps.init()))
.pipe($.autoprefixer({
browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1']
}))
.pipe($.if(argv.dev, $.sourcemaps.write()))
.pipe($.if(!argv.dev, $.minifyCss()))
.pipe(gulp.dest('build/css'));
});
gulp.task('print', function() {
return gulp.src('assets/sass/print/print.scss')
.pipe($.sass({
errLogToConsole: true
}))
.pipe($.if(argv.dev, $.sourcemaps.init()))
.pipe($.autoprefixer({
browsers: ['last 2 versions', 'safari 5', 'ie 8', 'ie 9', 'ff 27', 'opera 12.1']
}))
.pipe($.if(argv.dev, $.sourcemaps.write()))
.pipe($.if(!argv.dev, $.minifyCss()))
.pipe(gulp.dest('build/css'));
});
/**
* Build JS
* With error reporting on compiling (so that there's no crash)
*/
gulp.task('scripts', function() {
return gulp.src('assets/js/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'))
.pipe($.concat('main.js'))
.pipe(gulp.dest('build/js'))
.pipe($.rename({ suffix: '.min' }))
.pipe($.uglify())
.pipe(gulp.dest('build/js'));
});
/**
* Build Hologram Styleguide
*/
gulp.task('styleguide', function () {
return gulp.src('hologram_config.yml')
.pipe($.hologram({ bundler: true }));
});
gulp.task('build-images', function() {
return gulp.src(['assets/img/**'])
.pipe(gulp.dest('build/img'));
});
gulp.task('build-fonts', function() {
return gulp.src(['assets/fonts/**'])
.pipe(gulp.dest('build/fonts'));
});
/**
* Compile TWIG example pages
*/
gulp.task('twig', function () {
return gulp.src('assets/pages/*.twig')
.pipe($.twig())
.pipe(gulp.dest('styleguide/pages'));
});
/**
* Clean output directories
*/
gulp.task('clean', del.bind(null, ['build', 'styleguide']));
/**
* Serve
*/
gulp.task('serve', ['styles', 'scripts'], function () {
browserSync({
server: {
baseDir: ['styleguide'],
},
open: false
});
gulp.watch(['assets/sass/**/*.scss'], function() {
runSequence('styles', 'print', 'styleguide', reload);
});
gulp.watch(['assets/js/*.js'], function() {
runSequence('scripts', 'styleguide', reload);
});
gulp.watch(['assets/img/**/*.{jpg,png,gif,svg}'], function() {
runSequence('build-images', 'styleguide', reload);
});
gulp.watch(['assets/fonts/**/*.{eot,svg,woff,ttf}'], function() {
runSequence('build-fonts', 'styleguide', reload);
});
gulp.watch(['assets/pages/**/*.twig'], function() {
runSequence('twig', reload);
});
});
/**
* Deploy to GH pages
*/
gulp.task('deploy', function () {
return gulp.src("styleguide/**/*")
.pipe($.ghPages());
});
/**
* Default task
*/
gulp.task('default', ['clean'], function(cb) {
runSequence('vendors', 'polyfills', 'styles', 'print', 'scripts', 'twig', 'build-images', 'build-fonts', 'styleguide', cb);
});
|
'use strict';
var GerritEventEmitter = require('../lib/gerrit-event-emitter').GerritEventEmitter,
EventEmitter2 = require('eventemitter2').EventEmitter2,
sinon = require('sinon'),
chai = require('chai'),
expect = chai.expect;
describe('GerritEventEmitter', function() {
beforeEach(function() {
this.subject = new GerritEventEmitter('gerrit.example.com', 29418, false);
});
afterEach(function() {
this.subject.stop();
});
it('should inherit from EventEmitter2', function() {
expect(this.subject).to.be.an.instanceof(EventEmitter2);
});
it('should set host property', function() {
expect(this.subject.host).to.be.equal('gerrit.example.com');
});
it('should set port property', function() {
expect(this.subject.port).to.be.equal(29418);
});
it('should set enabledAutoRestart property', function() {
expect(this.subject.enabledAutoRestart).not.to.be.ok;
});
describe('#start()', function() {
it('should start gerrit stream', function() {
expect(this.subject.isStarted()).not.to.be.ok;
this.subject.start();
expect(this.subject.isStarted()).to.be.ok;
});
});
describe('#stop()', function() {
beforeEach(function() {
this.subject.start();
});
it('should stop gerrit stream', function() {
this.subject.stop();
expect(this.subject.isStarted()).not.to.be.ok;
});
});
describe('#onStreamWrite(output)', function() {
it('should emit gerrit stream event', function(done) {
this.subject.on('commentAdded', function(eventData) {
expect(eventData.id).to.be.equal(19234);
done();
});
this.subject.onStreamWrite('{"type":"comment-added","id":19234}\n');
});
it('should emit gerritStreamWrite event', function(done) {
this.subject.on('gerritStreamWrite', function(output) {
expect(output).to.be.equal('{"type":"comment-added","id":19234}\n');
done();
});
this.subject.onStreamWrite('{"type":"comment-added","id":19234}\n');
});
});
describe('#onStreamEnd(output)', function() {
beforeEach(function() {
sinon.spy(this.subject, 'start');
sinon.spy(this.subject, 'stop');
});
it('should receive #stop', function() {
this.subject.onStreamEnd('end');
expect(this.subject.stop.called).to.be.ok;
});
it('should emit gerritStreamEnd event', function(done) {
this.subject.on('gerritStreamEnd', function(output) {
expect(output).to.be.equal('end');
done();
});
this.subject.onStreamEnd('end');
});
context('enabledAutoRestart is true', function() {
beforeEach(function() {
this.subject.enabledAutoRestart = true;
});
it('should restart automatically', function() {
this.subject.onStreamEnd('end');
expect(this.subject.start.called).to.be.ok;
});
});
context('enabledAutoRestart is false', function() {
it('should not restart automatically', function() {
this.subject.onStreamEnd('end');
expect(this.subject.start.called).not.to.be.ok;
});
});
});
describe('#toCamelizedEventName(hypenated-event-name)', function() {
it('should return the camelized event name whose first letter is low', function() {
var actual = this.subject.toCamelizedEventName('patchset-created');
expect(actual).to.be.equal('patchsetCreated');
});
});
});
|
import e from"./input-c965e08d.js";import{n as s}from"./number-93d0ff7a.js";import{v as t,i}from"./index-fe8be053.js";export default class extends e{init(){this.props.value=e=>{null==e?this.setValue(null):this.setValue(t(e,0),!0)},this.props.min=e=>t(e,Number.MIN_SAFE_INTEGER),this.props.max=e=>t(e,Number.MAX_SAFE_INTEGER),this.props.type="number",super.init();const{ref:s}=this;s.type="number",s.inputMode="decimal",s.value=this.value,s.addEventListener("focus",e=>{try{s.select()}catch(e){}})}changed(e,t){super.changed(e,t),this.declareProps()}setValue(e,s){var l=e;null!=(e=null!=e?t(e):e)&&(e>this.max?e=this.max:e<this.min&&(e=this.min)),this.ref&&(null==l||""===l?this.ref.value&&(this.ref.value=""):this.ref.value=e),i(this.value,e)||(this.value=e,s||this.emit("input",this.value),this.declareProps())}declareProps(){var e=null!=this.value?`"${s(this.value,this.locale,this)}"`:`"${this.placeholder}"`;this.host.style.setProperty("--value",e)}} |
(function() {
'use strict';
angular.module('ss.bootstrap-component', [
'angularMoment',
'ngLodash'
]);
})(); |
Template.afEachArrayItem.helpers({
innerContext: function afEachArrayItemContext(options) {
var c = Utility.normalizeContext(options.hash, "afEachArrayItem");
var formId = c.af.formId;
var name = c.atts.name;
var docCount = fd.getDocCountForField(formId, name);
if (docCount == null) {
docCount = c.atts.initialCount;
}
arrayTracker.initField(formId, name, c.af.ss, docCount, c.atts.minCount, c.atts.maxCount);
return arrayTracker.getField(formId, name);
}
}); |
var AssetView = require('./AssetView');
var AssetImageView = require('./AssetImageView');
var FileUploader = require('./FileUploader');
module.exports = Backbone.View.extend({
events: {
submit: 'handleSubmit',
},
template(view) {
const pfx = view.pfx;
const ppfx = view.ppfx;
return `
<div class="${pfx}assets-cont">
<div class="${pfx}assets-header">
<form class="${pfx}add-asset">
<div class="${ppfx}field ${pfx}add-field">
<input placeholder="http://path/to/the/image.jpg"/>
</div>
<button class="${ppfx}btn-prim">${view.config.addBtnText}</button>
<div style="clear:both"></div>
</form>
<div class="${pfx}dips" style="display:none">
<button class="fa fa-th <%${ppfx}btnt"></button>
<button class="fa fa-th-list <%${ppfx}btnt"></button>
</div>
</div>
<div class="${pfx}assets" data-el="assets"></div>
<div style="clear:both"></div>
</div>
`;
},
initialize(o) {
this.options = o;
this.config = o.config;
this.pfx = this.config.stylePrefix || '';
this.ppfx = this.config.pStylePrefix || '';
const coll = this.collection;
this.listenTo(coll, 'reset', this.renderAssets);
this.listenTo(coll, 'add', this.addToAsset);
this.listenTo(coll, 'remove', this.removedAsset);
this.listenTo(coll, 'deselectAll', this.deselectAll);
},
/**
* Add new asset to the collection via string
* @param {Event} e Event object
* @return {this}
* @private
*/
handleSubmit(e) {
e.preventDefault();
const input = this.getAddInput();
const url = input.value.trim();
const handleAdd = this.config.handleAdd;
if (!url) {
return;
}
input.value = '';
this.getAssetsEl().scrollTop = 0;
if (handleAdd) {
handleAdd(url);
} else {
this.options.globalCollection.add(url, {at: 0});
}
},
/**
* Returns assets element
* @return {HTMLElement}
* @private
*/
getAssetsEl() {
//if(!this.assets) // Not able to cache as after the rerender it losses the ref
return this.el.querySelector(`.${this.pfx}assets`);
},
/**
* Returns input url element
* @return {HTMLElement}
* @private
*/
getAddInput() {
if(!this.inputUrl || !this.inputUrl.value)
this.inputUrl = this.el.querySelector(`.${this.pfx}add-asset input`);
return this.inputUrl;
},
/**
* Triggered when an asset is removed
* @param {Asset} model Removed asset
* @private
*/
removedAsset(model) {
if (!this.collection.length) {
this.toggleNoAssets();
}
},
/**
* Add asset to collection
* @private
* */
addToAsset(model) {
if (this.collection.length == 1) {
this.toggleNoAssets(1);
}
this.addAsset(model);
},
/**
* Add new asset to collection
* @param Object Model
* @param Object Fragment collection
* @return Object Object created
* @private
* */
addAsset(model, fragmentEl = null) {
const fragment = fragmentEl;
const collection = this.collection;
const config = this.config;
const rendered = new model.typeView({
model,
collection,
config,
}).render().el;
if (fragment) {
fragment.appendChild( rendered );
} else {
const assetsEl = this.getAssetsEl();
if (assetsEl) {
assetsEl.insertBefore(rendered, assetsEl.firstChild);
}
}
return rendered;
},
/**
* Checks if to show noAssets
* @param {Boolean} hide
* @private
*/
toggleNoAssets(hide) {
const assetsEl = this.$el.find(`.${this.pfx}assets`);
if (hide) {
assetsEl.empty();
} else {
assetsEl.append(this.config.noAssets);
}
},
/**
* Deselect all assets
* @private
* */
deselectAll() {
const pfx = this.pfx;
this.$el.find(`.${pfx}highlight`).removeClass(`${pfx}highlight`);
},
renderAssets() {
const fragment = document.createDocumentFragment();
const assets = this.$el.find(`.${this.pfx}assets`);
assets.empty();
this.toggleNoAssets(this.collection.length);
this.collection.each((model) => this.addAsset(model, fragment));
assets.append(fragment);
},
render() {
const fuRendered = this.options.fu.render().el;
this.$el.empty();
this.$el.append(fuRendered).append(this.template(this));
this.el.className = `${this.ppfx}asset-manager`;
this.renderAssets();
this.rendered = 1;
return this;
}
});
|
var debug = false;
var tabs = {};
function toggle(tab){
if(!tabs[tab.id])
addTab(tab);
else
deactivateTab(tab.id);
}
function addTab(tab){
tabs[tab.id] = Object.create(dimensions);
tabs[tab.id].activate(tab);
}
function deactivateTab(id){
tabs[id].deactivate();
}
function removeTab(id){
for(var tabId in tabs){
if(tabId == id)
delete tabs[tabId];
}
}
var lastBrowserAction = null;
chrome.browserAction.onClicked.addListener(function(tab){
if(lastBrowserAction && Date.now() - lastBrowserAction < 10){
// fix bug in Chrome Version 49.0.2623.87
// that triggers browserAction.onClicked twice
// when called from shortcut _execute_browser_action
return;
}
toggle(tab);
lastBrowserAction = Date.now();
});
chrome.runtime.onConnect.addListener(function(port) {
tabs[ port.sender.tab.id ].initialize(port);
});
chrome.runtime.onSuspend.addListener(function() {
for(var tabId in tabs){
tabs[tabId].deactivate(true);
}
});
var dimensions = {
image: new Image(),
canvas: document.createElement('canvas'),
alive: true,
activate: function(tab){
this.tab = tab;
this.onBrowserDisconnectClosure = this.onBrowserDisconnect.bind(this);
this.receiveBrowserMessageClosure = this.receiveBrowserMessage.bind(this);
chrome.tabs.insertCSS(this.tab.id, { file: 'tooltip.css' });
chrome.tabs.executeScript(this.tab.id, { file: 'tooltip.chrome.js' });
chrome.browserAction.setIcon({
tabId: this.tab.id,
path: {
16: "images/icon16_active.png",
19: "images/icon19_active.png",
32: "images/icon16_active@2x.png",
38: "images/icon19_active@2x.png"
}
});
this.worker = new Worker("dimensions.js");
this.worker.onmessage = this.receiveWorkerMessage.bind(this);
this.worker.postMessage({
type: 'init',
debug: debug
});
},
deactivate: function(silent){
if(!this.port){
// not yet initialized
this.alive = false;
return;
}
if(!silent)
this.port.postMessage({ type: 'destroy' });
this.port.onMessage.removeListener(this.receiveBrowserMessageClosure);
this.port.onDisconnect.removeListener(this.onBrowserDisconnectClosure);
chrome.browserAction.setIcon({
tabId: this.tab.id,
path: {
16: "images/icon16.png",
19: "images/icon19.png",
32: "images/icon16@2x.png",
38: "images/icon19@2x.png"
}
});
window.removeTab(this.tab.id);
},
onBrowserDisconnect: function(){
this.deactivate(true);
},
initialize: function(port){
this.port = port;
if(!this.alive){
// was deactivated whilest still booting up
this.deactivate();
return;
}
this.port.onMessage.addListener(this.receiveBrowserMessageClosure);
this.port.onDisconnect.addListener(this.onBrowserDisconnectClosure);
this.port.postMessage({
type: 'init',
debug: debug
});
},
receiveWorkerMessage: function(event){
var forward = ['debug screen', 'distances', 'screenshot processed'];
if(forward.indexOf(event.data.type) > -1){
this.port.postMessage(event.data)
}
},
receiveBrowserMessage: function(event){
var forward = ['position', 'area'];
if(forward.indexOf(event.type) > -1){
this.worker.postMessage(event)
} else {
switch(event.type){
case 'take screenshot':
this.takeScreenshot();
break;
case 'close_overlay':
this.deactivate();
break;
}
}
},
takeScreenshot: function(){
chrome.tabs.captureVisibleTab({ format: "png" }, this.parseScreenshot.bind(this));
},
parseScreenshot: function(dataUrl){
this.image.onload = this.loadImage.bind(this);
this.image.src = dataUrl;
},
//
// loadImage
// ---------
//
// responsible to load a image and extract the image data
//
loadImage: function(){
this.ctx = this.canvas.getContext('2d');
// adjust the canvas size to the image size
this.canvas.width = this.tab.width;
this.canvas.height = this.tab.height;
// draw the image to the canvas
this.ctx.drawImage(this.image, 0, 0, this.canvas.width, this.canvas.height);
// read out the image data from the canvas
var imgData = this.ctx.getImageData(0, 0, this.canvas.width, this.canvas.height).data;
this.worker.postMessage({
type: 'imgData',
imgData: imgData.buffer,
width: this.canvas.width,
height: this.canvas.height
}, [imgData.buffer]);
}
}; |
import { fromJS } from 'immutable';
import {
selectSearch,
selectLoading,
selectError,
selectMovieEntities,
selectMovieResults
} from 'containers/SearchPage/selectors';
describe('SearchPage/selectors', () => {
describe('selectSearch', () => {
const searchSelector = selectSearch();
it('should select the `search` state', () => {
const searchState = fromJS({});
const mockedState = fromJS({ search: searchState });
expect(searchSelector(mockedState)).to.equal(searchState);
});
});
describe('selectLoading', () => {
const loadingSelector = selectLoading();
it('should select the loading value', () => {
const loading = false;
const mockedState = fromJS({ search: { loading: false } });
expect(loadingSelector(mockedState)).to.equal(loading);
});
});
describe('selectError', () => {
const errorSelector = selectError();
it('should select the error value', () => {
const error = fromJS({});
const mockedState = fromJS({ search: { error: {} } });
expect(errorSelector(mockedState)).to.equal(error);
});
});
describe('selectMovieEntities', () => {
const movieEntitiesSelector = selectMovieEntities();
it('should select the movie entities', () => {
const entities = fromJS({});
const mockedState = fromJS({
search: {
movies: { entities: {}, results: [] }
}
});
expect(movieEntitiesSelector(mockedState)).to.equal(entities);
});
});
describe('selectMovieResults', () => {
const movieResultsSelector = selectMovieResults();
it('should select the movie results', () => {
const results = fromJS([]);
const mockedState = fromJS({
search: {
movies: { entities: {}, results: [] }
}
});
expect(movieResultsSelector(mockedState)).to.equal(results);
});
});
});
|
const TSLintWebpackPlugin = require('./src/plugin');
module.exports = TSLintWebpackPlugin;
|
"use strict";
const ccxt = require ('../../ccxt.js')
const countries = require ('../../countries.js')
const asTable = require ('as-table')
const util = require ('util')
const log = require ('ololog').configure ({ locate: false })
require ('ansicolor').nice;
process.on ('uncaughtException', e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })
let exchanges = {}
ccxt.exchanges.forEach (id => { exchanges[id] = new (ccxt)[id] () })
log ('The ccxt library supports', (ccxt.exchanges.length.toString ()).green, 'exchanges:')
var countryName = function (code) {
return ((typeof countries[code] !== 'undefined') ? countries[code] : code)
}
log (asTable.configure ({ delimiter: ' | ' }) (Object.values (exchanges).map (exchange => {
let countries = Array.isArray (exchange.countries) ?
exchange.countries.map (countryName).join (', ') :
countryName (exchange.countries)
let website = Array.isArray (exchange.urls.www) ? exchange.urls.www[0] : exchange.urls.www
return {
id: exchange.id,
name: exchange.name,
url: website,
countries: countries,
}
})))
|
$(document).ready(function () {
//get Parameter from url
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
//Array of all ="name" (variable of the Attr)
var names = [getUrlParameter('system'), getUrlParameter('gender'), getUrlParameter('age'), getUrlParameter('kilo'), getUrlParameter('centi'),
getUrlParameter('lbs'), getUrlParameter('foot'), getUrlParameter('inch'), getUrlParameter('activity'), getUrlParameter('formula'),
getUrlParameter('bfp'), getUrlParameter('neckin'), getUrlParameter('waistin'), getUrlParameter('hipin'), getUrlParameter('neckcm'),
getUrlParameter('waistcm'), getUrlParameter('hipcm')];
//Array of all "name"= (Attr)
var nameAttr = ["system", "gender", "age", "kilo", "centi", "lbs", "foot", "inch", "activity", "formula", "bfp", "neckin",
"waistin", "hipin", "neckcm", "waistcm", "hipcm"]
//When page loads, put the params in the inputs
for(i=0; i<17; i++){
if(names[i] != undefined){
//console.log(nameAttr[i] + ": " +names[i]);
//console.log($('#' + nameAttr[i]).val());
if($('#' + nameAttr[i]).val() == undefined){
$('#' + names[i]).prop('checked', true);
}
$('#' + nameAttr[i]).val(names[i]);
}
}
//change metric/imperial system when loaded
if($("#formStats input[name=system]:checked").val() == "imperial"){
$('.metric').css("display", "none");
$('.imperial').css("display", "initial");
$("#inch").prop('disabled', false);
$("#foot").prop('disabled', false);
$("#lbs").prop('disabled', false);
$("#neckin").prop('disabled', false);
$("#waistin").prop('disabled', false);
$("#hipin").prop('disabled', false);
$("#centi").prop('disabled', true);
$("#kilo").prop('disabled', true);
$("#neckcm").prop('disabled', true);
$("#waistcm").prop('disabled', true);
$("#hipcm").prop('disabled', true);
} else {
$('.imperial').css("display", "none");
$('.metric').css("display", "initial");
$("#inch").prop('disabled', true);
$("#foot").prop('disabled', true);
$("#lbs").prop('disabled', true);
$("#neckin").prop('disabled', true);
$("#waistin").prop('disabled', true);
$("#hipin").prop('disabled', true);
$("#centi").prop('disabled', false);
$("#kilo").prop('disabled', false);
$("#neckcm").prop('disabled', false);
$("#waistcm").prop('disabled', false);
$("#hipcm").prop('disabled', false);
}
//change mifflin/katch
if( $("#formTdee input[name=formula]:checked").val() == "katch"){
$("#bfp").prop('disabled', false);
} else {
$("#bfp").prop('disabled', true);
}
});
//change metric/imperial system
$('input:radio[name="system"]').change(
function (){
if( $( this ).val() == "imperial"){
$("#inch").prop('disabled', false);
$("#foot").prop('disabled', false);
$("#lbs").prop('disabled', false);
$("#neckin").prop('disabled', false);
$("#waistin").prop('disabled', false);
$("#hipin").prop('disabled', false);
$("#centi").prop('disabled', true);
$("#kilo").prop('disabled', true);
$("#neckcm").prop('disabled', true);
$("#waistcm").prop('disabled', true);
$("#hipcm").prop('disabled', true);
} else {
$("#inch").prop('disabled', true);
$("#foot").prop('disabled', true);
$("#lbs").prop('disabled', true);
$("#neckin").prop('disabled', true);
$("#waistin").prop('disabled', true);
$("#hipin").prop('disabled', true);
$("#centi").prop('disabled', false);
$("#kilo").prop('disabled', false);
$("#neckcm").prop('disabled', false);
$("#waistcm").prop('disabled', false);
$("#hipcm").prop('disabled', false);
}
$('.imperial').toggle();
$('.metric').toggle()
});
//change mifflin/katch
$('input:radio[name="formula"]').change(
function(){
if( $( this ).val() == "mifflin"){
$("#bfp").prop('disabled', true);
} else {
$("#bfp").prop('disabled', false);
}
});
//change url
function formSubmit(id){
var form1 = $('#formStats').serialize();
var form2 = $(id).serialize();
var dat = form1 + '&' + form2;
window.location.href = "?" + dat;
//Ajax test;
//$.ajax({
// url : '',
// type: "GET",
// data: dat,
//success: function (data) {
// alert(dat);
//},
// error: function (jXHR, textStatus, errorThrown) {
// alert(errorThrown);
// }
//});
};
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.0-master-bc4100a
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.progressLinear
* @description Linear Progress module!
*/
angular.module('material.components.progressLinear', [
'material.core'
])
.directive('mdProgressLinear', MdProgressLinearDirective);
/**
* @ngdoc directive
* @name mdProgressLinear
* @module material.components.progressLinear
* @restrict E
*
* @description
* The linear progress directive is used to make loading content
* in your app as delightful and painless as possible by minimizing
* the amount of visual change a user sees before they can view
* and interact with content.
*
* Each operation should only be represented by one activity indicator
* For example: one refresh operation should not display both a
* refresh bar and an activity circle.
*
* For operations where the percentage of the operation completed
* can be determined, use a determinate indicator. They give users
* a quick sense of how long an operation will take.
*
* For operations where the user is asked to wait a moment while
* something finishes up, and it’s not necessary to expose what's
* happening behind the scenes and how long it will take, use an
* indeterminate indicator.
*
* @param {string} md-mode Select from one of four modes: determinate, indeterminate, buffer or query.
*
* Note: if the `md-mode` value is set as undefined or specified as 1 of the four (4) valid modes, then `.ng-hide`
* will be auto-applied as a style to the component.
*
* Note: if not configured, the `md-mode="indeterminate"` will be auto injected as an attribute. If `value=""` is also specified, however,
* then `md-mode="determinate"` would be auto-injected instead.
* @param {number=} value In determinate and buffer modes, this number represents the percentage of the primary progress bar. Default: 0
* @param {number=} md-buffer-value In the buffer mode, this number represents the percentage of the secondary progress bar. Default: 0
*
* @usage
* <hljs lang="html">
* <md-progress-linear md-mode="determinate" value="..."></md-progress-linear>
*
* <md-progress-linear md-mode="determinate" ng-value="..."></md-progress-linear>
*
* <md-progress-linear md-mode="indeterminate"></md-progress-linear>
*
* <md-progress-linear md-mode="buffer" value="..." md-buffer-value="..."></md-progress-linear>
*
* <md-progress-linear md-mode="query"></md-progress-linear>
* </hljs>
*/
function MdProgressLinearDirective($mdTheming, $mdUtil, $log) {
var MODE_DETERMINATE = "determinate",
MODE_INDETERMINATE = "indeterminate",
MODE_BUFFER = "buffer",
MODE_QUERY = "query";
return {
restrict: 'E',
template: '<div class="md-container">' +
'<div class="md-dashed"></div>' +
'<div class="md-bar md-bar1"></div>' +
'<div class="md-bar md-bar2"></div>' +
'</div>',
compile: compile
};
function compile(tElement, tAttrs, transclude) {
tElement.attr('aria-valuemin', 0);
tElement.attr('aria-valuemax', 100);
tElement.attr('role', 'progressbar');
return postLink;
}
function postLink(scope, element, attr) {
$mdTheming(element);
var lastMode, toVendorCSS = $mdUtil.dom.animator.toCss;
var bar1 = angular.element(element[0].querySelector('.md-bar1')),
bar2 = angular.element(element[0].querySelector('.md-bar2')),
container = angular.element(element[0].querySelector('.md-container'));
element.attr('md-mode', mode());
validateMode();
watchAttributes();
/**
* Watch the value, md-buffer-value, and md-mode attributes
*/
function watchAttributes() {
attr.$observe('value', function(value) {
var percentValue = clamp(value);
element.attr('aria-valuenow', percentValue);
if (mode() != MODE_QUERY) animateIndicator(bar2, percentValue);
});
attr.$observe('mdBufferValue', function(value) {
animateIndicator(bar1, clamp(value));
});
attr.$observe('mdMode',function(mode){
switch( mode ) {
case MODE_QUERY:
case MODE_BUFFER:
case MODE_DETERMINATE:
case MODE_INDETERMINATE:
container.removeClass( 'ng-hide' + ' ' + lastMode );
container.addClass( lastMode = "md-mode-" + mode );
break;
default:
container.removeClass( lastMode );
container.addClass('ng-hide');
lastMode = undefined;
break;
}
});
}
/**
* Auto-defaults the mode to either `determinate` or `indeterminate` mode; if not specified
*/
function validateMode() {
if ( angular.isUndefined(attr.mdMode) ) {
var hasValue = angular.isDefined(attr.value);
var mode = hasValue ? MODE_DETERMINATE : MODE_INDETERMINATE;
var info = "Auto-adding the missing md-mode='{0}' to the ProgressLinear element";
$log.debug( $mdUtil.supplant(info, [mode]) );
element.attr("md-mode",mode);
attr['mdMode'] = mode;
}
}
/**
* Is the md-mode a valid option?
*/
function mode() {
var value = (attr.mdMode || "").trim();
if ( value ) {
switch(value) {
case MODE_DETERMINATE:
case MODE_INDETERMINATE:
case MODE_BUFFER:
case MODE_QUERY:
break;
default:
value = undefined;
break;
}
}
return value;
}
/**
* Manually set CSS to animate the Determinate indicator based on the specified
* percentage value (0-100).
*/
function animateIndicator(target, value) {
if ( !mode() ) return;
var to = $mdUtil.supplant("translateX({0}%) scale({1},1)", [ (value-100)/2, value/100 ]);
var styles = toVendorCSS({ transform : to });
angular.element(target).css( styles );
}
}
/**
* Clamps the value to be between 0 and 100.
* @param {number} value The value to clamp.
* @returns {number}
*/
function clamp(value) {
return Math.max(0, Math.min(value || 0, 100));
}
}
MdProgressLinearDirective.$inject = ["$mdTheming", "$mdUtil", "$log"];
})(window, window.angular); |
import { getByCypressTag } from "../../../utils";
class Dashboard {
answersOpen = "dashboard--fullAnswers--1-gA5Yaq";
//Sort, Help, and Open/Close Students
getSortDropdown() {
return getByCypressTag("sortDropdown");
}
getHelpPanel() {
return getByCypressTag("helpPanel");
}
getOpenCloseStudents() {
return getByCypressTag("openCloseStudents").find("a");
}
getActivityHeaders() {
return getByCypressTag("activityHeaders");
}
//Students
getStudentNames() {
return getByCypressTag("studentName");
}
getStudentAnswersRow() {
return getByCypressTag("studentAnswersRow");
}
getProgressBar() {
return getByCypressTag("progressBar");
}
//Icons
getOpenResponseIcon() {
return getByCypressTag("openResponseIcon");
}
getMultipleChoiceIcon() {
return getByCypressTag("multipleChoiceIcon");
}
//Expand Question
getExpandedQuestionPanel() {
return cy.get("div.modal-content");
}
getExpandQuestionDetails() {
return getByCypressTag("expand-question-details");
}
getExpandedMCAnswerDetails() {
return getByCypressTag("multiple-choice-details");
}
getExpandedMCAnswers() {
return getByCypressTag("multiple-choice-answers-table");
}
getShowHideResponse() {
return cy.get(".modal-body").find(".cc-button");
}
getCloseExpandedQuestion() {
return cy.get(".modal-footer > .cc-button");
}
//Activity Info
// This is the container of the questions
getActivityQuestions() {
return getByCypressTag("activityQuestions");
}
getActivityQuestionToggle() {
return getByCypressTag("activity-question-toggle");
}
getActivityQuestionsText() {
return getByCypressTag("activityQuestionsText");
}
getActivityAnswers() {
return getByCypressTag("activityAnswers");
}
getActivityNames() {
return getByCypressTag("activityName");
}
//Feedback Buttons
getFeedbackForStudent(activityIdx, questionIdx) {
this.getActivityNames().eq(activityIdx).click({force: true});
this.getActivityQuestions(activityIdx).eq(questionIdx).click({force: true});
}
}
export default Dashboard;
|
const Easypost = require('@easypost/api');
const api = new Easypost(process.env.API_KEY);
const webhook = new api.Webhook({ url: 'https://example.com`' });
webhook.save().then(console.log);
|
(function() {
RebelChat.Views.CallsignView = Falcon.View.extend({
url: 'callsign.html',
observables: {
'callsign': null,
'errorMessage': null
},
submit: function() {
var callsign = this.callsign();
if (callsign && callsign.length > 0) {
RebelChat.User.callsign = callsign
this.trigger('callsignChosen');
}
else {
this.errorMessage('Nice try, wise guy.');
}
}
});
})(); |
export default function layout() {
var cat = this;
/* Layout primary sections */
cat.controls.wrap = cat.wrap
.append('div')
.classed('cat-controls section', true)
.classed('hidden', !cat.config.showControls);
cat.chartWrap = cat.wrap.append('div').classed('cat-chart section', true);
cat.dataWrap = cat.wrap
.append('div')
.classed('cat-data section', true)
.classed('hidden', true);
/* Layout CAT Controls Divs */
cat.controls.wrap
.append('h2')
.classed('cat-controls-header', true)
.text('Charting Application Tester 😼');
cat.controls.submitWrap = cat.controls.wrap
.append('div')
.classed('control-section submit-section', true);
cat.controls.rendererWrap = cat.controls.wrap
.append('div')
.classed('control-section renderer-section', true);
cat.controls.dataWrap = cat.controls.wrap
.append('div')
.classed('control-section data-section', true);
cat.controls.settingsWrap = cat.controls.wrap
.append('div')
.classed('control-section settings-section', true);
cat.controls.environmentWrap = cat.controls.wrap
.append('div')
.classed('control-section environment-section', true);
}
|
'use strict';
var axe = require('axe-logger');
var JUNK_FOLDER_TYPE = 'Junk';
var ActionBarCtrl = function($scope, $q, email, dialog, status) {
axe.debug('action-bar.js 6');
//
// scope functions
//
$scope.CHECKNONE = 0;
$scope.CHECKALL = 1;
$scope.CHECKUNREAD = 2;
$scope.CHECKREAD = 3;
$scope.CHECKFLAGGED = 4;
$scope.CHECKUNFLAGGED = 5;
$scope.CHECKENCRYPTED = 6;
$scope.CHECKUNENCRYPTED = 7;
$scope.check = function(option) {
currentFolder().messages.forEach(function(email) {
if (!email.from) {
// only mark loaded messages, not the dummy messages
return;
}
if (option === $scope.CHECKNONE) {
email.checked = false;
} else if (option === $scope.CHECKALL) {
email.checked = true;
} else if (option === $scope.CHECKUNREAD) {
email.checked = !!email.unread;
} else if (option === $scope.CHECKREAD) {
email.checked = !email.unread;
} else if (option === $scope.CHECKFLAGGED) {
email.checked = !!email.flagged;
} else if (option === $scope.CHECKUNFLAGGED) {
email.checked = !email.flagged;
} else if (option === $scope.CHECKENCRYPTED) {
email.checked = !!email.encrypted;
} else if (option === $scope.CHECKUNENCRYPTED) {
email.checked = !email.encrypted;
}
});
};
/**
* Move a single message from the currently selected folder to another folder
* @param {Object} message The message that is to be moved
* @param {Object} destination The folder object where the message should be moved to
*/
$scope.moveMessage = function(message, destination) {
if (!message || !destination) {
return;
}
// close read state
status.setReading(false);
// show message
status.update('移动邮件...');
return $q(function(resolve) {
resolve();
}).then(function() {
return email.moveMessage({
folder: currentFolder(),
destination: destination,
message: message
});
}).then(function() {
status.update('在线');
}).catch(function(err) {
// show errors where appropriate
if (err.code === 42) {
$scope.select(message);
status.update('离线不能移动邮件!');
return;
}
status.update('移动邮件错误!');
return dialog.error(err);
});
};
/**
* Move all checked messages from the currently selected folder to another folder
* @param {Object} destination The folder object where the message should be moved to
*/
$scope.moveCheckedMessages = function(destination) {
getCheckMessages().forEach(function(message) {
$scope.moveMessage(message, destination);
});
};
/**
* Find the junk folder to mark a message as spam. If no junk folder is found, an error message will be displayed.
* @return {Object} The junk folder object tied to the account
*/
$scope.getJunkFolder = function() {
var folder = _.findWhere($scope.account.folders, {
type: JUNK_FOLDER_TYPE
});
if (!folder) {
dialog.error(new Error('Spam folder not found!'));
return;
}
return folder;
};
/**
* Delete a message. This moves the message from the current folder to the trash folder,
* or if the current folder is the trash folder, the message will be purged.
* @param {Object} message The message that is to be deleted
*/
$scope.deleteMessage = function(message) {
if (!message) {
return;
}
// close read state
status.setReading(false);
status.update('删除邮件...');
return $q(function(resolve) {
resolve();
}).then(function() {
return email.deleteMessage({
folder: currentFolder(),
message: message
});
}).then(function() {
status.update('在线');
}).catch(function(err) {
// show errors where appropriate
if (err.code === 42) {
$scope.select(message);
status.update('离线不能删除邮件!');
return;
}
status.update('删除邮件错误!');
return dialog.error(err);
});
};
/**
* Delete all of the checked messages. This moves the messages from the current folder to the trash folder,
* or if the current folder is the trash folder, the messages will be purged.
*/
$scope.deleteCheckedMessages = function() {
getCheckMessages().forEach($scope.deleteMessage);
};
/**
* Mark a single message as either read or unread
* @param {Object} message The message to be marked
* @param {boolean} unread If the message should be marked as read or unread
*/
$scope.markMessage = function(message, unread, keepOpen) {
if (!message || message.unread === unread) {
return;
}
status.update('更新...');
// close read state
if (!keepOpen) {
status.setReading(false);
}
var originalState = message.unread;
message.unread = unread;
return $q(function(resolve) {
resolve();
}).then(function() {
return email.setFlags({
folder: currentFolder(),
message: message
});
}).then(function() {
status.update('在线');
}).catch(function(err) {
if (err.code === 42) {
// offline, restore
message.unread = originalState;
status.update('离线不能标记!');
return;
}
status.update('同步失败!');
return dialog.error(err);
});
};
/**
* Mark all of the checked messages as either read or unread.
* @param {boolean} unread If the message should be marked as read or unread
*/
$scope.markCheckedMessages = function(unread) {
getCheckMessages().forEach(function(message) {
$scope.markMessage(message, unread);
});
};
/**
* Flag a single message
* @param {Object} message The message to be flagged
* @param {boolean} flagged If the message should be flagged or unflagged
*/
$scope.flagMessage = function(message, flagged) {
if (!message || message.flagged === flagged) {
return;
}
status.update(flagged ? '添加标签...' : '移除标签');
var originalState = message.flagged;
message.flagged = flagged;
return $q(function(resolve) {
resolve();
}).then(function() {
return email.setFlags({
folder: currentFolder(),
message: message
});
}).then(function() {
status.update('在线');
}).catch(function(err) {
if (err.code === 42) {
// offline, restore
message.unread = originalState;
status.update('离线不能' + (flagged ? '添加' : '移除') + '标签!');
return;
}
status.update('同步失败!');
return dialog.error(err);
});
};
/**
* Mark all of the checked messages as either flagged or unflagged.
* @param {boolean} flagged If the message should be marked as flagged or unflagged
*/
$scope.flagCheckedMessages = function(flagged) {
getCheckMessages().forEach(function(message) {
$scope.flagMessage(message, flagged);
});
};
/**
* This method is called when the user changes the searchText
*/
$scope.displaySearchResults = function(searchText) {
$scope.$root.$broadcast('search', searchText);
};
//
// scope state
//
// share local scope functions with root state
$scope.state.actionBar = {
markMessage: $scope.markMessage,
flagMessage: $scope.flagMessage
};
//
// Helper functions
//
function currentFolder() {
return $scope.state.nav.currentFolder;
}
function getCheckMessages() {
return currentFolder().messages.filter(function(message) {
return message.checked;
});
}
};
module.exports = ActionBarCtrl; |
/**
* Created by yangyxu on 7/14/15.
*/
zn.define([
'node:fs',
'node:path'
], function (fs, path) {
return zn.Class({
properties: {
env: null,
argv: null
},
methods: {
init: function (argv){
this._argv = argv;
this.exec();
},
exec: function (){
}
}
});
});
|
'use strict';
// Setting up route
angular.module('resource-project').config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider.
state('resource-project-list', {
url: '/resource/project',
templateUrl: 'modules/resource-project/views/list.project.view.client.html',
needRole: 'resource'
});
}
]);
|
/*
* GET home page.
*/
exports.view = function(req, res){
res.render('history');
}; |
import React from 'react';
import Icon from '../Icon';
export default class DeveloperBoardIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M44 18v-4h-4v-4c0-2.2-1.8-4-4-4H8c-2.2 0-4 1.8-4 4v28c0 2.2 1.8 4 4 4h28c2.2 0 4-1.8 4-4v-4h4v-4h-4v-4h4v-4h-4v-4h4zm-8 20H8V10h28v28zM12 26h10v8H12zm12-12h8v6h-8zm-12 0h10v10H12zm12 8h8v12h-8z"/></svg>;}
}; |
angular.module('GeneralShapeModule', ["MathModule", "ZomeDefinitionModule"])
.controller('GeneralShapeController', ["zomeDefinitionService", "mathService", function(zomeDef, mathService) {
this.bezierPoints = zomeDef().bezierPoints;
this.bezierGraph = zomeDef().bezierGraph;
mathService().buildBezierGraph(this.bezierPoints, this.bezierGraph);
this.zomeHeight = 500 - zomeDef().p0().y;
this.zomeRadius = zomeDef().p2().x;
this.parameterPoint = { "x" : zomeDef().p1().x, "y" : 500 - zomeDef().p1().y };
this.changeHeight = function() {
zomeDef().p0().y = 500 - this.zomeHeight;
this.render();
};
this.changeRadius = function() {
zomeDef().p2().x = this.zomeRadius;
this.render();
};
this.changeParameterPoint = function() {
zomeDef().p1().x = this.parameterPoint.x;
zomeDef().p1().y = 500 - this.parameterPoint.y;
this.render();
}
// point for axes
var axes = [ { "x" : 0, "y" : 0}, {"x" : 0, "y" : 500}, { "x" : 500, "y" : 500}]
var gridAxes = [];
for (var i = 0; i < 500; i = i + 50) {
gridAxes.push([{"x" : i, "y" : 0}, {"x" : i, "y": 500}]);
}
var bezierFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
var axeFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("linear");
//The SVG Container
var svg = d3.select("#generalShapeGraph").append("svg").attr("width", 600)
.attr("height", 600);
var svgContainer = svg.append("g").attr("transform", "translate(10, 10)");
for (var i = 0; i < gridAxes.length; i++) {
svgContainer.append("path") .attr("d", axeFunction(gridAxes[i]))
.attr("stroke", "green")
.attr("stroke-width", 1)
.attr("fill", function(d) { return "transparent"});
}
var axeGraph = svgContainer.append("path")
.attr("d", axeFunction(axes))
.attr("stroke", "green")
.attr("stroke-width", 3)
.attr("fill", function(d) { return "transparent"});
var zomeAsymptoteGraph = svgContainer.append("path")
.attr("class", "asymptotePath")
.attr("d", axeFunction(this.bezierPoints))
.attr("stroke", "red")
.attr("stroke-width", 1)
.attr("fill", function(d) { return "transparent"});
var parameterCircle = svgContainer.append("circle")
.attr("cx", zomeDef().p1().x)
.attr("cy", zomeDef().p1().y)
.attr("r", 7)
.attr("class", "parameterPoint")
.attr("fill", "red");
var zomeShapeGraph = svgContainer.append("path")
.attr("class", "bezierPath")
.attr("d", bezierFunction(this.bezierGraph))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", function(d) { return "transparent"});
this.render = function() {
var svg = d3.select("#generalShapeGraph").transition();
mathService().buildBezierGraph(this.bezierPoints, this.bezierGraph);
svg.select(".bezierPath")
.duration(750)
.attr("d", bezierFunction(this.bezierGraph));
svg.select(".asymptotePath")
.duration(750)
.attr("d", axeFunction(this.bezierPoints));
svg.select(".parameterPoint")
.duration(750)
.attr("cx", zomeDef().p1().x)
.attr("cy", zomeDef().p1().y)
}
}]);
|
var Contact = function() {
// this.username = element(by.model('username'));
// this.password = element(by.model('password'));
// this.button = element(by.id('login_btn'));
};
module.exports = Contact;
|
'use strict';
const problem48 = require('./problem-0048');
describe('selfPowers', () => {
it('calculates self powers for known input', () => {
expect(problem48.selfPowers(10, 10)).toBe(405071317);
});
});
|
// TODO: clean this up to be DRY
function fetchMessages (threadId, users, callback) {
var token = FB.getAccessToken();
var messages = [] || messages;
FB.api('/' + threadId, { access_token: token }, function(response) {
messages = messages.concat(response.comments.data);
// get subsequent pages
if(response.comments.paging && response.comments.paging.next) {
(function fetchNext (url) {
$.get(url, function(res) {
messages = messages.concat(res.data);
if(res.paging && res.paging.next) {
fetchNext(res.paging.next);
} else {
console.log('fetchMessages.js - messages', messages);
callback(messages, users);
}
});
})(response.comments.paging.next); // immediate invocation
}
});
}
|
/* global describe, expect, it, jest */
import Leaflet from 'leaflet'
import React, { Component } from 'react'
import { renderIntoDocument } from 'react-addons-test-utils'
import MapComponent from '../src/MapComponent'
describe('MapComponent', () => {
class TestComponent extends MapComponent {
componentWillMount () {
super.componentWillMount()
this.leafletElement = Leaflet.map('test')
}
render () {
return null
}
}
it('exposes a `leafletElement` getter', () => {
const component = renderIntoDocument(<TestComponent />)
expect(component.leafletElement._container).toBeDefined()
})
it('binds the event', () => {
const callback = jest.fn()
const component = renderIntoDocument(<TestComponent onClick={callback} />)
component.fireLeafletEvent('click')
expect(callback.mock.calls.length).toBe(1)
})
it('unbinds the event', () => {
const callback = jest.fn()
class EventComponent extends Component {
constructor () {
super()
this.state = {bindEvent: true}
}
dontBind () {
this.setState({bindEvent: false})
}
fire () {
this.refs.c.fireLeafletEvent('click')
}
render () {
return this.state.bindEvent
? <TestComponent onClick={callback} ref='c' />
: <TestComponent ref='c' />
}
}
const component = renderIntoDocument(<EventComponent />)
component.fire()
expect(callback.mock.calls.length).toBe(1)
component.dontBind()
component.fire()
expect(callback.mock.calls.length).toBe(1)
})
it('replaces the event', () => {
const callback1 = jest.fn()
const callback2 = jest.fn()
class EventComponent extends Component {
constructor () {
super()
this.state = {cb: callback1}
}
replaceCallback () {
this.setState({cb: callback2})
}
fire () {
this.refs.c.fireLeafletEvent('click')
}
render () {
return <TestComponent onClick={this.state.cb} ref='c' />
}
}
const component = renderIntoDocument(<EventComponent />)
component.fire()
expect(callback1.mock.calls.length).toBe(1)
expect(callback2.mock.calls.length).toBe(0)
component.replaceCallback()
component.fire()
expect(callback1.mock.calls.length).toBe(1)
expect(callback2.mock.calls.length).toBe(1)
})
})
|
const $e0_attrs$ = ["myRef"];
const $e1_attrs$ = ["myRef1", "myRef2", "myRef3"];
// ...
ViewQueryComponent.ɵcmp = /*@__PURE__*/ $r3$.ɵɵdefineComponent({
// ...
viewQuery: function ViewQueryComponent_Query(rf, ctx) {
if (rf & 1) {
$r3$.ɵɵviewQuery($e0_attrs$, 1);
$r3$.ɵɵviewQuery($e1_attrs$, 1);
}
if (rf & 2) {
let $tmp$;
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.myRef = $tmp$.first);
$r3$.ɵɵqueryRefresh($tmp$ = $r3$.ɵɵloadQuery()) && (ctx.myRefs = $tmp$);
}
},
// ...
});
|
// To use it create some files under `mocks/`
// e.g. `server/mocks/ember-hamsters.js`
//
// module.exports = function(app) {
// app.get('/ember-hamsters', function(req, res) {
// res.send('hello');
// });
// };
module.exports = function(app) {
require('coffee-script/register');
var globSync = require('glob').sync;
var mocks = globSync('./mocks/**/*.coffee', { cwd: __dirname }).map(require);
var proxies = globSync('./proxies/**/*.coffee', { cwd: __dirname }).map(require);
// Log proxy requests
var morgan = require('morgan');
app.use(morgan('dev'));
mocks.forEach(function(route) { route(app); });
proxies.forEach(function(route) { route(app); });
};
|
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
sap.ui.define(['jquery.sap.global'],
function(jQuery) {
"use strict";
/**
* Button renderer.
* @namespace
*/
var ButtonRenderer = {};
/**
* Renders the HTML for the given control, using the provided
* {@link sap.ui.core.RenderManager}.
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oButton
* the button to be rendered
*/
ButtonRenderer.render = function(oRm, oButton) {
// get control properties
var sType = oButton.getType();
var bEnabled = oButton.getEnabled();
var sWidth = oButton.getWidth();
var sTooltip = oButton.getTooltip_AsString();
// get icon from icon pool
var sBackURI = sap.ui.core.IconPool.getIconURI("nav-back");
// start button tag
oRm.write("<button type=\"button\"");
oRm.writeControlData(oButton);
// button container style class
if (!oButton._isUnstyled()) {
oRm.addClass("sapMBtn");
// extend minimum button size if icon is set without text for button types back and up
if ((sType === sap.m.ButtonType.Back || sType === sap.m.ButtonType.Up) && oButton.getIcon() && !oButton.getText()) {
oRm.addClass("sapMBtnBack");
}
}
//ARIA attributes
oRm.writeAccessibilityState(oButton, {
role: 'button',
disabled: !oButton.getEnabled()
});
// check if the button is disabled
if (!bEnabled) {
oRm.writeAttribute("disabled", "disabled");
if (!oButton._isUnstyled()) {
oRm.addClass("sapMBtnDisabled");
}
} else {
switch (sType) {
case sap.m.ButtonType.Accept:
case sap.m.ButtonType.Reject:
case sap.m.ButtonType.Emphasized:
oRm.addClass("sapMBtnInverted");
break;
default: // No need to do anything for other button types
break;
}
}
// add tooltip if available
if (sTooltip) {
oRm.writeAttributeEscaped("title", sTooltip);
}
oRm.writeClasses();
// set user defined width
if (sWidth != "" || sWidth.toLowerCase() === "auto") {
oRm.addStyle("width", sWidth);
oRm.writeStyles();
}
// close button tag
oRm.write(">");
// start inner button tag
oRm.write("<div");
oRm.writeAttribute("id", oButton.getId() + "-inner");
// button style class
if (!oButton._isUnstyled()) {
oRm.addClass("sapMBtnInner");
}
// check if button is hoverable
if (oButton._isHoverable()) {
oRm.addClass("sapMBtnHoverable");
}
// check if button is focusable (not disabled)
if (bEnabled) {
oRm.addClass("sapMFocusable");
}
//get render attributes of depended buttons (e.g. ToggleButton)
if (this.renderButtonAttributes) {
this.renderButtonAttributes(oRm, oButton);
}
// set padding depending on icons left or right or none
if (!oButton._isUnstyled()) {
if (!oButton.getIcon()) {
if (sType != sap.m.ButtonType.Back && sType != sap.m.ButtonType.Up) {
oRm.addClass("sapMBtnPaddingLeft");
}
if (oButton.getText()) {
oRm.addClass("sapMBtnPaddingRight");
}
} else {
if (oButton.getIcon() && oButton.getText() && oButton.getIconFirst()) {
oRm.addClass("sapMBtnPaddingRight");
}
if (oButton.getIcon() && oButton.getText() && !oButton.getIconFirst()) {
if (sType != sap.m.ButtonType.Back && sType != sap.m.ButtonType.Up) {
oRm.addClass("sapMBtnPaddingLeft");
}
}
}
}
// set button specific styles
if (!oButton._isUnstyled() && sType !== "") {
// set button specific styles
oRm.addClass("sapMBtn" + jQuery.sap.escapeHTML(sType));
}
// add all classes to inner button tag
oRm.writeClasses();
// close inner button tag
oRm.write(">");
// set image for internal image control (back)
if (sType === sap.m.ButtonType.Back || sType === sap.m.ButtonType.Up) {
this.writeInternalIconPoolHtml(oRm, oButton, sBackURI);
}
// write icon
if (oButton.getIcon()) {
this.writeImgHtml(oRm, oButton);
}
// write button text
if (oButton.getText()) {
oRm.write("<span");
oRm.addClass("sapMBtnContent");
// Check and add padding between icon and text
if (oButton.getIcon()) {
if (oButton.getIconFirst()) {
if (sType === sap.m.ButtonType.Back || sType === sap.m.ButtonType.Up) {
oRm.addClass("sapMBtnBackContentRight");
} else {
oRm.addClass("sapMBtnContentRight");
}
} else {
if (sType === sap.m.ButtonType.Back || sType === sap.m.ButtonType.Up) {
oRm.addClass("sapMBtnContentRight");
}
oRm.addClass("sapMBtnContentLeft");
}
} else if (sType === sap.m.ButtonType.Back || sType === sap.m.ButtonType.Up) {
oRm.addClass("sapMBtnContentRight");
}
oRm.writeClasses();
oRm.writeAttribute("id", oButton.getId() + "-content");
oRm.write(">");
oRm.writeEscaped(oButton.getText());
oRm.write("</span>");
}
// end inner button tag
oRm.write("</div>");
// end button tag
oRm.write("</button>");
};
/**
* HTML for image
*
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oButton
* the button to be rendered
* @private
*/
ButtonRenderer.writeImgHtml = function(oRm, oButton) {
oRm.renderControl(oButton._getImage((oButton.getId() + "-img"), oButton.getIcon(), oButton.getActiveIcon(), oButton.getIconDensityAware()));
};
/**
* @param {sap.ui.core.RenderManager} oRm
* the RenderManager that can be used for writing to
* the Render-Output-Buffer
* @param {sap.ui.core.Control} oButton
* the button to be rendered
* @param {sap.ui.core.URI} sURI
* URI of the icon to be written
* HTML for internal image (icon pool)
*/
ButtonRenderer.writeInternalIconPoolHtml = function(oRm, oButton, sURI) {
oRm.renderControl(oButton._getInternalIconBtn((oButton.getId() + "-iconBtn"), sURI));
};
return ButtonRenderer;
}, /* bExport= */ true);
|
var GameboyJS;
(function (GameboyJS) {
"use strict";
// The Input management system
//
// The pressKey() and releaseKey() functions should be called by a device class
// like GameboyJS.Keyboard after a physical button trigger event
//
// They rely on the name of the original buttons as parameters (see Input.keys)
var Input = function(cpu, pad) {
this.cpu = cpu;
this.memory = cpu.memory;
this.P1 = 0xFF00;
this.state = 0;
pad.init(this.pressKey.bind(this), this.releaseKey.bind(this));
};
Input.keys = {
START: 0x80,
SELECT: 0x40,
B: 0x20,
A: 0x10,
DOWN: 0x08,
UP: 0x04,
LEFT: 0x02,
RIGHT: 0x01
};
Input.prototype.pressKey = function(key) {
this.state |= Input.keys[key];
this.cpu.requestInterrupt(GameboyJS.CPU.INTERRUPTS.HILO);
};
Input.prototype.releaseKey = function(key) {
var mask = 0xFF - Input.keys[key];
this.state &= mask;
};
Input.prototype.update = function() {
var value = this.memory.rb(this.P1);
value = ((~value) & 0x30); // invert the value so 1 means 'active'
if (value & 0x10) { // direction keys listened
value |= (this.state & 0x0F);
} else if (value & 0x20) { // action keys listened
value |= ((this.state & 0xF0) >> 4);
} else if ((value & 0x30) == 0) { // no keys listened
value &= 0xF0;
}
value = ((~value) & 0x3F); // invert back
this.memory[this.P1] = value;
};
GameboyJS.Input = Input;
}(GameboyJS || (GameboyJS = {})));
|
import React, {PropTypes} from 'react';
import { Modal } from 'antd';
export default class FullScreenDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
showModal:false
};
}
setModal1Visible(isShow){
this.setState({
showModal:isShow
});
}
open(){
this.setModal1Visible(true);
}
close(){
this.setModal1Visible(false);
}
render(){
return (
<div>
<Modal
width="100%"
style={{top: 0}}
title=""
wrapClassName="cp-fullscreen-dialog"
visible={this.state.showModal}
footer = {<div></div>}
onOk={() => this.setModal1Visible(false)}
onCancel={() => this.setModal1Visible(false)}
>
{this.props.children}
</Modal>
</div>
);
}
}
|
"use strict";
const _ = require('lodash');
function astProgram(body, strict = true) {
return {
"type": "Program",
"body": strict ? [astExpression(astValue('use strict'))].concat(body) : body,
"sourceType": "script"
};
}
function astRequire(varName, requirePath) {
return {
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": astId(varName),
"init": astCallInline('require', [ astValue(requirePath) ])
}
],
"kind": "const"
};
}
function astDeclare(left, right, isConstant = false) {
return {
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": astId(left),
"init": right
}
],
"kind": isConstant ? "const" : "let"
};
}
function astIf(test, consequent, alternate) {
return {
"type": "IfStatement",
"test": test,
"consequent": Array.isArray(consequent) ? {
"type": "BlockStatement",
"body": consequent
} : consequent,
"alternate": Array.isArray(alternate) ? {
"type": "BlockStatement",
"body": alternate
} : alternate
};
}
function astBinExp(left, operator, right) {
return {
"type": "BinaryExpression",
"operator": operator,
"left": left,
"right": right
}
}
function astCall(functionName, args) {
return {
"type": "ExpressionStatement",
"expression": astCallInline(functionName, args)
};
}
function astCallInline(functionName, args) {
return {
"type": "CallExpression",
"callee": _.isPlainObject(functionName) ? functionName : astVarRef(functionName),
"arguments": Array.isArray(args) ? args : [args]
};
}
function astYield(target, delegate = false) {
return {
"type": "YieldExpression",
"argument": target,
"delegate": delegate
};
}
function astVarRef(name) {
let p = name.split('.');
if (p.length > 1) {
//p.reverse();
let result = {
"type": "MemberExpression",
"computed": false,
"property": astId(p.pop())
};
let last = result;
while (p.length > 1) {
last["object"] = {
"type": "MemberExpression",
"computed": false,
"property": astId(p.pop())
};
last = last["object"];
}
last["object"] = p[0] === 'this'
? astThis()
: astId(p[0]);
return result;
} else {
return astId(name);
}
}
function astThis() {
return { "type": "ThisExpression" };
}
function astId(name) {
return {
"type": "Identifier",
"name": name
};
}
function astMember(key, any, shorthand = false) {
return {
"type": "Property",
"key": astId(key),
"computed": false,
"value": any,
"kind": "init",
"method": false,
"shorthand": shorthand
};
}
function astValue(value) {
if (Array.isArray(value)) {
return {
"type": "ArrayExpression",
"elements": _.map(value, e => astValue(e))
};
}
if (_.isPlainObject(value)) {
if (value.type === 'ObjectReference' || value.type === 'Variable') {
return astVarRef(value.name);
}
if (value.type === 'Array') {
return astValue(value.value);
}
if (value.type === 'Object') {
let props = [];
_.forOwn(value.value, (any, key) => {
props.push(astMember(key, astValue(any)));
});
return {
"type": "ObjectExpression",
"properties": props
};
}
throw new Error('Unrecognized object: ' + JSON.stringify(value));
}
return {
"type": "Literal",
"value": value,
"raw": JSON.stringify(value)
};
}
function astAddMember(obj, member) {
obj.properties.push(member);
}
function astAddBodyExpression(obj, expr) {
if (Array.isArray(obj.body)) {
obj.body.push(expr);
} else {
obj.body.body.push(expr);
}
}
function astFunction(name, args, body, generator = false) {
return {
"type": "FunctionDeclaration",
"id": astId(name),
"generator": generator,
"expression": false,
"defaults": [],
"params": args,
"body": astBlock(body)
};
}
function astAnonymousFunction(args, body, generator = false) {
return {
"type": "FunctionExpression",
"id": null,
"params": args,
"defaults": [],
"body": {
"type": "BlockStatement",
"body": body
},
"generator": generator,
"expression": false
};
}
function astArrowFunction(args, body, generator = false) {
return {
"type": "ArrowFunctionExpression",
"id": null,
"params": args,
"body": body,
"generator": generator,
"expression": true
}
}
function astBlock(body) {
return {
"type": "BlockStatement",
"body": body
};
}
function astMatchObject(idList, right, isConstant = true) {
return {
"type": "VariableDeclaration",
"declarations": [
{
"type": "VariableDeclarator",
"id": {
"type": "ObjectPattern",
"properties": _.map(idList, id => astMember(id, astId(id), true))
},
"init": right
}
],
"kind": isConstant ? "const" : "let"
};
}
function astExpression(expr) {
return {
"type": "ExpressionStatement",
"expression": expr
};
}
function astAssign(left, right) {
return astExpression({
"type": "AssignmentExpression",
"operator": "=",
"left": astVarRef(left),
"right": right
});
}
function astThrow(name, args) {
return {
"type": "ThrowStatement",
"argument": {
"type": "NewExpression",
"callee": {
"type": "Identifier",
"name": name
},
"arguments": args
}
};
}
function astNot(expr) {
return {
"type": "UnaryExpression",
"operator": "!",
"argument": expr,
"prefix": true
};
}
function astReturn(val) {
return {
"type": "ReturnStatement",
"argument": val
};
}
module.exports = {
astProgram,
astRequire,
astDeclare,
astCall,
astCallInline,
astYield,
astThis,
astId,
astVarRef,
astValue,
astFunction,
astAnonymousFunction,
astArrowFunction,
astIf,
astBinExp,
astBlock,
astMatchObject,
astExpression,
astAssign,
astAddMember,
astMember,
astAddBodyExpression,
astThrow,
astNot,
astReturn
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.