code
stringlengths 2
1.05M
|
|---|
const { describe, it, beforeEach } = require('kocha')
const { createStore, documentObject } = require('./helper')
const genel = require('genel')
const { expect } = require('chai')
const { Action } = require('~')
const { make } = capsid
let store
describe('Store', () => {
beforeEach(async () => {
store = await createStore()
})
describe('save', () => {
it('saves the user object', done => {
store.userRepository = {
save (user) {
expect(user).to.equal(store.user)
done()
}
}
store.save()
})
it('saves the currentJournal if exists', async () => {
await store.dispatch({
type: Action.CREATE_JOURNAL_DOCUMENT,
detail: documentObject
})
await store.dispatch({ type: Action.LOAD_CHART })
const journalSaved = new Promise(resolve => {
store.journalRepository = {
save (journal) {
expect(journal).to.equal(store.currentJournal)
resolve()
}
}
})
await store.save()
return journalSaved
})
})
describe('notifyUpdate', () => {
it('notifies the model update', async () => {
const store = make(
'js-store',
genel.div`<p class="is-model-observer">hello</p>`
)
store.languageReady = Promise.resolve()
const p = new Promise(resolve => {
store.el.firstChild.addEventListener(Action.MODEL_UPDATE, () =>
resolve()
)
})
expect(await store.notifyUpdate()).to.equal(store)
return p
})
})
})
|
import React, { Component } from 'react'
import { Icon, Menu } from 'shengnian-ui-react'
export default class MenuExampleIcons extends Component {
state = { activeItem: 'gamepad' }
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
const { activeItem } = this.state
return (
<Menu icon>
<Menu.Item name='gamepad' active={activeItem === 'gamepad'} onClick={this.handleItemClick}>
<Icon name='gamepad' />
</Menu.Item>
<Menu.Item name='video camera' active={activeItem === 'video camera'} onClick={this.handleItemClick}>
<Icon name='video camera' />
</Menu.Item>
<Menu.Item name='video play' active={activeItem === 'video play'} onClick={this.handleItemClick}>
<Icon name='video play' />
</Menu.Item>
</Menu>
)
}
}
|
'use strict';
var React = require('react');
var LoginForm = require('./LoginForm');
var SignUpForm = require('./SignUpForm');
var Tab = require('./tabs/Tab');
var TabContents = require('./tabs/TabContents');
var TabbedPanel = require('./tabs/TabbedPanel');
var Tabs = require('./tabs/Tabs');
var ObtainUser = React.createClass({
render: function() {
return (
<TabbedPanel selected={0}>
<Tabs>
<Tab>I have an account</Tab>
<Tab>I don't have an account</Tab>
</Tabs>
<TabContents>
<LoginForm/>
<SignUpForm/>
</TabContents>
</TabbedPanel>
);
}
});
module.exports = ObtainUser;
|
'use strict';
/*
* Creates a fake project object for unit tests.
*
* @method getProject
* @private
*/
function getProject(options) {
options = options || {};
let root = options.root || 'default-root';
let pkg = options.pkg || {
version: '1.0.0'
};
return {
root,
pkg,
};
}
/*
* Creates a context (`this`) for `ember-cli` command to be able to successfully
* execute and test `run` method.
*
* In unit tests, we could simply
*
* @method contextFor
* @protected
* @param {String} type A name of the command, e.g. 'publish'
* @param {Object} options Any additional options that needs to be overwritten
* on the command (`project`, etc.)
*/
function contextFor(name, options) {
options = options || {};
let command = require(`../../lib/commands/${name}`);
command.project = getProject(options);
return command;
}
module.exports = {
contextFor
}
|
var curVersion = 'v34';
var request = require('request');
module.exports = function(grunt) {
var firebaseUrl = 'webhook';
var firebaseUri = null;
if(firebaseUrl) {
firebaseUri = 'https://' + firebaseUrl + '.firebaseio.com/generator_version.json';
}
var checkVersion = function(callback) {
if(firebaseUri === null) {
callback();
} else {
request({ url: firebaseUri, json: true }, function(e, r, body) {
if(body) {
if(body !== curVersion) {
console.log('========================================================'.red);
console.log('# This site is using old Webhook code. #'.red);
console.log('========================================================'.red);
console.log('#'.red + ' To update, run "wh update" in this folder.')
console.log('# ---------------------------------------------------- #'.red)
}
callback();
} else {
callback();
}
});
}
};
var generator = require('../libs/generator').generator(grunt.config, grunt.log, grunt.file, root);
grunt.registerTask('buildTemplates', 'Generate static files from templates directory', function() {
var done = this.async();
generator.renderTemplates(done, generator.reloadFiles);
});
grunt.registerTask('buildPages', 'Generate static files from pages directory', function() {
var done = this.async();
generator.renderPages(done, generator.reloadFiles);
});
grunt.registerTask('scaffolding', 'Generate scaffolding for a new object', function(name) {
var done = this.async();
var force = grunt.option('force');
var result = generator.makeScaffolding(name, done, force);
});
grunt.registerTask('watch', 'Watch for changes in templates and regenerate site', function() {
generator.startLiveReload();
grunt.task.run('simple-watch');
});
grunt.registerTask('webListener', 'Listens for commands from CMS through websocket', function() {
var done = this.async();
generator.webListener(done);
});
grunt.registerTask('webListener-open', 'Listens for commands from CMS through websocket', function() {
var done = this.async();
generator.webListener(done);
grunt.util.spawn({
grunt: true,
args: ['open:wh-open'].concat(grunt.option.flags()),
opts: { stdio: 'inherit' }
}, function (err, result, code) {
if (err || code > 0) {
grunt.log.warn('A problem occured while trying to open a browser window to connect to the site.')
grunt.log.warn(result.stderr || result.stdout);
grunt.log.warn('In order to access the site, please navigate to \'localhost:2002\' in your web browser.')
}
grunt.log.writeln('\n' + result.stdout);
});
});
grunt.registerTask('clean', 'Clean build files', function() {
var done = this.async();
generator.cleanFiles(done);
});
// Build Task.
grunt.registerTask('build', 'Clean files and then generate static site into build', function() {
var done = this.async();
var strict = grunt.option('strict');
if(strict === true) {
generator.enableStrictMode();
}
checkVersion(function() {
generator.buildBoth(done, generator.reloadFiles);
})
});
// Change this to optionally prompt instead of requiring a sitename
grunt.registerTask('assets', 'Initialize the firebase configuration file (installer should do this as well)', function() {
generator.assets(grunt);
});
grunt.registerTask('assetsMiddle', 'Initialize the firebase configuration file (installer should do this as well)', function() {
generator.assetsMiddle(grunt);
});
grunt.registerTask('assetsAfter', 'Initialize the firebase configuration file (installer should do this as well)', function() {
generator.assetsAfter(grunt);
});
// Change this to optionally prompt instead of requiring a sitename
grunt.registerTask('init', 'Initialize the firebase configuration file (installer should do this as well)', function() {
var done = this.async();
var sitename = grunt.option('sitename');
var secretkey = grunt.option('secretkey');
var copyCms = grunt.option('copycms');
generator.init(sitename, secretkey, copyCms, done);
});
// Check if initialized properly before running all these tasks
grunt.registerTask('default', 'Clean, Build, Start Local Server, and Watch', function() {
grunt.task.run('configureProxies:wh-server')
grunt.task.run('connect:wh-server');
grunt.task.run('build');
grunt.task.run('concurrent:wh-concurrent');
});
};
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define('/Plugin/bootstrap-treeview', ['exports', 'jquery', 'Plugin', 'Config'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('jquery'), require('Plugin'), require('Config'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.jQuery, global.Plugin, global.Config);
global.PluginBootstrapTreeview = mod.exports;
}
})(this, function (exports, _jquery, _Plugin2, _Config) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _jquery2 = babelHelpers.interopRequireDefault(_jquery);
var _Plugin3 = babelHelpers.interopRequireDefault(_Plugin2);
var Config = babelHelpers.interopRequireWildcard(_Config);
var NAME = 'treeview';
var Treeview = function (_Plugin) {
babelHelpers.inherits(Treeview, _Plugin);
function Treeview() {
babelHelpers.classCallCheck(this, Treeview);
return babelHelpers.possibleConstructorReturn(this, (Treeview.__proto__ || Object.getPrototypeOf(Treeview)).apply(this, arguments));
}
babelHelpers.createClass(Treeview, [{
key: 'getName',
value: function getName() {
return NAME;
}
}, {
key: 'render',
value: function render() {
if (!_jquery2.default.fn.treeview) {
return;
}
var $el = this.$el,
options = this.options;
if (typeof options.source === 'string' && _jquery2.default.isFunction(window[options.source])) {
options.data = window[options.source]();
delete options.source;
} else if (_jquery2.default.isFunction(options.souce)) {
options.data = options.source();
delete options.source;
}
$el.treeview(options);
}
}], [{
key: 'getDefaults',
value: function getDefaults() {
return {
injectStyle: false,
expandIcon: 'icon wb-plus',
collapseIcon: 'icon wb-minus',
emptyIcon: 'icon',
nodeIcon: 'icon wb-folder',
showBorder: false,
// color: undefined, // "#000000",
// backColor: undefined, // "#FFFFFF",
borderColor: Config.colors('blue-grey', 200),
onhoverColor: Config.colors('blue-grey', 100),
selectedColor: '#ffffff',
selectedBackColor: Config.colors('primary', 600),
searchResultColor: Config.colors('primary', 600),
searchResultBackColor: '#ffffff'
};
}
}]);
return Treeview;
}(_Plugin3.default);
_Plugin3.default.register(NAME, Treeview);
exports.default = Treeview;
});
|
var Game = {
tileW: 16,
tileH: 16,
width: 400,
height: 300,
System: {},
Map: {}
};
Game.BOOT = function() {};
Game.BOOT.prototype = {
preload: function() {
this.game.stage.backgroundColor = '#eee';
Game.operate = new Game.System.Operate(this.game);
Game.player = new Game.System.Player(this.game);
Game.npc = new Game.System.Npc(this.game);
},
create: function() {
this.game.state.start('LOAD');
}
};
|
'use strict';
notesApp.controller('showNotesController', function showNotesController($scope, $location, NotesData) {
$scope.notes = NotesData.getNotes();
$scope.searchFor = '';
$scope.$watch('[searchFor]', function () {
if ($scope.searchFor.trim() === '') {
$scope.notes = NotesData.getNotes();
} else {
$scope.notes = NotesData.search($scope.searchFor);
}
}, true);
$scope.goto = function(note) {
$location.path('/edit/' + note.id);
};
});
|
var GameCookieKey = "pic2wordkey";
var LevelsCookieKey = "pic2wordlevels";
function Controller() {
//questions
this.currentQuestionId;
this.currentQuestionLevel;
this.currentQuestionIndex;
this.nextQuestionLevel;
this.questions = [];
this.questionLevels = [];
this.questionRepo = [];
this.questionRepoSize = 10;
this.currentQuestionBatch = 1;
this.isFinish = false;
this.difficultyBoundary = 30;
//cookie related
this.forceFromCurrent = false;
this.isAllowCookie = true;
this.readLevelsFromCookie = false;
//preload
this.minPreloadTime = 3500;
this.isPreloadFinished = false;
this.isPreloadTimeUp = false;
this.preloadTimer;
//data url
this.dataBaseUrl = "data/";
this.loadCharactors();
}
Controller.currentQuestionId;
Controller.currentQuestionIndex;
Controller.questionRepo;
Controller.currentQuestionBatch;
Controller.forceFromCurrent;
Controller.charactors;
Controller.needPreload;
Controller.prototype.startGame = function () {
if (readCookie(GameCookieKey) != null) {
this.loadFromCookie();
}
if (readCookie(LevelsCookieKey) != null) {
this.loadLevelsFromCookie();
}
this.initBaseOnUrl();
}
Controller.prototype.stopGame = function()
{
}
Controller.prototype.loadCharactors = function () {
var that = this;
$.getJSON("data/charactors.json", function (data) {
that.charactors = data["charactors"];
});
}
Controller.prototype.loadFromCookie = function () {
var controllerData = readCookie(GameCookieKey);
var values = controllerData.split(',');
this.currentQuestionLevel = parseInt(values[0]);
this.currentQuestionIndex = parseInt(values[1]);
this.currentQuestionBatch = parseInt(values[2]);
this.nextQuestionLevel = parseInt(values[3]);
this.forceFromCurrent = true;
}
Controller.prototype.saveInCookie = function () {
if ( this.isAllowCookie ) {
createCookie( GameCookieKey, this.currentQuestionLevel + "," + this.currentQuestionIndex + "," + this.currentQuestionBatch + "," + this.nextQuestionLevel, 1000);
}
}
Controller.prototype.loadLevelsFromCookie = function() {
var controllerData = readCookie(LevelsCookieKey);
this.questionLevels = controllerData.split(',');
this.readLevelsFromCookie = true;
}
Controller.prototype.saveLevelsInCookie = function() {
if ( this.isAllowCookie ) {
createCookie( LevelsCookieKey, this.questionLevels.join(','));
}
}
Controller.prototype.handlePreloadRequest = function() {
if ( this.questions.length < 1 ) {
this.loadAllQuestions();
} else {
this.loadCurrentQuestions();
}
}
Controller.prototype.initBaseOnUrl = function() {
var date = getURLParameter('date');
if ( date != null && date != "" ) {
this.dataBaseUrl = "data/" + date + "/";
this.forceFromCurrent = false;
this.readLevelsFromCookie = false;
this.isAllowCookie = false;
this.currentQuestionBatch = 1;
this.currentQuestionId = 1;
this.currentQuestionIndex = 0;
this.currentQuestionLevel = 1;
}
}
Controller.prototype.loadAllQuestions = function () {
var that = this;
$.getJSON( this.dataBaseUrl + "questions.json", function(data) {
that.questions = data["questions"];
if ( data["questionRepoSize"] ) {
that.questionRepoSize = data["questionRepoSize"];
}
that.generateLevels();
that.loadCurrentQuestions();
});
}
Controller.prototype.generateLevels = function() {
if ( this.readLevelsFromCookie && this.questionLevels.length == this.questions.length) {
return;
}
var array = [], length = this.questions.length, difficultyBoundary = this.difficultyBoundary, i;
this.questionLevels = [];
for ( i = 0 ; i < Math.min( difficultyBoundary, length ); i ++ ) {
array.push(i);
}
$.merge(this.questionLevels, shuffleArray(array) );
if ( length > difficultyBoundary ) {
for ( i = difficultyBoundary, array = []; i < length; i ++ ) {
array.push(i);
}
$.merge(this.questionLevels, shuffleArray(array) );
}
this.saveLevelsInCookie();
}
Controller.prototype.loadCurrentQuestions = function() {
var start, end, repoLevels=[], that = this;
start = (this.currentQuestionBatch - 1) * this.questionRepoSize;
end = Math.min( this.questions.length, start + this.questionRepoSize);
if ( start > end ) {
//no more questions
this.saveInCookie();
controller.isFinish = true;
SM.SetStateByName('finish');
return;
}
this.questionRepo = [];
repoLevels = this.questionLevels.slice(start, end);
repoLevels.forEach( function(value, index ) {
that.questionRepo.push(that.questions[value]);
});
if (this.forceFromCurrent == false) {
this.currentQuestionIndex = 0;
this.currentQuestionLevel = 1;
this.nextQuestionLevel = this.currentQuestionLevel + 1;
}
this.currentQuestionId = this.questionRepo[this.currentQuestionIndex]["ID"];
this.saveInCookie();
preloadImages(this.questionRepo);
}
Controller.prototype.isAnswerCorrect = function () {
var answerText = '';
$(sprintf("#question-%d .answer-key", this.currentQuestionId)).filter(function () {
return $(this).attr("data-key") != "";
}).each(function (index, elem) {
answerText += elem.getAttribute("data-key");
});
return this.isAnswerCorrectByText(answerText);
}
Controller.prototype.isAnswerCorrectByText = function (answerText) {
if (this.questionRepo[this.currentQuestionIndex]["answer"] == answerText) {
return true;
}
return false;
}
Controller.prototype.processToNextQuestion = function () {
if (this.questionRepo.length > this.currentQuestionIndex + 1) {
this.currentQuestionIndex++;
this.currentQuestionLevel++;
this.nextQuestionLevel++;
this.currentQuestionId = this.questionRepo[this.currentQuestionIndex]["ID"];
this.saveInCookie();
controller.needPreload = false;
}
else {
this.forceFromCurrent = true;
this.currentQuestionBatch++;
this.currentQuestionLevel++;
this.nextQuestionLevel++;
this.currentQuestionIndex = 0;
controller.needPreload = true;
}
}
Controller.prototype.removeLetters = function () {
}
Controller.prototype.update = function () {
}
|
/***Generated Resource **/
var resource = require('resource');
var ComedyEvent = resource.define('ComedyEvent');
ComedyEvent.schema.description = "Event type: Comedy event.";
ComedyEvent.persist('fs');
ComedyEvent.property('additionalType', {
"name" : "additionalType",
"displayName" : "Additional Type",
"description" : "An additional type for the item, typically used for adding more specific types from external vocabularies in microdata syntax. This is a relationship between something and a class that the thing is in. In RDFa syntax, it is better to use the native RDFa syntax - the 'typeof' attribute - for multiple types. Schema.org tools may have only weaker understanding of extra types, in particular those defined externally.",
"type": "string"
});
ComedyEvent.property('description', {
"name" : "description",
"displayName" : "Description",
"description" : "A short description of the item.",
"type": "string"
});
ComedyEvent.property('image', {
"name" : "image",
"displayName" : "Image",
"description" : "URL of an image of the item.",
"type": "string"
});
ComedyEvent.property('name', {
"name" : "name",
"displayName" : "Name",
"description" : "The name of the item.",
"type": "string"
});
ComedyEvent.property('sameAs', {
"name" : "sameAs",
"displayName" : "Same as",
"description" : "URL of a reference Web page that unambiguously indicates the item's identity. E.g. the URL of the item's Wikipedia page, Freebase page, or official website.",
"type": "string"
});
ComedyEvent.property('url', {
"name" : "url",
"displayName" : "Url",
"description" : "URL of the item.",
"type": "string"
});
exports.ComedyEvent = ComedyEvent;
ComedyEvent.property('attendee', {
"name" : "attendee",
"displayName" : "Attendee",
"description" : "A person or organization attending the event.",
"type":"object","properties" : {"Organization" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Person" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('attendees', {
"name" : "attendees",
"displayName" : "Attendees",
"description" : "A person attending the event (legacy spelling; see singular form, attendee).",
"type":"object","properties" : {"Organization" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Person" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('duration', {
"name" : "duration",
"displayName" : "Duration",
"description" : "The duration of the item (movie, audio recording, event, etc.) in ISO 8601 date format.",
"type": "string"
});
ComedyEvent.property('endDate', {
"name" : "endDate",
"displayName" : "End Date",
"description" : "The end date and time of the event (in ISO 8601 date format).",
"type": "date"
});
ComedyEvent.property('location', {
"name" : "location",
"displayName" : "Location",
"description" : "The location of the event, organization or action.",
"type":"object","properties" : {"Place" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"PostalAddress" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('offers', {
"name" : "offers",
"displayName" : "Offers",
"description" : "An offer to sell this item—for example, an offer to sell a product, the DVD of a movie, or tickets to an event.",
"type":"object","properties" : {"Offer" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('performer', {
"name" : "performer",
"displayName" : "Performer",
"description" : "A performer at the event—for example, a presenter, musician, musical group or actor.",
"type":"object","properties" : {"Organization" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Person" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('performers', {
"name" : "performers",
"displayName" : "Performers",
"description" : "The main performer or performers of the event—for example, a presenter, musician, or actor (legacy spelling; see singular form, performer).",
"type":"object","properties" : {"Organization" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}},"Person" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('startDate', {
"name" : "startDate",
"displayName" : "Start Date",
"description" : "The start date and time of the event (in ISO 8601 date format).",
"type": "date"
});
ComedyEvent.property('subEvent', {
"name" : "subEvent",
"displayName" : "Sub Event",
"description" : "An Event that is part of this event. For example, a conference event includes many presentations, each are a subEvent of the conference.",
"type":"object","properties" : {"Event" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('subEvents', {
"name" : "subEvents",
"displayName" : "Sub Events",
"description" : "Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference (legacy spelling; see singular form, subEvent).",
"type":"object","properties" : {"Event" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
ComedyEvent.property('superEvent', {
"name" : "superEvent",
"displayName" : "Super Event",
"description" : "An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.",
"type":"object","properties" : {"Event" : {"type" :"object", "properties" : { "id" : { "type" : "array" }}}}
});
exports.ComedyEvent = ComedyEvent;
|
'use strict';
const dobby_bot = require('./jslib/dobby_bot');
const dobby_pull = require('./jslib/dobby_pull');
const dobby_spark = require('./jslib/dobby_spark');
const dobby_cass = require('./jslib/dobby_cass');
const async = require('async');
if (process.argv.length != 4) {
console.log('usage: node dobby.js <channel-name> <bot-email>');
process.exit(1);
}
const channelName = process.argv[2];
const botEmail = process.argv[3];
console.log("Chatbot: " + botEmail + " listening on channel: " + channelName);
const sessions = {};
const findOrCreateSession = (roomId) => {
let sessionId;
// Let's see if we already have a session for the roomId
Object.keys(sessions).forEach(k => {
if (sessions[k].roomId === roomId) {
// Yep, got it!
sessionId = k;
}
});
if (!sessionId) {
// No session found for roomId, let's create a new one
sessionId = new Date().toISOString();
sessions[sessionId] = { roomId: roomId, context: {} };
console.log("created new session:", sessions[sessionId]);
}
return sessionId;
};
const mergeContext = (sessionId, context) => {
// console.log("merging context:", sessions[sessionId].context);
context.intent = sessions[sessionId].context.intent;
context.topic = sessions[sessionId].context.topic;
context.input = sessions[sessionId].context.input;
context.state = sessions[sessionId].context.state;
};
// const nextEntry = (intent, topic, state, input) => {
const nextEntry = (context, nextEntryCB) => {
var next = null;
if (!context.intent) {
context.intent = '1';
}
if (!context.topic) {
context.topic = '1';
}
if (!context.state) {
context.state = '1';
}
if (!context.input) {
context.input = '1';
}
function convertResult(row) {
var res = {};
res.next = row.nextstate ? row.nextstate : null;
res.intent = row.nextintent ? row.nextintent : null;
res.msg = row.msg ? row.msg : null;
return res;
}
// next = msgs[context.intent][context.topic][context.state][context.input];
async.series([
function (callback) {
if (!next) {
dobby_cass.getState(context.intent, context.topic, context.state, context.input, function (err, result) {
if (err) {
next = null;
} else if (result.rows.length > 0) {
next = convertResult(result.rows[0]);
}
callback(err, null);
});
} else {
callback(null, null);
}
},
function (callback) {
if (!next) {
dobby_cass.getState(context.intent, context.topic, context.state, '1', function (err, result) {
if (err) {
next = null;
} else if (result.rows.length > 0) {
next = convertResult(result.rows[0]);
}
callback(err, null);
});
} else {
callback(null, null);
}
},
function (callback) {
if (!next) {
dobby_cass.getState(context.intent, context.topic, '1', '1', function (err, result) {
if (err) {
next = null;
} else if (result.rows.length > 0) {
next = convertResult(result.rows[0]);
}
callback(err, null);
});
} else {
callback(null, null);
}
},
function (callback) {
if (!next) {
dobby_cass.getState(context.intent, '1', '1', '1', function (err, result) {
if (err) {
next = null;
} else if (result.rows.length > 0) {
next = convertResult(result.rows[0]);
}
callback(err, null);
});
} else {
callback(null, null);
}
},
function (callback) {
if (!next) {
dobby_cass.getState('1', '1', '1', '1', function (err, result) {
if (err) {
next = null;
} else if (result.rows.length > 0) {
next = convertResult(result.rows[0]);
}
callback(err, null);
});
} else {
callback(null, null);
}
}
], function (err, results) {
nextEntryCB(next);
});
};
const actions = {
say(sessionId, context, message, cb) {
// console.log(message);
// send message to spark room
const roomId = sessions[sessionId].roomId;
if (roomId) {
// we have a room for this sesssion, send message there
dobby_spark.sendMessage(roomId, message, (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
roomId,
':',
err
);
}
});
} else {
console.log("did not find any room Id");
}
cb();
},
merge(sessionId, context, entities, message, cb) {
// console.log("entities:", entities);
// console.log("context", context);
// console.log("session context:", sessions[sessionId].context);
// const intent = bestEntityValue(entities, 'intent');
const intent = entities['intent'];
if (intent && (intent == 'command' || !sessions[sessionId].context.intent)) {
sessions[sessionId].context.intent = intent;
context.intent = intent;
}
// const topic = bestEntityValue(entities, 'topic');
const topic = entities['topic'];
if (!sessions[sessionId].context.topic && topic) {
sessions[sessionId].context.topic = topic;
context.topic = topic;
}
// const input = bestEntityValue(entities, 'input');
const input = entities['input'];
if (input) {
sessions[sessionId].context.input = input;
context.input = input;
}
cb(context);
},
error(sessionId, context, err) {
console.log(err.message);
actions.clean(sessionId, context);
},
clean(sessionId, context, cb) {
console.log("cleaning up state/context");
context = {};
delete sessions[sessionId];
cb(context);
},
nextState(sessionId, context, cb) {
mergeContext(sessionId, context);
sessions[sessionId].context.input = null;
// console.log("context", context);
nextEntry(context, function (result) {
var next = result;
// console.log("got next entry:", next);
if (next.intent) {
sessions[sessionId].context.intent = next.intent;
sessions[sessionId].context.state = next.next;
actions.nextState(sessionId, context, cb);
return;
}
// say whatever dobby says
actions.say(sessionId, context, next.msg, cb);
// run state transition
if (next.next == null) {
actions.clean(sessionId, context, cb);
} else {
sessions[sessionId].context.state = next.next;
}
});
},
};
function processSparkMessage(err, d) {
if (d) {
// console.log("got message:", d);
var data = JSON.parse(d);
const sessionId = findOrCreateSession(data.roomId);
try {
dobby_bot.runActions(
actions,
sessionId, // the user's current session
data['text'], // the user's message
sessions[sessionId].context, // the user's current session state
(error, context) => {
if (error) {
console.log('Oops! Got an error from Wit:', error);
} else {
// Our bot did everything it has to do.
// Now it's waiting for further messages to proceed.
// console.log('Waiting for further messages.');
}
}
);
} catch (e) {
console.log("parser error:", e);
dobby_spark.sendMessage(data.roomId, "could not parse response, please wake up Philip!", (err, data) => {
if (err) {
console.log(
'Oops! An error occurred while forwarding the response to',
data.roomId,
':',
err
);
}
});
}
}
}
dobby_pull.getMessages(channelName, botEmail, processSparkMessage);
|
// LICENSE : MIT
"use strict";
import {RuleHelper} from "textlint-rule-helper";
import alex from "alex";
const defaultOptions = {
allow: undefined,
deny: undefined,
noBinary: false,
profanitySureness: 0
};
module.exports = function textlintRuleAlex(context, options = {}) {
const {Syntax, RuleError, report, getSource} = context;
const helper = new RuleHelper(context);
const opts = {...defaultOptions, ...options};
/*
{ [1:5-1:14: `boogeyman` may be insensitive, use `boogey` instead]
message: '`boogeyman` may be insensitive, use `boogey` instead',
name: '1:5-1:14',
file: '',
reason: '`boogeyman` may be insensitive, use `boogey` instead',
line: 1,
column: 5,
location: Position { start: [Object], end: [Object] },
fatal: false,
ruleId: 'boogeyman-boogeywoman',
source: 'retext-equality' }
*/
const reportError = (node, result) => {
const ruleError = new RuleError(`[${result.ruleId}] ${result.message}`, {
line: result.line - 1,
column: result.column - 1
});
report(node, ruleError);
};
return {
[Syntax.Str](node){
if (helper.isChildNode(node, [Syntax.Link, Syntax.Image, Syntax.BlockQuote, Syntax.Emphasis])) {
return;
}
const text = getSource(node);
const messages = alex(text, opts).messages;
messages.forEach((result) => {
reportError(node, result);
});
}
}
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _createClass2 = require('babel-runtime/helpers/createClass');
var _createClass3 = _interopRequireDefault(_createClass2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _Node2 = require('../Node');
var _Node3 = _interopRequireDefault(_Node2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CatchClause = function (_Node) {
(0, _inherits3.default)(CatchClause, _Node);
function CatchClause(childNodes) {
(0, _classCallCheck3.default)(this, CatchClause);
return (0, _possibleConstructorReturn3.default)(this, (CatchClause.__proto__ || (0, _getPrototypeOf2.default)(CatchClause)).call(this, 'CatchClause', childNodes));
}
(0, _createClass3.default)(CatchClause, [{
key: '_acceptChildren',
value: function _acceptChildren(children) {
children.passToken('Keyword', 'catch');
children.skipNonCode();
children.passToken('Punctuator', '(');
children.skipNonCode();
var param = children.passPattern();
children.skipNonCode();
children.passToken('Punctuator', ')');
children.skipNonCode();
var body = children.passStatement('BlockStatement');
children.assertEnd();
this.param = param;
this.body = body;
}
}]);
return CatchClause;
}(_Node3.default);
exports.default = CatchClause;
//# sourceMappingURL=CatchClause.js.map
|
var uuid = require('uuid'),
logging = require('@tryghost/logging');
/**
* @TODO:
* - move middleware to ignition?
*/
module.exports = function logRequest(req, res, next) {
var startTime = Date.now(),
requestId = uuid.v1();
function logResponse() {
res.responseTime = (Date.now() - startTime) + 'ms';
req.requestId = requestId;
req.userId = req.user ? (req.user.id ? req.user.id : req.user) : null;
if (req.err) {
logging.error({req: req, res: res, err: req.err});
} else {
logging.info({req: req, res: res});
}
res.removeListener('finish', logResponse);
res.removeListener('close', logResponse);
}
res.on('finish', logResponse);
res.on('close', logResponse);
next();
};
|
/* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var timers = require('timers')
var Promise = require('bluebird')
var bitcore = require('bitcore')
var p2p = require('bitcore-p2p')
var RpcClient = require('bitcoind-rpc')
var config = require('../../lib/config')
var errors = require('../../lib/errors')
var logger = require('../../lib/logger').logger
var util = require('../../lib/util')
/**
* @event Network#block
* @param {string} hash
*/
/**
* @event Network#tx
* @param {string} txid
*/
/**
* @class Network
*/
function Network () {
EventEmitter.call(this)
}
inherits(Network, EventEmitter)
/**
* @return {Promise}
*/
Network.prototype.init = function () {
return Promise.all([this._initBitcoind(), this._initTrustedPeer()])
}
/**
* @return {Promise}
*/
Network.prototype._initBitcoind = function () {
var self = this
// create rpc client
self.bitcoind = Promise.promisifyAll(new RpcClient({
host: config.get('bitcoind.rpc.host'),
port: config.get('bitcoind.rpc.port'),
user: config.get('bitcoind.rpc.user'),
pass: config.get('bitcoind.rpc.pass'),
protocol: config.get('bitcoind.rpc.protocol')
}))
// request info
return self.bitcoind.getInfoAsync()
.then(function (ret) {
// check network
var bitcoindNetwork = ret.result.testnet ? 'testnet' : 'livenet'
if (bitcoindNetwork !== config.get('chromanode.network')) {
throw new errors.InvalidBitcoindNetwork()
}
// show info
logger.info(
'Bitcoind checked. (version %d, bestHeight: %s, connections: %s)',
ret.result.version, ret.result.blocks, ret.result.connections)
})
}
/**
* @return {Promise}
*/
Network.prototype._initTrustedPeer = function () {
var self = this
// create trusted peer
self.peer = new p2p.Peer({
host: config.get('chromanode.host'),
port: config.get('chromanode.port'),
network: config.get('chromanode.network')
})
timers.setImmediate(function () { self.peer.connect() })
// inv event
self.peer.on('inv', function (message) {
var names = []
message.inventory.forEach(function (inv) {
// store inv type name
names.push(p2p.Inventory.TYPE_NAME[inv.type])
// store inv if tx type
if (inv.type === p2p.Inventory.TYPE.TX) {
self.emit('tx', util.encode(inv.hash))
}
// emit block if block type
if (inv.type === p2p.Inventory.TYPE.BLOCK) {
self.emit('block', util.encode(inv.hash))
}
})
logger.verbose('Receive inv (%s) message from peer %s:%s',
names.join(', '), self.peer.host, self.peer.port)
})
// connect event
self.peer.on('connect', function () {
logger.info('Connected to network peer %s:%s',
self.peer.host, self.peer.port)
})
// disconnect event
self.peer.on('disconnect', function () {
logger.info('Disconnected from network peer %s:%s',
self.peer.host, self.peer.port)
})
// ready event
self.peer.on('ready', function () {
logger.info(
'Peer %s:%s is ready (version: %s, subversion: %s, bestHeight: %s)',
self.peer.host, self.peer.port,
self.peer.version, self.peer.subversion, self.peer.bestHeight)
})
// waiting peer ready
return new Promise(function (resolve) {
self.peer.on('ready', resolve)
})
}
/**
* @return {Promise<Object>}
*/
Network.prototype.getBitcoindInfo = function () {
return this.bitcoind.getInfoAsync()
.then(function (ret) { return ret.result })
}
/**
* @return {Promise<number>}
*/
Network.prototype.getBlockCount = function () {
return this.bitcoind.getBlockCountAsync()
.then(function (ret) { return ret.result })
}
/**
* @param {number} height
* @return {Promise<string>}
*/
Network.prototype.getBlockHash = function (height) {
return this.bitcoind.getBlockHashAsync(height)
.then(function (ret) { return ret.result })
}
/**
* @param {(number|string)} id
* @return {Promise<bitcore.Block>}
*/
Network.prototype.getBlock = function (id) {
var self = this
return Promise.try(function () {
if (_.isNumber(id)) {
return self.getBlockHash(id)
}
return id
})
.then(function (hash) {
return self.bitcoind.getBlockAsync(hash, false)
})
.then(function (ret) {
var rawBlock = new Buffer(ret.result, 'hex')
return new bitcore.Block(rawBlock)
})
}
/**
* @return {Promise<{hash: string, height: number}>}
*/
Network.prototype.getLatest = function () {
var self = this
return self.getBlockCount()
.then(function (height) {
return Promise.all([height, self.getBlockHash(height)])
})
.spread(function (height, hash) {
return {hash: hash, height: height}
})
}
/**
* @todo Add concurrency
* @param {string} txid
* @return {Promise<bitcore.Transaction>}
*/
Network.prototype.getTx = function (txid) {
return this.bitcoind.getRawTransactionAsync(txid)
.then(function (ret) {
var rawtx = new Buffer(ret.result, 'hex')
return new bitcore.Transaction(rawtx)
})
}
/**
* @param {string} rawtx
* @return {Promise}
*/
Network.prototype.sendTx = function (rawtx) {
return this.bitcoind.sendRawTransactionAsync(rawtx)
}
/**
* @return {Promise<string[]>}
*/
Network.prototype.getMempoolTxs = function () {
return this.bitcoind.getRawMemPoolAsync()
.then(function (ret) { return ret.result })
}
module.exports = Network
|
import React from 'react';
import {
header,
tabs,
tab,
description,
importExample,
title,
columns,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import BasicExample from '!raw-loader!./examples/BasicExample';
import FootnoteExample from '!raw-loader!./examples/FootnoteExample';
import ModalExample from '!raw-loader!./examples/ModalExample';
import PageExample from '!raw-loader!./examples/PageExample';
import PersistentDividersExample from '!raw-loader!./examples/PersistentDividersExample';
import TableExample from '!raw-loader!./examples/TableExample';
import MarketingExample from '!raw-loader!./examples/MarketingExample';
import HelpButtonExample from '!raw-loader!./examples/HelpButtonExample';
import DropdownExample from '!raw-loader!./examples/DropdownExample';
import InputExample from '!raw-loader!./examples/InputExample';
import CustomModalLayout from '..';
import Checkbox from '../../Checkbox';
import Text from '../../Text';
import Box from '../../Box';
export default {
category: storySettings.category,
storyName: storySettings.storyName,
component: CustomModalLayout,
componentPath: '..',
componentProps: {
title: 'Modal title',
children: (
<Box border={'1px dashed grey'} padding={2}>
<Text>Your content goes here...</Text>
</Box>
),
primaryButtonText: 'Confirm',
secondaryButtonText: 'Cancel',
sideActions: <Checkbox>Check</Checkbox>,
footnote: (
<Text size="small">
By sending an invite, you agree to the <a>Wix Terms of Use</a>
</Text>
),
onCloseButtonClick: () => {},
},
sections: [
header({
issueUrl: 'https://github.com/wix/wix-style-react/issues/new/choose',
sourceUrl:
'https://github.com/wix/wix-style-react/tree/master/src/CustomModalLayout/',
}),
tabs([
tab({
title: 'Description',
sections: [
columns([
description({
title: 'Description',
text:
'Use this component inside a Modal component to display content in this layout. You may place a title and/or a footer with actions relevant to the displayed content.',
}),
]),
columns([
importExample(
"import { CustomModalLayout } from 'wix-style-react';",
),
]),
divider(),
title('Examples'),
example({
title: 'Basic Usage',
text: 'A Basic example with compact preview',
source: BasicExample,
}),
example({
title: 'Footnote Example',
text: 'Same as the basic example, with the addition of a footnote',
source: FootnoteExample,
}),
example({
title: 'Opening in a modal',
text:
'Opening the CustomModalLayout is done with the Modal component, usually in the regular size of full-screen',
source: ModalExample,
}),
example({
title: 'Persistent Dividers Example',
text:
'If you need the header or footer dividers to always show, you can use the `showHeaderDivider` and `showFooterDivider` props',
source: PersistentDividersExample,
}),
example({
title: 'Table example - No content padding',
text:
'A simple example with a table as the content and without content padding.',
source: TableExample,
}),
example({
title: 'Help Button Example',
text: 'A basic example with a help button shown.',
source: HelpButtonExample,
}),
example({
title: 'Marketing Layout Example',
text: 'A custom modal example with a marketing layout.',
source: MarketingExample,
}),
example({
title: 'Custom Page & Title Example',
text: 'Open a custom page in a modal with a custom title.',
source: PageExample,
}),
example({
title: 'Input Example',
text:
'When Input element is inside modal, outline at the top and bottom is cut. In order to see full outline, Box component with 3px of height has to be used before and after Input element.',
source: InputExample,
}),
example({
title: 'Opening popovers from a modal',
text:
"CustomModalLayout doesn't let to overflow the content. To make popover elements work properly they need to be used with popover prop appendTo set to window.",
source: DropdownExample,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
|
/*
** Backbone-books by Sebastien Chopin
** @Atinux
** http://www.atinux.fr
*/
(function () {
// Please use your Google API key, be cool :) (http://code.google.com/apis/books/docs/v1/getting_started.html)
var Book, Books, BookView, LibraryView, apiKey = 'AIzaSyAUpierWu7ydjKsa2141jS55CCnqu7JXZo';
// Model
Book = Backbone.Model.extend(),
// Book View
BookView = Backbone.View.extend({
tagName: 'div',
initialize: function () {
var that = this;
this.model.attributes.volumeInfo = this.model.attributes.volumeInfo || {};
this.model.attributes.volumeInfo.imageLinks = this.model.attributes.volumeInfo.imageLinks || {};
setTimeout(function () {
that.render();
}, this.options.time);
},
events: {
'click': 'showBookDetail'
},
render: function () {
if (this.options.parent.lastSearch === this.options.lastSearch) {
var template = $('#bookTemplate').html();
this.$el.html(_.template(template, { model: this.model }));
this.$el.hide().appendTo('.books').fadeIn(200);
}
},
showBookDetail: function () {
var parent = this.options.parent,
scrollTop = parent.$('.library').scrollTop(),
bookDetail = parent.$('.bookDetail'),
that = this;
parent.showBookDetail = true;
parent.bookDetailTop = scrollTop;
bookDetail.css({
'top': scrollTop,
'bottom': -scrollTop
})
.html(_.template($('#bookDetailTemplate').html(), { hash: this.model.toJSON() }))
.fadeIn();
// Call the self link to check if a better resolution of the image is available
if (!this.model.attributes.volumeInfo.imageLinks.small) {
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes/'+this.model.id,
dataType: 'jsonp',
data: 'fields=volumeInfo/imageLinks&key='+apiKey,
success: function (res) {
if (res.volumeInfo && res.volumeInfo.imageLinks && res.volumeInfo.imageLinks.small) {
that.model.attributes.volumeInfo.imageLinks.small = res.volumeInfo.imageLinks.small;
}
else {
that.model.attributes.volumeInfo.imageLinks.small = 'bad';
}
that.addBiggerImage();
}
});
}
else {
this.addBiggerImage();
}
},
addBiggerImage: function () {
var smallImg = this.model.attributes.volumeInfo.imageLinks.small;
if (smallImg !== 'bad') {
this.options.parent.$('.imgBook').append('<img src="'+ smallImg.replace('&edge=curl', '') +'" />');
}
}
});
// Library View
LibraryView = Backbone.View.extend({
initialize: function () {
// this.books = new Books();
this.search();
// Bind scroll event
_.bindAll(this, 'hideBookDetailScroll');
this.$('.library').scroll(this.hideBookDetailScroll);
_.bindAll(this, 'moreBooks');
this.$('.library').scroll(this.moreBooks);
},
events: {
'change .searchValue': 'search',
'click .close': 'hideBookDetail'
},
search: function (e) {
this.s = this.$('.searchValue').val(),
lastSearch = new Date().getTime(),
that = this;
that.$('.books').html('');
this.lastSearch = lastSearch;
this.$('.spinner').fadeIn();
this.page = 0;
if (this.s.trim().length) {
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes',
dataType: 'jsonp',
data: 'q='+encodeURIComponent(this.s)+'&maxResults=40&key='+apiKey+'&fields=totalItems,items(id,volumeInfo/title,volumeInfo/subtitle,volumeInfo/authors,volumeInfo/publishedDate,volumeInfo/description,volumeInfo/imageLinks)',
success: function (res) {
that.$('.spinner').fadeOut();
that.nbMaxPage = Math.ceil(res.totalItems / 40);
if (that.lastSearch === lastSearch) {
if (res.items && res.items.length) {
for (var i in res.items) {
new BookView({
model: new Book(res.items[i]),
time: 80 * i,
lastSearch: lastSearch,
parent: that
});
}
}
else if (res.error) {
that.$('.books').html('<h1 class="notFound">Error, please retry later :s</h1>');
}
else {
that.$('.books').html('<h1 class="notFound">No books found</h1>');
}
}
}
});
}
else {
that.$('.books').html('<h1 class="notFound">Hummmm, can do better :)</h1>');
that.$('.spinner').fadeOut();
}
},
hideBookDetailScroll: function () {
if (this.showBookDetail) {
var actualTop = this.$('.library').scrollTop(),
marge = 150;
if (actualTop > this.bookDetailTop + marge || actualTop < this.bookDetailTop - marge) {
this.showBookDetail = false;
this.hideBookDetail();
}
}
},
hideBookDetail: function () {
this.$('.bookDetail').fadeOut();
},
moreBooks: function () {
var totalHeight = this.$('.library > div').height(),
scrollTop = this.$('.library').scrollTop() + this.$('.library').height(),
lastSearch = this.lastSearch,
that = this,
marge = 200;
if (scrollTop + marge >= totalHeight && !this.loadingMore && this.page < this.nbMaxPage) {
this.loadingMore = true;
this.page++;
this.$('.spinner').fadeIn();
$.ajax({
url: 'https://www.googleapis.com/books/v1/volumes',
dataType: 'jsonp',
data: 'q='+encodeURIComponent(this.s)+'&startIndex='+(this.page * 40)+'&maxResults=40&key='+apiKey+'&fields=totalItems,items(id,volumeInfo/title,volumeInfo/subtitle,volumeInfo/authors,volumeInfo/publishedDate,volumeInfo/description,volumeInfo/imageLinks)',
success: function (res) {
that.$('.spinner').fadeOut();
that.loadingMore = false;
if (that.lastSearch === lastSearch && res.items && res.items.length) {
for (var i in res.items) {
new BookView({
model: new Book(res.items[i]),
time: 80 * i,
lastSearch: lastSearch,
parent: that
});
}
}
}
});
}
}
});
// Run application
$(function () {
new LibraryView({
el: $('#content')
});
});
})();
|
define([ 'game/events', 'game/scene/scene', 'game/scene/camera' ], function (events, scene, camera) {
var container = document.getElementById('game-container');
var renderer = new THREE.WebGLRenderer( { clearColor: 0xefd1b5, clearAlpha: 1 } );
renderer.shadowMapEnabled = true;
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
events.on('game:resize', function () {
renderer.setSize(window.innerWidth, window.innerHeight);
});
events.on('game:render', function () {
renderer.render(scene, camera);
});
return renderer;
})
|
//var word : string = "请输入想要输出的金字塔层数"
function pyramid(totalLine) {
for (var currentLine = 1; currentLine <= totalLine; currentLine++) {
var singleLineStr = "";
for (var spaceCount = totalLine - currentLine; spaceCount > 0; spaceCount--) {
singleLineStr += " ";
}
for (var starCount = 1; starCount <= (currentLine * 2) - 1; starCount++) {
singleLineStr += "*";
}
console.log(singleLineStr);
}
}
var num = process.argv[2];
if (!num) {
}
else {
pyramid(parseInt(num));
}
//# sourceMappingURL=main.js.map
|
var _ = require('./');
// Browsers to run on Sauce Labs platforms
// (See https://saucelabs.com/platform/supported-browsers-devices for an
// up-to-date overview of supported versions of browsers and platforms.)
var sauceBrowsers = _.reduce([
['firefox', 'latest'],
['firefox', '60'],
['firefox', '40'],
['firefox', '11'],
// ['firefox', '4'], // failing due to "not enough arguments"
['chrome', 'latest'],
['chrome', '60'],
['chrome', '40'],
['chrome', '26'],
// latest Edge as well as pre-Blink versions
['microsoftedge', 'latest', 'Windows 10'],
['microsoftedge', '18', 'Windows 10'],
['microsoftedge', '13', 'Windows 10'],
['internet explorer', 'latest', 'Windows 10'],
['internet explorer', '10', 'Windows 8'],
['internet explorer', '9', 'Windows 7'],
// Older versions of IE no longer supported by Sauce Labs
['safari', 'latest', 'macOS 10.15'],
['safari', '12', 'macOS 10.14'],
['safari', '11', 'macOS 10.13'],
['safari', '8', 'OS X 10.10'],
], function(memo, platform) {
// internet explorer -> ie
var label = platform[0].split(' ');
if (label.length > 1) {
label = _.invoke(label, 'charAt', 0)
}
label = (label.join("") + '_v' + platform[1]).replace(' ', '_').toUpperCase();
memo[label] = _.pick({
'base': 'SauceLabs',
'browserName': platform[0],
'version': platform[1],
'platform': platform[2]
}, Boolean);
return memo;
}, {});
module.exports = function(config) {
if ( !process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY ) {
console.log('Sauce environments not set --- Skipping');
return process.exit(0);
}
config.set({
basePath: '',
frameworks: ['qunit'],
singleRun: true,
browserDisconnectTolerance: 5,
browserNoActivityTimeout: 240000,
// list of files / patterns to load in the browser
files: [
'test/vendor/qunit-extras.js',
'test/qunit-setup.js',
'underscore-umd.js',
'test/*.js'
],
// Number of sauce tests to start in parallel
concurrency: 9,
// test results reporter to use
reporters: ['dots', 'saucelabs'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
sauceLabs: {
build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
startConnect: true,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
captureTimeout: 120000,
customLaunchers: sauceBrowsers,
// Browsers to launch, commented out to prevent karma from starting
// too many concurrent browsers and timing sauce out.
browsers: _.keys(sauceBrowsers)
});
};
|
// 23: class - accessors
// To do: make all tests pass, leave the assert lines unchanged!
// Follow the hints of the failure messages!
describe('Class accessors (getter and setter)', () => {
it('a getter is defined like a method prefixed with `get`', () => {
class MyAccount {
//// get money() { return Infinity; }
get balance() { return Infinity; }
}
assert.equal(new MyAccount().balance, Infinity);
});
it('a setter has the prefix `set`', () => {
class MyAccount {
get balance() { return this.amount; }
set balance(amount) { this.amount = amount; }
}
const account = new MyAccount();
//// account.balance = 42;
account.balance = 23;
assert.equal(account.balance, 23);
});
describe('dynamic accessors', () => {
it('a dynamic getter name is enclosed in `[]`', function() {
//// const balance = 'yourMoney';
const getterName = 'yourMoney';
class YourAccount {
get [getterName]() { return -Infinity; }
}
assert.equal(new YourAccount().yourMoney, -Infinity);
});
it('a dynamic setter name as well', function() {
const propertyName = 'balance';
class MyAccount {
get [propertyName]() { return this.amount; }
//// set propertyName(amount) { this.amount = 23; }
set [propertyName](amount) { this.amount = 23; }
}
const account = new MyAccount();
account.balance = 42;
assert.equal(account.balance, 23);
});
});
});
|
import 'antd-mobile/lib/swipe-action/style/index';
|
/** @flow */
import type { t } from '../types'
/**
*
* @param sources
* @param target
*/
export function applyAverage (sources: t[], target: t): void {
const source = sources[0]
if (!source || sources.length === 0) return
if (sources.length === 1) {
target.data.set(source.data, 0)
return
}
const quantity = sources.length
const width = source.width
const height = source.height
const pointsLength = width * height
let matrixIndex
let pointIndex
let currentSum
for (pointIndex = 0; pointIndex < pointsLength; pointIndex++) {
currentSum = 0
for (matrixIndex = 0; matrixIndex < quantity; matrixIndex++) {
currentSum += sources[matrixIndex].data[pointIndex]
}
target.data[pointIndex] = currentSum / quantity
}
}
|
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds_midnight");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.TokenEditor = React.createClass({displayName: "TokenEditor",
handleChange:function(){
var new_token = this.refs.tokenInput.value;
this.props.updateToken(new_token);
},
render: function(){
return (
React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
var url_str = this.refs.urlInput.value;
if (app.isUrl(url_str)){
this.setState({url_vaild:true});
//this.probs.updateUrl(url_str)
}else{
this.setState({url_vaild:false});
}
this.props.updateUrl(url_str);
},
classNames:function(){
return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error');
},
render: function(){
return (
React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"})
);
}
});
app.ResultDisplay = React.createClass({displayName: "ResultDisplay",
getInitialState:function(){
return {'level':-1, test_type:0, 'steps':[]}
},
displayResult:function(res_dict){
var test_type = res_dict.test_type
this.setState({'test_type':test_type})
if (test_type == 0){
this.setState({'level':res_dict.level});
}
this.setState({'steps':res_dict['steps']});
},
render: function(){
return (
React.createElement("div", {className: "result-container"},
React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)),
React.createElement("div", {className: "detail-result"},
React.createElement("div", {className: "result-sum"},
this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null
),
this.state
)
)
)
}
});
var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay",
getInitialState: function(){
return {
is_img_hide:true,
is_modal_show:false
}
},
handleTextClick:function(){
this.setState({is_img_hide:!this.state.is_img_hide});
},
handleShowFullImage:function(event){
event.stopPropagation();
this.setState({is_modal_show:true});
},
handleHideModal(){
this.setState({is_modal_show:false});
},
handleShowModal(){
this.setState({is_modal_show: true});
},
showSteps: function(steps){
},
render:function(){
return (
React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick},
React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, "This is a step info")),
React.createElement("div", {hidden: this.state.is_img_hide, className: "step-img-block"},
React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"),
React.createElement("img", {className: "img-responsive img-rounded step-img", src: "../img/1.png"})
),
this.state.is_modal_show ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: "../img/1.png"})}) : null
)
);
}
});
var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea",
render:function(){
return(
React.createElement("img", {src: this.props.img_src, className: "img-responsive"})
);
}
});
var Modal = app.Modal = React.createClass({displayName: "Modal",
componentDidMount(){
$(ReactDOM.findDOMNode(this)).modal('show');
$(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal);
},
render:function(){
return (
React.createElement("div", {className: "modal modal-wide fade"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.content
),
React.createElement("div", {className: "modal-footer text-center"},
React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close")
)
)
)
)
);
}
});
})();
|
import Ember from 'ember';
import RouteChildrenMixin from '../../../mixins/route-children';
import { module, test } from 'qunit';
module('Unit | Mixin | route children');
// Replace this with your real tests.
test('it works', function(assert) {
var RouteChildrenObject = Ember.Object.extend(RouteChildrenMixin);
var subject = RouteChildrenObject.create();
assert.ok(subject);
});
|
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
define(["require", "exports", "react", "office-ui-fabric-react/lib/Button", "office-ui-fabric-react/lib/Panel"], function (require, exports, React, Button_1, Panel_1) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var PanelExtraLargeExample = (function (_super) {
__extends(PanelExtraLargeExample, _super);
function PanelExtraLargeExample() {
var _this = _super.call(this) || this;
_this.state = { showPanel: false };
return _this;
}
PanelExtraLargeExample.prototype.render = function () {
var _this = this;
return (React.createElement("div", null,
React.createElement(Button_1.DefaultButton, { description: 'Opens the Sample Panel', onClick: function () { return _this.setState({ showPanel: true }); }, text: 'Open Panel' }),
React.createElement(Panel_1.Panel, { isOpen: this.state.showPanel, onDismiss: function () { return _this.setState({ showPanel: false }); }, type: Panel_1.PanelType.extraLarge, headerText: 'Extra Large Panel', closeButtonAriaLabel: 'Close' },
React.createElement("span", { className: 'ms-font-m' }, "Content goes here."))));
};
return PanelExtraLargeExample;
}(React.Component));
exports.PanelExtraLargeExample = PanelExtraLargeExample;
});
//# sourceMappingURL=Panel.ExtraLarge.Example.js.map
|
'use strict';
var fs = require('fs-extra')
, async = require('async')
, nconf = require('nconf');
var config = nconf.file('./conf/pp.' + (process.env.NODE_ENV || 'development') + '.json').load();
require('date-utils');
var pp = {};
pp.poetry = "";
pp.poetryPlain = "";
pp.rawPoetry = [];
pp.cleanPoetry = [];
pp.checkSum = 0;
pp.isFeedFresh = function(cb) {
// checks if conf.Feed is older than conf.maxAgeInMinutes
console.log('\tisFeedFresh checking how old feed is');
console.log(config.feed);
fs.stat(config.feed, function(err, stats) {
if (err) {
if (err.errno === 34) {
console.error('\tisFeedFresh error: Feed not found!');
cb(new Error('Feed not found!'));
} else {
console.error('\tisFeedFresh Unhandled error: %s', JSON.stringify(err, null, 4));
cb(err);
}
} else {
var feed = new Date(stats.mtime)
, now = new Date()
, delta = feed.getMinutesBetween(now);
console.log('\tisFeedFresh stats:\n\t\t%s\n\t\tnow %s\n\t\tdelta (min) %s\n\t\tthreshold (min) %s', feed, now, delta, config.maxAgeInMinutes);
cb(null, delta < config.maxAgeInMinutes);
}
});
};
function start(cb) {
console.log('start');
return cb(null, config.url);
}
var downloadFeed = require('./download.js').downloadFeed
, parseTweets = require('./parseTweets.js').parseTweets
, saveFile = require('./archiveFile.js').saveFile
, saveAndArchiveFile = require('./archiveFile.js').saveAndArchiveFile
, cleanText = require('./sanitiseTweets.js').cleanText
, createMatrix = require('./createMatrix.js').createMatrix
, createPlainText = require('./createPlainText.js').createPlainText;
function finished(d, cb) { // mock cleanText
console.log('finished d: %s', typeof d);
cb(null);
}
pp.updateFeed = function(cb) {
var waterfall = [start, downloadFeed, saveAndArchiveFile, parseTweets, saveAndArchiveFile, cleanText, saveAndArchiveFile,
//FIXME: refactor
function glue(data, cb) {
createMatrix(data, function(err, file, data2, encoding) {
if (err) {
return cb(err);
}
saveFile(file, data2, encoding, function(meh) {
console.log('created banner: %s', typeof meh);
createPlainText(data, function(err, file, data3, encoding) {
saveFile(file, data3, encoding, function(meh) {
console.log('created plain: %s', typeof meh);
cb(null, meh); // :(
}); // saveFileInner
}); // createPlainText
}); // saveFile outer
}); // createMatrix
},finished];
console.log('\tstart time: %s', new Date());
async.waterfall(waterfall, function finished(err) {
if (err) {
// 500
console.log('\tupdateFeed error: %s', JSON.stringify(err, null, 4));
cb(err);
} else {
console.log('\tupdateFeed completed successfully!');
console.log('\tend time: %s', new Date());
cb(null);
}
});
};
pp.ok = function() { return true; };
module.exports = pp;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var laptop = exports.laptop = { "viewBox": "0 0 16 16", "children": [{ "name": "path", "attribs": { "fill": "#000000", "d": "M14 11v-8c0-0.55-0.45-1-1-1h-10c-0.55 0-1 0.45-1 1v8h-2v3h16v-3h-2zM10 13h-4v-1h4v1zM13 11h-10v-7.998c0.001-0.001 0.001-0.001 0.002-0.002h9.996c0.001 0.001 0.001 0.001 0.002 0.002v7.998z" } }] };
|
(function (module) {
var questionData = function ($q, urlConfig, proxy, adalAuthenticationService) {
var getUserQuestions = function () {
var url = urlConfig.questionsByUserId(adalAuthenticationService.userInfo.userName);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getPublicQuestions = function () {
var url = urlConfig.getPublicQuestions;
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionById = function (id) {
var url = urlConfig.getQuestionById(id);
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var getQuestionByValue = function (question) {
var url = urlConfig.getQuestionByValue(encodeURIComponent(question));
var deferred = $q.defer();
proxy.get(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error)
});
return deferred.promise;
}
var addQuestion = function (question) {
var url = urlConfig.addNewQuestion;
var deferred = $q.defer();
//Audit
question.createdBy = adalAuthenticationService.userInfo.userName;
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.createdOn = today;
question.lastModifedOn = today;
proxy.post(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var editQuestion = function (question) {
var url = urlConfig.editQuestion;
var deferred = $q.defer();
//Audit
question.lastModifiedBy = adalAuthenticationService.userInfo.userName;
var today = new Date();
question.lastModifedOn = today;
proxy.put(url, question)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
var deleteQuestion = function (questionId) {
var url = urlConfig.deleteQuestion(questionId);
var deferred = $q.defer();
proxy.del(url)
.then(function (response) {
deferred.resolve(response.data);
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
return {
getUserQuestions: getUserQuestions,
getPublicQuestions: getPublicQuestions,
getQuestionByValue: getQuestionByValue,
getQuestionById: getQuestionById,
addQuestion: addQuestion,
editQuestion: editQuestion,
deleteQuestion: deleteQuestion
}
}
module.factory("questionsData", questionData);
}(angular.module("question")))
|
import { A } from '@ember/array';
import { module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click } from '@ember/test-helpers';
import test from 'ember-sinon-qunit/test-support/test';
import hbs from 'htmlbars-inline-precompile';
import setupNoDeprecations from '../../helpers/setup-no-deprecations';
import { testBS3 } from '../../helpers/bootstrap-test';
module('Integration | Component | bs-button-group', function(hooks) {
setupRenderingTest(hooks);
setupNoDeprecations(hooks);
hooks.beforeEach(function() {
this.actions = {};
this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
});
test('button group has correct CSS classes', async function(assert) {
await render(
hbs`{{#bs-button-group size="lg" justified=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').exists('has btn-group class');
assert.dom('.btn-group').hasClass('btn-group-lg', 'has size class');
});
testBS3('button group supports justified layout', async function(assert) {
await render(
hbs`{{#bs-button-group justified=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').exists('has btn-group class');
assert.dom('.btn-group').hasClass('btn-group-justified', 'has justified class');
});
test('button group supports vertical layout', async function(assert) {
await render(
hbs`{{#bs-button-group vertical=true as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
assert.dom('.btn-group').doesNotExist('has not btn-group class');
assert.dom('.btn-group-vertical').exists('has vertical class');
});
test('radio button group calls onChange with value of selected button', async function(assert) {
let action = this.spy();
this.actions.change = action;
await render(
hbs`{{#bs-button-group type="radio" value=value onChange=(action "change") as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
await click(`button:nth-child(${i + 1})`);
assert.ok(action.calledWith(i + 1), 'onChange has been called with correct value');
}
});
test('checkbox button group calls onChange with value of all selected buttons', async function(assert) {
assert.expect(1);
let expectedValue = [1, 2];
this.actions.change = (value) => {
assert.deepEqual(value, expectedValue);
};
await render(
hbs`{{#bs-button-group type="checkbox" value=value onChange=(action "change") as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', [1]);
await click('button:nth-child(2)');
});
test('radio button group with value set activates button with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', 1);
assert.equal(this.get('value'), 1, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), 0 === k, 'only button with same value is active');
}
});
test('checkbox button group with value set activates buttons with same value', async function(assert) {
let value = A([1, 3]);
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
this.set('value', value);
assert.deepEqual(this.get('value'), value, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), value.includes(k + 1), 'only buttons with value contained in set value are active');
}
});
test('setting radio button group value activates button with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
this.set('value', i + 1);
assert.equal(this.get('value'), i + 1, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), i === k, 'only button with same value is active');
}
}
});
test('setting checkbox button group value with array of values activates buttons with same value', async function(assert) {
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
let value = A([1, 3]);
this.set('value', value);
assert.deepEqual(this.get('value'), value, 'value must match set value');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.equal(this.element.querySelector(`button:nth-child(${k + 1})`).classList.contains('active'), value.includes(k + 1), 'only buttons with value contained in set value is active');
}
});
test('when clicking active radio button, onChange must not be called', async function(assert) {
let action = this.spy();
this.actions.change = action;
await render(
hbs`{{#bs-button-group type="radio" value=1 as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
await click('button:nth-child(1)');
assert.notOk(action.called, 'onChange has not been called');
});
test('setting radio button group value to null sets buttons active state to false', async function(assert) {
await render(
hbs`{{#bs-button-group type="radio" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
for (let i = 0; i < 3; i++) {
this.set('value', i + 1);
this.set('value', null);
assert.equal(this.get('value'), null, 'value must be null');
// check button's active property
for (let k = 0; k < 3; k++) {
assert.dom(`button:nth-child(${k + 1})`).hasNoClass('active', 'button active state is true');
}
}
});
test('clicking button group does not change public value porperty', async function(assert) {
let value = A([1]);
this.set('value', value);
await render(
hbs`{{#bs-button-group type="checkbox" value=value as |bg|}}{{#bg.button value=1}}1{{/bg.button}}{{#bg.button value=2}}2{{/bg.button}}{{#bg.button value=3}}3{{/bg.button}}{{/bs-button-group}}`
);
await click('button:nth-child(3)');
assert.equal(this.get('value'), value, 'Does not change value property');
});
});
|
import React, { Component } from 'react';
import {
View,
Text,
Image,
StyleSheet,
Linking,
TouchableOpacity
} from 'react-native';
import HtmlRender from 'react-native-html-render';
import { parseImgUrl } from '../../utils';
import moment from 'moment';
class TopicCommentItem extends Component {
render() {
const { reply, idx } = this.props;
const avatar = parseImgUrl(reply.member.avatar_normal);
const date = moment.unix(reply.created).fromNow();
const content = `<p>${reply.content_rendered}</p>`;
const floor = `#${idx + 1}`;
return (
<View style={styles.reply} key={reply.id}>
<View style={styles.header}>
<TouchableOpacity>
<Image
style={[styles.avatar]}
source={{uri: avatar}}>
</Image>
</TouchableOpacity>
<View style={styles.info}>
<View style={styles.usernameWrapper}>
<Text style={styles.username}>
{reply.member.username}
</Text>
</View>
<View style={styles.dateWrapper}>
<Text style={styles.date}>
{date}
</Text>
</View>
</View>
<View style={styles.floorWrapper}>
<Text style={styles.floor}>
{floor}
</Text>
</View>
</View>
<View style={styles.content}>
<HtmlRender
value={content}
stylesheet={htmlStyles}
onLinkPress={url => Linking.openURL(url)}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
reply: {
padding: 10,
borderBottomColor: 'rgba(0, 0, 0, 0.05)',
borderBottomWidth: 1,
},
header: {
flexDirection: 'row',
},
avatar: {
height: 30,
width: 30,
borderRadius: 20,
marginRight: 10,
},
info: {
flexDirection: 'row',
},
usernameWrapper: {
marginRight: 10,
},
username: {
fontSize: 14,
},
dateWrapper: {
marginRight: 10,
},
date: {
fontSize: 14,
},
floorWrapper: {
position: 'absolute',
right: 5,
},
floor: {
fontSize: 12,
},
content: {
marginLeft: 25,
}
});
const htmlStyles = StyleSheet.create({
pwrapper: {
marginTop: 5,
marginBottom: 5,
paddingLeft: 15,
paddingRight: 15
},
p: {
fontSize: 14,
},
a: {
color: '#4078c0',
fontSize: 14,
}
});
export default TopicCommentItem;
|
/**
* Created by dli on 25.01.2015.
*/
define('sync/time/Clock', ['sync/time/CONST'], function (CONST) {
var Clock = function (time){
this.time = time || 0;
}
Clock.prototype.tick = function(){
return this.time < CONST.LOGICAL_HOUR - 1 ? ++this.time : (this.time = 0);
}
Clock.prototype.setTime = function(time) {
this.time = time;
}
Clock.prototype.getTime = function(time) {
return this.time;
}
return Clock;
});
|
'use strict';
angular.module('startingPointJsApp')
.service('Auth', ['$rootScope', '$http', 'localStorageService', function Auth($rootScope, $http, localStorageService) {
this.eventName = 'Auth.changes';
Auth.prototype.getUser = function () {
return localStorageService.get('user');
};
Auth.prototype.signIn = function (data, callback) {
$http.post('/signin', data).success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.set('user', result.result);
Auth.prototype.broadcast();
}
});
};
Auth.prototype.signOut = function (callback) {
$http.post('/signout').success(function (result) {
if (result.status.code !== 200) {
callback(result.error, null);
} else {
callback(null, result.result);
localStorageService.clearAll();
Auth.prototype.broadcast();
}
});
};
Auth.prototype.subscribe = function ($scope, callback) {
$scope.$on(Auth.eventName, callback);
};
Auth.prototype.broadcast = function () {
$rootScope.$broadcast(Auth.eventName);
};
}]);
|
/**
* Created by ila on 5/18/2015.
*/
"use strict"
class SettingStore {
static set(object) {
const KEY = 'Setting';
return localforage.setItem(KEY, object.toArray());
}
static get() {
const KEY = 'Setting';
return localforage.getItem(KEY).then(function (v) {
return new Promise(function (resolve, reject) {
let setting = new Setting();
if (v) setting.fromArray(v);
resolve(setting);
});
});
}
}
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { Optional, Inject, Injectable, NgZone, NgModule, SkipSelf, ApplicationRef, ComponentFactoryResolver, Injector, ElementRef, Directive, EventEmitter, InjectionToken, Input, Output, TemplateRef, ViewContainerRef, defineInjectable, inject } from '@angular/core';
import { coerceCssPixelValue, coerceArray, coerceBooleanProperty } from '@angular/cdk/coercion';
import { ScrollDispatcher, ViewportRuler, ScrollDispatchModule, VIEWPORT_RULER_PROVIDER } from '@angular/cdk/scrolling';
export { ViewportRuler, VIEWPORT_RULER_PROVIDER, CdkScrollable, ScrollDispatcher } from '@angular/cdk/scrolling';
import { DOCUMENT } from '@angular/common';
import { Observable, Subject, merge, Subscription } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';
import { Platform } from '@angular/cdk/platform';
import { Directionality, BidiModule } from '@angular/cdk/bidi';
import { DomPortalOutlet, TemplatePortal, PortalModule } from '@angular/cdk/portal';
import { ESCAPE } from '@angular/cdk/keycodes';
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Scroll strategy that doesn't do anything.
*/
class NoopScrollStrategy {
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
enable() { }
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
disable() { }
/**
* Does nothing, as this scroll strategy is a no-op.
* @return {?}
*/
attach() { }
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Initial configuration used when creating an overlay.
*/
class OverlayConfig {
/**
* @param {?=} config
*/
constructor(config) {
/**
* Strategy to be used when handling scroll events while the overlay is open.
*/
this.scrollStrategy = new NoopScrollStrategy();
/**
* Custom class to add to the overlay pane.
*/
this.panelClass = '';
/**
* Whether the overlay has a backdrop.
*/
this.hasBackdrop = false;
/**
* Custom class to add to the backdrop
*/
this.backdropClass = 'cdk-overlay-dark-backdrop';
if (config) {
Object.keys(config)
.filter(key => typeof config[key] !== 'undefined')
.forEach(key => this[key] = config[key]);
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* The points of the origin element and the overlay element to connect.
*/
class ConnectionPositionPair {
/**
* @param {?} origin
* @param {?} overlay
* @param {?=} offsetX
* @param {?=} offsetY
*/
constructor(origin, overlay, offsetX, offsetY) {
this.offsetX = offsetX;
this.offsetY = offsetY;
this.originX = origin.originX;
this.originY = origin.originY;
this.overlayX = overlay.overlayX;
this.overlayY = overlay.overlayY;
}
}
/**
* Set of properties regarding the position of the origin and overlay relative to the viewport
* with respect to the containing Scrollable elements.
*
* The overlay and origin are clipped if any part of their bounding client rectangle exceeds the
* bounds of any one of the strategy's Scrollable's bounding client rectangle.
*
* The overlay and origin are outside view if there is no overlap between their bounding client
* rectangle and any one of the strategy's Scrollable's bounding client rectangle.
*
* ----------- -----------
* | outside | | clipped |
* | view | --------------------------
* | | | | | |
* ---------- | ----------- |
* -------------------------- | |
* | | | Scrollable |
* | | | |
* | | --------------------------
* | Scrollable |
* | |
* --------------------------
*
* \@docs-private
*/
class ScrollingVisibility {
}
/**
* The change event emitted by the strategy when a fallback position is used.
*/
class ConnectedOverlayPositionChange {
/**
* @param {?} connectionPair
* @param {?} scrollableViewProperties
*/
constructor(connectionPair, /** @docs-private */
scrollableViewProperties) {
this.connectionPair = connectionPair;
this.scrollableViewProperties = scrollableViewProperties;
}
}
/** @nocollapse */
ConnectedOverlayPositionChange.ctorParameters = () => [
{ type: ConnectionPositionPair, },
{ type: ScrollingVisibility, decorators: [{ type: Optional },] },
];
/**
* Validates whether a vertical position property matches the expected values.
* \@docs-private
* @param {?} property Name of the property being validated.
* @param {?} value Value of the property being validated.
* @return {?}
*/
function validateVerticalPosition(property, value) {
if (value !== 'top' && value !== 'bottom' && value !== 'center') {
throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
`Expected "top", "bottom" or "center".`);
}
}
/**
* Validates whether a horizontal position property matches the expected values.
* \@docs-private
* @param {?} property Name of the property being validated.
* @param {?} value Value of the property being validated.
* @return {?}
*/
function validateHorizontalPosition(property, value) {
if (value !== 'start' && value !== 'end' && value !== 'center') {
throw Error(`ConnectedPosition: Invalid ${property} "${value}". ` +
`Expected "start", "end" or "center".`);
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will prevent the user from scrolling while the overlay is visible.
*/
class BlockScrollStrategy {
/**
* @param {?} _viewportRuler
* @param {?} document
*/
constructor(_viewportRuler, document) {
this._viewportRuler = _viewportRuler;
this._previousHTMLStyles = { top: '', left: '' };
this._isEnabled = false;
this._document = document;
}
/**
* Attaches this scroll strategy to an overlay.
* @return {?}
*/
attach() { }
/**
* Blocks page-level scroll while the attached overlay is open.
* @return {?}
*/
enable() {
if (this._canBeEnabled()) {
const /** @type {?} */ root = this._document.documentElement;
this._previousScrollPosition = this._viewportRuler.getViewportScrollPosition();
// Cache the previous inline styles in case the user had set them.
this._previousHTMLStyles.left = root.style.left || '';
this._previousHTMLStyles.top = root.style.top || '';
// Note: we're using the `html` node, instead of the `body`, because the `body` may
// have the user agent margin, whereas the `html` is guaranteed not to have one.
root.style.left = coerceCssPixelValue(-this._previousScrollPosition.left);
root.style.top = coerceCssPixelValue(-this._previousScrollPosition.top);
root.classList.add('cdk-global-scrollblock');
this._isEnabled = true;
}
}
/**
* Unblocks page-level scroll while the attached overlay is open.
* @return {?}
*/
disable() {
if (this._isEnabled) {
const /** @type {?} */ html = this._document.documentElement;
const /** @type {?} */ body = this._document.body;
const /** @type {?} */ previousHtmlScrollBehavior = html.style['scrollBehavior'] || '';
const /** @type {?} */ previousBodyScrollBehavior = body.style['scrollBehavior'] || '';
this._isEnabled = false;
html.style.left = this._previousHTMLStyles.left;
html.style.top = this._previousHTMLStyles.top;
html.classList.remove('cdk-global-scrollblock');
// Disable user-defined smooth scrolling temporarily while we restore the scroll position.
// See https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior
html.style['scrollBehavior'] = body.style['scrollBehavior'] = 'auto';
window.scroll(this._previousScrollPosition.left, this._previousScrollPosition.top);
html.style['scrollBehavior'] = previousHtmlScrollBehavior;
body.style['scrollBehavior'] = previousBodyScrollBehavior;
}
}
/**
* @return {?}
*/
_canBeEnabled() {
// Since the scroll strategies can't be singletons, we have to use a global CSS class
// (`cdk-global-scrollblock`) to make sure that we don't try to disable global
// scrolling multiple times.
const /** @type {?} */ html = this._document.documentElement;
if (html.classList.contains('cdk-global-scrollblock') || this._isEnabled) {
return false;
}
const /** @type {?} */ body = this._document.body;
const /** @type {?} */ viewport = this._viewportRuler.getViewportSize();
return body.scrollHeight > viewport.height || body.scrollWidth > viewport.width;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Returns an error to be thrown when attempting to attach an already-attached scroll strategy.
* @return {?}
*/
function getMatScrollStrategyAlreadyAttachedError() {
return Error(`Scroll strategy has already been attached.`);
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will close the overlay as soon as the user starts scrolling.
*/
class CloseScrollStrategy {
/**
* @param {?} _scrollDispatcher
* @param {?} _ngZone
* @param {?} _viewportRuler
* @param {?=} _config
*/
constructor(_scrollDispatcher, _ngZone, _viewportRuler, _config) {
this._scrollDispatcher = _scrollDispatcher;
this._ngZone = _ngZone;
this._viewportRuler = _viewportRuler;
this._config = _config;
this._scrollSubscription = null;
/**
* Detaches the overlay ref and disables the scroll strategy.
*/
this._detach = () => {
this.disable();
if (this._overlayRef.hasAttached()) {
this._ngZone.run(() => this._overlayRef.detach());
}
};
}
/**
* Attaches this scroll strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef) {
throw getMatScrollStrategyAlreadyAttachedError();
}
this._overlayRef = overlayRef;
}
/**
* Enables the closing of the attached overlay on scroll.
* @return {?}
*/
enable() {
if (this._scrollSubscription) {
return;
}
const /** @type {?} */ stream = this._scrollDispatcher.scrolled(0);
if (this._config && this._config.threshold && this._config.threshold > 1) {
this._initialScrollPosition = this._viewportRuler.getViewportScrollPosition().top;
this._scrollSubscription = stream.subscribe(() => {
const /** @type {?} */ scrollPosition = this._viewportRuler.getViewportScrollPosition().top;
if (Math.abs(scrollPosition - this._initialScrollPosition) > /** @type {?} */ ((/** @type {?} */ ((this._config)).threshold))) {
this._detach();
}
else {
this._overlayRef.updatePosition();
}
});
}
else {
this._scrollSubscription = stream.subscribe(this._detach);
}
}
/**
* Disables the closing the attached overlay on scroll.
* @return {?}
*/
disable() {
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
this._scrollSubscription = null;
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
// TODO(jelbourn): move this to live with the rest of the scrolling code
// TODO(jelbourn): someday replace this with IntersectionObservers
/**
* Gets whether an element is scrolled outside of view by any of its parent scrolling containers.
* \@docs-private
* @param {?} element Dimensions of the element (from getBoundingClientRect)
* @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
* @return {?} Whether the element is scrolled out of view
*/
function isElementScrolledOutsideView(element, scrollContainers) {
return scrollContainers.some(containerBounds => {
const /** @type {?} */ outsideAbove = element.bottom < containerBounds.top;
const /** @type {?} */ outsideBelow = element.top > containerBounds.bottom;
const /** @type {?} */ outsideLeft = element.right < containerBounds.left;
const /** @type {?} */ outsideRight = element.left > containerBounds.right;
return outsideAbove || outsideBelow || outsideLeft || outsideRight;
});
}
/**
* Gets whether an element is clipped by any of its scrolling containers.
* \@docs-private
* @param {?} element Dimensions of the element (from getBoundingClientRect)
* @param {?} scrollContainers Dimensions of element's scrolling containers (from getBoundingClientRect)
* @return {?} Whether the element is clipped
*/
function isElementClippedByScrolling(element, scrollContainers) {
return scrollContainers.some(scrollContainerRect => {
const /** @type {?} */ clippedAbove = element.top < scrollContainerRect.top;
const /** @type {?} */ clippedBelow = element.bottom > scrollContainerRect.bottom;
const /** @type {?} */ clippedLeft = element.left < scrollContainerRect.left;
const /** @type {?} */ clippedRight = element.right > scrollContainerRect.right;
return clippedAbove || clippedBelow || clippedLeft || clippedRight;
});
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Strategy that will update the element position as the user is scrolling.
*/
class RepositionScrollStrategy {
/**
* @param {?} _scrollDispatcher
* @param {?} _viewportRuler
* @param {?} _ngZone
* @param {?=} _config
*/
constructor(_scrollDispatcher, _viewportRuler, _ngZone, _config) {
this._scrollDispatcher = _scrollDispatcher;
this._viewportRuler = _viewportRuler;
this._ngZone = _ngZone;
this._config = _config;
this._scrollSubscription = null;
}
/**
* Attaches this scroll strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef) {
throw getMatScrollStrategyAlreadyAttachedError();
}
this._overlayRef = overlayRef;
}
/**
* Enables repositioning of the attached overlay on scroll.
* @return {?}
*/
enable() {
if (!this._scrollSubscription) {
const /** @type {?} */ throttle = this._config ? this._config.scrollThrottle : 0;
this._scrollSubscription = this._scrollDispatcher.scrolled(throttle).subscribe(() => {
this._overlayRef.updatePosition();
// TODO(crisbeto): make `close` on by default once all components can handle it.
if (this._config && this._config.autoClose) {
const /** @type {?} */ overlayRect = this._overlayRef.overlayElement.getBoundingClientRect();
const { width, height } = this._viewportRuler.getViewportSize();
// TODO(crisbeto): include all ancestor scroll containers here once
// we have a way of exposing the trigger element to the scroll strategy.
const /** @type {?} */ parentRects = [{ width, height, bottom: height, right: width, top: 0, left: 0 }];
if (isElementScrolledOutsideView(overlayRect, parentRects)) {
this.disable();
this._ngZone.run(() => this._overlayRef.detach());
}
}
});
}
}
/**
* Disables repositioning of the attached overlay on scroll.
* @return {?}
*/
disable() {
if (this._scrollSubscription) {
this._scrollSubscription.unsubscribe();
this._scrollSubscription = null;
}
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Options for how an overlay will handle scrolling.
*
* Users can provide a custom value for `ScrollStrategyOptions` to replace the default
* behaviors. This class primarily acts as a factory for ScrollStrategy instances.
*/
class ScrollStrategyOptions {
/**
* @param {?} _scrollDispatcher
* @param {?} _viewportRuler
* @param {?} _ngZone
* @param {?} document
*/
constructor(_scrollDispatcher, _viewportRuler, _ngZone, document) {
this._scrollDispatcher = _scrollDispatcher;
this._viewportRuler = _viewportRuler;
this._ngZone = _ngZone;
/**
* Do nothing on scroll.
*/
this.noop = () => new NoopScrollStrategy();
/**
* Close the overlay as soon as the user scrolls.
* @param config Configuration to be used inside the scroll strategy.
*/
this.close = (config) => new CloseScrollStrategy(this._scrollDispatcher, this._ngZone, this._viewportRuler, config);
/**
* Block scrolling.
*/
this.block = () => new BlockScrollStrategy(this._viewportRuler, this._document);
/**
* Update the overlay's position on scroll.
* @param config Configuration to be used inside the scroll strategy.
* Allows debouncing the reposition calls.
*/
this.reposition = (config) => new RepositionScrollStrategy(this._scrollDispatcher, this._viewportRuler, this._ngZone, config);
this._document = document;
}
}
ScrollStrategyOptions.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
ScrollStrategyOptions.ctorParameters = () => [
{ type: ScrollDispatcher, },
{ type: ViewportRuler, },
{ type: NgZone, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ ScrollStrategyOptions.ngInjectableDef = defineInjectable({ factory: function ScrollStrategyOptions_Factory() { return new ScrollStrategyOptions(inject(ScrollDispatcher), inject(ViewportRuler), inject(NgZone), inject(DOCUMENT)); }, token: ScrollStrategyOptions, providedIn: "root" });
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Service for dispatching keyboard events that land on the body to appropriate overlay ref,
* if any. It maintains a list of attached overlays to determine best suited overlay based
* on event target and order of overlay opens.
*/
class OverlayKeyboardDispatcher {
/**
* @param {?} document
*/
constructor(document) {
/**
* Currently attached overlays in the order they were attached.
*/
this._attachedOverlays = [];
/**
* Keyboard event listener that will be attached to the body.
*/
this._keydownListener = (event) => {
const /** @type {?} */ overlays = this._attachedOverlays;
for (let /** @type {?} */ i = overlays.length - 1; i > -1; i--) {
// Dispatch the keydown event to the top overlay which has subscribers to its keydown events.
// We want to target the most recent overlay, rather than trying to match where the event came
// from, because some components might open an overlay, but keep focus on a trigger element
// (e.g. for select and autocomplete). We skip overlays without keydown event subscriptions,
// because we don't want overlays that don't handle keyboard events to block the ones below
// them that do.
if (overlays[i]._keydownEventSubscriptions > 0) {
overlays[i]._keydownEvents.next(event);
break;
}
}
};
this._document = document;
}
/**
* @return {?}
*/
ngOnDestroy() {
this._detach();
}
/**
* Add a new overlay to the list of attached overlay refs.
* @param {?} overlayRef
* @return {?}
*/
add(overlayRef) {
// Ensure that we don't get the same overlay multiple times.
this.remove(overlayRef);
// Lazily start dispatcher once first overlay is added
if (!this._isAttached) {
this._document.body.addEventListener('keydown', this._keydownListener, true);
this._isAttached = true;
}
this._attachedOverlays.push(overlayRef);
}
/**
* Remove an overlay from the list of attached overlay refs.
* @param {?} overlayRef
* @return {?}
*/
remove(overlayRef) {
const /** @type {?} */ index = this._attachedOverlays.indexOf(overlayRef);
if (index > -1) {
this._attachedOverlays.splice(index, 1);
}
// Remove the global listener once there are no more overlays.
if (this._attachedOverlays.length === 0) {
this._detach();
}
}
/**
* Detaches the global keyboard event listener.
* @return {?}
*/
_detach() {
if (this._isAttached) {
this._document.body.removeEventListener('keydown', this._keydownListener, true);
this._isAttached = false;
}
}
}
OverlayKeyboardDispatcher.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayKeyboardDispatcher.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ OverlayKeyboardDispatcher.ngInjectableDef = defineInjectable({ factory: function OverlayKeyboardDispatcher_Factory() { return new OverlayKeyboardDispatcher(inject(DOCUMENT)); }, token: OverlayKeyboardDispatcher, providedIn: "root" });
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
* @param {?} dispatcher
* @param {?} _document
* @return {?}
*/
function OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY(dispatcher, _document) {
return dispatcher || new OverlayKeyboardDispatcher(_document);
}
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_KEYBOARD_DISPATCHER_PROVIDER = {
// If there is already an OverlayKeyboardDispatcher available, use that.
// Otherwise, provide a new one.
provide: OverlayKeyboardDispatcher,
deps: [
[new Optional(), new SkipSelf(), OverlayKeyboardDispatcher],
/** @type {?} */ (
// Coerce to `InjectionToken` so that the `deps` match the "shape"
// of the type expected by Angular
DOCUMENT)
],
useFactory: OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Container inside which all overlays will render.
*/
class OverlayContainer {
/**
* @param {?} _document
*/
constructor(_document) {
this._document = _document;
}
/**
* @return {?}
*/
ngOnDestroy() {
if (this._containerElement && this._containerElement.parentNode) {
this._containerElement.parentNode.removeChild(this._containerElement);
}
}
/**
* This method returns the overlay container element. It will lazily
* create the element the first time it is called to facilitate using
* the container in non-browser environments.
* @return {?} the container element
*/
getContainerElement() {
if (!this._containerElement) {
this._createContainer();
}
return this._containerElement;
}
/**
* Create the overlay container element, which is simply a div
* with the 'cdk-overlay-container' class on the document body.
* @return {?}
*/
_createContainer() {
const /** @type {?} */ container = this._document.createElement('div');
container.classList.add('cdk-overlay-container');
this._document.body.appendChild(container);
this._containerElement = container;
}
}
OverlayContainer.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayContainer.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/** @nocollapse */ OverlayContainer.ngInjectableDef = defineInjectable({ factory: function OverlayContainer_Factory() { return new OverlayContainer(inject(DOCUMENT)); }, token: OverlayContainer, providedIn: "root" });
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
* @param {?} parentContainer
* @param {?} _document
* @return {?}
*/
function OVERLAY_CONTAINER_PROVIDER_FACTORY(parentContainer, _document) {
return parentContainer || new OverlayContainer(_document);
}
/**
* \@docs-private \@deprecated \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_CONTAINER_PROVIDER = {
// If there is already an OverlayContainer available, use that. Otherwise, provide a new one.
provide: OverlayContainer,
deps: [
[new Optional(), new SkipSelf(), OverlayContainer],
/** @type {?} */ (DOCUMENT // We need to use the InjectionToken somewhere to keep TS happy
) // We need to use the InjectionToken somewhere to keep TS happy
],
useFactory: OVERLAY_CONTAINER_PROVIDER_FACTORY
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Reference to an overlay that has been created with the Overlay service.
* Used to manipulate or dispose of said overlay.
*/
class OverlayRef {
/**
* @param {?} _portalOutlet
* @param {?} _host
* @param {?} _pane
* @param {?} _config
* @param {?} _ngZone
* @param {?} _keyboardDispatcher
* @param {?} _document
*/
constructor(_portalOutlet, _host, _pane, _config, _ngZone, _keyboardDispatcher, _document) {
this._portalOutlet = _portalOutlet;
this._host = _host;
this._pane = _pane;
this._config = _config;
this._ngZone = _ngZone;
this._keyboardDispatcher = _keyboardDispatcher;
this._document = _document;
this._backdropElement = null;
this._backdropClick = new Subject();
this._attachments = new Subject();
this._detachments = new Subject();
this._keydownEventsObservable = Observable.create(observer => {
const /** @type {?} */ subscription = this._keydownEvents.subscribe(observer);
this._keydownEventSubscriptions++;
return () => {
subscription.unsubscribe();
this._keydownEventSubscriptions--;
};
});
/**
* Stream of keydown events dispatched to this overlay.
*/
this._keydownEvents = new Subject();
/**
* Amount of subscriptions to the keydown events.
*/
this._keydownEventSubscriptions = 0;
if (_config.scrollStrategy) {
_config.scrollStrategy.attach(this);
}
}
/**
* The overlay's HTML element
* @return {?}
*/
get overlayElement() {
return this._pane;
}
/**
* The overlay's backdrop HTML element.
* @return {?}
*/
get backdropElement() {
return this._backdropElement;
}
/**
* Wrapper around the panel element. Can be used for advanced
* positioning where a wrapper with specific styling is
* required around the overlay pane.
* @return {?}
*/
get hostElement() {
return this._host;
}
/**
* Attaches content, given via a Portal, to the overlay.
* If the overlay is configured to have a backdrop, it will be created.
*
* @param {?} portal Portal instance to which to attach the overlay.
* @return {?} The portal attachment result.
*/
attach(portal) {
let /** @type {?} */ attachResult = this._portalOutlet.attach(portal);
if (this._config.positionStrategy) {
this._config.positionStrategy.attach(this);
}
// Update the pane element with the given configuration.
if (!this._host.parentElement && this._previousHostParent) {
this._previousHostParent.appendChild(this._host);
}
this._updateStackingOrder();
this._updateElementSize();
this._updateElementDirection();
if (this._config.scrollStrategy) {
this._config.scrollStrategy.enable();
}
// Update the position once the zone is stable so that the overlay will be fully rendered
// before attempting to position it, as the position may depend on the size of the rendered
// content.
this._ngZone.onStable
.asObservable()
.pipe(take(1))
.subscribe(() => {
// The overlay could've been detached before the zone has stabilized.
if (this.hasAttached()) {
this.updatePosition();
}
});
// Enable pointer events for the overlay pane element.
this._togglePointerEvents(true);
if (this._config.hasBackdrop) {
this._attachBackdrop();
}
if (this._config.panelClass) {
this._toggleClasses(this._pane, this._config.panelClass, true);
}
// Only emit the `attachments` event once all other setup is done.
this._attachments.next();
// Track this overlay by the keyboard dispatcher
this._keyboardDispatcher.add(this);
return attachResult;
}
/**
* Detaches an overlay from a portal.
* @return {?} The portal detachment result.
*/
detach() {
if (!this.hasAttached()) {
return;
}
this.detachBackdrop();
// When the overlay is detached, the pane element should disable pointer events.
// This is necessary because otherwise the pane element will cover the page and disable
// pointer events therefore. Depends on the position strategy and the applied pane boundaries.
this._togglePointerEvents(false);
if (this._config.positionStrategy && this._config.positionStrategy.detach) {
this._config.positionStrategy.detach();
}
if (this._config.scrollStrategy) {
this._config.scrollStrategy.disable();
}
if (this._config.panelClass) {
this._toggleClasses(this._pane, this._config.panelClass, false);
}
const /** @type {?} */ detachmentResult = this._portalOutlet.detach();
// Only emit after everything is detached.
this._detachments.next();
// Remove this overlay from keyboard dispatcher tracking.
this._keyboardDispatcher.remove(this);
// Keeping the host element in DOM the can cause scroll jank, because it still gets rendered,
// even though it's transparent and unclickable. We can't remove the host here immediately,
// because the overlay pane's content might still be animating. This stream helps us avoid
// interrupting the animation by waiting for the pane to become empty.
const /** @type {?} */ subscription = this._ngZone.onStable
.asObservable()
.pipe(takeUntil(merge(this._attachments, this._detachments)))
.subscribe(() => {
// Needs a couple of checks for the pane and host, because
// they may have been removed by the time the zone stabilizes.
if (!this._pane || !this._host || this._pane.children.length === 0) {
if (this._host && this._host.parentElement) {
this._previousHostParent = this._host.parentElement;
this._previousHostParent.removeChild(this._host);
}
subscription.unsubscribe();
}
});
return detachmentResult;
}
/**
* Cleans up the overlay from the DOM.
* @return {?}
*/
dispose() {
const /** @type {?} */ isAttached = this.hasAttached();
if (this._config.positionStrategy) {
this._config.positionStrategy.dispose();
}
if (this._config.scrollStrategy) {
this._config.scrollStrategy.disable();
}
this.detachBackdrop();
this._keyboardDispatcher.remove(this);
this._portalOutlet.dispose();
this._attachments.complete();
this._backdropClick.complete();
this._keydownEvents.complete();
if (this._host && this._host.parentNode) {
this._host.parentNode.removeChild(this._host);
this._host = /** @type {?} */ ((null));
}
this._previousHostParent = this._pane = /** @type {?} */ ((null));
if (isAttached) {
this._detachments.next();
}
this._detachments.complete();
}
/**
* Whether the overlay has attached content.
* @return {?}
*/
hasAttached() {
return this._portalOutlet.hasAttached();
}
/**
* Gets an observable that emits when the backdrop has been clicked.
* @return {?}
*/
backdropClick() {
return this._backdropClick.asObservable();
}
/**
* Gets an observable that emits when the overlay has been attached.
* @return {?}
*/
attachments() {
return this._attachments.asObservable();
}
/**
* Gets an observable that emits when the overlay has been detached.
* @return {?}
*/
detachments() {
return this._detachments.asObservable();
}
/**
* Gets an observable of keydown events targeted to this overlay.
* @return {?}
*/
keydownEvents() {
return this._keydownEventsObservable;
}
/**
* Gets the the current overlay configuration, which is immutable.
* @return {?}
*/
getConfig() {
return this._config;
}
/**
* Updates the position of the overlay based on the position strategy.
* @return {?}
*/
updatePosition() {
if (this._config.positionStrategy) {
this._config.positionStrategy.apply();
}
}
/**
* Update the size properties of the overlay.
* @param {?} sizeConfig
* @return {?}
*/
updateSize(sizeConfig) {
this._config = Object.assign({}, this._config, sizeConfig);
this._updateElementSize();
}
/**
* Sets the LTR/RTL direction for the overlay.
* @param {?} dir
* @return {?}
*/
setDirection(dir) {
this._config = Object.assign({}, this._config, { direction: dir });
this._updateElementDirection();
}
/**
* Returns the layout direction of the overlay panel.
* @return {?}
*/
getDirection() {
const /** @type {?} */ direction = this._config.direction;
if (!direction) {
return 'ltr';
}
return typeof direction === 'string' ? direction : direction.value;
}
/**
* Updates the text direction of the overlay panel.
* @return {?}
*/
_updateElementDirection() {
this._host.setAttribute('dir', this.getDirection());
}
/**
* Updates the size of the overlay element based on the overlay config.
* @return {?}
*/
_updateElementSize() {
const /** @type {?} */ style = this._pane.style;
style.width = coerceCssPixelValue(this._config.width);
style.height = coerceCssPixelValue(this._config.height);
style.minWidth = coerceCssPixelValue(this._config.minWidth);
style.minHeight = coerceCssPixelValue(this._config.minHeight);
style.maxWidth = coerceCssPixelValue(this._config.maxWidth);
style.maxHeight = coerceCssPixelValue(this._config.maxHeight);
}
/**
* Toggles the pointer events for the overlay pane element.
* @param {?} enablePointer
* @return {?}
*/
_togglePointerEvents(enablePointer) {
this._pane.style.pointerEvents = enablePointer ? 'auto' : 'none';
}
/**
* Attaches a backdrop for this overlay.
* @return {?}
*/
_attachBackdrop() {
const /** @type {?} */ showingClass = 'cdk-overlay-backdrop-showing';
this._backdropElement = this._document.createElement('div');
this._backdropElement.classList.add('cdk-overlay-backdrop');
if (this._config.backdropClass) {
this._toggleClasses(this._backdropElement, this._config.backdropClass, true);
} /** @type {?} */
((
// Insert the backdrop before the pane in the DOM order,
// in order to handle stacked overlays properly.
this._host.parentElement)).insertBefore(this._backdropElement, this._host);
// Forward backdrop clicks such that the consumer of the overlay can perform whatever
// action desired when such a click occurs (usually closing the overlay).
this._backdropElement.addEventListener('click', (event) => this._backdropClick.next(event));
// Add class to fade-in the backdrop after one frame.
if (typeof requestAnimationFrame !== 'undefined') {
this._ngZone.runOutsideAngular(() => {
requestAnimationFrame(() => {
if (this._backdropElement) {
this._backdropElement.classList.add(showingClass);
}
});
});
}
else {
this._backdropElement.classList.add(showingClass);
}
}
/**
* Updates the stacking order of the element, moving it to the top if necessary.
* This is required in cases where one overlay was detached, while another one,
* that should be behind it, was destroyed. The next time both of them are opened,
* the stacking will be wrong, because the detached element's pane will still be
* in its original DOM position.
* @return {?}
*/
_updateStackingOrder() {
if (this._host.nextSibling) {
/** @type {?} */ ((this._host.parentNode)).appendChild(this._host);
}
}
/**
* Detaches the backdrop (if any) associated with the overlay.
* @return {?}
*/
detachBackdrop() {
let /** @type {?} */ backdropToDetach = this._backdropElement;
if (backdropToDetach) {
let /** @type {?} */ timeoutId;
let /** @type {?} */ finishDetach = () => {
// It may not be attached to anything in certain cases (e.g. unit tests).
if (backdropToDetach && backdropToDetach.parentNode) {
backdropToDetach.parentNode.removeChild(backdropToDetach);
}
// It is possible that a new portal has been attached to this overlay since we started
// removing the backdrop. If that is the case, only clear the backdrop reference if it
// is still the same instance that we started to remove.
if (this._backdropElement == backdropToDetach) {
this._backdropElement = null;
}
clearTimeout(timeoutId);
};
backdropToDetach.classList.remove('cdk-overlay-backdrop-showing');
if (this._config.backdropClass) {
this._toggleClasses(backdropToDetach, this._config.backdropClass, false);
}
this._ngZone.runOutsideAngular(() => {
/** @type {?} */ ((backdropToDetach)).addEventListener('transitionend', finishDetach);
});
// If the backdrop doesn't have a transition, the `transitionend` event won't fire.
// In this case we make it unclickable and we try to remove it after a delay.
backdropToDetach.style.pointerEvents = 'none';
// Run this outside the Angular zone because there's nothing that Angular cares about.
// If it were to run inside the Angular zone, every test that used Overlay would have to be
// either async or fakeAsync.
timeoutId = this._ngZone.runOutsideAngular(() => setTimeout(finishDetach, 500));
}
}
/**
* Toggles a single CSS class or an array of classes on an element.
* @param {?} element
* @param {?} cssClasses
* @param {?} isAdd
* @return {?}
*/
_toggleClasses(element, cssClasses, isAdd) {
const /** @type {?} */ classList = element.classList;
coerceArray(cssClasses).forEach(cssClass => {
// We can't do a spread here, because IE doesn't support setting multiple classes.
isAdd ? classList.add(cssClass) : classList.remove(cssClass);
});
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* implicit position relative some origin element. The relative position is defined in terms of
* a point on the origin element that is connected to a point on the overlay element. For example,
* a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
* of the overlay.
*/
class FlexibleConnectedPositionStrategy {
/**
* @param {?} connectedTo
* @param {?} _viewportRuler
* @param {?} _document
* @param {?=} _platform
* @param {?=} _overlayContainer
*/
constructor(connectedTo, _viewportRuler, _document, _platform, _overlayContainer) {
this._viewportRuler = _viewportRuler;
this._document = _document;
this._platform = _platform;
this._overlayContainer = _overlayContainer;
/**
* Whether we're performing the very first positioning of the overlay.
*/
this._isInitialRender = true;
/**
* Last size used for the bounding box. Used to avoid resizing the overlay after open.
*/
this._lastBoundingBoxSize = { width: 0, height: 0 };
/**
* Whether the overlay was pushed in a previous positioning.
*/
this._isPushed = false;
/**
* Whether the overlay can be pushed on-screen on the initial open.
*/
this._canPush = true;
/**
* Whether the overlay can grow via flexible width/height after the initial open.
*/
this._growAfterOpen = false;
/**
* Whether the overlay's width and height can be constrained to fit within the viewport.
*/
this._hasFlexibleDimensions = true;
/**
* Whether the overlay position is locked.
*/
this._positionLocked = false;
/**
* Amount of space that must be maintained between the overlay and the edge of the viewport.
*/
this._viewportMargin = 0;
/**
* The Scrollable containers used to check scrollable view properties on position change.
*/
this.scrollables = [];
/**
* Ordered list of preferred positions, from most to least desirable.
*/
this._preferredPositions = [];
/**
* Subject that emits whenever the position changes.
*/
this._positionChanges = new Subject();
/**
* Subscription to viewport size changes.
*/
this._resizeSubscription = Subscription.EMPTY;
/**
* Default offset for the overlay along the x axis.
*/
this._offsetX = 0;
/**
* Default offset for the overlay along the y axis.
*/
this._offsetY = 0;
/**
* Amount of subscribers to the `positionChanges` stream.
*/
this._positionChangeSubscriptions = 0;
/**
* Observable sequence of position changes.
*/
this.positionChanges = Observable.create(observer => {
const /** @type {?} */ subscription = this._positionChanges.subscribe(observer);
this._positionChangeSubscriptions++;
return () => {
subscription.unsubscribe();
this._positionChangeSubscriptions--;
};
});
this.setOrigin(connectedTo);
}
/**
* Ordered list of preferred positions, from most to least desirable.
* @return {?}
*/
get positions() {
return this._preferredPositions;
}
/**
* Attaches this position strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
if (this._overlayRef && overlayRef !== this._overlayRef) {
throw Error('This position strategy is already attached to an overlay');
}
this._validatePositions();
overlayRef.hostElement.classList.add('cdk-overlay-connected-position-bounding-box');
this._overlayRef = overlayRef;
this._boundingBox = overlayRef.hostElement;
this._pane = overlayRef.overlayElement;
this._resizeSubscription.unsubscribe();
this._resizeSubscription = this._viewportRuler.change().subscribe(() => this.apply());
}
/**
* Updates the position of the overlay element, using whichever preferred position relative
* to the origin best fits on-screen.
*
* The selection of a position goes as follows:
* - If any positions fit completely within the viewport as-is,
* choose the first position that does so.
* - If flexible dimensions are enabled and at least one satifies the given minimum width/height,
* choose the position with the greatest available size modified by the positions' weight.
* - If pushing is enabled, take the position that went off-screen the least and push it
* on-screen.
* - If none of the previous criteria were met, use the position that goes off-screen the least.
* \@docs-private
* @return {?}
*/
apply() {
// We shouldn't do anything if the strategy was disposed or we're on the server.
// @breaking-change 7.0.0 Remove `_platform` null check once it's guaranteed to be defined.
if (this._isDisposed || (this._platform && !this._platform.isBrowser)) {
return;
}
// If the position has been applied already (e.g. when the overlay was opened) and the
// consumer opted into locking in the position, re-use the old position, in order to
// prevent the overlay from jumping around.
if (!this._isInitialRender && this._positionLocked && this._lastPosition) {
this.reapplyLastPosition();
return;
}
this._resetOverlayElementStyles();
this._resetBoundingBoxStyles();
// We need the bounding rects for the origin and the overlay to determine how to position
// the overlay relative to the origin.
// We use the viewport rect to determine whether a position would go off-screen.
this._viewportRect = this._getNarrowedViewportRect();
this._originRect = this._origin.getBoundingClientRect();
this._overlayRect = this._pane.getBoundingClientRect();
const /** @type {?} */ originRect = this._originRect;
const /** @type {?} */ overlayRect = this._overlayRect;
const /** @type {?} */ viewportRect = this._viewportRect;
// Positions where the overlay will fit with flexible dimensions.
const /** @type {?} */ flexibleFits = [];
// Fallback if none of the preferred positions fit within the viewport.
let /** @type {?} */ fallback;
// Go through each of the preferred positions looking for a good fit.
// If a good fit is found, it will be applied immediately.
for (let /** @type {?} */ pos of this._preferredPositions) {
// Get the exact (x, y) coordinate for the point-of-origin on the origin element.
let /** @type {?} */ originPoint = this._getOriginPoint(originRect, pos);
// From that point-of-origin, get the exact (x, y) coordinate for the top-left corner of the
// overlay in this position. We use the top-left corner for calculations and later translate
// this into an appropriate (top, left, bottom, right) style.
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, overlayRect, pos);
// Calculate how well the overlay would fit into the viewport with this point.
let /** @type {?} */ overlayFit = this._getOverlayFit(overlayPoint, overlayRect, viewportRect, pos);
// If the overlay, without any further work, fits into the viewport, use this position.
if (overlayFit.isCompletelyWithinViewport) {
this._isPushed = false;
this._applyPosition(pos, originPoint);
return;
}
// If the overlay has flexible dimensions, we can use this position
// so long as there's enough space for the minimum dimensions.
if (this._canFitWithFlexibleDimensions(overlayFit, overlayPoint, viewportRect)) {
// Save positions where the overlay will fit with flexible dimensions. We will use these
// if none of the positions fit *without* flexible dimensions.
flexibleFits.push({
position: pos,
origin: originPoint,
overlayRect,
boundingBoxRect: this._calculateBoundingBoxRect(originPoint, pos)
});
continue;
}
// If the current preferred position does not fit on the screen, remember the position
// if it has more visible area on-screen than we've seen and move onto the next preferred
// position.
if (!fallback || fallback.overlayFit.visibleArea < overlayFit.visibleArea) {
fallback = { overlayFit, overlayPoint, originPoint, position: pos, overlayRect };
}
}
// If there are any positions where the overlay would fit with flexible dimensions, choose the
// one that has the greatest area available modified by the position's weight
if (flexibleFits.length) {
let /** @type {?} */ bestFit = null;
let /** @type {?} */ bestScore = -1;
for (const /** @type {?} */ fit of flexibleFits) {
const /** @type {?} */ score = fit.boundingBoxRect.width * fit.boundingBoxRect.height * (fit.position.weight || 1);
if (score > bestScore) {
bestScore = score;
bestFit = fit;
}
}
this._isPushed = false;
this._applyPosition(/** @type {?} */ ((bestFit)).position, /** @type {?} */ ((bestFit)).origin);
return;
}
// When none of the preferred positions fit within the viewport, take the position
// that went off-screen the least and attempt to push it on-screen.
if (this._canPush) {
// TODO(jelbourn): after pushing, the opening "direction" of the overlay might not make sense.
this._isPushed = true;
this._applyPosition(/** @type {?} */ ((fallback)).position, /** @type {?} */ ((fallback)).originPoint);
return;
}
// All options for getting the overlay within the viewport have been exhausted, so go with the
// position that went off-screen the least.
this._applyPosition(/** @type {?} */ ((fallback)).position, /** @type {?} */ ((fallback)).originPoint);
}
/**
* @return {?}
*/
detach() {
this._resizeSubscription.unsubscribe();
}
/**
* Cleanup after the element gets destroyed.
* @return {?}
*/
dispose() {
if (!this._isDisposed) {
this.detach();
this._boundingBox = null;
this._positionChanges.complete();
this._isDisposed = true;
}
}
/**
* This re-aligns the overlay element with the trigger in its last calculated position,
* even if a position higher in the "preferred positions" list would now fit. This
* allows one to re-align the panel without changing the orientation of the panel.
* @return {?}
*/
reapplyLastPosition() {
if (!this._isDisposed && (!this._platform || this._platform.isBrowser)) {
this._originRect = this._origin.getBoundingClientRect();
this._overlayRect = this._pane.getBoundingClientRect();
this._viewportRect = this._getNarrowedViewportRect();
const /** @type {?} */ lastPosition = this._lastPosition || this._preferredPositions[0];
const /** @type {?} */ originPoint = this._getOriginPoint(this._originRect, lastPosition);
this._applyPosition(lastPosition, originPoint);
}
}
/**
* Sets the list of Scrollable containers that host the origin element so that
* on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
* Scrollable must be an ancestor element of the strategy's origin element.
* @param {?} scrollables
* @return {?}
*/
withScrollableContainers(scrollables) {
this.scrollables = scrollables;
}
/**
* Adds new preferred positions.
* @param {?} positions List of positions options for this overlay.
* @return {?}
*/
withPositions(positions) {
this._preferredPositions = positions;
// If the last calculated position object isn't part of the positions anymore, clear
// it in order to avoid it being picked up if the consumer tries to re-apply.
if (positions.indexOf(/** @type {?} */ ((this._lastPosition))) === -1) {
this._lastPosition = null;
}
this._validatePositions();
return this;
}
/**
* Sets a minimum distance the overlay may be positioned to the edge of the viewport.
* @param {?} margin Required margin between the overlay and the viewport edge in pixels.
* @return {?}
*/
withViewportMargin(margin) {
this._viewportMargin = margin;
return this;
}
/**
* Sets whether the overlay's width and height can be constrained to fit within the viewport.
* @param {?=} flexibleDimensions
* @return {?}
*/
withFlexibleDimensions(flexibleDimensions = true) {
this._hasFlexibleDimensions = flexibleDimensions;
return this;
}
/**
* Sets whether the overlay can grow after the initial open via flexible width/height.
* @param {?=} growAfterOpen
* @return {?}
*/
withGrowAfterOpen(growAfterOpen = true) {
this._growAfterOpen = growAfterOpen;
return this;
}
/**
* Sets whether the overlay can be pushed on-screen if none of the provided positions fit.
* @param {?=} canPush
* @return {?}
*/
withPush(canPush = true) {
this._canPush = canPush;
return this;
}
/**
* Sets whether the overlay's position should be locked in after it is positioned
* initially. When an overlay is locked in, it won't attempt to reposition itself
* when the position is re-applied (e.g. when the user scrolls away).
* @param {?=} isLocked Whether the overlay should locked in.
* @return {?}
*/
withLockedPosition(isLocked = true) {
this._positionLocked = isLocked;
return this;
}
/**
* Sets the origin element, relative to which to position the overlay.
* @param {?} origin Reference to the new origin element.
* @return {?}
*/
setOrigin(origin) {
this._origin = origin instanceof ElementRef ? origin.nativeElement : origin;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the x-axis.
* @param {?} offset New offset in the X axis.
* @return {?}
*/
withDefaultOffsetX(offset) {
this._offsetX = offset;
return this;
}
/**
* Sets the default offset for the overlay's connection point on the y-axis.
* @param {?} offset New offset in the Y axis.
* @return {?}
*/
withDefaultOffsetY(offset) {
this._offsetY = offset;
return this;
}
/**
* Configures that the position strategy should set a `transform-origin` on some elements
* inside the overlay, depending on the current position that is being applied. This is
* useful for the cases where the origin of an animation can change depending on the
* alignment of the overlay.
* @param {?} selector CSS selector that will be used to find the target
* elements onto which to set the transform origin.
* @return {?}
*/
withTransformOriginOn(selector) {
this._transformOriginSelector = selector;
return this;
}
/**
* Gets the (x, y) coordinate of a connection point on the origin based on a relative position.
* @param {?} originRect
* @param {?} pos
* @return {?}
*/
_getOriginPoint(originRect, pos) {
let /** @type {?} */ x;
if (pos.originX == 'center') {
// Note: when centering we should always use the `left`
// offset, otherwise the position will be wrong in RTL.
x = originRect.left + (originRect.width / 2);
}
else {
const /** @type {?} */ startX = this._isRtl() ? originRect.right : originRect.left;
const /** @type {?} */ endX = this._isRtl() ? originRect.left : originRect.right;
x = pos.originX == 'start' ? startX : endX;
}
let /** @type {?} */ y;
if (pos.originY == 'center') {
y = originRect.top + (originRect.height / 2);
}
else {
y = pos.originY == 'top' ? originRect.top : originRect.bottom;
}
return { x, y };
}
/**
* Gets the (x, y) coordinate of the top-left corner of the overlay given a given position and
* origin point to which the overlay should be connected.
* @param {?} originPoint
* @param {?} overlayRect
* @param {?} pos
* @return {?}
*/
_getOverlayPoint(originPoint, overlayRect, pos) {
// Calculate the (overlayStartX, overlayStartY), the start of the
// potential overlay position relative to the origin point.
let /** @type {?} */ overlayStartX;
if (pos.overlayX == 'center') {
overlayStartX = -overlayRect.width / 2;
}
else if (pos.overlayX === 'start') {
overlayStartX = this._isRtl() ? -overlayRect.width : 0;
}
else {
overlayStartX = this._isRtl() ? 0 : -overlayRect.width;
}
let /** @type {?} */ overlayStartY;
if (pos.overlayY == 'center') {
overlayStartY = -overlayRect.height / 2;
}
else {
overlayStartY = pos.overlayY == 'top' ? 0 : -overlayRect.height;
}
// The (x, y) coordinates of the overlay.
return {
x: originPoint.x + overlayStartX,
y: originPoint.y + overlayStartY,
};
}
/**
* Gets how well an overlay at the given point will fit within the viewport.
* @param {?} point
* @param {?} overlay
* @param {?} viewport
* @param {?} position
* @return {?}
*/
_getOverlayFit(point, overlay, viewport, position) {
let { x, y } = point;
let /** @type {?} */ offsetX = this._getOffset(position, 'x');
let /** @type {?} */ offsetY = this._getOffset(position, 'y');
// Account for the offsets since they could push the overlay out of the viewport.
if (offsetX) {
x += offsetX;
}
if (offsetY) {
y += offsetY;
}
// How much the overlay would overflow at this position, on each side.
let /** @type {?} */ leftOverflow = 0 - x;
let /** @type {?} */ rightOverflow = (x + overlay.width) - viewport.width;
let /** @type {?} */ topOverflow = 0 - y;
let /** @type {?} */ bottomOverflow = (y + overlay.height) - viewport.height;
// Visible parts of the element on each axis.
let /** @type {?} */ visibleWidth = this._subtractOverflows(overlay.width, leftOverflow, rightOverflow);
let /** @type {?} */ visibleHeight = this._subtractOverflows(overlay.height, topOverflow, bottomOverflow);
let /** @type {?} */ visibleArea = visibleWidth * visibleHeight;
return {
visibleArea,
isCompletelyWithinViewport: (overlay.width * overlay.height) === visibleArea,
fitsInViewportVertically: visibleHeight === overlay.height,
fitsInViewportHorizontally: visibleWidth == overlay.width,
};
}
/**
* Whether the overlay can fit within the viewport when it may resize either its width or height.
* @param {?} fit How well the overlay fits in the viewport at some position.
* @param {?} point The (x, y) coordinates of the overlat at some position.
* @param {?} viewport The geometry of the viewport.
* @return {?}
*/
_canFitWithFlexibleDimensions(fit, point, viewport) {
if (this._hasFlexibleDimensions) {
const /** @type {?} */ availableHeight = viewport.bottom - point.y;
const /** @type {?} */ availableWidth = viewport.right - point.x;
const /** @type {?} */ minHeight = this._overlayRef.getConfig().minHeight;
const /** @type {?} */ minWidth = this._overlayRef.getConfig().minWidth;
const /** @type {?} */ verticalFit = fit.fitsInViewportVertically ||
(minHeight != null && minHeight <= availableHeight);
const /** @type {?} */ horizontalFit = fit.fitsInViewportHorizontally ||
(minWidth != null && minWidth <= availableWidth);
return verticalFit && horizontalFit;
}
}
/**
* Gets the point at which the overlay can be "pushed" on-screen. If the overlay is larger than
* the viewport, the top-left corner will be pushed on-screen (with overflow occuring on the
* right and bottom).
*
* @param {?} start The starting point from which the overlay is pushed.
* @param {?} overlay The overlay dimensions.
* @return {?} The point at which to position the overlay after pushing. This is effectively a new
* originPoint.
*/
_pushOverlayOnScreen(start, overlay) {
const /** @type {?} */ viewport = this._viewportRect;
// Determine how much the overlay goes outside the viewport on each side, which we'll use to
// decide which direction to push it.
const /** @type {?} */ overflowRight = Math.max(start.x + overlay.width - viewport.right, 0);
const /** @type {?} */ overflowBottom = Math.max(start.y + overlay.height - viewport.bottom, 0);
const /** @type {?} */ overflowTop = Math.max(viewport.top - start.y, 0);
const /** @type {?} */ overflowLeft = Math.max(viewport.left - start.x, 0);
// Amount by which to push the overlay in each direction such that it remains on-screen.
let /** @type {?} */ pushX, /** @type {?} */ pushY = 0;
// If the overlay fits completely within the bounds of the viewport, push it from whichever
// direction is goes off-screen. Otherwise, push the top-left corner such that its in the
// viewport and allow for the trailing end of the overlay to go out of bounds.
if (overlay.width <= viewport.width) {
pushX = overflowLeft || -overflowRight;
}
else {
pushX = viewport.left - start.x;
}
if (overlay.height <= viewport.height) {
pushY = overflowTop || -overflowBottom;
}
else {
pushY = viewport.top - start.y;
}
return {
x: start.x + pushX,
y: start.y + pushY,
};
}
/**
* Applies a computed position to the overlay and emits a position change.
* @param {?} position The position preference
* @param {?} originPoint The point on the origin element where the overlay is connected.
* @return {?}
*/
_applyPosition(position, originPoint) {
this._setTransformOrigin(position);
this._setOverlayElementStyles(originPoint, position);
this._setBoundingBoxStyles(originPoint, position);
// Save the last connected position in case the position needs to be re-calculated.
this._lastPosition = position;
// Notify that the position has been changed along with its change properties.
// We only emit if we've got any subscriptions, because the scroll visibility
// calculcations can be somewhat expensive.
if (this._positionChangeSubscriptions > 0) {
const /** @type {?} */ scrollableViewProperties = this._getScrollVisibility();
const /** @type {?} */ changeEvent = new ConnectedOverlayPositionChange(position, scrollableViewProperties);
this._positionChanges.next(changeEvent);
}
this._isInitialRender = false;
}
/**
* Sets the transform origin based on the configured selector and the passed-in position.
* @param {?} position
* @return {?}
*/
_setTransformOrigin(position) {
if (!this._transformOriginSelector) {
return;
}
const /** @type {?} */ elements = /** @type {?} */ ((this._boundingBox)).querySelectorAll(this._transformOriginSelector);
let /** @type {?} */ xOrigin;
let /** @type {?} */ yOrigin = position.overlayY;
if (position.overlayX === 'center') {
xOrigin = 'center';
}
else if (this._isRtl()) {
xOrigin = position.overlayX === 'start' ? 'right' : 'left';
}
else {
xOrigin = position.overlayX === 'start' ? 'left' : 'right';
}
for (let /** @type {?} */ i = 0; i < elements.length; i++) {
elements[i].style.transformOrigin = `${xOrigin} ${yOrigin}`;
}
}
/**
* Gets the position and size of the overlay's sizing container.
*
* This method does no measuring and applies no styles so that we can cheaply compute the
* bounds for all positions and choose the best fit based on these results.
* @param {?} origin
* @param {?} position
* @return {?}
*/
_calculateBoundingBoxRect(origin, position) {
const /** @type {?} */ viewport = this._viewportRect;
const /** @type {?} */ isRtl = this._isRtl();
let /** @type {?} */ height, /** @type {?} */ top, /** @type {?} */ bottom;
if (position.overlayY === 'top') {
// Overlay is opening "downward" and thus is bound by the bottom viewport edge.
top = origin.y;
height = viewport.bottom - origin.y;
}
else if (position.overlayY === 'bottom') {
// Overlay is opening "upward" and thus is bound by the top viewport edge. We need to add
// the viewport margin back in, because the viewport rect is narrowed down to remove the
// margin, whereas the `origin` position is calculated based on its `ClientRect`.
bottom = viewport.height - origin.y + this._viewportMargin * 2;
height = viewport.height - bottom + this._viewportMargin;
}
else {
// If neither top nor bottom, it means that the overlay
// is vertically centered on the origin point.
const /** @type {?} */ smallestDistanceToViewportEdge = Math.min(viewport.bottom - origin.y, origin.y - viewport.left);
const /** @type {?} */ previousHeight = this._lastBoundingBoxSize.height;
height = smallestDistanceToViewportEdge * 2;
top = origin.y - smallestDistanceToViewportEdge;
if (height > previousHeight && !this._isInitialRender && !this._growAfterOpen) {
top = origin.y - (previousHeight / 2);
}
}
// The overlay is opening 'right-ward' (the content flows to the right).
const /** @type {?} */ isBoundedByRightViewportEdge = (position.overlayX === 'start' && !isRtl) ||
(position.overlayX === 'end' && isRtl);
// The overlay is opening 'left-ward' (the content flows to the left).
const /** @type {?} */ isBoundedByLeftViewportEdge = (position.overlayX === 'end' && !isRtl) ||
(position.overlayX === 'start' && isRtl);
let /** @type {?} */ width, /** @type {?} */ left, /** @type {?} */ right;
if (isBoundedByLeftViewportEdge) {
right = viewport.right - origin.x + this._viewportMargin;
width = origin.x - viewport.left;
}
else if (isBoundedByRightViewportEdge) {
left = origin.x;
width = viewport.right - origin.x;
}
else {
// If neither start nor end, it means that the overlay
// is horizontally centered on the origin point.
const /** @type {?} */ smallestDistanceToViewportEdge = Math.min(viewport.right - origin.x, origin.x - viewport.top);
const /** @type {?} */ previousWidth = this._lastBoundingBoxSize.width;
width = smallestDistanceToViewportEdge * 2;
left = origin.x - smallestDistanceToViewportEdge;
if (width > previousWidth && !this._isInitialRender && !this._growAfterOpen) {
left = origin.x - (previousWidth / 2);
}
}
return { top, left, bottom, right, width, height };
}
/**
* Sets the position and size of the overlay's sizing wrapper. The wrapper is positioned on the
* origin's connection point and stetches to the bounds of the viewport.
*
* @param {?} origin The point on the origin element where the overlay is connected.
* @param {?} position The position preference
* @return {?}
*/
_setBoundingBoxStyles(origin, position) {
const /** @type {?} */ boundingBoxRect = this._calculateBoundingBoxRect(origin, position);
// It's weird if the overlay *grows* while scrolling, so we take the last size into account
// when applying a new size.
if (!this._isInitialRender && !this._growAfterOpen) {
boundingBoxRect.height = Math.min(boundingBoxRect.height, this._lastBoundingBoxSize.height);
boundingBoxRect.width = Math.min(boundingBoxRect.width, this._lastBoundingBoxSize.width);
}
const /** @type {?} */ styles = /** @type {?} */ ({});
if (this._hasExactPosition()) {
styles.top = styles.left = '0';
styles.bottom = styles.right = '';
styles.width = styles.height = '100%';
}
else {
const /** @type {?} */ maxHeight = this._overlayRef.getConfig().maxHeight;
const /** @type {?} */ maxWidth = this._overlayRef.getConfig().maxWidth;
styles.height = coerceCssPixelValue(boundingBoxRect.height);
styles.top = coerceCssPixelValue(boundingBoxRect.top);
styles.bottom = coerceCssPixelValue(boundingBoxRect.bottom);
styles.width = coerceCssPixelValue(boundingBoxRect.width);
styles.left = coerceCssPixelValue(boundingBoxRect.left);
styles.right = coerceCssPixelValue(boundingBoxRect.right);
// Push the pane content towards the proper direction.
if (position.overlayX === 'center') {
styles.alignItems = 'center';
}
else {
styles.alignItems = position.overlayX === 'end' ? 'flex-end' : 'flex-start';
}
if (position.overlayY === 'center') {
styles.justifyContent = 'center';
}
else {
styles.justifyContent = position.overlayY === 'bottom' ? 'flex-end' : 'flex-start';
}
if (maxHeight) {
styles.maxHeight = coerceCssPixelValue(maxHeight);
}
if (maxWidth) {
styles.maxWidth = coerceCssPixelValue(maxWidth);
}
}
this._lastBoundingBoxSize = boundingBoxRect;
extendStyles(/** @type {?} */ ((this._boundingBox)).style, styles);
}
/**
* Resets the styles for the bounding box so that a new positioning can be computed.
* @return {?}
*/
_resetBoundingBoxStyles() {
extendStyles(/** @type {?} */ ((this._boundingBox)).style, /** @type {?} */ ({
top: '0',
left: '0',
right: '0',
bottom: '0',
height: '',
width: '',
alignItems: '',
justifyContent: '',
}));
}
/**
* Resets the styles for the overlay pane so that a new positioning can be computed.
* @return {?}
*/
_resetOverlayElementStyles() {
extendStyles(this._pane.style, /** @type {?} */ ({
top: '',
left: '',
bottom: '',
right: '',
position: '',
}));
}
/**
* Sets positioning styles to the overlay element.
* @param {?} originPoint
* @param {?} position
* @return {?}
*/
_setOverlayElementStyles(originPoint, position) {
const /** @type {?} */ styles = /** @type {?} */ ({});
if (this._hasExactPosition()) {
extendStyles(styles, this._getExactOverlayY(position, originPoint));
extendStyles(styles, this._getExactOverlayX(position, originPoint));
}
else {
styles.position = 'static';
}
// Use a transform to apply the offsets. We do this because the `center` positions rely on
// being in the normal flex flow and setting a `top` / `left` at all will completely throw
// off the position. We also can't use margins, because they won't have an effect in some
// cases where the element doesn't have anything to "push off of". Finally, this works
// better both with flexible and non-flexible positioning.
let /** @type {?} */ transformString = '';
let /** @type {?} */ offsetX = this._getOffset(position, 'x');
let /** @type {?} */ offsetY = this._getOffset(position, 'y');
if (offsetX) {
transformString += `translateX(${offsetX}px) `;
}
if (offsetY) {
transformString += `translateY(${offsetY}px)`;
}
styles.transform = transformString.trim();
// If a maxWidth or maxHeight is specified on the overlay, we remove them. We do this because
// we need these values to both be set to "100%" for the automatic flexible sizing to work.
// The maxHeight and maxWidth are set on the boundingBox in order to enforce the constraint.
if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxHeight) {
styles.maxHeight = '';
}
if (this._hasFlexibleDimensions && this._overlayRef.getConfig().maxWidth) {
styles.maxWidth = '';
}
extendStyles(this._pane.style, styles);
}
/**
* Gets the exact top/bottom for the overlay when not using flexible sizing or when pushing.
* @param {?} position
* @param {?} originPoint
* @return {?}
*/
_getExactOverlayY(position, originPoint) {
// Reset any existing styles. This is necessary in case the
// preferred position has changed since the last `apply`.
let /** @type {?} */ styles = /** @type {?} */ ({ top: null, bottom: null });
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
if (this._isPushed) {
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
}
// @breaking-change 7.0.0 Currently the `_overlayContainer` is optional in order to avoid a
// breaking change. The null check here can be removed once the `_overlayContainer` becomes
// a required parameter.
let /** @type {?} */ virtualKeyboardOffset = this._overlayContainer ?
this._overlayContainer.getContainerElement().getBoundingClientRect().top : 0;
// Normally this would be zero, however when the overlay is attached to an input (e.g. in an
// autocomplete), mobile browsers will shift everything in order to put the input in the middle
// of the screen and to make space for the virtual keyboard. We need to account for this offset,
// otherwise our positioning will be thrown off.
overlayPoint.y -= virtualKeyboardOffset;
// We want to set either `top` or `bottom` based on whether the overlay wants to appear
// above or below the origin and the direction in which the element will expand.
if (position.overlayY === 'bottom') {
// When using `bottom`, we adjust the y position such that it is the distance
// from the bottom of the viewport rather than the top.
const /** @type {?} */ documentHeight = this._document.documentElement.clientHeight;
styles.bottom = `${documentHeight - (overlayPoint.y + this._overlayRect.height)}px`;
}
else {
styles.top = coerceCssPixelValue(overlayPoint.y);
}
return styles;
}
/**
* Gets the exact left/right for the overlay when not using flexible sizing or when pushing.
* @param {?} position
* @param {?} originPoint
* @return {?}
*/
_getExactOverlayX(position, originPoint) {
// Reset any existing styles. This is necessary in case the preferred position has
// changed since the last `apply`.
let /** @type {?} */ styles = /** @type {?} */ ({ left: null, right: null });
let /** @type {?} */ overlayPoint = this._getOverlayPoint(originPoint, this._overlayRect, position);
if (this._isPushed) {
overlayPoint = this._pushOverlayOnScreen(overlayPoint, this._overlayRect);
}
// We want to set either `left` or `right` based on whether the overlay wants to appear "before"
// or "after" the origin, which determines the direction in which the element will expand.
// For the horizontal axis, the meaning of "before" and "after" change based on whether the
// page is in RTL or LTR.
let /** @type {?} */ horizontalStyleProperty;
if (this._isRtl()) {
horizontalStyleProperty = position.overlayX === 'end' ? 'left' : 'right';
}
else {
horizontalStyleProperty = position.overlayX === 'end' ? 'right' : 'left';
}
// When we're setting `right`, we adjust the x position such that it is the distance
// from the right edge of the viewport rather than the left edge.
if (horizontalStyleProperty === 'right') {
const /** @type {?} */ documentWidth = this._document.documentElement.clientWidth;
styles.right = `${documentWidth - (overlayPoint.x + this._overlayRect.width)}px`;
}
else {
styles.left = coerceCssPixelValue(overlayPoint.x);
}
return styles;
}
/**
* Gets the view properties of the trigger and overlay, including whether they are clipped
* or completely outside the view of any of the strategy's scrollables.
* @return {?}
*/
_getScrollVisibility() {
// Note: needs fresh rects since the position could've changed.
const /** @type {?} */ originBounds = this._origin.getBoundingClientRect();
const /** @type {?} */ overlayBounds = this._pane.getBoundingClientRect();
// TODO(jelbourn): instead of needing all of the client rects for these scrolling containers
// every time, we should be able to use the scrollTop of the containers if the size of those
// containers hasn't changed.
const /** @type {?} */ scrollContainerBounds = this.scrollables.map(scrollable => {
return scrollable.getElementRef().nativeElement.getBoundingClientRect();
});
return {
isOriginClipped: isElementClippedByScrolling(originBounds, scrollContainerBounds),
isOriginOutsideView: isElementScrolledOutsideView(originBounds, scrollContainerBounds),
isOverlayClipped: isElementClippedByScrolling(overlayBounds, scrollContainerBounds),
isOverlayOutsideView: isElementScrolledOutsideView(overlayBounds, scrollContainerBounds),
};
}
/**
* Subtracts the amount that an element is overflowing on an axis from it's length.
* @param {?} length
* @param {...?} overflows
* @return {?}
*/
_subtractOverflows(length, ...overflows) {
return overflows.reduce((currentValue, currentOverflow) => {
return currentValue - Math.max(currentOverflow, 0);
}, length);
}
/**
* Narrows the given viewport rect by the current _viewportMargin.
* @return {?}
*/
_getNarrowedViewportRect() {
// We recalculate the viewport rect here ourselves, rather than using the ViewportRuler,
// because we want to use the `clientWidth` and `clientHeight` as the base. The difference
// being that the client properties don't include the scrollbar, as opposed to `innerWidth`
// and `innerHeight` that do. This is necessary, because the overlay container uses
// 100% `width` and `height` which don't include the scrollbar either.
const /** @type {?} */ width = this._document.documentElement.clientWidth;
const /** @type {?} */ height = this._document.documentElement.clientHeight;
const /** @type {?} */ scrollPosition = this._viewportRuler.getViewportScrollPosition();
return {
top: scrollPosition.top + this._viewportMargin,
left: scrollPosition.left + this._viewportMargin,
right: scrollPosition.left + width - this._viewportMargin,
bottom: scrollPosition.top + height - this._viewportMargin,
width: width - (2 * this._viewportMargin),
height: height - (2 * this._viewportMargin),
};
}
/**
* Whether the we're dealing with an RTL context
* @return {?}
*/
_isRtl() {
return this._overlayRef.getDirection() === 'rtl';
}
/**
* Determines whether the overlay uses exact or flexible positioning.
* @return {?}
*/
_hasExactPosition() {
return !this._hasFlexibleDimensions || this._isPushed;
}
/**
* Retrieves the offset of a position along the x or y axis.
* @param {?} position
* @param {?} axis
* @return {?}
*/
_getOffset(position, axis) {
if (axis === 'x') {
// We don't do something like `position['offset' + axis]` in
// order to avoid breking minifiers that rename properties.
return position.offsetX == null ? this._offsetX : position.offsetX;
}
return position.offsetY == null ? this._offsetY : position.offsetY;
}
/**
* Validates that the current position match the expected values.
* @return {?}
*/
_validatePositions() {
if (!this._preferredPositions.length) {
throw Error('FlexibleConnectedPositionStrategy: At least one position is required.');
}
// TODO(crisbeto): remove these once Angular's template type
// checking is advanced enough to catch these cases.
this._preferredPositions.forEach(pair => {
validateHorizontalPosition('originX', pair.originX);
validateVerticalPosition('originY', pair.originY);
validateHorizontalPosition('overlayX', pair.overlayX);
validateVerticalPosition('overlayY', pair.overlayY);
});
}
}
/**
* Shallow-extends a stylesheet object with another stylesheet object.
* @param {?} dest
* @param {?} source
* @return {?}
*/
function extendStyles(dest, source) {
for (let /** @type {?} */ key in source) {
if (source.hasOwnProperty(key)) {
dest[key] = source[key];
}
}
return dest;
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* implicit position relative to some origin element. The relative position is defined in terms of
* a point on the origin element that is connected to a point on the overlay element. For example,
* a basic dropdown is connecting the bottom-left corner of the origin to the top-left corner
* of the overlay.
* @deprecated Use `FlexibleConnectedPositionStrategy` instead.
* \@breaking-change 7.0.0
*/
class ConnectedPositionStrategy {
/**
* @param {?} originPos
* @param {?} overlayPos
* @param {?} connectedTo
* @param {?} viewportRuler
* @param {?} document
* @param {?=} platform
*/
constructor(originPos, overlayPos, connectedTo, viewportRuler, document,
// @breaking-change 7.0.0 `platform` parameter to be made required.
// @breaking-change 7.0.0 `platform` parameter to be made required.
platform) {
/**
* Ordered list of preferred positions, from most to least desirable.
*/
this._preferredPositions = [];
// Since the `ConnectedPositionStrategy` is deprecated and we don't want to maintain
// the extra logic, we create an instance of the positioning strategy that has some
// defaults that make it behave as the old position strategy and to which we'll
// proxy all of the API calls.
this._positionStrategy =
new FlexibleConnectedPositionStrategy(connectedTo, viewportRuler, document, platform)
.withFlexibleDimensions(false)
.withPush(false)
.withViewportMargin(0);
this.withFallbackPosition(originPos, overlayPos);
}
/**
* Whether the we're dealing with an RTL context
* @return {?}
*/
get _isRtl() {
return this._overlayRef.getDirection() === 'rtl';
}
/**
* Emits an event when the connection point changes.
* @return {?}
*/
get onPositionChange() {
return this._positionStrategy.positionChanges;
}
/**
* Ordered list of preferred positions, from most to least desirable.
* @return {?}
*/
get positions() {
return this._preferredPositions;
}
/**
* Attach this position strategy to an overlay.
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
this._overlayRef = overlayRef;
this._positionStrategy.attach(overlayRef);
if (this._direction) {
overlayRef.setDirection(this._direction);
this._direction = null;
}
}
/**
* Disposes all resources used by the position strategy.
* @return {?}
*/
dispose() {
this._positionStrategy.dispose();
}
/**
* \@docs-private
* @return {?}
*/
detach() {
this._positionStrategy.detach();
}
/**
* Updates the position of the overlay element, using whichever preferred position relative
* to the origin fits on-screen.
* \@docs-private
* @return {?}
*/
apply() {
this._positionStrategy.apply();
}
/**
* Re-positions the overlay element with the trigger in its last calculated position,
* even if a position higher in the "preferred positions" list would now fit. This
* allows one to re-align the panel without changing the orientation of the panel.
* @return {?}
*/
recalculateLastPosition() {
this._positionStrategy.reapplyLastPosition();
}
/**
* Sets the list of Scrollable containers that host the origin element so that
* on reposition we can evaluate if it or the overlay has been clipped or outside view. Every
* Scrollable must be an ancestor element of the strategy's origin element.
* @param {?} scrollables
* @return {?}
*/
withScrollableContainers(scrollables) {
this._positionStrategy.withScrollableContainers(scrollables);
}
/**
* Adds a new preferred fallback position.
* @param {?} originPos
* @param {?} overlayPos
* @param {?=} offsetX
* @param {?=} offsetY
* @return {?}
*/
withFallbackPosition(originPos, overlayPos, offsetX, offsetY) {
const /** @type {?} */ position = new ConnectionPositionPair(originPos, overlayPos, offsetX, offsetY);
this._preferredPositions.push(position);
this._positionStrategy.withPositions(this._preferredPositions);
return this;
}
/**
* Sets the layout direction so the overlay's position can be adjusted to match.
* @param {?} dir New layout direction.
* @return {?}
*/
withDirection(dir) {
// Since the direction might be declared before the strategy is attached,
// we save the value in a temporary property and we'll transfer it to the
// overlay ref on attachment.
if (this._overlayRef) {
this._overlayRef.setDirection(dir);
}
else {
this._direction = dir;
}
return this;
}
/**
* Sets an offset for the overlay's connection point on the x-axis
* @param {?} offset New offset in the X axis.
* @return {?}
*/
withOffsetX(offset) {
this._positionStrategy.withDefaultOffsetX(offset);
return this;
}
/**
* Sets an offset for the overlay's connection point on the y-axis
* @param {?} offset New offset in the Y axis.
* @return {?}
*/
withOffsetY(offset) {
this._positionStrategy.withDefaultOffsetY(offset);
return this;
}
/**
* Sets whether the overlay's position should be locked in after it is positioned
* initially. When an overlay is locked in, it won't attempt to reposition itself
* when the position is re-applied (e.g. when the user scrolls away).
* @param {?} isLocked Whether the overlay should locked in.
* @return {?}
*/
withLockedPosition(isLocked) {
this._positionStrategy.withLockedPosition(isLocked);
return this;
}
/**
* Overwrites the current set of positions with an array of new ones.
* @param {?} positions Position pairs to be set on the strategy.
* @return {?}
*/
withPositions(positions) {
this._preferredPositions = positions.slice();
this._positionStrategy.withPositions(this._preferredPositions);
return this;
}
/**
* Sets the origin element, relative to which to position the overlay.
* @param {?} origin Reference to the new origin element.
* @return {?}
*/
setOrigin(origin) {
this._positionStrategy.setOrigin(origin);
return this;
}
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* A strategy for positioning overlays. Using this strategy, an overlay is given an
* explicit position relative to the browser's viewport. We use flexbox, instead of
* transforms, in order to avoid issues with subpixel rendering which can cause the
* element to become blurry.
*/
class GlobalPositionStrategy {
constructor() {
this._cssPosition = 'static';
this._topOffset = '';
this._bottomOffset = '';
this._leftOffset = '';
this._rightOffset = '';
this._alignItems = '';
this._justifyContent = '';
this._width = '';
this._height = '';
}
/**
* @param {?} overlayRef
* @return {?}
*/
attach(overlayRef) {
const /** @type {?} */ config = overlayRef.getConfig();
this._overlayRef = overlayRef;
if (this._width && !config.width) {
overlayRef.updateSize({ width: this._width });
}
if (this._height && !config.height) {
overlayRef.updateSize({ height: this._height });
}
overlayRef.hostElement.classList.add('cdk-global-overlay-wrapper');
}
/**
* Sets the top position of the overlay. Clears any previously set vertical position.
* @param {?=} value New top offset.
* @return {?}
*/
top(value = '') {
this._bottomOffset = '';
this._topOffset = value;
this._alignItems = 'flex-start';
return this;
}
/**
* Sets the left position of the overlay. Clears any previously set horizontal position.
* @param {?=} value New left offset.
* @return {?}
*/
left(value = '') {
this._rightOffset = '';
this._leftOffset = value;
this._justifyContent = 'flex-start';
return this;
}
/**
* Sets the bottom position of the overlay. Clears any previously set vertical position.
* @param {?=} value New bottom offset.
* @return {?}
*/
bottom(value = '') {
this._topOffset = '';
this._bottomOffset = value;
this._alignItems = 'flex-end';
return this;
}
/**
* Sets the right position of the overlay. Clears any previously set horizontal position.
* @param {?=} value New right offset.
* @return {?}
*/
right(value = '') {
this._leftOffset = '';
this._rightOffset = value;
this._justifyContent = 'flex-end';
return this;
}
/**
* Sets the overlay width and clears any previously set width.
* @deprecated Pass the `width` through the `OverlayConfig`.
* \@breaking-change 7.0.0
* @param {?=} value New width for the overlay
* @return {?}
*/
width(value = '') {
if (this._overlayRef) {
this._overlayRef.updateSize({ width: value });
}
else {
this._width = value;
}
return this;
}
/**
* Sets the overlay height and clears any previously set height.
* @deprecated Pass the `height` through the `OverlayConfig`.
* \@breaking-change 7.0.0
* @param {?=} value New height for the overlay
* @return {?}
*/
height(value = '') {
if (this._overlayRef) {
this._overlayRef.updateSize({ height: value });
}
else {
this._height = value;
}
return this;
}
/**
* Centers the overlay horizontally with an optional offset.
* Clears any previously set horizontal position.
*
* @param {?=} offset Overlay offset from the horizontal center.
* @return {?}
*/
centerHorizontally(offset = '') {
this.left(offset);
this._justifyContent = 'center';
return this;
}
/**
* Centers the overlay vertically with an optional offset.
* Clears any previously set vertical position.
*
* @param {?=} offset Overlay offset from the vertical center.
* @return {?}
*/
centerVertically(offset = '') {
this.top(offset);
this._alignItems = 'center';
return this;
}
/**
* Apply the position to the element.
* \@docs-private
* @return {?}
*/
apply() {
// Since the overlay ref applies the strategy asynchronously, it could
// have been disposed before it ends up being applied. If that is the
// case, we shouldn't do anything.
if (!this._overlayRef.hasAttached()) {
return;
}
const /** @type {?} */ styles = this._overlayRef.overlayElement.style;
const /** @type {?} */ parentStyles = this._overlayRef.hostElement.style;
const /** @type {?} */ config = this._overlayRef.getConfig();
styles.position = this._cssPosition;
styles.marginLeft = config.width === '100%' ? '0' : this._leftOffset;
styles.marginTop = config.height === '100%' ? '0' : this._topOffset;
styles.marginBottom = this._bottomOffset;
styles.marginRight = this._rightOffset;
if (config.width === '100%') {
parentStyles.justifyContent = 'flex-start';
}
else if (this._justifyContent === 'center') {
parentStyles.justifyContent = 'center';
}
else if (this._overlayRef.getConfig().direction === 'rtl') {
// In RTL the browser will invert `flex-start` and `flex-end` automatically, but we
// don't want that because our positioning is explicitly `left` and `right`, hence
// why we do another inversion to ensure that the overlay stays in the same position.
// TODO: reconsider this if we add `start` and `end` methods.
if (this._justifyContent === 'flex-start') {
parentStyles.justifyContent = 'flex-end';
}
else if (this._justifyContent === 'flex-end') {
parentStyles.justifyContent = 'flex-start';
}
}
else {
parentStyles.justifyContent = this._justifyContent;
}
parentStyles.alignItems = config.height === '100%' ? 'flex-start' : this._alignItems;
}
/**
* Noop implemented as a part of the PositionStrategy interface.
* \@docs-private
* @return {?}
*/
dispose() { }
}
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Builder for overlay position strategy.
*/
class OverlayPositionBuilder {
/**
* @param {?} _viewportRuler
* @param {?} _document
* @param {?=} _platform
* @param {?=} _overlayContainer
*/
constructor(_viewportRuler, _document,
// @breaking-change 7.0.0 `_platform` and `_overlayContainer` parameters to be made required.
_platform, _overlayContainer) {
this._viewportRuler = _viewportRuler;
this._document = _document;
this._platform = _platform;
this._overlayContainer = _overlayContainer;
}
/**
* Creates a global position strategy.
* @return {?}
*/
global() {
return new GlobalPositionStrategy();
}
/**
* Creates a relative position strategy.
* @deprecated Use `flexibleConnectedTo` instead.
* \@breaking-change 7.0.0
* @param {?} elementRef
* @param {?} originPos
* @param {?} overlayPos
* @return {?}
*/
connectedTo(elementRef, originPos, overlayPos) {
return new ConnectedPositionStrategy(originPos, overlayPos, elementRef, this._viewportRuler, this._document);
}
/**
* Creates a flexible position strategy.
* @param {?} elementRef
* @return {?}
*/
flexibleConnectedTo(elementRef) {
return new FlexibleConnectedPositionStrategy(elementRef, this._viewportRuler, this._document, this._platform, this._overlayContainer);
}
}
OverlayPositionBuilder.decorators = [
{ type: Injectable, args: [{ providedIn: 'root' },] },
];
/** @nocollapse */
OverlayPositionBuilder.ctorParameters = () => [
{ type: ViewportRuler, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: Platform, decorators: [{ type: Optional },] },
{ type: OverlayContainer, decorators: [{ type: Optional },] },
];
/** @nocollapse */ OverlayPositionBuilder.ngInjectableDef = defineInjectable({ factory: function OverlayPositionBuilder_Factory() { return new OverlayPositionBuilder(inject(ViewportRuler), inject(DOCUMENT), inject(Platform, 8), inject(OverlayContainer, 8)); }, token: OverlayPositionBuilder, providedIn: "root" });
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Next overlay unique ID.
*/
let /** @type {?} */ nextUniqueId = 0;
/**
* Service to create Overlays. Overlays are dynamically added pieces of floating UI, meant to be
* used as a low-level building block for other components. Dialogs, tooltips, menus,
* selects, etc. can all be built using overlays. The service should primarily be used by authors
* of re-usable components rather than developers building end-user applications.
*
* An overlay *is* a PortalOutlet, so any kind of Portal can be loaded into one.
*/
class Overlay {
/**
* @param {?} scrollStrategies
* @param {?} _overlayContainer
* @param {?} _componentFactoryResolver
* @param {?} _positionBuilder
* @param {?} _keyboardDispatcher
* @param {?} _injector
* @param {?} _ngZone
* @param {?} _document
* @param {?} _directionality
*/
constructor(scrollStrategies, _overlayContainer, _componentFactoryResolver, _positionBuilder, _keyboardDispatcher, _injector, _ngZone, _document, _directionality) {
this.scrollStrategies = scrollStrategies;
this._overlayContainer = _overlayContainer;
this._componentFactoryResolver = _componentFactoryResolver;
this._positionBuilder = _positionBuilder;
this._keyboardDispatcher = _keyboardDispatcher;
this._injector = _injector;
this._ngZone = _ngZone;
this._document = _document;
this._directionality = _directionality;
}
/**
* Creates an overlay.
* @param {?=} config Configuration applied to the overlay.
* @return {?} Reference to the created overlay.
*/
create(config) {
const /** @type {?} */ host = this._createHostElement();
const /** @type {?} */ pane = this._createPaneElement(host);
const /** @type {?} */ portalOutlet = this._createPortalOutlet(pane);
const /** @type {?} */ overlayConfig = new OverlayConfig(config);
overlayConfig.direction = overlayConfig.direction || this._directionality.value;
return new OverlayRef(portalOutlet, host, pane, overlayConfig, this._ngZone, this._keyboardDispatcher, this._document);
}
/**
* Gets a position builder that can be used, via fluent API,
* to construct and configure a position strategy.
* @return {?} An overlay position builder.
*/
position() {
return this._positionBuilder;
}
/**
* Creates the DOM element for an overlay and appends it to the overlay container.
* @param {?} host
* @return {?} Newly-created pane element
*/
_createPaneElement(host) {
const /** @type {?} */ pane = this._document.createElement('div');
pane.id = `cdk-overlay-${nextUniqueId++}`;
pane.classList.add('cdk-overlay-pane');
host.appendChild(pane);
return pane;
}
/**
* Creates the host element that wraps around an overlay
* and can be used for advanced positioning.
* @return {?} Newly-create host element.
*/
_createHostElement() {
const /** @type {?} */ host = this._document.createElement('div');
this._overlayContainer.getContainerElement().appendChild(host);
return host;
}
/**
* Create a DomPortalOutlet into which the overlay content can be loaded.
* @param {?} pane The DOM element to turn into a portal outlet.
* @return {?} A portal outlet for the given DOM element.
*/
_createPortalOutlet(pane) {
// We have to resolve the ApplicationRef later in order to allow people
// to use overlay-based providers during app initialization.
if (!this._appRef) {
this._appRef = this._injector.get(ApplicationRef);
}
return new DomPortalOutlet(pane, this._componentFactoryResolver, this._appRef, this._injector);
}
}
Overlay.decorators = [
{ type: Injectable },
];
/** @nocollapse */
Overlay.ctorParameters = () => [
{ type: ScrollStrategyOptions, },
{ type: OverlayContainer, },
{ type: ComponentFactoryResolver, },
{ type: OverlayPositionBuilder, },
{ type: OverlayKeyboardDispatcher, },
{ type: Injector, },
{ type: NgZone, },
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
{ type: Directionality, },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Default set of positions for the overlay. Follows the behavior of a dropdown.
*/
const /** @type {?} */ defaultPositionList = [
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top'
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom'
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top'
}
];
/**
* Injection token that determines the scroll handling while the connected overlay is open.
*/
const /** @type {?} */ CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY = new InjectionToken('cdk-connected-overlay-scroll-strategy');
/**
* Directive applied to an element to make it usable as an origin for an Overlay using a
* ConnectedPositionStrategy.
*/
class CdkOverlayOrigin {
/**
* @param {?} elementRef
*/
constructor(elementRef) {
this.elementRef = elementRef;
}
}
CdkOverlayOrigin.decorators = [
{ type: Directive, args: [{
selector: '[cdk-overlay-origin], [overlay-origin], [cdkOverlayOrigin]',
exportAs: 'cdkOverlayOrigin',
},] },
];
/** @nocollapse */
CdkOverlayOrigin.ctorParameters = () => [
{ type: ElementRef, },
];
/**
* Directive to facilitate declarative creation of an
* Overlay using a FlexibleConnectedPositionStrategy.
*/
class CdkConnectedOverlay {
/**
* @param {?} _overlay
* @param {?} templateRef
* @param {?} viewContainerRef
* @param {?} _scrollStrategy
* @param {?} _dir
*/
constructor(_overlay, templateRef, viewContainerRef, _scrollStrategy, _dir) {
this._overlay = _overlay;
this._scrollStrategy = _scrollStrategy;
this._dir = _dir;
this._hasBackdrop = false;
this._lockPosition = false;
this._growAfterOpen = false;
this._flexibleDimensions = false;
this._push = false;
this._backdropSubscription = Subscription.EMPTY;
/**
* Margin between the overlay and the viewport edges.
*/
this.viewportMargin = 0;
/**
* Strategy to be used when handling scroll events while the overlay is open.
*/
this.scrollStrategy = this._scrollStrategy();
/**
* Whether the overlay is open.
*/
this.open = false;
/**
* Event emitted when the backdrop is clicked.
*/
this.backdropClick = new EventEmitter();
/**
* Event emitted when the position has changed.
*/
this.positionChange = new EventEmitter();
/**
* Event emitted when the overlay has been attached.
*/
this.attach = new EventEmitter();
/**
* Event emitted when the overlay has been detached.
*/
this.detach = new EventEmitter();
/**
* Emits when there are keyboard events that are targeted at the overlay.
*/
this.overlayKeydown = new EventEmitter();
this._templatePortal = new TemplatePortal(templateRef, viewContainerRef);
}
/**
* The offset in pixels for the overlay connection point on the x-axis
* @return {?}
*/
get offsetX() { return this._offsetX; }
/**
* @param {?} offsetX
* @return {?}
*/
set offsetX(offsetX) {
this._offsetX = offsetX;
if (this._position) {
this._setPositions(this._position);
}
}
/**
* The offset in pixels for the overlay connection point on the y-axis
* @return {?}
*/
get offsetY() { return this._offsetY; }
/**
* @param {?} offsetY
* @return {?}
*/
set offsetY(offsetY) {
this._offsetY = offsetY;
if (this._position) {
this._setPositions(this._position);
}
}
/**
* Whether or not the overlay should attach a backdrop.
* @return {?}
*/
get hasBackdrop() { return this._hasBackdrop; }
/**
* @param {?} value
* @return {?}
*/
set hasBackdrop(value) { this._hasBackdrop = coerceBooleanProperty(value); }
/**
* Whether or not the overlay should be locked when scrolling.
* @return {?}
*/
get lockPosition() { return this._lockPosition; }
/**
* @param {?} value
* @return {?}
*/
set lockPosition(value) { this._lockPosition = coerceBooleanProperty(value); }
/**
* Whether the overlay's width and height can be constrained to fit within the viewport.
* @return {?}
*/
get flexibleDiemsions() { return this._flexibleDimensions; }
/**
* @param {?} value
* @return {?}
*/
set flexibleDiemsions(value) { this._flexibleDimensions = coerceBooleanProperty(value); }
/**
* Whether the overlay can grow after the initial open when flexible positioning is turned on.
* @return {?}
*/
get growAfterOpen() { return this._growAfterOpen; }
/**
* @param {?} value
* @return {?}
*/
set growAfterOpen(value) { this._growAfterOpen = coerceBooleanProperty(value); }
/**
* Whether the overlay can be pushed on-screen if none of the provided positions fit.
* @return {?}
*/
get push() { return this._push; }
/**
* @param {?} value
* @return {?}
*/
set push(value) { this._push = coerceBooleanProperty(value); }
/**
* The associated overlay reference.
* @return {?}
*/
get overlayRef() {
return this._overlayRef;
}
/**
* The element's layout direction.
* @return {?}
*/
get dir() {
return this._dir ? this._dir.value : 'ltr';
}
/**
* @return {?}
*/
ngOnDestroy() {
this._destroyOverlay();
}
/**
* @param {?} changes
* @return {?}
*/
ngOnChanges(changes) {
if (this._position) {
if (changes['positions']) {
this._position.withPositions(this.positions);
}
if (changes['lockPosition']) {
this._position.withLockedPosition(this.lockPosition);
}
if (changes['origin']) {
this._position.setOrigin(this.origin.elementRef);
if (this.open) {
this._position.apply();
}
}
}
if (changes['open']) {
this.open ? this._attachOverlay() : this._detachOverlay();
}
}
/**
* Creates an overlay
* @return {?}
*/
_createOverlay() {
if (!this.positions || !this.positions.length) {
this.positions = defaultPositionList;
}
this._overlayRef = this._overlay.create(this._buildConfig());
}
/**
* Builds the overlay config based on the directive's inputs
* @return {?}
*/
_buildConfig() {
const /** @type {?} */ positionStrategy = this._position = this._createPositionStrategy();
const /** @type {?} */ overlayConfig = new OverlayConfig({
direction: this._dir,
positionStrategy,
scrollStrategy: this.scrollStrategy,
hasBackdrop: this.hasBackdrop
});
if (this.width || this.width === 0) {
overlayConfig.width = this.width;
}
if (this.height || this.height === 0) {
overlayConfig.height = this.height;
}
if (this.minWidth || this.minWidth === 0) {
overlayConfig.minWidth = this.minWidth;
}
if (this.minHeight || this.minHeight === 0) {
overlayConfig.minHeight = this.minHeight;
}
if (this.backdropClass) {
overlayConfig.backdropClass = this.backdropClass;
}
return overlayConfig;
}
/**
* Returns the position strategy of the overlay to be set on the overlay config
* @return {?}
*/
_createPositionStrategy() {
const /** @type {?} */ strategy = this._overlay.position()
.flexibleConnectedTo(this.origin.elementRef)
.withFlexibleDimensions(this.flexibleDiemsions)
.withPush(this.push)
.withGrowAfterOpen(this.growAfterOpen)
.withViewportMargin(this.viewportMargin)
.withLockedPosition(this.lockPosition);
this._setPositions(strategy);
strategy.positionChanges.subscribe(p => this.positionChange.emit(p));
return strategy;
}
/**
* Sets the primary and fallback positions of a positions strategy,
* based on the current directive inputs.
* @param {?} positionStrategy
* @return {?}
*/
_setPositions(positionStrategy) {
const /** @type {?} */ positions = this.positions.map(pos => ({
originX: pos.originX,
originY: pos.originY,
overlayX: pos.overlayX,
overlayY: pos.overlayY,
offsetX: pos.offsetX || this.offsetX,
offsetY: pos.offsetY || this.offsetY
}));
positionStrategy.withPositions(positions);
}
/**
* Attaches the overlay and subscribes to backdrop clicks if backdrop exists
* @return {?}
*/
_attachOverlay() {
if (!this._overlayRef) {
this._createOverlay(); /** @type {?} */
((this._overlayRef)).keydownEvents().subscribe((event) => {
this.overlayKeydown.next(event);
if (event.keyCode === ESCAPE) {
this._detachOverlay();
}
});
}
else {
// Update the overlay size, in case the directive's inputs have changed
this._overlayRef.updateSize({
width: this.width,
minWidth: this.minWidth,
height: this.height,
minHeight: this.minHeight,
});
}
if (!this._overlayRef.hasAttached()) {
this._overlayRef.attach(this._templatePortal);
this.attach.emit();
}
if (this.hasBackdrop) {
this._backdropSubscription = this._overlayRef.backdropClick().subscribe(event => {
this.backdropClick.emit(event);
});
}
}
/**
* Detaches the overlay and unsubscribes to backdrop clicks if backdrop exists
* @return {?}
*/
_detachOverlay() {
if (this._overlayRef) {
this._overlayRef.detach();
this.detach.emit();
}
this._backdropSubscription.unsubscribe();
}
/**
* Destroys the overlay created by this directive.
* @return {?}
*/
_destroyOverlay() {
if (this._overlayRef) {
this._overlayRef.dispose();
}
this._backdropSubscription.unsubscribe();
}
}
CdkConnectedOverlay.decorators = [
{ type: Directive, args: [{
selector: '[cdk-connected-overlay], [connected-overlay], [cdkConnectedOverlay]',
exportAs: 'cdkConnectedOverlay'
},] },
];
/** @nocollapse */
CdkConnectedOverlay.ctorParameters = () => [
{ type: Overlay, },
{ type: TemplateRef, },
{ type: ViewContainerRef, },
{ type: undefined, decorators: [{ type: Inject, args: [CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,] },] },
{ type: Directionality, decorators: [{ type: Optional },] },
];
CdkConnectedOverlay.propDecorators = {
"origin": [{ type: Input, args: ['cdkConnectedOverlayOrigin',] },],
"positions": [{ type: Input, args: ['cdkConnectedOverlayPositions',] },],
"offsetX": [{ type: Input, args: ['cdkConnectedOverlayOffsetX',] },],
"offsetY": [{ type: Input, args: ['cdkConnectedOverlayOffsetY',] },],
"width": [{ type: Input, args: ['cdkConnectedOverlayWidth',] },],
"height": [{ type: Input, args: ['cdkConnectedOverlayHeight',] },],
"minWidth": [{ type: Input, args: ['cdkConnectedOverlayMinWidth',] },],
"minHeight": [{ type: Input, args: ['cdkConnectedOverlayMinHeight',] },],
"backdropClass": [{ type: Input, args: ['cdkConnectedOverlayBackdropClass',] },],
"viewportMargin": [{ type: Input, args: ['cdkConnectedOverlayViewportMargin',] },],
"scrollStrategy": [{ type: Input, args: ['cdkConnectedOverlayScrollStrategy',] },],
"open": [{ type: Input, args: ['cdkConnectedOverlayOpen',] },],
"hasBackdrop": [{ type: Input, args: ['cdkConnectedOverlayHasBackdrop',] },],
"lockPosition": [{ type: Input, args: ['cdkConnectedOverlayLockPosition',] },],
"flexibleDiemsions": [{ type: Input, args: ['cdkConnectedOverlayFlexibleDimensions',] },],
"growAfterOpen": [{ type: Input, args: ['cdkConnectedOverlayGrowAfterOpen',] },],
"push": [{ type: Input, args: ['cdkConnectedOverlayPush',] },],
"backdropClick": [{ type: Output },],
"positionChange": [{ type: Output },],
"attach": [{ type: Output },],
"detach": [{ type: Output },],
"overlayKeydown": [{ type: Output },],
};
/**
* \@docs-private
* @param {?} overlay
* @return {?}
*/
function CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY(overlay) {
return () => overlay.scrollStrategies.reposition();
}
/**
* \@docs-private
*/
const /** @type {?} */ CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER = {
provide: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
class OverlayModule {
}
OverlayModule.decorators = [
{ type: NgModule, args: [{
imports: [BidiModule, PortalModule, ScrollDispatchModule],
exports: [CdkConnectedOverlay, CdkOverlayOrigin, ScrollDispatchModule],
declarations: [CdkConnectedOverlay, CdkOverlayOrigin],
providers: [
Overlay,
CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
],
},] },
];
/**
* @deprecated Use `OverlayModule` instead.
* \@breaking-change 7.0.0
*/
const /** @type {?} */ OVERLAY_PROVIDERS = [
Overlay,
OverlayPositionBuilder,
OVERLAY_KEYBOARD_DISPATCHER_PROVIDER,
VIEWPORT_RULER_PROVIDER,
OVERLAY_CONTAINER_PROVIDER,
CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER,
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* Alternative to OverlayContainer that supports correct displaying of overlay elements in
* Fullscreen mode
* https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen
*
* Should be provided in the root component.
*/
class FullscreenOverlayContainer extends OverlayContainer {
/**
* @param {?} _document
*/
constructor(_document) {
super(_document);
}
/**
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
if (this._fullScreenEventName && this._fullScreenListener) {
this._document.removeEventListener(this._fullScreenEventName, this._fullScreenListener);
}
}
/**
* @return {?}
*/
_createContainer() {
super._createContainer();
this._adjustParentForFullscreenChange();
this._addFullscreenChangeListener(() => this._adjustParentForFullscreenChange());
}
/**
* @return {?}
*/
_adjustParentForFullscreenChange() {
if (!this._containerElement) {
return;
}
const /** @type {?} */ fullscreenElement = this.getFullscreenElement();
const /** @type {?} */ parent = fullscreenElement || this._document.body;
parent.appendChild(this._containerElement);
}
/**
* @param {?} fn
* @return {?}
*/
_addFullscreenChangeListener(fn) {
const /** @type {?} */ eventName = this._getEventName();
if (eventName) {
if (this._fullScreenListener) {
this._document.removeEventListener(eventName, this._fullScreenListener);
}
this._document.addEventListener(eventName, fn);
this._fullScreenListener = fn;
}
}
/**
* @return {?}
*/
_getEventName() {
if (!this._fullScreenEventName) {
if (this._document.fullscreenEnabled) {
this._fullScreenEventName = 'fullscreenchange';
}
else if (this._document.webkitFullscreenEnabled) {
this._fullScreenEventName = 'webkitfullscreenchange';
}
else if ((/** @type {?} */ (this._document)).mozFullScreenEnabled) {
this._fullScreenEventName = 'mozfullscreenchange';
}
else if ((/** @type {?} */ (this._document)).msFullscreenEnabled) {
this._fullScreenEventName = 'MSFullscreenChange';
}
}
return this._fullScreenEventName;
}
/**
* When the page is put into fullscreen mode, a specific element is specified.
* Only that element and its children are visible when in fullscreen mode.
* @return {?}
*/
getFullscreenElement() {
return this._document.fullscreenElement ||
this._document.webkitFullscreenElement ||
(/** @type {?} */ (this._document)).mozFullScreenElement ||
(/** @type {?} */ (this._document)).msFullscreenElement ||
null;
}
}
FullscreenOverlayContainer.decorators = [
{ type: Injectable },
];
/** @nocollapse */
FullscreenOverlayContainer.ctorParameters = () => [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
];
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
export { Overlay, OverlayContainer, CdkOverlayOrigin, CdkConnectedOverlay, FullscreenOverlayContainer, OverlayRef, OverlayKeyboardDispatcher, OverlayPositionBuilder, GlobalPositionStrategy, ConnectedPositionStrategy, FlexibleConnectedPositionStrategy, OverlayConfig, ConnectionPositionPair, ScrollingVisibility, ConnectedOverlayPositionChange, validateVerticalPosition, validateHorizontalPosition, ScrollStrategyOptions, RepositionScrollStrategy, CloseScrollStrategy, NoopScrollStrategy, BlockScrollStrategy, OverlayModule, OVERLAY_PROVIDERS, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER as ɵg, OVERLAY_KEYBOARD_DISPATCHER_PROVIDER_FACTORY as ɵf, OVERLAY_CONTAINER_PROVIDER as ɵb, OVERLAY_CONTAINER_PROVIDER_FACTORY as ɵa, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY as ɵc, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER as ɵe, CDK_CONNECTED_OVERLAY_SCROLL_STRATEGY_PROVIDER_FACTORY as ɵd };
//# sourceMappingURL=overlay.js.map
|
var ThorElement = require('./thorElement');
var ThorController = function(){
ThorElement.call(this);
this.type = ThorElement.TYPES.CONTROLLER;
}
module.exports = ThorController;
|
var test2 = true;
|
function initTask(subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { img: "paint.png", side: cellSide, category: "paint", isPaint: true, isObstacle: false, hasColor: true, color: "gris", zOrder: 1 },
marker: { num: 2, img: "marker.png", side: cellSide, category: "marker", isObstacle: false, isMarker: true, zOrder: 0 }
},
maxInstructions: 15,
includeBlocks: {
groupByCategory: false,
generatedBlocks: {
robot: ["east", "west", "north", "south", "paint", "markedCell"]
},
standardBlocks: {
includeAll: false,
wholeCategories: [],
singleBlocks: ["controls_repeat", "controls_if"]
}
},
ignoreInvalidMoves: false,
checkEndEveryTurn: false,
checkEndCondition: robotEndConditions.checkMarkersPainted
};
subTask.data = {
easy: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 2, 2, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 1, 1],
[1, 1, 2, 1, 1, 1, 1, 2, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 1, 1, 2, 2, 1, 1, 2, 1],
[1, 2, 2, 2, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 9, col: 0, dir: 0, type: "green_robot" }
]
}
]
};
initBlocklySubTask(subTask);
displayHelper.thresholdEasy = 5000;
displayHelper.thresholdMedium = 10000;
}
initWrapper(initTask, null, null, true);
|
exports.BattleScripts = {
init: function() {
for (var i in this.data.Pokedex) {
var template = this.getTemplate(i);
var newStats = {
hp: template.id === 'shedinja' ? 1 : this.clampIntRange(150 - template.baseStats.hp, 5, 145),
atk: this.clampIntRange(150 - template.baseStats.atk, 5, 145),
def: this.clampIntRange(150 - template.baseStats.def, 5, 145),
spa: this.clampIntRange(150 - template.baseStats.spa, 5, 145),
spd: this.clampIntRange(150 - template.baseStats.spd, 5, 145),
spe: this.clampIntRange(150 - template.baseStats.spe, 5, 145)
}
this.modData('Pokedex', i).baseStats = newStats;
}
}
};
|
/* jshint node: true */
'use strict';
module.exports = {
name: 'ember-cli-patch-twilio',
contentFor: function(type) {
var environment = this.app.env.toString();
if (type === 'head') {
if (environment === 'production') {
return '<script type="text/javascript" src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>';
} else {
return '<script type="text/javascript"> var Twilio = { disconnectCallback: false, Device: { error: function() {}, setup: function() {}, connect: function() {}, disconnect: function (callback) { if (callback) { this.disconnectCallback = callback; } else { this.disconnectCallback(); } }, disconnectAll: function() {} } }; </script>';
}
}
}
};
|
// ─────────────────────────────────────────────────────────────────────────────
// import
// ─────────────────────────────────────────────────────────────────────────────
import React from 'react';
import { graphql } from 'gatsby';
import { RootContainer, BlogPreviewsContainer, SEOContainer } from '~containers';
import { Main, Section, H2 } from '~components';
import { renderBlocks, pagePropTypes } from '~utils';
// ─────────────────────────────────────────────────────────────────────────────
// query
// ─────────────────────────────────────────────────────────────────────────────
export const query = graphql`
{
page: mdx(frontmatter: { meta: { permalink: { eq: "/blog/" } } }) {
frontmatter {
...MetaFragment
blocks {
title
type
}
}
}
posts: allMdx(
filter: { fileAbsolutePath: { regex: "/cms/posts/" } }
sort: { fields: [frontmatter___date], order: DESC }
) {
nodes {
...BlogPreviewFragment
}
}
}
`;
// ─────────────────────────────────────────────────────────────────────────────
// component
// ─────────────────────────────────────────────────────────────────────────────
export default function BlogPage({
data: {
page: {
frontmatter: { meta, blocks },
},
posts,
},
}) {
return (
<RootContainer>
<SEOContainer meta={meta} />
<Main
css={`
grid-template: 'hero' 'blog';
grid-gap: 10vh 4rem;
`}
>
{renderBlocks(blocks)}
<Section
id="blog"
css={`
grid-area: blog;
`}
>
<H2>All blog articles</H2>
<BlogPreviewsContainer posts={posts} />
</Section>
</Main>
</RootContainer>
);
}
BlogPage.propTypes = pagePropTypes;
|
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import { expect } from 'chai';
import {
FIREBASE_LOGOUT_BEGIN,
FIREBASE_LOGOUT_SUCCESS,
FIREBASE_LOGOUT_FAILURE,
FIREBASE_LOGOUT_DISMISS_ERROR,
} from 'features/common/redux/constants';
import {
firebaseLogout,
dismissFirebaseLogoutError,
reducer,
} from 'features/common/redux/firebaseLogout';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('common/redux/firebaseLogout', () => {
afterEach(() => {
nock.cleanAll();
});
it('action should handle firebaseLogout success', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} },
];
return store.dispatch(firebaseLogout({ error: false }))
.then(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle firebaseLogout failure', () => {
const store = mockStore({});
const expectedActions = [
{ type: FIREBASE_LOGOUT_BEGIN },
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: 'some error' } },
];
return store.dispatch(firebaseLogout({ error: true }))
.catch(() => {
expect(store.getActions()).to.deep.equal(expectedActions);
});
});
it('action should handle dismissFirebaseLogoutError', () => {
const expectedAction = {
type: FIREBASE_LOGOUT_DISMISS_ERROR,
};
expect(dismissFirebaseLogoutError()).to.deep.equal(expectedAction);
});
it('reducer should handle FIREBASE_LOGOUT_BEGIN', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_BEGIN }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.true;
});
it('reducer should handle FIREBASE_LOGOUT_SUCCESS', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_SUCCESS, data: {} }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
});
it('reducer should handle FIREBASE_LOGOUT_FAILURE', () => {
const prevState = { firebaseLogoutPending: true };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_FAILURE, data: { error: new Error('some error') } }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutPending).to.be.false;
expect(state.firebaseLogoutError).to.exist;
});
it('reducer should handle FIREBASE_LOGOUT_DISMISS_ERROR', () => {
const prevState = { firebaseLogoutError: new Error('some error') };
const state = reducer(
prevState,
{ type: FIREBASE_LOGOUT_DISMISS_ERROR }
);
expect(state).to.not.equal(prevState); // should be immutable
expect(state.firebaseLogoutError).to.be.null;
});
});
|
'use strict'
let models = require('../models')
let express = require('express')
let multer = require('multer')
let upload = multer({dest: 'uploads/'})
let router = express.Router()
let utils = require('./utils')
router.get('', (req, res, next) => {
let result = {
messages: []
}
models.File.findAndCountAll(
).then(files => {
result.data = files.rows
result.length = files.count
res.writeHead(200, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.get('/:id', (req, res, next) => {
let params = {}
let result = {
messages: []
}
params = req.query
models.File.findById(
req.params.id || -1,
utils.setWhere(params)
).then(file => {
result.data = file || {}
result.length = (file) ? 1 : 0
res.writeHead((file) ? 200 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
router.post('', upload.array('file', 10), (req, res, next) => {
let result = {}
let file = {
id: req.body.id || (new Date()).valueOf(),
originalName: req.files[0].originalname,
fileName: req.files[0].filename,
size: req.files[0].size
}
models.File.create(
file
).then(file => {
result = {
data: file,
length: 1,
messages: [{
type: 'success',
code: 201,
detail: 'Recurso criado com sucesso'
}]
}
res.writeHead(201, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`, 422, {})
})
})
router.delete('', (req, res, next) => {
utils.fnError405(res)
})
router.delete('/:id', (req, res, next) => {
let result = {
data: {},
length: 0,
messages: []
}
models.File.destroy({
where: {
id: req.params.id
}
}).then(file => {
if (file === 1) {
result.messages = [{
type: 'success',
code: 204,
detail: 'Recurso excluído com sucesso'
}]
} else {
result.messages = [{
type: 'warning',
code: 404,
detail: 'Recurso não encontrado'
}]
}
res.writeHead(file === 1 ? 204 : 404, utils.contentType)
res.end(JSON.stringify(result))
}, error => {
utils.fnError(res, `${error.name}:${error.message}`)
})
})
module.exports = router
|
'use strict';
// MODULES //
var factory = require( './factory.js' );
// URLS //
/**
* FUNCTION: urls( options, clbk )
* Get repository URLs for one or more packages.
*
* @param {Object} options - function options
* @param {String[]} options.packages - package names
* @param {String} [options.registry="registry.npmjs.org"] - registry
* @param {Number} [options.port=443] - registry port
* @param {String} [options.protocol="https"] - registry protocol
* @param {Function} clbk - callback to invoke upon query completion
* @returns {Void}
*/
function urls( options, clbk ) {
factory( options, clbk )();
} // end FUNCTION urls()
// EXPORTS //
module.exports = urls;
|
// media query constants
(function() {
'use strict';
var MQ = {
SMALL: '(max-width: 767px)',
LARGE: '(min-width: 768px)'
};
angular
.module('rBox')
.constant('MQ', MQ);
}());
|
"use strict"
// Keep in length order
module.exports = {
object: {},
objectModule: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
file: 'object.routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
listModule: {
dir: 'list',
templates: [{
name: 'list.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'list.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'list-resolve.service.ts',
file: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'list.component.pug',
},{
name: 'list.component.css',
},{
name: 'list.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
detailModule: {
dir: 'detail',
templates: [{
name: 'detail.module.ts',
file: 'form.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'detail.component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'detail-resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail-auth.service.ts',
file: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
},{
name: 'detail.component.pug',
},{
name: 'detail.component.css',
file: 'component.css',
},{
name: 'detail.routes.ts',
imports: ['routes.ts'],
//addRoute: true,
}],
},
resolveService: {
dir: false,
templates: [{
name: 'resolve.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
canActivateService: {
dir: false,
templates: [{
name: 'can-activate.service.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['providers'],
}],
},
commonModule: {
dir: true,
templates: [{
name: 'module.ts',
file: 'common.module.ts',
imports: ['module.ts'],
listItems: ['imports'],
}],
},
service: {
dir: false,
templates: [{
name: 'service.ts',
imports: ['module.ts'],
listItems: ['providers'],
}],
},
component: {
dir: true,
templates: [{
name: 'component.ts',
imports: ['module.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
},{
name: 'component.css',
}],
},
module: {
dir: true,
templates: [{
name: 'module.ts',
imports: ['module.ts'],
listItems: ['imports'],
},{
name: 'component.ts',
imports: ['module.ts', 'routes.ts'],
listItems: ['declarations', 'exports'],
},{
name: 'component.pug',
file: 'router.component.pug',
},{
name: 'component.css',
},{
name: 'routes.ts',
imports: ['routes.ts'],
addRoute: true,
}],
},
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:ed3c069c3fb213c279f09fea7c7fe53e4340d9da1e27b560b4ffcb4009dd23e0
size 9790
|
'use strict';
var assert = require('assert');
var x = [1, 2, 3];
var sum = 0;
for (var value of x) {
sum += value;
}
assert(sum === 6);
|
'use strict';
var compiler = require('gss-compiler');
var through2 = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
module.exports = function() {
function transform (file, enc, next) {
var self = this;
if (file.isNull()) {
self.push(file);
return next();
}
if (file.isStream()) {
self.emit('error', new PluginError('gulp-gss', 'Streaming not supported'));
return next();
}
var str = file.contents.toString('utf8');
var ast = compiler.compile(str);
file.contents = new Buffer(JSON.stringify(ast, null, 2) + "\n");
file.path = gutil.replaceExtension(file.path, '.json');
self.push(file);
return next();
};
return through2.obj(transform);
};
|
const concat = require('concat-stream')
const test = require('tape')
const fs = require('fs')
const gherkin = require('../')
test('should assert input types', function (t) {
t.plan(3)
const rs = fs.createReadStream(__dirname + '/file.feature')
const ts = gherkin()
const ws = concat({ object: true }, function (buf) {
const ast = JSON.parse(buf.toString())
t.equal(typeof ast, 'object')
t.deepEqual(ast, [ {
perspective: 'drinker',
feature: 'Can drink beer when thirsty',
desire: 'to take beer off the wall',
reason: 'to satisfy my thirst',
scenarios: [ {
given: [ '100 bottles of beer on the wall' ],
scenario: 'Can take a single beer',
then: [ 'there are 99 bottles of beer on the wall' ],
when: [ 'a bottle is taken down' ]
} ]
} ])
})
ts.on('end', t.pass.bind('null', 'stream ended'))
rs.pipe(ts).pipe(ws)
})
|
/* DASHBOARDS */
Router.route('/', {
name: 'sitesIndex',
controller: SitesController,
action: 'index',
});
/* EOF DASHBOARDS */
|
import baseController from '../../shared/baseController';
export default class ngbGenomeAnnotationsController extends baseController{
static get UID() {
return 'ngbGenomeAnnotationsController';
}
projectContext;
scope;
showTrackOriginalName = true;
constructor($scope, dispatcher, projectContext, trackNamingService, localDataService) {
super(dispatcher);
this.projectContext = projectContext;
this.trackNamingService = trackNamingService;
this.scope = $scope;
this.localDataService = localDataService;
this.showTrackOriginalName = localDataService.getSettings().showTrackOriginalName;
this.annotationFiles = [
{
name: 'Human_genome.fa'
},
{
name: 'Human_genome.bed'
}
];
const globalSettingsChangedHandler = (state) => {
this.showTrackOriginalName = state.showTrackOriginalName;
};
this.dispatcher.on('settings:change', globalSettingsChangedHandler);
// We must remove event listener when component is destroyed.
$scope.$on('$destroy', () => {
dispatcher.removeListener('settings:change', globalSettingsChangedHandler);
});
}
openMenu($mdOpenMenu, $event) {
if (this.referenceContainsAnnotations) {
$mdOpenMenu($event);
}
}
get reference() {
if (this.projectContext && this.projectContext.reference) {
return this.projectContext.reference;
}
return {
annotationFiles: null,
name: null,
};
}
get referenceContainsAnnotations() {
if (this.projectContext && this.projectContext.reference) {
return this.projectContext.reference.annotationFiles && this.projectContext.reference.annotationFiles.length;
}
return false;
}
getCustomName(file) {
return this.trackNamingService.getCustomName(file);
}
onAnnotationFileChanged(file) {
if (file.selected) {
const state = this.projectContext.reference.annotationFiles;
const sortFn = (file1, file2) => {
if (file1.selected !== file2.selected) {
if (file1.selected) {
return -1;
} else {
return 1;
}
}
const index1 = state.indexOf(file1.name.toLowerCase());
const index2 = state.indexOf(file2.name.toLowerCase());
if (file1.name.toLowerCase() === file2.name.toLowerCase()) {
return 0;
}
if (file1.name.toLowerCase() === file.name.toLowerCase()) {
return 1;
}
if (file2.name.toLowerCase() === file.name.toLowerCase()) {
return -1;
}
if (index1 < index2) {
return -1;
} else if (index1 > index2) {
return 1;
}
return 0;
};
this.projectContext.reference.annotationFiles.sort(sortFn);
const tracks = this.projectContext.tracks;
file.projectId = '';
file.isLocal = true;
tracks.push(file);
const tracksState = this.projectContext.tracksState;
const savedState = this.projectContext.getTrackState((file.name || '').toLowerCase(), file.projectId);
if (savedState) {
tracksState.push(Object.assign(savedState,{
bioDataItemId: file.name,
format: file.format,
isLocal: true,
projectId: '',
}));
} else {
tracksState.push({
bioDataItemId: file.name,
format: file.format,
isLocal: true,
projectId: '',
});
}
this.projectContext.changeState({tracks, tracksState});
} else {
const tracks = this.projectContext.tracks;
const tracksToRemove = tracks.filter(
(t) =>
t.name.toLowerCase() === file.name.toLowerCase() &&
t.format.toLowerCase() === file.format.toLowerCase() &&
t.projectId === ''
);
tracksToRemove.forEach(track => {
const index = tracks.indexOf(track);
tracks.splice(index, 1);
});
const tracksState = this.projectContext.tracksState;
const trackStateToRemove = tracksState.filter(
(t) =>
t.bioDataItemId.toLowerCase() === file.name.toLowerCase() &&
t.format.toLowerCase() === file.format.toLowerCase() &&
t.projectId === ''
);
trackStateToRemove.forEach(trackState => {
tracksState.splice(tracksState.indexOf(trackState), 1);
});
this.projectContext.changeState({tracks, tracksState});
}
this.projectContext.saveAnnotationFilesState();
}
}
|
/**
* Usage: 程序配置项
* Author: Spikef < Spikef@Foxmail.com >
* Copyright: Envirs Team < http://envirs.com >
*/
var fs = require('fs');
var program = require('commander');
var prompts = require('inquirer').prompt;
program
.command('config <option>')
.description('修改配置')
.action(function(option) {
var site = process.site();
var configs = require(site + '/config.json');
if ( !configs[option] ) configs[option] = {};
var questions = [];
switch(option) {
case 'ftp':
questions = [
{
type: 'input',
name: 'address',
message: 'FTP地址'
},
{
type: 'input',
name: 'port',
message: '端口地址,如果不知道则跳过',
default: 21,
filter: Number
},
{
type: 'input',
name: 'username',
message: '登录用户'
},
{
type: 'password',
name: 'username',
message: '登录密码'
},
{
type: 'input',
name: 'folder',
message: '子目录,如果没有则跳过'
}
];
break;
case 'blog':
questions = [
{
type: 'input',
name: 'name',
message: '博客名称'
},
{
type: 'input',
name: 'title',
message: '博客标题'
},
{
type: 'input',
name: 'author',
message: '博主名称'
},
{
type: 'input',
name: 'username',
message: '登录用户'
},
{
type: 'password',
name: 'password',
message: '管理密码,'
},
{
type: 'input',
name: 'keywords',
message: '博客整站关键字'
},
{
type: 'input',
name: 'description',
message: '博客整站描述'
},
{
type: 'input',
name: 'copyright',
message: '博客版权信息'
},
{
type: 'input',
name: 'pageSize',
message: '每页显示日志条数',
filter: Number
}
];
break;
}
if ( questions.length > 0 ) {
for (var i=0;i<questions.length;i++) {
questions[i].default = configs[option][questions[i].name];
}
prompts(questions, function(answers) {
for (var i in answers) {
configs[option][i] = answers[i]
}
fs.writeFileSync(site + '/config.json', JSON.format(configs));
});
} else {
console.log('未知命令');
}
});
|
;( function( d3 ) {
/**
* Get parent of dom element with
* given class
*
* @param {Object} el element
* @param {String} className className
* @return {Object} parent element with given class
*/
function getParent( el, className ) {
var parent = null;
var p = el.parentNode;
while ( p !== null ) {
var o = p;
if ( o.classList.contains( className ) ) {
parent = o;
break;
}
p = o.parentNode;
}
return parent; // returns an Array []
}
var id = window.location.href.split( '/' ).pop();
var keysToRender = [ {
key : 'render',
label : 'Start Render',
timing : true
}, {
key : 'SpeedIndex',
label : 'SpeedIndex'
}, {
key : 'domElements',
label : 'Number of DOM Elements'
}, {
key : 'docTime',
label : 'Document Complete',
timing : true
}, {
key : 'fullyLoaded',
label : 'Fully loaded',
timing : true
}, {
key : 'requests',
label : 'Number of Requests'
} ];
var loading = document.getElementById( 'loading' );
var table = document.getElementById( 'resultTable' );
var template = document.getElementById( 'resultTableEachTpl' );
var status = document.getElementById( 'status' );
function _getNormalizedData( data ) {
var normalizedData = [];
function getNormalizedDate( date, key, type ) {
var returnValue;
if ( key.key !== 'requests' ) {
returnValue = {
value : date.response.data.median[ type ] ?
date.response.data.median[ type ][ key.key ] :
0,
allowed : date.allowedUrl
};
} else {
returnValue = {
value : date.response.data.median[ type ] ?
date.response.data.median[ type ][ key.key ][ 0 ] :
0,
allowed : date.allowedUrl
};
}
if ( key.timing ) {
returnValue.withoutTTFB = returnValue.value - date.response.data.median[ type ].TTFB;
}
return returnValue;
}
keysToRender.forEach( function( key ) {
normalizedData.push( {
name : key.label,
key : key.key,
timing : !! key.timing,
data : [
data.map( function( date ) {
return getNormalizedDate( date, key, 'firstView' );
} ),
data.map( function( date ) {
return getNormalizedDate( date, key, 'repeatView' );
} )
]
} );
} )
return normalizedData;
}
function showBarHelp( data ) {
d3.selectAll( '.resultGraphs--help' ).remove();
var bar = this;
var bBox = bar.getBBox();
var detailBox = document.createElement( 'div' );
var listContainer = getParent( bar, 'resultGraphs--item--container' );
detailBox.classList.add( 'resultGraphs--help' );
detailBox.innerHTML =
'Allowed 3rd Party URL(s):<br><strong>' + bar.dataset.allowed + '</strong>';
listContainer.appendChild( detailBox );
detailBox.style.left = ( bBox.x + bBox.width / 2 - detailBox.getBoundingClientRect().width / 2 ) + 'px';
detailBox.style.top = ( bBox.y + bBox.height + detailBox.getBoundingClientRect().height ) + 'px';
}
function renderTable( container, data ) {
var table = document.querySelector( container );
table.innerHTML = nunjucks.renderString( template.innerHTML, { data : data } );
}
function renderGraphs( container, data ) {
var resultGraphs = d3.select( container );
var normalizedData = _getNormalizedData( data );
var items = resultGraphs.selectAll( '.resultGraphs--item' )
.data( normalizedData );
items.enter()
.append( 'li' )
.attr( 'class', 'resultGraphs--item' )
.attr( 'id', function( d ) {
return 'resultGraph--item-' + d.key;
} )
.html( function( d ) {
return '<h4 class="resultGraphs--item--headline">' + d.name + '</h4>' +
'<div class="resultGraphs--legend">' +
'<span class="resultGraphs--legend__first">First</span>' +
'<span class="resultGraphs--legend__repeat">Repeat</span>' +
'</div>' +
'<div class="resultGraphs--item--container"></div>';
} );
items.each( renderGraph );
items.exit().remove()
}
function renderGraph( data ) {
var containerEl = this.querySelector( '.resultGraphs--item--container' );
var margin = { top : 25, right : 0, bottom : 30, left : 0 };
var width = containerEl.clientWidth - margin.left - margin.right;
var height = width * 0.6 - margin.top - margin.bottom;
var y = d3.scale.linear()
.domain( [
0,
d3.max(
[
d3.max( data.data[ 0 ].map( function( d ) { return d.value; } ) ),
d3.max( data.data[ 1 ].map( function( d ) { return d.value; } ) )
]
)
] )
.range( [ height, 0 ] )
var x = d3.scale.linear()
.domain( [ 0, data.data[ 0 ].length + 1 ] )
.range( [ 0, width ] );
var xAxis = d3.svg.axis()
.scale( x )
.tickFormat( function( d ) {
return ( d % 1 !== 0 || ! d || d === data.data[ 0 ].length + 1 ) ?
'' :
d;
} )
.orient( 'bottom' );
var yAxis = d3.svg.axis()
.scale( y )
.tickSize( width )
.orient( 'right' );
var line = d3.svg.line()
.x( function( d, i ) { return x( i + 1 ); } )
.y( function( d ) { return y( d.value ); } )
.interpolate( 'cardinal' );
var container = d3.select( containerEl ).html( '<svg></svg>' );
var svg = container.select( 'svg' )
.attr( 'width', width + margin.left + margin.right )
.attr( 'height', height + margin.top + margin.bottom )
.append( 'g' )
.attr( 'transform', 'translate(' + margin.left + ',' + margin.top + ')');
var barChartWidth = 12;
var marks = svg.append( 'g' )
.attr( 'class', 'resultGraphs--marks' );
var bgBars = svg.append( 'g' )
.attr( 'class', 'resultGraphs--bgBars' );
bgBars.selectAll( '.resultGraphs--bgBar' )
.data( data.data[ 0 ] )
.enter().append( 'rect' )
.attr( 'class', 'resultGraphs--bgBar' )
.attr( 'x', function( d, i ) { return x( i + .5 ); } )
.attr( 'width', function( d, i ) { return x( i + .5 ) - x( i - .5 ) } )
.attr( 'y', function( d ) { return 0; } )
.attr( 'height', function( d ) { return height; } )
.attr( 'data-allowed', function( d ) { return d.allowed } )
.on( 'mouseenter', showBarHelp );
var gy = svg.append( 'g' )
.attr( 'class', 'resultGraphs--yAxisTicks' )
.call( yAxis )
.call( customAxis );
var gx = svg.append( 'g' )
.attr( 'class', 'resultGraphs--xAxisTicks' )
.attr( 'transform', 'translate(0,' + height + ')' )
.call( xAxis );
var circles = svg.append( 'g' )
.attr( 'class', 'resultGraphs--circles' );
drawLineWithCircles( data.data[ 0 ], 'first', svg, circles );
drawLineWithCircles( data.data[ 1 ], 'repeat', svg, circles );
// TODO implement this in a different way
// if ( data.timing ) {
// drawLineWithCircles( data.data[ 0 ].map( function( date ) {
// return {
// allowed : date.allowed,
// value : date.withoutTTFB
// };
// } ), 'firstWithoutTTFB', svg, circles );
// drawLineWithCircles( data.data[ 1 ].map( function( date ) {
// return {
// allowed : date.allowed,
// value : date.withoutTTFB
// };
// } ), 'repeatWithoutTTFB', svg, circles );
// }
function drawLineWithCircles( data, type, svg, circleContainer ) {
svg.append( 'path' )
.datum( data )
.attr( 'class', 'resultGraphs--line__' + type )
.attr( 'd', line );
circleContainer.selectAll( '.resultGraphs--circle__' + type )
.data( data )
.enter().append( 'circle' )
.attr( 'r', 5 )
.attr( 'class', 'resultGraphs--circle__' + type )
.attr( 'cx', function( d, i ) { return x( i + 1 ); } )
.attr( 'cy', function( d ) { return y( d.value ); });
}
function customAxis( g ) {
g.selectAll( 'text' )
.attr( 'x', 4 )
.attr( 'dy', -4 );
}
}
function fetchData() {
fetch( '/results/data/' + id )
.then( function( response ) {
return response.json();
} )
.then( function( result ) {
if ( result.data.length > 1 && ! result.error ) {
var allVsNoneData = [ result.data[ 0 ], result.data[ 1 ] ];
renderTable( '#resultTable--allVsNone', allVsNoneData );
renderGraphs( '#resultGraphs--allVsNone', allVsNoneData );
var noneVsEachData = result.data.slice( 1 );
renderTable( '#resultTable--noneVsEach', noneVsEachData );
renderGraphs( '#resultGraphs--noneVsEach', noneVsEachData );
}
if ( ! result.finished ) {
loading.innerText = result.runsToGo ?
result.runsToGo + ' run(s) to go' :
'Processing...';
setTimeout( fetchData, 7500 );
} else {
status.classList.remove( 'is-processing' );
if ( ! result.error ) {
status.classList.add( 'is-done' );
loading.innerText = 'DONE!';
} else {
status.classList.add( 'is-failed' );
loading.innerText = 'FAILED...';
}
}
} );
}
fetchData();
} )( d3 );
|
module.exports = function (Clase) {
Clase.saluda = function (msg, cb) {
cb(null, 'Hola pos... ' + msg);
};
Clase.remoteMethod(
'saluda', {
accepts: {
arg: 'msg',
type: 'string'
},
returns: {
arg: 'greeting',
type: 'string'
}
}
);
Clase.getcomuna = function (idcomuna, callback) {
Clase.find({
//include: ['deporte', 'establecimiento', 'entrenador'],
include: ['deporte', {
establecimiento: ['comuna'],
}],
where: {
idComuna: idcomuna
}
},
function (err, clases) {
callback(null, clases);
});
};
Clase.remoteMethod(
'getcomuna', {
accepts: {
art: 'idcomuna',
type: 'integer'
},
returns: {
arg: 'comuna',
type: 'string'
}
});
};
|
var util = require('util');
var path = require('path');
var chalk = require('chalk');
var BaseReporter = require('./base');
var Match = require('../match');
/**
* A PMD CPD XML reporter, which tries to fit jsinspect's output to something
* CI tools might expect from PMD.
*
* @constructor
*
* @param {Inspector} inspector The instance on which to register its listeners
* @param {object} opts Options to set for the reporter
*/
function PMDReporter(inspector, opts) {
var self, enabled;
self = this;
enabled = chalk.enabled;
opts = opts || {};
BaseReporter.call(this, inspector, opts);
this._diff = opts.diff;
inspector.on('start', function() {
chalk.enabled = false;
self._writableStream.write(
'<?xml version="1.0" encoding="utf-8"?>\n' +
'<pmd-cpd>\n'
);
});
inspector.on('end', function() {
chalk.enabled = enabled;
self._writableStream.write('</pmd-cpd>\n');
});
}
util.inherits(PMDReporter, BaseReporter);
module.exports = PMDReporter;
/**
* Returns an XML string containing a <duplication> element, with <file>
* children indicating the instance locations, and <codefragment> to hold the
* diff.
*
* @private
*
* @param {Match} match The inspector match to output
* @returns {string} The formatted output
*/
PMDReporter.prototype._getOutput = function(match) {
var self, output, diff, i, nodes, files;
self = this;
output = '';
diff = '';
nodes = match.nodes;
if (this._found > 1) {
output += '\n';
}
output += '<duplication lines="' + this._getTotalLines(nodes) + '">\n';
nodes.forEach(function(node) {
output += self._getFile(node);
});
output += '<codefragment>';
if (this._diff) {
for (i = 0; i < match.diffs.length; i++) {
diff += '\n- ' + this._getFormattedLocation(nodes[0]) + '\n+ ' +
this._getFormattedLocation(nodes[i + 1]) + '\n\n' +
this._getFormattedDiff(match.diffs[i]);
}
}
output += this._escape(diff) + '</codefragment>\n</duplication>\n';
return output;
};
/**
* Returns the total number of lines spanned by each node in an array.
*
* @param {[]Node} nodes The nodes for which to get the total
* @returns {int} Total number of lines
*/
PMDReporter.prototype._getTotalLines = function(nodes) {
return nodes.reduce(function(prev, curr) {
return prev + curr.loc.end.line - curr.loc.start.line + 1;
}, 0);
};
/**
* Returns an XML string containing the path to the file in which the node is
* located, as well as its starting line. Absolute paths are required for
* Jenkins.
*
* @param {Node} node The node from which to get a formatted location
* @returns {string} The formatted string
*/
PMDReporter.prototype._getFile = function(node) {
var filePath = node.loc.source;
// Convert any relative paths to absolute
if (filePath.charAt(0) !== '/') {
filePath = path.resolve(process.cwd(), filePath);
}
return '<file path="' + filePath + '" line="' + node.loc.start.line + '"/>\n';
};
/**
* Returns an escaped string for use within XML.
*
* @param {string} string The string to escape
* @returns {string} The escaped string
*/
PMDReporter.prototype._escape = function(string) {
var escaped = {
"'": ''',
'"': '"',
'&': '&',
'>': '>',
'<': '<'
};
return string.replace(/(['"&><])/g, function(string, char) {
return escaped[char];
});
};
|
import React from 'react'
import './blocks.scss'
export default class Block extends React.Component {
render() {
let {title, secondary, content, additional, style} = this.props;
return(
<div className={"amazo-tile " + (style ? style : 'default')}>
<div className="tile-heading">
<div className="title">{title ? title : 'TITLE'}</div>
<div className="secondary">{secondary ? secondary : 'SECONDARY'}</div>
</div>
<div className="tile-body">
<span className="content">{content ? content : 'CONTENT'}</span>
</div>
<div className="tile-footer text-center">
<span className="info-text text-right">{additional ? additional : 'ADDITIONAL'}</span>
</div>
</div>)
}
}
|
{
jestExpect(value).toBe(false);
}
|
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var DelegateFolderPermissionLevel_1 = require("../Enumerations/DelegateFolderPermissionLevel");
var AltDictionary_1 = require("../AltDictionary");
var ServiceValidationException_1 = require('../Exceptions/ServiceValidationException');
var Strings_1 = require("../Strings");
var XmlElementNames_1 = require("../Core/XmlElementNames");
var XmlNamespace_1 = require("../Enumerations/XmlNamespace");
var ComplexProperty_1 = require("./ComplexProperty");
/**
* Represents the permissions of a delegate user.
*
* @sealed
*/
var DelegatePermissions = (function (_super) {
__extends(DelegatePermissions, _super);
/**
* @internal Initializes a new instance of the **DelegatePermissions** class.
*/
function DelegatePermissions() {
_super.call(this);
this.delegateFolderPermissions = null;
var dictionary = new AltDictionary_1.DictionaryWithStringKey();
dictionary.Add(XmlElementNames_1.XmlElementNames.CalendarFolderPermissionLevel, new DelegateFolderPermission());
dictionary.Add(XmlElementNames_1.XmlElementNames.TasksFolderPermissionLevel, new DelegateFolderPermission());
dictionary.Add(XmlElementNames_1.XmlElementNames.InboxFolderPermissionLevel, new DelegateFolderPermission());
dictionary.Add(XmlElementNames_1.XmlElementNames.ContactsFolderPermissionLevel, new DelegateFolderPermission());
dictionary.Add(XmlElementNames_1.XmlElementNames.NotesFolderPermissionLevel, new DelegateFolderPermission());
dictionary.Add(XmlElementNames_1.XmlElementNames.JournalFolderPermissionLevel, new DelegateFolderPermission());
this.delegateFolderPermissions = dictionary;
}
Object.defineProperty(DelegatePermissions.prototype, "CalendarFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's calendar.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.CalendarFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.CalendarFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DelegatePermissions.prototype, "TasksFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's tasks folder.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.TasksFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.TasksFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DelegatePermissions.prototype, "InboxFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's inbox.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.InboxFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.InboxFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DelegatePermissions.prototype, "ContactsFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's contacts folder.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.ContactsFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.ContactsFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DelegatePermissions.prototype, "NotesFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's notes folder.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.NotesFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.NotesFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(DelegatePermissions.prototype, "JournalFolderPermissionLevel", {
/**
* Gets or sets the delegate user's permission on the principal's journal folder.
*/
get: function () {
return this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.JournalFolderPermissionLevel).PermissionLevel;
},
set: function (value) {
this.delegateFolderPermissions.get(XmlElementNames_1.XmlElementNames.JournalFolderPermissionLevel).PermissionLevel = value;
},
enumerable: true,
configurable: true
});
/**
* @internal Loads service object from XML.
*
* @param {any} jsObject Json Object converted from XML.
* @param {ExchangeService} service The service.
*/
DelegatePermissions.prototype.LoadFromXmlJsObject = function (jsObject, service) {
for (var key in jsObject) {
var delegateFolderPermission = null;
if (this.delegateFolderPermissions.containsKey(key)) {
delegateFolderPermission = this.delegateFolderPermissions.get(key);
delegateFolderPermission.Initialize(DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel[jsObject[key]]);
}
}
};
/**
* @internal Resets this instance.
*/
DelegatePermissions.prototype.Reset = function () {
for (var _i = 0, _a = this.delegateFolderPermissions.Values; _i < _a.length; _i++) {
var delegateFolderPermission = _a[_i];
delegateFolderPermission.Reset();
}
};
/**
* @internal Validates this instance for AddDelegate.
*/
DelegatePermissions.prototype.ValidateAddDelegate = function () {
// If any folder permission is Custom, throw
//
this.delegateFolderPermissions.Values.forEach(function (permission) {
if (permission.PermissionLevel == DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.Custom) {
throw new ServiceValidationException_1.ServiceValidationException(Strings_1.Strings.CannotSetDelegateFolderPermissionLevelToCustom);
}
});
};
/**
* @internal Validates this instance for UpdateDelegate.
*/
DelegatePermissions.prototype.ValidateUpdateDelegate = function () {
// If any folder permission was changed to custom, throw
//
this.delegateFolderPermissions.Values.forEach(function (permission) {
if (permission.PermissionLevel == DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.Custom && !permission.IsExistingPermissionLevelCustom) {
throw new ServiceValidationException_1.ServiceValidationException(Strings_1.Strings.CannotSetDelegateFolderPermissionLevelToCustom);
}
});
};
/**
* @internal Writes the elements to XML.
*
* @param {EwsServiceXmlWriter} writer The writer.
*/
DelegatePermissions.prototype.WriteElementsToXml = function (writer) {
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.CalendarFolderPermissionLevel);
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.TasksFolderPermissionLevel);
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.InboxFolderPermissionLevel);
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.ContactsFolderPermissionLevel);
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.NotesFolderPermissionLevel);
this.WritePermissionToXml(writer, XmlElementNames_1.XmlElementNames.JournalFolderPermissionLevel);
};
/**
* Write permission to Xml.
*
* @param {EwsServiceXmlWriter} writer The writer.
* @param {string} xmlElementName The element name.
*/
DelegatePermissions.prototype.WritePermissionToXml = function (writer, xmlElementName) {
var delegateFolderPermissionLevel = this.delegateFolderPermissions.get(xmlElementName).PermissionLevel;
// UpdateDelegate fails if Custom permission level is round tripped
//
if (delegateFolderPermissionLevel != DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.Custom) {
writer.WriteElementValue(XmlNamespace_1.XmlNamespace.Types, xmlElementName, DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel[delegateFolderPermissionLevel]);
}
};
return DelegatePermissions;
}(ComplexProperty_1.ComplexProperty));
exports.DelegatePermissions = DelegatePermissions;
/**
* @internal Represents a folder's DelegateFolderPermissionLevel
*/
var DelegateFolderPermission = (function () {
function DelegateFolderPermission() {
/**
* @internal Gets or sets the delegate user's permission on a principal's folder.
*/
this.PermissionLevel = DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.None;
/**
* @internal Gets IsExistingPermissionLevelCustom.
*/
this.IsExistingPermissionLevelCustom = false;
}
/**
* Intializes this DelegateFolderPermission.
*
* @param {DelegateFolderPermissionLevel} permissionLevel The DelegateFolderPermissionLevel
*/
DelegateFolderPermission.prototype.Initialize = function (permissionLevel) {
this.PermissionLevel = permissionLevel;
this.IsExistingPermissionLevelCustom = (permissionLevel === DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.Custom);
};
/**
* @internal Resets this DelegateFolderPermission.
*/
DelegateFolderPermission.prototype.Reset = function () {
this.Initialize(DelegateFolderPermissionLevel_1.DelegateFolderPermissionLevel.None);
};
return DelegateFolderPermission;
}());
|
import Element from './Element'
import Text from './Text'
import RunFormat from './RunFormat'
import Run from './Run'
import ParagraphFormat from './ParagraphFormat'
import Paragraph from './Paragraph'
import TableFormat from './TableFormat'
import Table from './Table'
import Section from './Section'
import File from './File'
import Document from './Document'
import { version } from '../package.json'
export {
Element,
Text,
RunFormat,
Run,
ParagraphFormat,
Paragraph,
TableFormat,
Table,
Section,
File,
Document,
version
}
|
import { connectModule } from '../../lib/phoneContext';
import DialerPanel from '../../components/DialerPanel';
export default connectModule((phone) => phone.dialerUI)(DialerPanel);
|
// Generated by CoffeeScript 1.6.3
(function() {
var Console, FileSystem, colors, _data,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
colors = require('colors');
module.exports = {
Console: Console = (function() {
var MODE_REPL, MODE_RUN;
MODE_REPL = 0;
MODE_RUN = 1;
Console.prototype.buffer = null;
Console.prototype.vars = null;
Console.prototype.paused = false;
Console.prototype.prompt = '';
Console.prototype.altPrompt = '?';
function Console(prompt) {
var stdin;
this.prompt = prompt != null ? prompt : 'katra> ';
this.pause = __bind(this.pause, this);
this.listener = __bind(this.listener, this);
stdin = process.openStdin();
process.stdout.write(this.prompt);
stdin.addListener("data", this.listener);
}
Console.prototype.listener = function($data) {
this.commandHandle($data.toString());
if (this.mode === MODE_REPL) {
if (!this.paused) {
return process.stdout.write(this.prompt);
}
} else {
return process.stdout.write(this.altPrompt);
}
};
Console.prototype.setPrompt = function($prompt) {};
Console.prototype.pause = function($set) {
if (this.paused === $set) {
return;
}
if ((this.paused = $set)) {
return process.stdin.removeListener("data", this.listener);
} else {
process.stdin.addListener("data", this.listener);
if (this.mode === MODE_REPL) {
return process.stdout.write(this.prompt);
} else {
return process.stdout.write(this.altPrompt);
}
}
};
Console.prototype.input = function($prompt, $vars) {
if (this.paused) {
this.pause(false);
}
if ($prompt != null) {
this.print($prompt);
}
this.buffer = [];
this.vars = $vars;
return true;
};
Console.prototype.debug = function($text) {
return process.stdout.write($text.blue + '\n');
};
Console.prototype.hilite = function($text) {
return process.stdout.write($text.yellow + '\n');
};
Console.prototype.print = function($text) {
if ($text == null) {
$text = '';
}
return process.stdout.write($text);
};
Console.prototype.println = function($text) {
if ($text == null) {
$text = '';
}
return process.stdout.write($text + '\n');
};
Console.prototype.clear = function() {};
return Console;
})(),
FileSystem: FileSystem = (function() {
var $root, fs, path;
function FileSystem() {}
fs = require('fs');
path = require('path');
$root = __dirname.slice(0, +__dirname.lastIndexOf('/') + 1 || 9e9);
FileSystem.prototype.setRoot = function($path) {
return $root = $path;
};
FileSystem.prototype.readFile = function($filename, $next) {
return fs.readFile(path.join($root, $filename) + '.bas', function($err, $data) {
if ($err != null) {
return $next($err);
} else {
return $next(null, String($data));
}
});
};
FileSystem.prototype.writeFile = function($filename, $data, $next) {
return fs.writeFile(path.join($root, $filename) + '.bas', "" + $filename + "\n\n" + $data, $next);
};
FileSystem.prototype.deleteFile = function($filename, $next) {
return fs.unlink(path.join($root, $filename) + '.bas', $next);
};
FileSystem.prototype.readDir = function($dir, $next) {
return fs.readdir($root + _data[$dir], function($err, $files) {
var $name;
if ($err != null) {
return $next([]);
} else {
return $next((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = $files.length; _i < _len; _i++) {
$name = $files[_i];
if (/.*\.bas$/.test($name)) {
_results.push($name);
}
}
return _results;
})());
}
});
};
return FileSystem;
})()
};
_data = {
ATARI: 'bas/atari/',
GWBASIC: 'bas/gwbasic/',
GROUP: 'bas/hp2k/group/',
LIBRARY: 'bas/hp2k/system/',
TEST: 'bas/hp2k/test/',
CATALOG: 'bas/hp2k/'
};
}).call(this);
|
var Joi = require('joi');
var ObjectAssign = require('object-assign');
var BaseModel = require('hapi-mongo-models').BaseModel;
var Slug = require('slug');
var AdminGroup = BaseModel.extend({
constructor: function (attrs) {
ObjectAssign(this, attrs);
},
hasPermissionTo: function (permission) {
if (this.permissions && this.permissions.hasOwnProperty(permission)) {
return this.permissions[permission];
}
return false;
}
});
AdminGroup._collection = 'adminGroups';
AdminGroup._idClass = String;
AdminGroup.schema = Joi.object().keys({
_id: Joi.string(),
name: Joi.string().required(),
permissions: Joi.object().description('{ permission: boolean, ... }')
});
AdminGroup.create = function (name, callback) {
var document = {
_id: Slug(name).toLowerCase(),
name: name
};
this.insertOne(document, function (err, docs) {
if (err) {
return callback(err);
}
callback(null, docs[0]);
});
};
module.exports = AdminGroup;
|
/*
Copyright 2013, KISSY UI Library v1.40dev
MIT Licensed
build time: Aug 14 23:54
*/
KISSY.add("editor/plugin/dent-cmd",function(m,q,r){function s(c){return c.nodeType==k.NodeType.ELEMENT_NODE&&"li"==k.nodeName(c)}function v(c,d,e){for(var f=c.startContainer,a=c.endContainer;f&&!f.parent().equals(d);)f=f.parent();for(;a&&!a.parent().equals(d);)a=a.parent();if(f&&a){for(var b=f,f=[],i=!1;!i;)b.equals(a)&&(i=!0),f.push(b),b=b.next();if(!(1>f.length)){var g=d._4e_parents(!0,void 0);g.each(function(a,b){g[b]=a});for(a=0;a<g.length;a++)if(n[g[a].nodeName()]){d=g[a];break}for(var b="indent"==
e?1:-1,a=f[0],i=f[f.length-1],f={},h=r.listToArray(d,f),o=h[i.data("listarray_index")].indent,a=a.data("listarray_index");a<=i.data("listarray_index");a++){h[a].indent+=b;var m=h[a].parent;h[a].parent=new t(m[0].ownerDocument.createElement(m.nodeName()))}for(a=i.data("listarray_index")+1;a<h.length&&h[a].indent>o;a++)h[a].indent+=b;i=r.arrayToList(h,f,null,"p");b=[];if("outdent"==e){var l;if((l=d.parent())&&"li"==l.nodeName())for(var e=i.listNode.childNodes,j,a=e.length-1;0<=a;a--)(j=new t(e[a]))&&
"li"==j.nodeName()&&b.push(j)}i&&(k.insertBefore(i.listNode[0]||i.listNode,d[0]||d),d.remove());if(b&&b.length)for(a=0;a<b.length;a++){for(j=d=b[a];(j=j.next())&&j.nodeName()in n;)w.ie&&!d.first(function(a){return x(a)&&y(a)},1)&&d[0].appendChild(c.document.createTextNode("\u00a0")),d[0].appendChild(j[0]);k.insertAfter(d[0],l[0])}q.Utils.clearAllMarkers(f)}}}function u(c,d){var e=parseInt(c.style(l),10);isNaN(e)&&(e=0);e+=("indent"==d?1:-1)*p;if(0>e)return!1;e=Math.max(e,0);e=Math.ceil(e/p)*p;c.css(l,
e?e+z:"");""===c[0].style.cssText&&c.removeAttr("style");return!0}var n={ol:1,ul:1},o=q.Walker,k=m.DOM,t=m.Node,w=m.UA,x=o.whitespaces(!0),l="margin-left",p=40,z="px",y=o.bookmark(!1,!0);return{checkOutdentActive:function(c){var d=c.blockLimit;return c.contains(n)?!0:(c=c.block||d)&&c.style(l)},addCommand:function(c,d){c.hasCommand(d)||c.addCommand(d,{exec:function(e){e.execCommand("save");var f=e.getSelection(),a=f&&f.getRanges()[0];if(a){for(var b=a.startContainer,c=a.endContainer,g=a.getCommonAncestor();g&&
!(g[0].nodeType==k.NodeType.ELEMENT_NODE&&n[g.nodeName()]);)g=g.parent();g&&b[0].nodeType==k.NodeType.ELEMENT_NODE&&b.nodeName()in n&&(b=new o(a),b.evaluator=s,a.startContainer=b.next());g&&c[0].nodeType==k.NodeType.ELEMENT_NODE&&c.nodeName()in n&&(b=new o(a),b.evaluator=s,a.endContainer=b.previous());c=f.createBookmarks(!0);if(g){for(b=g.first();b&&"li"!=b.nodeName();)b=b.next();var h=a.startContainer;(!(b[0]==h[0]||b.contains(h))||!u(g,d))&&v(a,g,d)}else{a=a.createIterator();a.enforceRealBlocks=
!0;for(a.enlargeBr=!0;g=a.getNextParagraph();)u(g,d)}f.selectBookmarks(c)}e.execCommand("save");e.notifySelectionChange()}})}}},{requires:["editor","./list-utils"]});
|
import _isArray from "./internal/is_array";
/**
* Returns `true` if the argument is an atom; `false` otherwise. An atom is defined as any
* value that is not an array, `undefined`, or `null`.
*
* @func
* @memberOf R
* @category Array
* @sig a -> Boolean
* @param {*} x The element to consider.
* @return {boolean} `true` if `x` is an atom, and `false` otherwise.
* @example
*
* ramda.isAtom([]); //=> false
* ramda.isAtom(null); //=> false
* ramda.isAtom(undefined); //=> false
*
* ramda.isAtom(0); //=> true
* ramda.isAtom(''); //=> true
* ramda.isAtom('test'); //=> true
* ramda.isAtom({}); //=> true
*/
export default function(x) {
return x != null && !_isArray(x);
};
|
define([
'app-lib/vstack'
], function(vstack) {
/*
afterAll(function(done) {
vstack.dropTables().then(function() {
done();
});
});
*/
describe("test that createTables vstack works when tables exist.", function() {
it("returns successfully", function(done) {
done();
vstack.createTables().then(function() {
expect(true).toBeTruthy();
done();
});
});
});
});
|
var gulp = require('gulp');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var awsLambda = require("node-aws-lambda");
gulp.task('clean', function() {
return del(['./dist', './dist.zip']);
});
gulp.task('js', function() {
return gulp.src('index.js')
.pipe(gulp.dest('dist/'));
});
gulp.task('node-mods', function() {
return gulp.src('./package.json')
.pipe(gulp.dest('dist/'))
.pipe(install({production: true}));
});
gulp.task('zip', function() {
return gulp.src(['dist/**/*', '!dist/package.json'])
.pipe(zip('dist.zip'))
.pipe(gulp.dest('./'));
});
gulp.task('upload', function(callback) {
awsLambda.deploy('./dist.zip', require("./lambda-config.js"), callback);
});
gulp.task('deploy', function(callback) {
return runSequence(
['clean'],
['js', 'node-mods'],
['zip'],
['upload'],
callback
);
});
|
// Use this mixin at HTML/BODY level to enable pjax behavior
// Your fluxexapp should provide routeToURL() for this mixin
// See routeToURL.js for more info
//
// To support IE8,
// You will need to npm install html5-history-api,
// then add require('fluxex/extra/history'); in your fluxexapp.js
module.exports = {
componentDidMount: function () {
/*global window,document*/
var blockDoublePop = (document.readyState !== 'complete'),
initState = JSON.stringify(this._getContext()._context),
location = window.history.location || window.location,
initUrl = location.href;
window.addEventListener('load', function() {
setTimeout(function () {
blockDoublePop = false;
}, 1);
});
window.addEventListener('popstate', function (E) {
var state = E.state || ((location.href === initUrl) ? initState : undefined);
if (blockDoublePop && (document.readyState === 'complete')) {
return;
}
try {
state = JSON.parse(state);
} catch (E) {
state = 0;
}
if (!state) {
// NO STATE DATA....can not re-render, so reload.
location.reload();
return;
}
// Ya, trigger page restore by an anonymous action
this.executeAction(function () {
this._restore(state);
this.dispatch('**UPDATEALL**');
return Promise.resolve(true);
}.bind(this._getContext()));
}.bind(this));
},
handleClickLink: function (E) {
var A = E.target.closest('a[href]') || E.target;
var HREF = A.href;
if (!HREF || HREF.match(/#/) || (A.target === '_blank')) {
return;
}
if ((A.target === '_top') && (window.top !== window)) {
return;
}
if ((A.target === '_parent') && (window.parent !== window)) {
return;
}
E.preventDefault();
E.stopPropagation();
return this._getContext().routeToURL(HREF);
}
};
|
import angular from 'angular';
import { Inject, Bind } from 'angular-es-utils';
import {hasScrolled} from '../../../common/utils/style-helper';
import { isPromiseLike } from 'angular-es-utils/type-auth';
@Inject('$scope', '$element')
export default class DropdownSelectCtrl {
// 选项 item 字段映射
static defaultMapping = {
valueField: 'value',
displayField: 'title',
iconField: 'icon'
};
constructor() {
this.datalist = [];
this._clampedDatalist = [];
this.items = [];
this.mapping = {};
this.title = '';
this.placeholder = '';
this.searchable = false;
this.supportInputValue = false;
this.model = null;
this.focusIndex = 0;
this.isOpen = false;
this.autoClose = true;
this.isActive = false;
this.oldText = '';
this.containerElement = null;
this.onSelectChange = () => {};
this.onDropdownOpen = () => {};
this.onDropdownClose = () => {};
this._openFn = null;
}
$onInit() {
this._prepareOptions();
this._prepareWatches();
}
$postLink() {
this._prepareMouseEvents();
this._prepareKeyboardEvents();
}
_prepareOptions() {
const defaultMapping = DropdownSelectCtrl.defaultMapping;
this.mapping = Object.assign({}, defaultMapping, this.mapping);
this.items = this._getClampedDatalist(this.datalist || []);
if (typeof this.autoClose !== 'undefined' && this.autoClose !== false) {
this.autoClose = true;
}
if (typeof this.disabled === 'undefined') {
this.disabled = false;
}
this.onSelectChange = this.onSelectChange || (() => {});
}
_prepareWatches() {
const scope = this.getScope();
scope.$watch(() => this.datalist, (datalist, oldDatalist) => {
this.model = this.modelCopy ? this.modelCopy : this.model;
this.items = this._clampedDatalist = this._getClampedDatalist(datalist || []);
// TODO: SB requirement
if (this.supportInputValue) {
this._searchText = this.model;
}
// 选中预设值
this.setModelValue(this.model);
// 设置预设值的 focusIndex
this.focusAt(this.getItemIndexByItemValue(this.model, this.items));
});
scope.$watch(() => this.model, (model, oldModel) => {
if (this.model && (!this.items || !this.items.length)) {
this.modelCopy = this.model;
}
if (!angular.equals(model, oldModel)) {
const item = this.getItemByValue(this.model);
const itemIndex = this.getItemIndexByItemValue(this.model, this.items);
if (this.supportInputValue) {
this._searchText = this.model;
}
this.setModelValue(this.model);
this.focusAt(itemIndex);
// 增加回调参数 itemIndex item
this.onSelectChange({ model, oldModel, itemIndex, item });
}
});
scope.$watch(() => this.isOpen, (openState, oldOpenstate) => {
if (this.disabled && openState) {
this.isOpen = false;
}
});
}
_prepareMouseEvents() {
let inputElement = this.getInputElement();
if (!this.searchable) {
inputElement.addEventListener('click', this.toggle);
} else {
this._openFn = this::(event => {
let scope = this.getScope();
this.open();
scope.$root.$$phase || scope.$apply();
inputElement.removeEventListener('click', this._openFn);
});
inputElement.addEventListener('click', this._openFn);
}
}
_prepareKeyboardEvents() {
let keydownFn = event => {
let scope = this.getScope();
let keyCode = event.keyCode;
if (!this.isOpen) {
// 下拉激活且关闭时,按 回车、上、下 键打开下拉
if (keyCode === 13 || keyCode === 38 || keyCode === 40) {
this.open();
}
} else {
switch (keyCode) {
case 13: // enter
this.selectItemAt(this.focusIndex);
break;
case 38: // up
this.focusUp();
event.preventDefault();
break;
case 40: // down
this.focusDown();
event.preventDefault();
break;
default:
}
}
scope.$root.$$phase || scope.$digest();
};
this.getScope().$watch(() => this.isActive, (isActive, oldState) => {
if (isActive !== oldState) {
let inputElement = this.getInputElement();
if (isActive) {
inputElement.addEventListener('keydown', keydownFn);
} else {
inputElement.removeEventListener('keydown', keydownFn);
}
}
});
}
onSearchTextChange(text) {
this._searchText = text;
if (text !== this.oldText) {
this.oldText = text;
text = text.trim();
if (!this.isOpen) {
this.open();
}
if (text.length) {
this._search(text);
} else {
this.setModelValue(null);
this.items = this._clampedDatalist;
}
this.focusAt(0);
}
}
onOpen() {
let scope = this.getScope();
const input = this.getInputElement();
input.focus();
if (this.searchable && this.title && this.title.length) {
this._search(this.title);
this.focusAt(0);
scope.$root.$$phase || scope.$apply();
}
// 如果有下拉选项框有滚动条, 且滚动条没有置顶, 进行置顶
const itemList = this.getItemListElement();
if (hasScrolled(itemList) && itemList.scrollTop !== 0) {
itemList.scrollTop = 0;
}
const containerHeight = this.containerElement ? this.containerElement.getClientRects()[0].bottom : document.documentElement.clientHeight;
// 将菜单滚动到可视区域
if (input.getClientRects()[0].bottom + itemList.getClientRects()[0].height > containerHeight) {
itemList.scrollIntoView({behavior: 'smooth', block: 'end', inline: 'nearest'});
}
this.onDropdownOpen();
}
onClose() {
let scope = this.getScope();
if (this.searchable) {
this.getInputElement().addEventListener('click', this._openFn);
this.setModelValue(this.model);
scope.$root.$$phase || scope.$apply();
}
this.onDropdownClose();
}
getItemByValue(value) {
const valueField = this.mapping.valueField;
return this.items.find(item => angular.equals(item[valueField], value));
}
setModelValue(modelValue) {
const displayField = this.mapping.displayField;
const iconField = this.mapping.iconField;
const newItem = this.getItemByValue(modelValue);
if (newItem) {
this.title = newItem[displayField];
this.model = modelValue;
this.icon = newItem[iconField];
} else {
if (this.supportInputValue) {
this.title = this._searchText;
this.model = this._searchText;
this.icon = false;
this.items = this._clampedDatalist;
} else {
this.title = '';
this.model = null;
this.icon = false;
this.items = this._clampedDatalist;
}
}
}
clear() {
this._searchText = null;
this.modelCopy = null;
this.setModelValue(null);
this.getInputElement().focus();
this.focusAt(0);
}
@Bind
toggle() {
let scope = this.getScope();
if (this.isOpen) {
this.close();
} else {
this.open();
}
scope.$root.$$phase || scope.$apply();
}
open() {
this.isOpen = true;
}
close() {
this.isOpen = false;
}
selectItemAt(index) {
const item = this.items[index];
const scope = this.getScope();
if (!item) {
return;
}
this.onBeforeSelectChange = this.onBeforeSelectChange || (() => Promise.resolve());
let callbackResult = this.onBeforeSelectChange({ item });
if (!isPromiseLike(callbackResult)) {
callbackResult = Promise.resolve(callbackResult);
}
callbackResult
.then(() => {
scope.$evalAsync(() => {
this.title = item[this.mapping.displayField];
this.model = item[this.mapping.valueField];
this.icon = item[this.mapping.iconField];
this.focusAt(index);
this.close();
});
})
.catch(() => {
scope.$evalAsync(() => this.close());
});
// todo Promise.prototype.finally travis-ci 暂时不支持等支持后修改
}
focusAt(index) {
this.focusIndex = index;
}
focusUp() {
let index = this.focusIndex - 1;
if (index < 0) {
index = 0;
}
this.focusAt(index);
let itemElement = this.getItemElementAt(index);
if (itemElement) {
itemElement.scrollIntoView(true);
}
}
focusDown() {
let listCount = this.items.length;
let index = this.focusIndex + 1;
if (index > listCount - 1) {
index = listCount - 1;
}
this.focusAt(index);
let itemElement = this.getItemElementAt(index);
if (itemElement) {
itemElement.scrollIntoView(false);
}
}
getElement() {
return this._$element[0];
}
getInputElement() {
return this.getElement().querySelector('.dropdown-select-input');
}
getItemListElement() {
return this.getElement()
.querySelector('.dropdown-list');
}
getItemElementAt(index) {
return this.getItemListElement()
.querySelectorAll('li:not(.empty-list-item)')[index];
}
getScope() {
return this._$scope;
}
highlight(content, hiText) {
if (!this.searchable || !hiText) {
return content;
}
return content.replace(new RegExp(hiText, 'gi'), '<span class="highlight">$&</span>');
}
getItemIndexByItemValue(ItemValue, items) {
return items.findIndex(item => {
return item[this.mapping.valueField] === ItemValue;
});
}
_getClampedDatalist(datalist) {
// 将每个 item 构造为对象
// e.g. 将 ['北京', '上海'] 构造为
// [{title: '北京', value: '北京'}, {title: '上海', value: '上海'}]
return datalist.map(item => {
if (typeof item !== 'object') {
return {
[this.mapping.displayField]: item,
[this.mapping.valueField]: item
};
} else {
return item;
}
});
}
_search(text) {
let datalist = this._clampedDatalist;
let mapping = this.mapping;
let searchFields = [mapping.valueField, mapping.displayField];
let filteredItems = [];
searchFields.forEach(field => {
datalist.forEach(item => {
const fieldValue = item[field];
if (fieldValue.toString().toLocaleUpperCase().indexOf(text && text.toLocaleUpperCase()) !== -1 &&
filteredItems.indexOf(item) === -1) {
filteredItems.push(item);
}
});
});
this.items = filteredItems;
}
};
|
import dispatcher from "../stores/dispatcher";
export function createPosts(post) {
dispatcher.dispatch({
type: "CREATE_POST",
post
});
}
export function deletePost(id) {
dispatcher.dispatch({
type: "DELETE_POST",
id
})
}
|
/**
* @param {number} c
* @return {boolean}
*/
const judgeSquareSum = function (c) {
for (let i = 0; i <= Math.sqrt(c / 2); ++i) {
let x = c - i * i;
let sqrtX = Math.sqrt(x);
if (sqrtX === Math.floor(sqrtX)) {
return true;
}
}
return false;
};
module.exports = judgeSquareSum;
|
export default {
dialPlaceholder: "Name oder Nr. eingeben"
};
// @key: @#@"dialPlaceholder"@#@ @source: @#@"Enter Name or Number"@#@
|
define([
'streamhub-sdk/content/views/content-list-view',
'streamhub-gallery/content/content-view-factory',
'text!streamhub-gallery/css/horizontal-list-view.css',
'streamhub-sdk/debug',
'inherits'
], function (ContentListView, HorizontalContentViewFactory, HorizontalListViewCss, debug, inherits) {
'use strict';
var log = debug('streamhub-gallery/views/horizontal-list-view');
var STYLE_EL;
/**
* A simple View that displays Content in a horizontal list.
*
* @param opts {Object} A set of options to config the view with
* @param opts.el {HTMLElement} The element in which to render the streamed content
* @exports streamhub-gallery/views/horizontal-list-view
* @augments streamhub-sdk/views/list-view
* @constructor
*/
var HorizontalListView = function (opts) {
opts = opts || {};
this._id = 'streamhub-horizontal-list-'+new Date().getTime();
this._aspectRatio = opts.aspectRatio || 16/9;
opts.contentViewFactory = new HorizontalContentViewFactory();
ContentListView.call(this, opts);
if (!STYLE_EL) {
STYLE_EL = $('<style></style>').text(HorizontalListViewCss).prependTo('head');
}
var self = this;
$(window).on('resize', function (e) {
self._handleResize(e);
});
this._adjustContentSize();
};
inherits(HorizontalListView, ContentListView);
HorizontalListView.prototype.horizontalListViewClassName = 'streamhub-horizontal-list-view';
HorizontalListView.prototype.contentContainerClassName = 'content-container';
/**
* Set the element for the view to render in.
* You will probably want to call .render() after this, but not always.
* @param element {HTMLElement} The element to render this View in
* @return this
*/
HorizontalListView.prototype.setElement = function (el) {
ContentListView.prototype.setElement.call(this, el);
this.$el.addClass(this.horizontalListViewClassName).addClass(this._id);
};
HorizontalListView.prototype._handleResize = function (e) {
this._adjustContentSize();
};
/**
* @private
* Sets appropriate dimensions on each ContentView in the gallery.
* By default, a ContentViews new dimensions respects the gallery's specified aspect ratio.
* For content whose intrinsic apsect ratio is 1:1, it will retain a 1:1 aspect ratio.
* ContentViews with tiled attachments will also retain a 1:1 aspect ratio.
*/
HorizontalListView.prototype._adjustContentSize = function () {
if (! this._aspectRatio) {
return;
}
var styleEl = $('style.'+this._id);
if (styleEl) {
styleEl.remove();
}
styleEl = $('<style class="'+this._id+'"></style>');
var styles = '';
var containerHeight = this.$el.height();
var contentWidth = containerHeight * this._aspectRatio;
styles = '.'+this.horizontalListViewClassName + ' .'+this.contentContainerClassName + '{ max-width: ' + contentWidth + 'px; }';
styleEl.html(styles);
$('head').append(styleEl);
return styleEl;
};
/**
* @private
* Insert a contentView into the ListView's .el
* after being wrapped by a container element.
* Get insertion index based on this.comparator
* @param contentView {ContentView} The ContentView's element to insert to the DOM
*/
HorizontalListView.prototype._insert = function (contentView) {
var newContentViewIndex,
$previousEl;
newContentViewIndex = this.views.indexOf(contentView);
var $containerEl = $('<div class="' + this.contentContainerClassName + '"></div>');
contentView.$el.wrap($containerEl);
var $wrappedEl = contentView.$el.parent();
if (newContentViewIndex === 0) {
// Beginning!
$wrappedEl.prependTo(this.el);
} else {
// Find it's previous contentView and insert new contentView after
$previousEl = this.views[newContentViewIndex - 1].$el;
$wrappedEl.insertAfter($previousEl.parent('.'+this.contentContainerClassName));
}
this.$el.css('width', this.views.length * this.views[0].$el.parent().outerWidth(true) + 'px');
};
return HorizontalListView;
});
|
(function() {
'use strict';
/**
* @name RootController
* @description The root controller that contains some rootScope accessible methods
* @memberof ag
*/
angular.module('ag').controller('RootController', getRootController);
var inject = ['$rootScope'];
getRootController.$inject = inject;
function getRootController($rootScope) {
// Method visible in the entire app and
// allows to start the loading spinner
$rootScope.startLoading = function() {
$rootScope.root.loading = true;
$rootScope.root.loadingQueue++;
};
// Method visible in the entire app and
// allows to stop the loading spinner
$rootScope.endLoading = function() {
$rootScope.root.loadingQueue--;
// Prevent bad call of the function
if ($rootScope.root.loadingQueue < 0) {
$rootScope.root.loadingQueue = 0;
}
if ($rootScope.root.loadingQueue === 0) {
$rootScope.root.loading = false;
}
};
}
})();
|
'use strict';
/**
* @ngdoc function
* @name wavesApp.controller:EventsCtrl
* @description
* # EventsCtrl
* Controller of the wavesApp
*/
angular.module('wavesApp')
.controller('EventsCtrl', ['$scope', function ($scope) {
$scope.events = [
'Evento1', 'Evento2', 'Evento3', 'Evento4', 'Evento5', 'Evento6', 'Evento7'
];
}]);
|
'use strict';
angular.module('core.admin').run(['Menus',
function (Menus) {
Menus.addMenuItem('topbar', {
title: 'Admin',
state: 'admin',
type: 'dropdown',
roles: ['admin']
});
Menus.addSubMenuItem('topbar', 'admin', {
title: 'Dashboard',
state: 'admin.dashboard',
type: 'dropdown',
roles: ['admin']
});
}
]);
|
'use strict';
angular.module('vppApp')
.factory('User', function ($resource) {
// TODO
});
|
/**
* 所有组件的基类
*/
class BaseModule {
constructor() {
//this.__exp 接口引用,使用实例绑定上下文,不直接使用
//this.__exports 接口引用,未绑定上下文,不直接使用
//this.exports 提供设置和获取暴露接口的get、set,
}
get exports() {
return this.__exp;
}
set exports(exp_s) {
var context = this;
//用于编译时候的原始方法备份,防止编译出[native code]
var __exports = context.__exports = {};
var es = this.__exp = exp_s;
for(var exp in es){
if(es.hasOwnProperty(exp) && es[exp] instanceof Function){
__exports[exp] = es[exp];
es[exp] = es[exp].bind(context)
}
}
return context
}
//bindExports(context){
// //用于编译时候的原始方法备份,防止编译出[native code]
// var __exports = context.__exports = {};
// var es = context.exports
//
// for(var exp in es){
// if(es.hasOwnProperty(exp)){
// __exports[exp] = es[exp];
// es[exp] = es[exp].bind(context)
// }
// }
// return context
//}
//获取所有可编辑、配置的项,默认写法,可被重写
superFields() {
if(!this.element){
return undefined
}
//var param = this.element.param || {}
var $html;
if(this.configs instanceof Function){
$html = $(this.configs(this.element))
}else{
$html = $(this.configs)
}
//$html.find("[data-name]").each(function (i, n) {
// var $this = $(n)
// $this.val(param[$this.data("name")]);
//});
return $html;
}
fields(deferred, param) {
deferred.resolve(this.superFields())
}
config(key, value) {
var data = this.$dom.data("data")
if (arguments.length === 1) {
return data.param[key]
} else if (arguments.length > 1) {
return data.param[key] = value;
}
}
exec(code,api){
try{
var fun = new Function("api","" +
"var API = api;"
+code)
fun(api)
}catch(e){
console.log(e)
}
}
}
module.exports = BaseModule
|
/* globals __DEV__ */
import Phaser from 'phaser'
import Player from '../sprites/Player'
import Asteroid from '../sprites/Asteroid'
import Space from '../environment/Space'
import Bullet from '../sprites/Bullet'
import Pickup from '../sprites/Pickup'
import Overlay from '../UI/overlay'
import AsteroidDefinitions from '../definitions/asteroidDefinitions'
import LevelDefinitions from '../definitions/levelDefintions'
const ASTEROID_COUNT = 25;
const NO_FIRE_COOLDOWN = 400;
const INVULNERABLE_AFTER_DAMAGE_COOLDOWN = 2000;
const STARTING_BULLETS = 100;
const STARTING_TIMER = 5000;
export default class extends Phaser.State {
init() { }
preload() {
game.load.audio('bullet', 'assets/audio/SoundEffects/laser.wav');
game.load.audio('explosion', 'assets/audio/SoundEffects/explosion.wav');
game.load.audio('music', 'assets/audio/Music/Corruption.mp3');
game.load.audio('damage', 'assets/audio/SoundEffects/alarm.wav');
game.load.audio('noammo', 'assets/audio/SoundEffects/noammo.wav');
game.load.audio('death', 'assets/audio/SoundEffects/bigboom.wav');
game.load.audio('victory', 'assets/audio/SoundEffects/chime.wav');
game.load.audio('reload', 'assets/audio/SoundEffects/reload.mp3');
game.load.audio('powerup', 'assets/audio/SoundEffects/powerup.wav');
game.load.audio('powerdown', 'assets/audio/SoundEffects/powerdown.wav');
}
create() {
this.game.physics.startSystem(Phaser.Physics.ARCADE);
this.space = new Space(this);
this.player = new Player({
game: this,
x: this.world.centerX,
y: this.world.centerY,
asset: 'ship'
});
this.player.resetPosition();
this.game.add.existing(this.player);
this.fireCooldown = NO_FIRE_COOLDOWN;
this.playerScore = 0;
this.waveNumber = 0;
this.gameTimer = STARTING_TIMER;
this.inbetweenWave = false;
this.bullets = [];
this.asteroids = [];
this.pickups = [];
this.asteroidsGroup = this.game.add.group();
this.overlay = new Overlay({
game: this.game,
player: this.player,
wave: this.waveNumber
});
// Sound
this.sfxBullet = game.add.audio('bullet');
this.sfxExplosion = game.add.audio('explosion');
this.sfxDamage = game.add.audio('damage');
this.sfxNoAmmo = game.add.audio('noammo');
this.sfxDeath = game.add.audio('death');
this.sfxVictory = game.add.audio('victory');
this.sfxReload = game.add.audio('reload');
this.sfxPowerup = game.add.audio('powerup');
this.sfxPowerdown = game.add.audio('powerdown');
this.music = game.add.audio('music');
this.music.loopFull(1);
// particles
this.particleEmitter = game.add.emitter(0, 0, 300);
this.particleEmitter.makeParticles('asteroidParticle');
this.particleEmitter.minParticleSpeed.setTo(-100, -100);
this.particleEmitter.maxParticleSpeed.setTo(100, 100);
this.fireParticleEmitter = game.add.emitter(0, 0, 300);
this.fireParticleEmitter.makeParticles('fireParticle');
this.fireParticleEmitter.minParticleSpeed.setTo(0, 0);
this.fireParticleEmitter.maxParticleSpeed.setTo(0, 0);
}
update() {
this.game.physics.arcade.collide(this.asteroidsGroup);
this.overlay.update(this.waveNumber, this.gameTimer, this.inbetweenWave);
this.fireCooldown -= this.getDelta();
if (this.player.isAlive() && !this.inbetweenWave) {
this.gameTimer -= this.getDelta();
}
// if game time is out, destroy player
if (this.player.isAlive() && this.gameTimer <= 0) {
this.player.changeHealth(-999);
this.endGame();
}
this.space.update();
// damage player if they are hitting an asteroid
if (!this.player.isInvulnerable() && this.player.isCollidingWithAnyInArray(this.asteroids) && this.player.isAlive() > 0) {
this.player.changeHealth(-1);
if (!this.player.isAlive()) {
this.endGame();
} else if (this.player.isAlive()){
this.sfxDamage.play();
this.player.setInvulnerable(INVULNERABLE_AFTER_DAMAGE_COOLDOWN);
}
}
// assign pickup bonuses if player is close enough
for (var i = 0; i < this.pickups.length; i++) {
var pickup = this.pickups[i];
if (pickup.isCollidingWithEntity(this.player)) {
pickup.applyPowerup();
pickup.destroy();
this.pickups.splice(i, 1);
}
}
// clean up old bullets
for (var i = 0; i < this.bullets.length; i++) {
var b = this.bullets[i];
var destroyBullet = false;
b.update();
// damage or destroy and asteroids this bullet is in contact with
for (var j = 0; j < this.asteroids.length; j++) {
var asteroid = this.asteroids[j];
if (b.isCollidingWithEntity(asteroid)) {
destroyBullet = true;
asteroid.damage(b.getDamage());
this.sfxExplosion.play();
if (asteroid.hp <= 0) {
this.asteroids.splice(j, 1);
asteroid.destroy();
this.player.score += asteroid.getProfitValue();
}
}
}
// destroy any pickups this bullet is in contact with
for (var j = 0; j < this.pickups.length; j++) {
var pickup = this.pickups[j];
if (pickup.isCollidingWithEntity(b)) {
destroyBullet = true;
this.pickups.splice(j, 1);
pickup.destroy();
this.sfxPowerdown.play();
}
}
if (b.isOutOfBounds() || destroyBullet) {
this.bullets.splice(i, 1);
b.destroy();
}
}
if (this.waveComplete()) {
this.game.time.events.add(3000, function() {
this.startWave();
}, this);
}
}
spawnObject(type) {
var location = this.getRandomPositionNotNearPlayer();
var asteroid = new Asteroid({
game: this,
x: location.x,
y: location.y,
asset: 'asteroid',
type: type
});
this.asteroidsGroup.add(asteroid);
this.asteroids.push(asteroid);
}
spawnAsteroids() {
var levelDefinition = LevelDefinitions[this.waveNumber - 1].enemies;
for (var key in levelDefinition) {
for (var i = 0; i < levelDefinition[key]; i++) {
this.spawnObject(key);
}
}
this.asteroidsGroup.enableBody = true;
this.asteroidsGroup.physicsBodyType = Phaser.Physics.ARCADE;
this.asteroidsGroup.setAll('body.collideWorldBounds', true);
this.asteroidsGroup.setAll('body.bounce.x', 1);
this.asteroidsGroup.setAll('body.bounce.y', 1);
}
spawnPickup(type) {
var pickup = new Pickup({
game: this,
x: Math.random() * this.world.width,
y: Math.random() * this.world.height,
asset: type
});
game.add.existing(pickup);
this.pickups.push(pickup);
}
spawnPickups() {
var levelDefinition = LevelDefinitions[this.waveNumber - 1].pickups;
for (var key in levelDefinition) {
for (var i = 0; i < levelDefinition[key]; i++) {
this.spawnPickup(key);
}
}
}
addBullets() {
if (this.fireCooldown > 0) {
return;
} else if (this.player.bullets <= 0) {
this.sfxNoAmmo.play();
return;
} else {
this.fireCooldown = NO_FIRE_COOLDOWN;
this.player.useBullet();
this.sfxBullet.play();
}
var ammotype = "regular";
if (this.player.hasPowerup()) {
ammotype = "strong";
}
for (var i = 0; i < 4; i++) {
var bullet1 = new Bullet({
game: this,
x: this.player.x,
y: this.player.y,
asset: 'bullet',
type: ammotype
});
if (i===0) {
bullet1.velocity.x = .3;
} else if (i===1) {
bullet1.velocity.x = -.3;
} else if (i===2) {
bullet1.velocity.y = .3;
} else {
bullet1.velocity.y = -.3;
}
this.bullets.push(bullet1);
this.game.add.existing(bullet1);
}
}
waveComplete() {
if (this.inbetweenWave === false && this.asteroidsGroup.countLiving() === 0) {
this.inbetweenWave = true;
return true;
}
return false;
}
startWave(wave) {
this.inbetweenWave = false;
if (this.waveNumber > 0) {
this.sfxVictory.play();
}
this.waveNumber++;
this.gameTimer += 20000;
this.player.resetPosition();
this.player.setInvulnerable(INVULNERABLE_AFTER_DAMAGE_COOLDOWN*2);;
this.player.giveBullets(10);
this.spawnAsteroids();
for (var pickup of this.pickups) {
pickup.destroy();
}
this.pickups = [];
this.spawnPickups();
}
endGame() {
this.player.destroy();
this.sfxDeath.play();
}
getRandomPositionNotNearPlayer() {
var distance = 0;
var output = {x: 0, y: 0};
while (distance < 150) {
output.x = Math.random() * this.world.width;
output.y = Math.random() * this.world.height;
distance = Math.sqrt((output.x - this.player.x) * (output.x - this.player.x) +
(output.y - this.player.y) * (output.y - this.player.y));
}
return output;
}
render() {
if (__DEV__) {
//this.game.debug.spriteInfo(this.mushroom, 32, 32)
}
}
getDelta() {
return this.time.now - this.time.prevTime;
}
}
|
var vows = require('vows'),
assert = require('assert');
var Generateur = require('./generateur.js');
vows.describe('Générateur')
.addBatch({
'A name - ': {
topic: new (Generateur),
'when is generated': {
topic: function (generateur) {
params = {};
return generateur.getName(params);
},
'it should have a name': function (result) {
assert.ok(result.name);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.addBatch({
'A funny name - ': {
topic: new (Generateur),
'when is generated': {
topic: function (generateur) {
params = {
funny: "true"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a param "funny" set to true': function (result) {
assert.equal(result.funny, true);
}
}
}
})
.addBatch({
'A not funny name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
funny: "false"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.addBatch({
'A male name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "M"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a male gender': function (result) {
assert.equal(result.gender, "M");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.addBatch({
'A female name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "F"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a female gender': function (result) {
assert.equal(result.gender, "F");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.addBatch({
'A funny female name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "F",
funny: "true"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a female gender': function (result) {
assert.equal(result.gender, "F");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, true);
}
}
}
})
.addBatch({
'A funny male name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "M",
funny: "true"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a male gender': function (result) {
assert.equal(result.gender, "M");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, true);
}
}
}
})
.addBatch({
'A not funny female name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "F",
funny: "false"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a female gender': function (result) {
assert.equal(result.gender, "F");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.addBatch({
'A not funny male name - ': {
topic: new (Generateur),
'when generated': {
topic: function (generateur) {
params = {
gender: "M",
funny: "false"
};
return generateur.getName(params);
},
'it should have a valid name': function (result) {
assert.equal(typeof(result.name), 'string')
},
'it should have a gender': function (result) {
assert.ok(result.gender);
},
'it should have a male gender': function (result) {
assert.equal(result.gender, "M");
},
'it should have a param "funny" set to false': function (result) {
assert.equal(result.funny, false);
}
}
}
})
.export(module);
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _jestDiff = require('jest-diff');
var _jestDiff2 = _interopRequireDefault(_jestDiff);
var _jestGetType = require('jest-get-type');
var _jestGetType2 = _interopRequireDefault(_jestGetType);
var _jestRegexUtil = require('jest-regex-util');
var _jestMatcherUtils = require('jest-matcher-utils');
var _utils = require('./utils');
var _jasmine_utils = require('./jasmine_utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
const matchers = {
toBe: function(received, expected) {
const comment = 'Object.is equality';
const pass = Object.is(received, expected);
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)('.toBe', undefined, undefined, {
comment: comment,
isNot: true
}) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(received)}`
: () => {
const suggestToEqual =
(0, _jestGetType2.default)(received) ===
(0, _jestGetType2.default)(expected) &&
((0, _jestGetType2.default)(received) === 'object' ||
(0, _jestGetType2.default)(expected) === 'array') &&
(0, _jasmine_utils.equals)(received, expected, [
_utils.iterableEquality
]);
const oneline = (0, _utils.isOneline)(expected, received);
const diffString = (0, _jestDiff2.default)(expected, received, {
expand: this.expand
});
return (
(0, _jestMatcherUtils.matcherHint)('.toBe', undefined, undefined, {
comment: comment,
isNot: false
}) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(received)}` +
(diffString && !oneline ? `\n\nDifference:\n\n${diffString}` : '') +
(suggestToEqual ? ` ${_jestMatcherUtils.SUGGEST_TO_EQUAL}` : '')
);
};
// Passing the the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual: received,
expected: expected,
message: message,
name: 'toBe',
pass: pass
};
},
toBeCloseTo: function(actual, expected) {
let precision =
arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
const secondArgument = arguments.length === 3 ? 'precision' : null;
(0, _jestMatcherUtils.ensureNumbers)(actual, expected, '.toBeCloseTo');
const pass = Math.abs(expected - actual) < Math.pow(10, -precision) / 2;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeCloseTo', undefined, undefined, {
isNot: this.isNot,
secondArgument: secondArgument
}) +
'\n\n' +
`Precision: ${(0, _jestMatcherUtils.printExpected)(precision)}-digit\n` +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeDefined: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeDefined');
const pass = actual !== void 0;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeDefined', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeFalsy: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeFalsy');
const pass = !actual;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeFalsy', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeGreaterThan: function(actual, expected) {
(0, _jestMatcherUtils.ensureNumbers)(actual, expected, '.toBeGreaterThan');
const pass = actual > expected;
const message = () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeGreaterThan',
undefined,
undefined,
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeGreaterThanOrEqual: function(actual, expected) {
(0, _jestMatcherUtils.ensureNumbers)(
actual,
expected,
'.toBeGreaterThanOrEqual'
);
const pass = actual >= expected;
const message = () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeGreaterThanOrEqual',
undefined,
undefined,
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeInstanceOf: function(received, constructor) {
const constType = (0, _jestGetType2.default)(constructor);
if (constType !== 'function') {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'.toBeInstanceOf',
'value',
'constructor',
{
isNot: this.isNot
}
) +
`\n\n` +
`Expected constructor to be a function. Instead got:\n` +
` ${(0, _jestMatcherUtils.printExpected)(constType)}`
);
}
const pass = received instanceof constructor;
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeInstanceOf',
'value',
'constructor',
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected constructor: ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
constructor.name || String(constructor)
)}\n` +
`Received value: ${(0, _jestMatcherUtils.printReceived)(received)}`
: () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeInstanceOf',
'value',
'constructor',
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected constructor: ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
constructor.name || String(constructor)
)}\n` +
`Received constructor: ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
received.constructor && received.constructor.name
)}\n` +
`Received value: ${(0, _jestMatcherUtils.printReceived)(received)}`;
return {message: message, pass: pass};
},
toBeLessThan: function(actual, expected) {
(0, _jestMatcherUtils.ensureNumbers)(actual, expected, '.toBeLessThan');
const pass = actual < expected;
const message = () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeLessThan',
undefined,
undefined,
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeLessThanOrEqual: function(actual, expected) {
(0, _jestMatcherUtils.ensureNumbers)(
actual,
expected,
'.toBeLessThanOrEqual'
);
const pass = actual <= expected;
const message = () =>
(0, _jestMatcherUtils.matcherHint)(
'.toBeLessThanOrEqual',
undefined,
undefined,
{
isNot: this.isNot
}
) +
'\n\n' +
`Expected: ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeNaN: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeNaN');
const pass = Number.isNaN(actual);
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeNaN', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeNull: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeNull');
const pass = actual === null;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeNull', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeTruthy: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeTruthy');
const pass = !!actual;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeTruthy', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toBeUndefined: function(actual, expected) {
(0, _jestMatcherUtils.ensureNoExpected)(expected, '.toBeUndefined');
const pass = actual === void 0;
const message = () =>
(0, _jestMatcherUtils.matcherHint)('.toBeUndefined', 'received', '', {
isNot: this.isNot
}) +
'\n\n' +
`Received: ${(0, _jestMatcherUtils.printReceived)(actual)}`;
return {message: message, pass: pass};
},
toContain: function(collection, value) {
const collectionType = (0, _jestGetType2.default)(collection);
let converted = null;
if (Array.isArray(collection) || typeof collection === 'string') {
// strings have `indexOf` so we don't need to convert
// arrays have `indexOf` and we don't want to make a copy
converted = collection;
} else {
try {
converted = Array.from(collection);
} catch (e) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toContainEqual',
'collection',
'value'
) +
'\n\n' +
`Expected ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'collection'
)} to be an array-like structure.\n` +
(0, _jestMatcherUtils.printWithType)(
'Received',
collection,
_jestMatcherUtils.printReceived
)
);
}
}
// At this point, we're either a string or an Array,
// which was converted from an array-like structure.
const pass = converted.indexOf(value) != -1;
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)(
'.not.toContain',
collectionType,
'value'
) +
'\n\n' +
`Expected ${collectionType}:\n` +
` ${(0, _jestMatcherUtils.printReceived)(collection)}\n` +
`Not to contain value:\n` +
` ${(0, _jestMatcherUtils.printExpected)(value)}\n`
: () => {
const suggestToContainEqual =
converted !== null &&
typeof converted !== 'string' &&
converted instanceof Array &&
converted.findIndex(item =>
(0, _jasmine_utils.equals)(item, value, [_utils.iterableEquality])
) !== -1;
return (
(0, _jestMatcherUtils.matcherHint)(
'.toContain',
collectionType,
'value'
) +
'\n\n' +
`Expected ${collectionType}:\n` +
` ${(0, _jestMatcherUtils.printReceived)(collection)}\n` +
`To contain value:\n` +
` ${(0, _jestMatcherUtils.printExpected)(value)}` +
(suggestToContainEqual
? `\n\n${_jestMatcherUtils.SUGGEST_TO_CONTAIN_EQUAL}`
: '')
);
};
return {message: message, pass: pass};
},
toContainEqual: function(collection, value) {
const collectionType = (0, _jestGetType2.default)(collection);
let converted = null;
if (Array.isArray(collection)) {
converted = collection;
} else {
try {
converted = Array.from(collection);
} catch (e) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toContainEqual',
'collection',
'value'
) +
'\n\n' +
`Expected ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'collection'
)} to be an array-like structure.\n` +
(0, _jestMatcherUtils.printWithType)(
'Received',
collection,
_jestMatcherUtils.printReceived
)
);
}
}
const pass =
converted.findIndex(item =>
(0, _jasmine_utils.equals)(item, value, [_utils.iterableEquality])
) !== -1;
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)(
'.not.toContainEqual',
collectionType,
'value'
) +
'\n\n' +
`Expected ${collectionType}:\n` +
` ${(0, _jestMatcherUtils.printReceived)(collection)}\n` +
`Not to contain a value equal to:\n` +
` ${(0, _jestMatcherUtils.printExpected)(value)}\n`
: () =>
(0, _jestMatcherUtils.matcherHint)(
'.toContainEqual',
collectionType,
'value'
) +
'\n\n' +
`Expected ${collectionType}:\n` +
` ${(0, _jestMatcherUtils.printReceived)(collection)}\n` +
`To contain a value equal to:\n` +
` ${(0, _jestMatcherUtils.printExpected)(value)}`;
return {message: message, pass: pass};
},
toEqual: function(received, expected) {
const pass = (0, _jasmine_utils.equals)(received, expected, [
_utils.iterableEquality
]);
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)('.not.toEqual') +
'\n\n' +
`Expected value to not equal:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}`
: () => {
const oneline = (0, _utils.isOneline)(expected, received);
const diffString = (0, _jestDiff2.default)(expected, received, {
expand: this.expand
});
return (
(0, _jestMatcherUtils.matcherHint)('.toEqual') +
'\n\n' +
`Expected value to equal:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}` +
(diffString && !oneline ? `\n\nDifference:\n\n${diffString}` : '')
);
};
// Passing the the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual: received,
expected: expected,
message: message,
name: 'toEqual',
pass: pass
};
},
toHaveLength: function(received, length) {
if (
typeof received !== 'string' &&
(!received || typeof received.length !== 'number')
) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toHaveLength',
'received',
'length'
) +
'\n\n' +
`Expected value to have a 'length' property that is a number. ` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}\n` +
(received
? `received.length:\n ${(0, _jestMatcherUtils.printReceived)(
received.length
)}`
: '')
);
}
const pass = received.length === length;
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)(
'.not.toHaveLength',
'received',
'length'
) +
'\n\n' +
`Expected value to not have length:\n` +
` ${(0, _jestMatcherUtils.printExpected)(length)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}\n` +
`received.length:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received.length)}`
: () =>
(0, _jestMatcherUtils.matcherHint)(
'.toHaveLength',
'received',
'length'
) +
'\n\n' +
`Expected value to have length:\n` +
` ${(0, _jestMatcherUtils.printExpected)(length)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}\n` +
`received.length:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received.length)}`;
return {message: message, pass: pass};
},
toHaveProperty: function(object, keyPath, value) {
const valuePassed = arguments.length === 3;
const secondArgument = valuePassed ? 'value' : null;
if (!object && typeof object !== 'string' && typeof object !== 'number') {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toHaveProperty',
'object',
'path',
{
secondArgument: secondArgument
}
) +
'\n\n' +
`Expected ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'object'
)} to be an object. Received:\n` +
` ${(0, _jestGetType2.default)(object)}: ${(0,
_jestMatcherUtils.printReceived)(object)}`
);
}
const keyPathType = (0, _jestGetType2.default)(keyPath);
if (keyPathType !== 'string' && keyPathType !== 'array') {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toHaveProperty',
'object',
'path',
{
secondArgument: secondArgument
}
) +
'\n\n' +
`Expected ${(0, _jestMatcherUtils.EXPECTED_COLOR)(
'path'
)} to be a string or an array. Received:\n` +
` ${(0, _jestGetType2.default)(keyPath)}: ${(0,
_jestMatcherUtils.printReceived)(keyPath)}`
);
}
const result = (0, _utils.getPath)(object, keyPath);
const lastTraversedObject = result.lastTraversedObject,
hasEndProp = result.hasEndProp;
const pass = valuePassed
? (0, _jasmine_utils.equals)(result.value, value, [
_utils.iterableEquality
])
: hasEndProp;
const traversedPath = result.traversedPath.join('.');
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)(
'.not.toHaveProperty',
'object',
'path',
{
secondArgument: secondArgument
}
) +
'\n\n' +
`Expected the object:\n` +
` ${(0, _jestMatcherUtils.printReceived)(object)}\n` +
`Not to have a nested property:\n` +
` ${(0, _jestMatcherUtils.printExpected)(keyPath)}\n` +
(valuePassed
? `With a value of:\n ${(0, _jestMatcherUtils.printExpected)(
value
)}\n`
: '')
: () => {
const diffString =
valuePassed && hasEndProp
? (0, _jestDiff2.default)(value, result.value, {
expand: this.expand
})
: '';
return (
(0, _jestMatcherUtils.matcherHint)(
'.toHaveProperty',
'object',
'path',
{
secondArgument: secondArgument
}
) +
'\n\n' +
`Expected the object:\n` +
` ${(0, _jestMatcherUtils.printReceived)(object)}\n` +
`To have a nested property:\n` +
` ${(0, _jestMatcherUtils.printExpected)(keyPath)}\n` +
(valuePassed
? `With a value of:\n ${(0, _jestMatcherUtils.printExpected)(
value
)}\n`
: '') +
(hasEndProp
? `Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(result.value)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
: traversedPath
? `Received:\n ${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'object'
)}.${traversedPath}: ${(0, _jestMatcherUtils.printReceived)(
lastTraversedObject
)}`
: '')
);
};
if (pass === undefined) {
throw new Error('pass must be initialized');
}
return {message: message, pass: pass};
},
toMatch: function(received, expected) {
if (typeof received !== 'string') {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toMatch',
'string',
'expected'
) +
'\n\n' +
`${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'string'
)} value must be a string.\n` +
(0, _jestMatcherUtils.printWithType)(
'Received',
received,
_jestMatcherUtils.printReceived
)
);
}
if (
!(expected && typeof expected.test === 'function') &&
!(typeof expected === 'string')
) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toMatch',
'string',
'expected'
) +
'\n\n' +
`${(0, _jestMatcherUtils.EXPECTED_COLOR)(
'expected'
)} value must be a string or a regular expression.\n` +
(0, _jestMatcherUtils.printWithType)(
'Expected',
expected,
_jestMatcherUtils.printExpected
)
);
}
const pass = new RegExp(
typeof expected === 'string'
? (0, _jestRegexUtil.escapeStrForRegex)(expected)
: expected
).test(received);
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)('.not.toMatch') +
`\n\nExpected value not to match:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}` +
`\nReceived:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}`
: () =>
(0, _jestMatcherUtils.matcherHint)('.toMatch') +
`\n\nExpected value to match:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}` +
`\nReceived:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}`;
return {message: message, pass: pass};
},
toMatchObject: function(receivedObject, expectedObject) {
if (typeof receivedObject !== 'object' || receivedObject === null) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toMatchObject',
'object',
'expected'
) +
'\n\n' +
`${(0, _jestMatcherUtils.RECEIVED_COLOR)(
'received'
)} value must be an object.\n` +
(0, _jestMatcherUtils.printWithType)(
'Received',
receivedObject,
_jestMatcherUtils.printReceived
)
);
}
if (typeof expectedObject !== 'object' || expectedObject === null) {
throw new Error(
(0, _jestMatcherUtils.matcherHint)(
'[.not].toMatchObject',
'object',
'expected'
) +
'\n\n' +
`${(0, _jestMatcherUtils.EXPECTED_COLOR)(
'expected'
)} value must be an object.\n` +
(0, _jestMatcherUtils.printWithType)(
'Expected',
expectedObject,
_jestMatcherUtils.printExpected
)
);
}
const pass = (0, _jasmine_utils.equals)(receivedObject, expectedObject, [
_utils.iterableEquality,
_utils.subsetEquality
]);
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)('.not.toMatchObject') +
`\n\nExpected value not to match object:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expectedObject)}` +
`\nReceived:\n` +
` ${(0, _jestMatcherUtils.printReceived)(receivedObject)}`
: () => {
const diffString = (0, _jestDiff2.default)(
expectedObject,
(0, _utils.getObjectSubset)(receivedObject, expectedObject),
{
expand: this.expand
}
);
return (
(0, _jestMatcherUtils.matcherHint)('.toMatchObject') +
`\n\nExpected value to match object:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expectedObject)}` +
`\nReceived:\n` +
` ${(0, _jestMatcherUtils.printReceived)(receivedObject)}` +
(diffString ? `\nDifference:\n${diffString}` : '')
);
};
return {message: message, pass: pass};
},
toStrictEqual: function(received, expected) {
const pass = (0, _jasmine_utils.equals)(
received,
expected,
[_utils.iterableEquality, _utils.typeEquality],
true
);
const message = pass
? () =>
(0, _jestMatcherUtils.matcherHint)('.not.toStrictEqual') +
'\n\n' +
`Expected value to not equal:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}`
: () => {
const diffString = (0, _jestDiff2.default)(expected, received, {
expand: this.expand
});
return (
(0, _jestMatcherUtils.matcherHint)('.toStrictEqual') +
'\n\n' +
`Expected value to equal:\n` +
` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
`Received:\n` +
` ${(0, _jestMatcherUtils.printReceived)(received)}` +
(diffString ? `\n\nDifference:\n\n${diffString}` : '')
);
};
// Passing the the actual and expected objects so that a custom reporter
// could access them, for example in order to display a custom visual diff,
// or create a different error message
return {
actual: received,
expected: expected,
message: message,
name: 'toStrictEqual',
pass: pass
};
}
};
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*
*/
exports.default = matchers;
|
/*
notes
getBoolPref is not a function
http://comments.gmane.org/gmane.comp.mozilla.project-owners/241
*/
//*********** export named single global object while using shorthand internally
var spenibus_zoomMonitor = (function() {
//************************************************************** run on load
window.addEventListener('load', (function f(){
// remove init listener
window.removeEventListener('load', f, false);
// init
//s.init.call(s);
s.init();
}), false);
//******************************************************* internal shorthand
var s = {};
//***************************************************************** elements
s.nodeMain = null;
s.nodeLabel = null;
s.nodeMenu = null;
//************************************************************ prefs service
s.ps = null;
//************************************************************** node getter
s.nodeGet = function(id) {
// try document first
var n = document.getElementById(id);
// try toolbar palette if document yielded nothing
if(n == null) {
n = gNavToolbox.palette.querySelector('#'+id);
}
return n;
};
//***************************************************** check full-page mode
s.fullGet = function() {
return s.ps.getBoolPref("browser.zoom.full");
};
//******************************************************* zoom values getter
s.zoomValuesGet = function() {
return s.ps.getCharPref("toolkit.zoomManager.zoomValues")
.split(",")
.reverse();
};
//************************************************************** zoom setter
s.zoomSet = function(z) {
// change relevant zoom value
s.fullGet()
? gBrowser.selectedBrowser.markupDocumentViewer.fullZoom = z
: gBrowser.selectedBrowser.markupDocumentViewer.textZoom = z;
// update ui
s.updateUI();
};
//*************************************************************** ui updater
s.updateUI = function(e) {
// main display
s.nodeLabel.innerHTML = s.fullGet()
? 'F'+Math.round(gBrowser.selectedBrowser.markupDocumentViewer.fullZoom * 100)+'%'
: 'T'+Math.round(gBrowser.selectedBrowser.markupDocumentViewer.textZoom * 100)+'%';
// get current zoom level
var currentZoom = s.fullGet()
? gBrowser.selectedBrowser.markupDocumentViewer.fullZoom
: gBrowser.selectedBrowser.markupDocumentViewer.textZoom;
var currentZoomPercentage = Math.round(currentZoom*100);
// get zoom values
var list = s.zoomValuesGet();
// clear menu
s.nodeMenu.innerHTML = '';
// build menu
for(var i=0; i<list.length; ++i) {
var zoomFactor = list[i];
var zoomPercentage = Math.round(zoomFactor*100);
// create menu item
var item = document.createElement('menuitem');
// set attributes
item.setAttribute('label', zoomPercentage+'%');
item.setAttribute('data-zoom', zoomFactor);
// highlight current zoom
if(currentZoomPercentage == zoomPercentage) {
item.classList.add("current");
}
// set command
item.addEventListener("command", function(e){
s.zoomSet(e.target.getAttribute('data-zoom'));
}, false);
// add item to menu
s.nodeMenu.appendChild(item);
}
};
//********************************************************************* init
s.init = function() {
// prefs service
s.ps = Components
.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.QueryInterface(Components.interfaces.nsIPrefBranch);
// get elements
s.nodeMain = s.nodeGet('spenibus_zoom_monitor_main');
s.nodeLabel = s.nodeGet('spenibus_zoom_monitor_label');
s.nodeMenu = s.nodeGet('spenibus_zoom_monitor_menu');
// override native function: enlarge/reduce
FullZoom._applyZoomToPrefOriginal = FullZoom._applyZoomToPref;
FullZoom._applyZoomToPref = function() {
FullZoom._applyZoomToPrefOriginal.apply(this, arguments);
s.updateUI();
}
// override native function: reset
FullZoom._removePrefOriginal = FullZoom._removePref;
FullZoom._removePref = function() {
FullZoom._removePrefOriginal.apply(this, arguments);
s.updateUI();
}
// event callback
var callback = function(){
s.updateUI.call(s);
}
// observe certain events
gBrowser.tabContainer.addEventListener("TabOpen", callback, false);
gBrowser.tabContainer.addEventListener("TabSelect", callback, false);
gBrowser.addEventListener("pageshow", callback, false);
gBrowser.addEventListener("click", callback, false);
// update ui
s.updateUI();
};
//******************************************************************* export
return s;
})();
|
/**
* @author Amazzing
* @copyright Amazzing
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)*
*/
var ajax_action_path;
var blockAjax = false;
$(document).ready(function(){
ajax_action_path = window.location.href.replace('#', '')+'&ajax=1';
activateSortable();
$(document).on('change', '.hookSelector', function(){
var hook_name = $(this).val();
$('.hook_content#'+hook_name).addClass('active').siblings().removeClass('active');
$('#settings_content').hide().html('');
$('.callSettings').removeClass('active');
});
$('.hookSelector').change();
$(document).on('click', '.callSettings', function(e){
e.preventDefault();
$el = $(this);
if ($el.hasClass('active'))
{
$('#settings-content').slideUp(function(){
$(this).html('');
$('.callSettings').removeClass('active');
});
return;
}
$('#settings-content').hide().html('');
$('.callSettings').removeClass('active');
var settings_type = $(this).data('settings');
var hook_name = $(this).closest('form').find('.hookSelector').val();
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=CallSettingsForm&settings_type='+settings_type+'&hook_name='+hook_name,
dataType : 'json',
success: function(r)
{
console.dir(r);
if ('form_html' in r){
$('#settings-content').html(utf8_decode(r.form_html)).slideDown().tooltip({selector: '.label-tooltip'});
$el.addClass('active');
}
},
error: function(r)
{
$('#settings-content').hide().html('');
$('.callSettings').removeClass('active');
console.warn(r.responseText);
}
});
});
$(document).on('click', '.chk-action', function(e){
e.preventDefault();
var $checkboxes = $(this).closest('#settings_content').find('input[type="checkbox"]');
if ($(this).hasClass('checkall')){
$checkboxes.each(function(){
$(this).prop('checked', true);
});
}
else if ($(this).hasClass('uncheckall')){
$checkboxes.each(function(){
$(this).prop('checked', false);
});
}
else if ($(this).hasClass('invert')){
$checkboxes.each(function(){
$(this).prop('checked', !$(this).prop('checked'));
});
}
});
$(document).on('click', '.saveHookSettings', function(e){
e.preventDefault();
var hook_name = $(this).attr('data-hook');
var data = $(this).closest('form').serialize();
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=SaveHookSettings&'+data,
dataType : 'json',
success: function(r)
{
console.dir(r);
if (r.saved){
$('#settings-content').slideUp(function(){
$('.callSettings').removeClass('active');
$(this).html('');
$.growl.notice({ title: '', message: savedTxt});
});
}
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('click', '.hide-settings', function(){
$('.callSettings.active').click();
});
$(document).on('click', '.chk-action', function(e){
e.preventDefault();
var $checkboxes = $(this).closest('#settings-content').find('input[type="checkbox"]');
if ($(this).hasClass('checkall')){
$checkboxes.each(function(){
$(this).prop('checked', true);
});
}
else if ($(this).hasClass('uncheckall')){
$checkboxes.each(function(){
$(this).prop('checked', false);
});
}
else if ($(this).hasClass('invert')){
$checkboxes.each(function(){
$(this).prop('checked', !$(this).prop('checked'));
});
}
});
$(document).on('click', '.bulk-select, .bulk-unselect', function(e){
e.preventDefault();
var checked = $(this).hasClass('bulk-select');
$('.carousel-item:visible .carousel-box').prop('checked', checked);
});
$(document).on('click', '[data-bulk-act]', function(e){
e.preventDefault();
$('.bulk-actions-error').remove();
var ids = [];
$('.carousel-box:checked').each(function(){
ids.push($(this).val());
});
var act = $(this).data('bulk-act');
if (act == 'delete' && ids.length && !confirm(areYouSureTxt))
return;
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=BulkAction',
dataType : 'json',
data: {
act : act,
ids : ids
},
success: function(r)
{
if ('errors' in r){
var err = '<div class="bulk-actions-error" style="display:none;">'+utf8_decode(r.errors)+'</div>';
$('.bulk-actions').removeClass('open').before(err);
$('.bulk-actions-error').slideDown();
}
else if (r.success){
$.growl.notice({ title: '', message: r.reponseText});
blockAjax = true;
switch (act){
case 'enable':
for (var i in ids)
$('.carousel-item[data-id="'+ids[i]+'"] .activateCarousel').addClass('action-enabled').removeClass('action-disabled').find('input').prop('checked', true);
break;
case 'disable':
for (var i in ids)
$('.carousel-item[data-id="'+ids[i]+'"] .activateCarousel').removeClass('action-enabled').addClass('action-disabled').find('input').prop('checked', false);
break;
case 'group_in_tabs':
case 'ungroup':
var checked = act == 'group_in_tabs';
for (var i in ids)
$('.carousel-item[data-id="'+ids[i]+'"] [name="in_tabs"]').prop('checked', checked);
break;
case 'delete':
removeCarouselRows(ids);
break;
}
blockAjax = false;
}
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('click', '.addCarousel', function(e){
e.preventDefault();
scrollUpAllCarousels();
var $carousel_list = $(this).closest('.hook_content').find('.carousel_list');
var hook_name = $(this).closest('.hook_content').attr('id');
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=CallCarouselForm&id_carousel=0&hook_name='+hook_name,
dataType : 'json',
success: function(r)
{
$newItem = $(utf8_decode(r));
$newItem.appendTo($carousel_list).addClass('open').find('.carousel-details').slideDown().find('#carousel_type').change();
$newItem.tooltip({selector: '.label-tooltip'});
var carousels_num = $('#'+hook_name+' .carousel-item:visible').length;
$('.hookSelector').find('option[value="'+hook_name+'"]').text(hook_name+' ('+carousels_num+')');
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('click', '.activateCarousel', function(e){
e.preventDefault();
$checkbox = $(this).find('input[type="checkbox"]');
$checkbox.prop('checked', !$checkbox.prop('checked')).change();
if ($(this).closest('.carousel-item').attr('data-id') == 0)
$(this).toggleClass('action-enabled action-disabled');
});
$(document).on('change', '.toggleable_param', function(e){
var $parent = $(this).closest('.carousel-item');
var id_carousel = $parent.attr('data-id');
if (blockAjax || id_carousel == 0)
return;
var param_name = $(this).attr('name');
var param_value = $(this).prop('checked') ? 1 : 0;
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=ToggleParam¶m_name='+param_name+'¶m_value='+param_value+'&id_carousel='+id_carousel,
dataType : 'json',
success: function(r)
{
console.dir(r);
if(r.success){
$.growl.notice({ title: '', message: savedTxt});
if (param_name == 'active')
$parent.find('.activateCarousel').toggleClass('action-enabled action-disabled');
}
else
$.growl.error({ title: '', message: failedTxt});
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('click', '.editCarousel', function(e){
e.preventDefault();
scrollUpAllCarousels();
var $item = $(this).closest('.carousel-item');
id = $item.attr('data-id');
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=CallCarouselForm&id_carousel='+id,
dataType : 'json',
success: function(r)
{
// console.dir(r);
var newItemHTML = $(utf8_decode(r)).html();
$item.html(newItemHTML).addClass('open').find('.carousel-details').slideDown().find('#carousel_type').change();
$item.tooltip({selector: '.label-tooltip'});
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('click', '.scrollUp', function(e){
e.preventDefault();
scrollUpAllCarousels();
});
$(document).on('click', '.deleteCarousel', function(){
if (!confirm(areYouSureTxt))
return;
var $item = $(this).closest('.carousel-item');
id = $item.attr('data-id');
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=DeleteCarousel&id_carousel='+id,
dataType : 'json',
success: function(r)
{
if (r.deleted)
removeCarouselRows(id);
},
error: function(r)
{
console.warn(r.responseText);
}
});
});
$(document).on('change', '#carousel_type', function(){
// special options for products/manufacturers/suppliers
var show_hide = ['product', 'manufacturer', 'supplier'];
if ($(this).val() == 'manufacturers')
show_hide = ['manufacturer', 'supplier', 'product'];
else if ($(this).val() == 'suppliers')
show_hide = ['supplier', 'manufacturer', 'product'];
$('.'+show_hide[0]+'_option').removeClass('hidden');
$('.'+show_hide[1]+'_option, .'+show_hide[2]+'_option').addClass('hidden');
var img_type = $('select[name="tpl_settings[image_type]"] option.saved').not('.hidden').first().val();
if (!img_type)
img_type = $('select[name="tpl_settings[image_type]"] option').not('.hidden').first().val();
$('select[name="tpl_settings[image_type]"]').val(img_type).change();
// special options for some carousel types
$('.special_option').addClass('hidden').closest('.special').hide();
$('.special_option.'+$(this).val()).removeClass('hidden').closest('.special').show();
// update name field if it is not saved yet
var carousel_name = $.trim($(this).find('option:selected').text());
$('input[data-saved="false"]').val(carousel_name);
});
$(document).on('click', '#saveCarousel', function(e){
e.preventDefault();
var $item = $(this).closest('.carousel-item');
$item.find('.ajax_errors').slideUp().html('');
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=saveCarousel',
data: {
id_carousel: $item.attr('data-id'),
hook_name: $item.closest('.hook_content').attr('id'),
carousel_data: $item.find('form').serialize(),
},
dataType : 'json',
success: function(r)
{
// console.dir(r);
if ('errors' in r){
$item.prepend(utf8_decode(r.errors));
$('html, body').animate({
scrollTop: $item.offset().top - 100
}, 500);
return;
}
else{
$.growl.notice({ title: '', message: r.responseText});
$item.find('form').slideUp(function(){
$item.replaceWith(utf8_decode(r.updated_form_header));
});
}
},
error: function(r)
{
$item.find('.ajax_errors').slideDown().append('<div>'+r.responseText+'</div>');
}
});
});
$(document).on('click', '.lang_switcher', function(){
var id_lang = $(this).attr('data-id-lang');
$('.multilang').hide();
$('.multilang.lang_'+id_lang).show();
});
$(document).on('click', '.importer .import', function(){
$('input[name="carousels_data_file"]').click();
}).on('change', 'input[name="carousels_data_file"]', function(){
if (!this.files || this.files[0].type != 'text/plain')
return;
$('.importer .import i').toggleClass('icon-cloud-upload icon-refresh icon-spin');
var data = new FormData();
data.append($(this).attr('name'), $(this).prop('files')[0]);
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=ImportCarousels',
dataType : 'json',
processData: false,
contentType: false,
data: data,
success: function(r)
{
if ('errors' in r)
$('.importer').closest('.panel').before(utf8_decode(r.errors));
else if ('upd_html' in r){
$upd = $('<div>'+utf8_decode(r.upd_html)+'</div>');
$('.all-carousels').replaceWith($upd.find('.all-carousels'));
$('.all-carousels').find('.hookSelector').change();
$('.all-carousels').before($upd.find('.module_confirmation'));
activateSortable();
}
$('.importer .import i').toggleClass('icon-cloud-upload icon-refresh icon-spin');
},
error: function(r)
{
console.warn(r.responseText);
$('.importer .import i').toggleClass('icon-cloud-upload icon-refresh icon-spin');
}
});
});
// ajax progress
$('body').append('<div id="re-progress"><div class="progress-inner"></div></div>');
$(document).ajaxStart(function(){
$('#re-progress .progress-inner').width(0).fadeIn('fast').animate({'width':'70%'},500);
})
.ajaxSuccess(function(){
$('#re-progress .progress-inner').animate({'width':'100%'},500,function(){
$(this).fadeOut('fast');
});
})
});
function scrollUpAllCarousels(){
$('.carousel-item').removeClass('open').find('.carousel-details').slideUp(function(){$(this).html('')});
}
function removeCarouselRows(ids){
if (!$.isArray(ids))
ids = [ids];
for (var i in ids){
$('.carousel-item[data-id="'+ids[i]+'"]').fadeOut(function(){
if (!$(this).closest('.carousel-item').next().length) {
var hook_name = $('.hookSelector').val();
var carousels_num = $('#'+hook_name+' .carousel-item:visible').length;
$('.hookSelector').find('option[value="'+hook_name+'"]').text(hook_name+' ('+carousels_num+')');
}
});
}
}
function activateSortable(){
$('.carousel_list').sortable({
placeholder: 'new_position_placeholder',
handle: '.dragger',
update: function(event, ui) {
var ordered_ids = [];
ui.item.closest('.carousel_list').find('.carousel-item').each(function(){
ordered_ids.push($(this).attr('data-id'));
});
$.ajax({
type: 'POST',
url: ajax_action_path+'&action=UpdatePositionsInHook',
dataType : 'json',
data: {
ordered_ids: ordered_ids,
},
success: function(r)
{
if('successText' in r)
$.growl.notice({ title: '', message: r.successText});
},
error: function(r)
{
$.growl.notice({ title: '', message: r.responseText});
}
});
}
});
}
function utf8_decode(utfstr) {
var res = '';
for (var i = 0; i < utfstr.length;) {
var c = utfstr.charCodeAt(i);
if (c < 128)
{
res += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224))
{
var c1 = utfstr.charCodeAt(i+1);
res += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
i += 2;
}
else
{
var c1 = utfstr.charCodeAt(i+1);
var c2 = utfstr.charCodeAt(i+2);
res += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
i += 3;
}
}
return res;
}
|
/**
* Created by Pencroff on 04-Sep-16.
*/
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var dotify = require('gulp-dotify');
var watch = require('gulp-watch');
var transform = require('gulp-transform');
var wrapper = require('gulp-wrapper');
var destination = 'assets';
gulp.task('generate-data-file', function() {
global.window = {};
return gulp.src('tests/*.js')
.pipe(plumber())
.pipe(transform(function (content) {
eval(content);
var test = global.window.test;
return [
'{ ',
'id:\'', test.id, '\',',
'name:\'', test.name, '\',',
'description:\'', test.description, '\',',
'tags:', '[\'', test.tags.join('\',\''), '\'],',
'url:\'', test.url, '\'',
' }'
].join('');
}, {encoding: 'utf8'}))
.pipe(concat('data.js', {newLine: ','}))
.pipe(wrapper({
header: '(function (r) {r.data=[',
footer: '];})(window.PerformanceJs);'
}))
.pipe(gulp.dest(destination));
});
gulp.task('templates', function() {
return gulp.src('src/views/**/*.html')
.pipe(plumber())
.pipe(dotify({
dictionary: 'r.JST'
}))
.pipe(concat('templates.min.js'))
.pipe(uglify())
.pipe(wrapper({
header: '(function (r) {r.JST={},',
footer: '})(window.PerformanceJs);'
}))
.pipe(gulp.dest(destination));
});
gulp.task('templates-watch', function () {
watch('src/views/**/*.html', function () {
gulp.start('templates')
})
}
);
makeTask({
name: 'app',
files: 'src/**/*.js',
destination: destination,
uglify: true
});
makeTask({
name: 'vendor',
files: ['assets/js/lodash.min.js', 'assets/js/bluebird.min.js',
'assets/js/domtastic.min.js', 'assets/js/grapnel.min.js'],
destination: destination,
});
makeTask({
name: 'benchmark',
files: ['assets/js/benchmark.js', 'assets/js/platform.js'],
destination: destination
});
gulp.task('engine', ['app', 'vendor', 'benchmark', 'templates', 'generate-data-file']);
gulp.task('engine-watch', ['app-watch', 'templates-watch']);
function makeTask(options) {
gulp.task(options.name, function() {
var stream = gulp.src(options.files)
.pipe(plumber())
.pipe(concat(options.name + '.js'))
.pipe(gulp.dest(options.destination));
if (options.uglify) {
stream.pipe(rename(options.name + '.min.js'))
.pipe(uglify())
.pipe(gulp.dest(options.destination));
}
return stream;
});
gulp.task(options.name + '-watch', function () {
watch(options.files, function () {
gulp.start(options.name)
})
}
);
}
|
'use strict' ;
var Emitter = require('events').EventEmitter ;
var util = require('util') ;
var outboundCallProcessor = require('./outbound-call-processor') ;
var inboundCallProcessor = require('./inbound-call-processor') ;
var spawn = require('child_process').spawn;
var iptables = require('iptables') ;
var parseUri = require('drachtio-sip').parser.parseUri ;
var ban = true ;
var chain = 'LOGDROP';
// verify the chain exists
var cmd = spawn('sudo', ['iptables','-S', chain]);
cmd.stderr.on('data', function(buf) {
console.error('NB: blacklisting is disabled, error listing chain LOGs: ', chain, String(buf)) ;
ban = false ;
}) ;
module.exports = exports = CallProcessor ;
function CallProcessor( srf, mediaServer, registrar ){
if (!(this instanceof CallProcessor)) { return new CallProcessor(srf, mediaServer, registrar); }
Emitter.call(this);
console.log('mediaServer: ', mediaServer);
this.srf = srf ;
this.mediaServer = mediaServer ;
this.registrar = registrar ;
this.calls = new Map() ;
}
util.inherits(CallProcessor, Emitter) ;
CallProcessor.prototype.start = function() {
this.srf.invite( ( req, res ) => {
console.log(`received invite from ${req.protocol}/${req.source_address}:${req.uri} with request uri %s` ) ;
var user = parseUri( req.uri ).user ;
if( this.registrar.hasUser( user ) ) {
var details = this.registrar.getUser( user ) ;
console.log(`inbound call with details: ${JSON.stringify(details)}`) ;
inboundCallProcessor( this.srf, req, res, details.uri, this.mediaServer, this.registrar, (err, uas, uac, ms, ep1, ep2) => {
if( err ) {
console.error(`${req.get('Call-Id')}: error connecting call: ${err.message}`) ;
return ;
}
this.setHandlers( uas, uac, ms, ep1, ep2 ) ;
}) ;
}
else if( 'udp' === req.protocol ) {
// outbound call, but it is coming via UDP. We only allow outbound calls via WSS
console.error(`banning ${req.source_address}:${req.source_port} due to unauthorized attempt to ${req.uri}`) ;
if( ban ) {
iptables.drop({
chain: chain,
src: req.source_address,
sudo: true
}) ;
}
}
else {
outboundCallProcessor( this.srf, req, res, req.uri, this.mediaServer, this.registrar, (err, uas, uac, ms, ep1, ep2) => {
if( err ) {
if( err.status !== 401 && err.status !== 407 ) {
console.error(`${req.get('Call-Id')}: error connecting call: ${err.status}`) ;
}
return ;
}
this.setHandlers( uas, uac, ms, ep1, ep2 ) ;
}) ;
}
});
} ;
CallProcessor.prototype.setHandlers = function( uas, uac, ms, ep1, ep2 ) {
var key = makeReplacesStr(uas) ;
var value = makeReplacesStr(uac) ;
this.calls.set(key, value) ;
console.log(`after adding call there are now ${this.calls.size} calls in progress`);
uas.on('destroy', this._onDestroy.bind( this, uas, uac, ms, ep1, ep2 )) ;
uac.on('destroy', this._onDestroy.bind( this, uac, uas, ms, ep1, ep2 )) ;
uas.once('refer', this._handleRefer.bind( this, uas, uac ) ) ;
uac.once('refer', this._handleRefer.bind( this, uac, uas ) ) ;
uas.on('hold', this._hold.bind( this, uas, uac, ep1, ep2 )) ;
uac.on('hold', this._hold.bind( this, uac, uas, ep1, ep2 )) ;
uas.on('unhold', this._unhold.bind( this, uas, uac, ep1, ep2 )) ;
uac.on('unhold', this._unhold.bind( this, uac, uas, ep1, ep2 )) ;
uas.on('info', this._handleInfo.bind( this, uas, uac, ep1, ep2 ) ) ;
uac.on('info', this._handleInfo.bind( this, uac, uas, ep2, ep1 ) ) ;
} ;
CallProcessor.prototype._onDestroy = function( dlg, dlgOther, ms, ep1, ep2 ) {
var key = makeReplacesStr(dlg) ;
if( this.calls.has( key ) ) {
this.calls.delete( key );
}
else {
key = makeReplacesStr(dlgOther) ;
if( this.calls.has( key ) ) {
this.calls.delete( key );
}
else {
console.error(`key ${key} not found`);
}
}
[dlgOther, ep1, ep2].forEach( function(e) { e.destroy(); }) ;
ms.disconnect() ;
console.log(`after ending call there are now ${this.calls.size} calls in progress`);
} ;
CallProcessor.prototype._handleRefer = function( dlg, dlgOther, req, res ) {
var referTo = req.get('Refer-To') ;
var arr = /(.*)Replaces=(.*)>/.exec(referTo) ;
if( arr && arr.length > 1 ) {
// attended transfer: fixup the Replaces part of the Refer-To header
var key = arr[2] ;
if( key in this._calls ) {
referTo = arr[1] + 'Replaces=' + this._calls[key] + '>' ;
}
else {
console.error(`attended transfer but we cant find ${key}`);
}
}
dlgOther.request({
method: 'REFER',
headers: {
'Refer-To': referTo
}
});
res.send(202);
} ;
CallProcessor.prototype._hold = function( dlg, dlgOther, ep1 /*, ep2 */) {
ep1.unbridge( function(err) {
if( err ) {
console.error(`Error unbridging endpoints when going on hold: ${err}`) ;
}
});
} ;
CallProcessor.prototype._unhold = function( dlg, dlgOther, ep1, ep2 ) {
ep1.bridge( ep2, function(err) {
if( err ) {
console.error(`Error bridging endpoints back together after unhold: ${err}`) ;
}
});
} ;
CallProcessor.prototype._handleInfo = function( dlg, dlgOther, ep1, ep2, req, res ) {
console.log('received info with content-type: %s', req.get('Content-Type'));
res.send(200) ;
if( req.get('Content-Type') === 'application/media_control+xml' ) {
console.log('forwarding to freeswitch ');
dlgOther.request({
method: 'INFO',
headers: {
'Content-Type': req.get('Content-Type'),
},
body: req.body
});
}
} ;
function makeReplacesStr( dlg ) {
var s = '';
if( dlg.type === 'uas') {
s = encodeURIComponent( dlg.sip.callId + ';to-tag=' + dlg.sip.localTag + ';from-tag=' + dlg.sip.remoteTag ) ;
}
else {
s = encodeURIComponent( dlg.sip.callId + ';to-tag=' + dlg.sip.remoteTag + ';from-tag=' + dlg.sip.localTag ) ;
}
return s ;
}
|
// Regular expression that matches all symbols in the `Deseret` script as per Unicode v5.0.0:
/\uD801[\uDC00-\uDC4F]/;
|
define([
'jquery',
'underscore',
'backbone',
'scripts/main/models/forum',
], function($, _, Backbone, ForumModel){
var ForumCollection = Backbone.Collection.extend({
model : ForumModel,
url : ForumModel.prototype.urlRoot,
});
return ForumCollection;
});
|
import _ from '../lib/utils'
import App from './app'
let Cards = {
Plains: 401994,
Island: 401927,
Swamp: 402059,
Mountain: 401961,
Forest: 401886
}
export let BASICS = Object.keys(Cards)
let COLORS_TO_LANDS = {
'W': 'Plains',
'U': 'Island',
'B': 'Swamp',
'R': 'Mountain',
'G': 'Forest',
}
for (let name in Cards)
Cards[name] = {name,
cmc: 0,
code: 'BFZ',
color: 'colorless',
rarity: 'basic',
type: 'Land',
url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&' +
`multiverseid=${Cards[name]}`
}
let rawPack, clicked
export let Zones = {
pack: {},
main: {},
side: {},
junk: {}
}
function hash() {
let {main, side} = Zones
App.send('hash', { main, side })
}
let events = {
side() {
let dst = Zones[App.state.side ? 'side' : 'main']
let srcName = App.state.side ? 'main' : 'side'
let src = Zones[srcName]
_.add(src, dst)
Zones[srcName] = {}
},
add(cardName) {
let zone = Zones[App.state.side ? 'side' : 'main']
zone[cardName] || (zone[cardName] = 0)
zone[cardName]++
App.update()
},
click(zoneName, cardName, e) {
if (zoneName === 'pack')
return clickPack(cardName)
let src = Zones[zoneName]
let dst = Zones[e.shiftKey
? zoneName === 'junk' ? 'main' : 'junk'
: zoneName === 'side' ? 'main' : 'side']
dst[cardName] || (dst[cardName] = 0)
src[cardName]--
dst[cardName]++
if (!src[cardName])
delete src[cardName]
App.update()
},
copy(ref) {
let node = ref.getDOMNode()
node.value = filetypes.txt()
node.select()
hash()
},
download() {
let {filename, filetype} = App.state
let data = filetypes[filetype]()
_.download(data, filename + '.' + filetype)
hash()
},
start() {
let {addBots, useTimer, timerLength} = App.state
let options = {addBots, useTimer, timerLength}
App.send('start', options)
},
pack(cards) {
rawPack = cards
let pack = Zones.pack = {}
for (let card of cards) {
let {name} = card
Cards[name] = card
pack[name] = 1
}
App.update()
if (App.state.beep)
document.getElementById('beep').play()
},
create() {
let {type, seats, title, isPrivate} = App.state
seats = Number(seats)
let options = { type, seats, title, isPrivate }
if (/cube/.test(type))
options.cube = cube()
else {
let {sets} = App.state
if (type === 'draft')
sets = sets.slice(0, 3)
options.sets = sets
}
App.send('create', options)
},
pool(cards) {
['main', 'side', 'junk'].forEach(zoneName => Zones[zoneName] = {})
let zone = Zones[App.state.side
? 'side'
: 'main']
for (let card of cards) {
let {name} = card
Cards[name] = card
zone[name] || (zone[name] = 0)
zone[name]++
}
App.update()
},
land(zoneName, cardName, e) {
let n = Number(e.target.value)
if (n)
Zones[zoneName][cardName] = n
else
delete Zones[zoneName][cardName]
App.update()
},
deckSize(e) {
let n = Number(e.target.value)
if (n && n > 0)
App.state.deckSize = n
App.update()
},
suggestLands() {
// Algorithm: count the number of mana symbols appearing in the costs of
// the cards in the pool, then assign lands roughly commensurately.
let colors = ['W', 'U', 'B', 'R', 'G']
let colorRegex = /\{[^}]+\}/g
let manaSymbols = {}
colors.forEach(x => manaSymbols[x] = 0)
// Count the number of mana symbols of each type.
for (let card of Object.keys(Zones['main'])) {
let quantity = Zones['main'][card]
card = Cards[card]
if (!card.manaCost)
continue
let cardManaSymbols = card.manaCost.match(colorRegex)
for (let color of colors)
for (let symbol of cardManaSymbols)
// Test to see if '{U}' contains 'U'. This also handles things like
// '{G/U}' triggering both 'G' and 'U'.
if (symbol.indexOf(color) !== -1)
manaSymbols[color] += quantity
}
_resetLands()
// NB: We could set only the sideboard lands of the colors we are using to
// 5, but this reveals information to the opponent on Cockatrice (and
// possibly other clients) since it tells the opponent the sideboard size.
colors.forEach(color => Zones['side'][COLORS_TO_LANDS[color]] = 5)
colors = colors.filter(x => manaSymbols[x] > 0)
colors.forEach(x => manaSymbols[x] = Math.max(3, manaSymbols[x]))
colors.sort((a, b) => manaSymbols[b] - manaSymbols[a])
// Round-robin choose the lands to go into the deck. For example, if the
// mana symbol counts are W: 2, U: 2, B: 1, cycle through the sequence
// [Plains, Island, Swamp, Plains, Island] infinitely until the deck is
// finished.
//
// This has a few nice effects:
//
// * Colors with greater mana symbol counts get more lands.
//
// * When in a typical two color deck adding 17 lands, the 9/8 split will
// be in favor of the color with slightly more mana symbols of that
// color.
//
// * Every color in the deck is represented, if it is possible to do so
// in the remaining number of cards.
//
// * Because of the minimum mana symbol count for each represented color,
// splashing cards doesn't add exactly one land of the given type
// (although the land count may still be low for that color).
//
// * The problem of deciding how to round land counts is now easy to
// solve.
let manaSymbolsToAdd = colors.map(color => manaSymbols[color])
let colorsToAdd = []
for (let i = 0; true; i = (i + 1) % colors.length) {
if (manaSymbolsToAdd.every(x => x === 0))
break
if (manaSymbolsToAdd[i] === 0)
continue
colorsToAdd.push(colors[i])
manaSymbolsToAdd[i]--
}
let mainDeckSize = Object.keys(Zones['main'])
.map(x => Zones['main'][x])
.reduce((a, b) => a + b)
let landsToAdd = App.state.deckSize - mainDeckSize
let j = 0
for (let i = 0; i < landsToAdd; i++) {
let color = colorsToAdd[j]
let land = COLORS_TO_LANDS[color]
if (!Zones['main'].hasOwnProperty(land))
Zones['main'][land] = 0
Zones['main'][land]++
j = (j + 1) % colorsToAdd.length
}
App.update()
},
resetLands() {
_resetLands()
App.update()
},
}
function _resetLands() {
Object.keys(COLORS_TO_LANDS).forEach((key) => {
let land = COLORS_TO_LANDS[key]
Zones['main'][land] = Zones['side'][land] = 0
})
}
for (let event in events)
App.on(event, events[event])
function codify(zone) {
let arr = []
for (let name in zone)
arr.push(` <card number="${zone[name]}" name="${name}"/>`)
return arr.join('\n')
}
let filetypes = {
cod() {
return `\
<?xml version="1.0" encoding="UTF-8"?>
<cockatrice_deck version="1">
<deckname>${App.state.filename}</deckname>
<zone name="main">
${codify(Zones.main)}
</zone>
<zone name="side">
${codify(Zones.side)}
</zone>
</cockatrice_deck>`
},
mwdeck() {
let arr = []
;['main', 'side'].forEach(zoneName => {
let prefix = zoneName === 'side' ? 'SB: ' : ''
let zone = Zones[zoneName]
for (let name in zone) {
let {code} = Cards[name]
let count = zone[name]
name = name.replace(' // ', '/')
arr.push(`${prefix}${count} [${code}] ${name}`)
}
})
return arr.join('\n')
},
json() {
let {main, side} = Zones
return JSON.stringify({ main, side }, null, 2)
},
txt() {
let arr = []
;['main', 'side'].forEach(zoneName => {
if (zoneName === 'side')
arr.push('Sideboard')
let zone = Zones[zoneName]
for (let name in zone) {
let count = zone[name]
arr.push(count + ' ' + name)
}
})
return arr.join('\n')
}
}
function cube() {
let {list, cards, packs} = App.state
cards = Number(cards)
packs = Number(packs)
list = list
.split('\n')
.map(x => x
.trim()
.replace(/^\d+.\s*/, '')
.replace(/\s*\/+\s*/g, ' // ')
.toLowerCase())
.filter(x => x)
.join('\n')
return { list, cards, packs }
}
function clickPack(cardName) {
let index = rawPack.findIndex(x => x.name === cardName)
let card = rawPack[index]
if (clicked !== cardName) {
clicked = cardName
// There may be duplicate cards in a pack, but only one copy of a card is
// shown in the pick view. We must be sure to mark them all since we don't
// know which one is being displayed.
rawPack.forEach(card => card.isAutopick = card.name === cardName)
App.update()
App.send('autopick', index)
return clicked
}
clicked = null
Zones.pack = {}
App.update()
App.send('pick', index)
}
function Key(groups, sort) {
let keys = Object.keys(groups)
switch(sort) {
case 'cmc':
let arr = []
for (let key in groups)
if (parseInt(key) > 6) {
;[].push.apply(arr, groups[key])
delete groups[key]
}
if (arr.length) {
groups['6'] || (groups['6'] = [])
;[].push.apply(groups['6'], arr)
}
return groups
case 'color':
keys =
['colorless', 'white', 'blue', 'black', 'red', 'green', 'multicolor']
.filter(x => keys.indexOf(x) > -1)
break
case 'rarity':
keys =
['basic', 'common', 'uncommon', 'rare', 'mythic', 'special']
.filter(x => keys.indexOf(x) > -1)
break
case 'type':
keys = keys.sort()
break
}
let o = {}
for (let key of keys)
o[key] = groups[key]
return o
}
function sortLandsBeforeNonLands(lhs, rhs) {
let isLand = x => x.type.toLowerCase().indexOf('land') !== -1
let lhsIsLand = isLand(lhs)
let rhsIsLand = isLand(rhs)
return rhsIsLand - lhsIsLand
}
export function getZone(zoneName) {
let zone = Zones[zoneName]
let cards = []
for (let cardName in zone)
for (let i = 0; i < zone[cardName]; i++)
cards.push(Cards[cardName])
let {sort} = App.state
let groups = _.group(cards, sort)
for (let key in groups)
_.sort(groups[key], sortLandsBeforeNonLands, 'color', 'cmc', 'name')
groups = Key(groups, sort)
return groups
}
|
/**
* This file does the main work of building a domTree structure from a parse
* tree. The entry point is the `buildHTML` function, which takes a parse tree.
* Then, the buildExpression, buildGroup, and various groupTypes functions are
* called, to produce a final HTML tree.
*/
var Options = require("./Options");
var ParseError = require("./ParseError");
var Style = require("./Style");
var buildCommon = require("./buildCommon");
var delimiter = require("./delimiter");
var domTree = require("./domTree");
var fontMetrics = require("./fontMetrics");
var utils = require("./utils");
var makeSpan = buildCommon.makeSpan;
/**
* Take a list of nodes, build them in order, and return a list of the built
* nodes. This function handles the `prev` node correctly, and passes the
* previous element from the list as the prev of the next element.
*/
var buildExpression = function(expression, options, prev) {
var groups = [];
for (var i = 0; i < expression.length; i++) {
var group = expression[i];
groups.push(buildGroup(group, options, prev));
prev = group;
}
return groups;
};
// List of types used by getTypeOfGroup,
// see https://github.com/Khan/KaTeX/wiki/Examining-TeX#group-types
var groupToType = {
mathord: "mord",
textord: "mord",
bin: "mbin",
rel: "mrel",
text: "mord",
open: "mopen",
close: "mclose",
inner: "minner",
genfrac: "mord",
array: "mord",
spacing: "mord",
punct: "mpunct",
ordgroup: "mord",
op: "mop",
katex: "mord",
overline: "mord",
rule: "mord",
leftright: "minner",
sqrt: "mord",
accent: "mord"
};
/**
* Gets the final math type of an expression, given its group type. This type is
* used to determine spacing between elements, and affects bin elements by
* causing them to change depending on what types are around them. This type
* must be attached to the outermost node of an element as a CSS class so that
* spacing with its surrounding elements works correctly.
*
* Some elements can be mapped one-to-one from group type to math type, and
* those are listed in the `groupToType` table.
*
* Others (usually elements that wrap around other elements) often have
* recursive definitions, and thus call `getTypeOfGroup` on their inner
* elements.
*/
var getTypeOfGroup = function(group) {
if (group == null) {
// Like when typesetting $^3$
return groupToType.mathord;
} else if (group.type === "supsub") {
return getTypeOfGroup(group.value.base);
} else if (group.type === "llap" || group.type === "rlap") {
return getTypeOfGroup(group.value);
} else if (group.type === "color") {
return getTypeOfGroup(group.value.value);
} else if (group.type === "sizing") {
return getTypeOfGroup(group.value.value);
} else if (group.type === "styling") {
return getTypeOfGroup(group.value.value);
} else if (group.type === "delimsizing") {
return groupToType[group.value.delimType];
} else {
return groupToType[group.type];
}
};
/**
* Sometimes, groups perform special rules when they have superscripts or
* subscripts attached to them. This function lets the `supsub` group know that
* its inner element should handle the superscripts and subscripts instead of
* handling them itself.
*/
var shouldHandleSupSub = function(group, options) {
if (!group) {
return false;
} else if (group.type === "op") {
// Operators handle supsubs differently when they have limits
// (e.g. `\displaystyle\sum_2^3`)
return group.value.limits &&
(options.style.size === Style.DISPLAY.size || group.value.alwaysHandleSupSub);
} else if (group.type === "accent") {
return isCharacterBox(group.value.base);
} else {
return null;
}
};
/**
* Sometimes we want to pull out the innermost element of a group. In most
* cases, this will just be the group itself, but when ordgroups and colors have
* a single element, we want to pull that out.
*/
var getBaseElem = function(group) {
if (!group) {
return false;
} else if (group.type === "ordgroup") {
if (group.value.length === 1) {
return getBaseElem(group.value[0]);
} else {
return group;
}
} else if (group.type === "color") {
if (group.value.value.length === 1) {
return getBaseElem(group.value.value[0]);
} else {
return group;
}
} else {
return group;
}
};
/**
* TeXbook algorithms often reference "character boxes", which are simply groups
* with a single character in them. To decide if something is a character box,
* we find its innermost group, and see if it is a single character.
*/
var isCharacterBox = function(group) {
var baseElem = getBaseElem(group);
// These are all they types of groups which hold single characters
return baseElem.type === "mathord" ||
baseElem.type === "textord" ||
baseElem.type === "bin" ||
baseElem.type === "rel" ||
baseElem.type === "inner" ||
baseElem.type === "open" ||
baseElem.type === "close" ||
baseElem.type === "punct";
};
var makeNullDelimiter = function(options) {
return makeSpan([
"sizing", "reset-" + options.size, "size5",
options.style.reset(), Style.TEXT.cls(),
"nulldelimiter"
]);
};
/**
* This is a map of group types to the function used to handle that type.
* Simpler types come at the beginning, while complicated types come afterwards.
*/
var groupTypes = {
mathord: function(group, options, prev) {
return buildCommon.makeOrd(group, options, "mathord");
},
textord: function(group, options, prev) {
return buildCommon.makeOrd(group, options, "textord");
},
bin: function(group, options, prev) {
var className = "mbin";
// Pull out the most recent element. Do some special handling to find
// things at the end of a \color group. Note that we don't use the same
// logic for ordgroups (which count as ords).
var prevAtom = prev;
while (prevAtom && prevAtom.type === "color") {
var atoms = prevAtom.value.value;
prevAtom = atoms[atoms.length - 1];
}
// See TeXbook pg. 442-446, Rules 5 and 6, and the text before Rule 19.
// Here, we determine whether the bin should turn into an ord. We
// currently only apply Rule 5.
if (!prev || utils.contains(["mbin", "mopen", "mrel", "mop", "mpunct"],
getTypeOfGroup(prevAtom))) {
group.type = "textord";
className = "mord";
}
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), [className]);
},
rel: function(group, options, prev) {
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), ["mrel"]);
},
open: function(group, options, prev) {
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), ["mopen"]);
},
close: function(group, options, prev) {
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), ["mclose"]);
},
inner: function(group, options, prev) {
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), ["minner"]);
},
punct: function(group, options, prev) {
return buildCommon.mathsym(
group.value, group.mode, options.getColor(), ["mpunct"]);
},
ordgroup: function(group, options, prev) {
return makeSpan(
["mord", options.style.cls()],
buildExpression(group.value, options.reset())
);
},
text: function(group, options, prev) {
return makeSpan(["text", "mord", options.style.cls()],
buildExpression(group.value.body, options.reset()));
},
color: function(group, options, prev) {
var elements = buildExpression(
group.value.value,
options.withColor(group.value.color),
prev
);
// \color isn't supposed to affect the type of the elements it contains.
// To accomplish this, we wrap the results in a fragment, so the inner
// elements will be able to directly interact with their neighbors. For
// example, `\color{red}{2 +} 3` has the same spacing as `2 + 3`
return new buildCommon.makeFragment(elements);
},
supsub: function(group, options, prev) {
// Superscript and subscripts are handled in the TeXbook on page
// 445-446, rules 18(a-f).
// Here is where we defer to the inner group if it should handle
// superscripts and subscripts itself.
if (shouldHandleSupSub(group.value.base, options)) {
return groupTypes[group.value.base.type](group, options, prev);
}
var base = buildGroup(group.value.base, options.reset());
var supmid, submid, sup, sub;
if (group.value.sup) {
sup = buildGroup(group.value.sup,
options.withStyle(options.style.sup()));
supmid = makeSpan(
[options.style.reset(), options.style.sup().cls()], [sup]);
}
if (group.value.sub) {
sub = buildGroup(group.value.sub,
options.withStyle(options.style.sub()));
submid = makeSpan(
[options.style.reset(), options.style.sub().cls()], [sub]);
}
// Rule 18a
var supShift, subShift;
if (isCharacterBox(group.value.base)) {
supShift = 0;
subShift = 0;
} else {
supShift = base.height - fontMetrics.metrics.supDrop;
subShift = base.depth + fontMetrics.metrics.subDrop;
}
// Rule 18c
var minSupShift;
if (options.style === Style.DISPLAY) {
minSupShift = fontMetrics.metrics.sup1;
} else if (options.style.cramped) {
minSupShift = fontMetrics.metrics.sup3;
} else {
minSupShift = fontMetrics.metrics.sup2;
}
// scriptspace is a font-size-independent size, so scale it
// appropriately
var multiplier = Style.TEXT.sizeMultiplier *
options.style.sizeMultiplier;
var scriptspace =
(0.5 / fontMetrics.metrics.ptPerEm) / multiplier + "em";
var supsub;
if (!group.value.sup) {
// Rule 18b
subShift = Math.max(
subShift, fontMetrics.metrics.sub1,
sub.height - 0.8 * fontMetrics.metrics.xHeight);
supsub = buildCommon.makeVList([
{type: "elem", elem: submid}
], "shift", subShift, options);
supsub.children[0].style.marginRight = scriptspace;
// Subscripts shouldn't be shifted by the base's italic correction.
// Account for that by shifting the subscript back the appropriate
// amount. Note we only do this when the base is a single symbol.
if (base instanceof domTree.symbolNode) {
supsub.children[0].style.marginLeft = -base.italic + "em";
}
} else if (!group.value.sub) {
// Rule 18c, d
supShift = Math.max(supShift, minSupShift,
sup.depth + 0.25 * fontMetrics.metrics.xHeight);
supsub = buildCommon.makeVList([
{type: "elem", elem: supmid}
], "shift", -supShift, options);
supsub.children[0].style.marginRight = scriptspace;
} else {
supShift = Math.max(
supShift, minSupShift,
sup.depth + 0.25 * fontMetrics.metrics.xHeight);
subShift = Math.max(subShift, fontMetrics.metrics.sub2);
var ruleWidth = fontMetrics.metrics.defaultRuleThickness;
// Rule 18e
if ((supShift - sup.depth) - (sub.height - subShift) <
4 * ruleWidth) {
subShift = 4 * ruleWidth - (supShift - sup.depth) + sub.height;
var psi = 0.8 * fontMetrics.metrics.xHeight -
(supShift - sup.depth);
if (psi > 0) {
supShift += psi;
subShift -= psi;
}
}
supsub = buildCommon.makeVList([
{type: "elem", elem: submid, shift: subShift},
{type: "elem", elem: supmid, shift: -supShift}
], "individualShift", null, options);
// See comment above about subscripts not being shifted
if (base instanceof domTree.symbolNode) {
supsub.children[0].style.marginLeft = -base.italic + "em";
}
supsub.children[0].style.marginRight = scriptspace;
supsub.children[1].style.marginRight = scriptspace;
}
return makeSpan([getTypeOfGroup(group.value.base)],
[base, supsub]);
},
genfrac: function(group, options, prev) {
// Fractions are handled in the TeXbook on pages 444-445, rules 15(a-e).
// Figure out what style this fraction should be in based on the
// function used
var fstyle = options.style;
if (group.value.size === "display") {
fstyle = Style.DISPLAY;
} else if (group.value.size === "text") {
fstyle = Style.TEXT;
}
var nstyle = fstyle.fracNum();
var dstyle = fstyle.fracDen();
var numer = buildGroup(group.value.numer, options.withStyle(nstyle));
var numerreset = makeSpan([fstyle.reset(), nstyle.cls()], [numer]);
var denom = buildGroup(group.value.denom, options.withStyle(dstyle));
var denomreset = makeSpan([fstyle.reset(), dstyle.cls()], [denom]);
var ruleWidth;
if (group.value.hasBarLine) {
ruleWidth = fontMetrics.metrics.defaultRuleThickness /
options.style.sizeMultiplier;
} else {
ruleWidth = 0;
}
// Rule 15b
var numShift;
var clearance;
var denomShift;
if (fstyle.size === Style.DISPLAY.size) {
numShift = fontMetrics.metrics.num1;
if (ruleWidth > 0) {
clearance = 3 * ruleWidth;
} else {
clearance = 7 * fontMetrics.metrics.defaultRuleThickness;
}
denomShift = fontMetrics.metrics.denom1;
} else {
if (ruleWidth > 0) {
numShift = fontMetrics.metrics.num2;
clearance = ruleWidth;
} else {
numShift = fontMetrics.metrics.num3;
clearance = 3 * fontMetrics.metrics.defaultRuleThickness;
}
denomShift = fontMetrics.metrics.denom2;
}
var frac;
if (ruleWidth === 0) {
// Rule 15c
var candiateClearance =
(numShift - numer.depth) - (denom.height - denomShift);
if (candiateClearance < clearance) {
numShift += 0.5 * (clearance - candiateClearance);
denomShift += 0.5 * (clearance - candiateClearance);
}
frac = buildCommon.makeVList([
{type: "elem", elem: denomreset, shift: denomShift},
{type: "elem", elem: numerreset, shift: -numShift}
], "individualShift", null, options);
} else {
// Rule 15d
var axisHeight = fontMetrics.metrics.axisHeight;
if ((numShift - numer.depth) - (axisHeight + 0.5 * ruleWidth) <
clearance) {
numShift +=
clearance - ((numShift - numer.depth) -
(axisHeight + 0.5 * ruleWidth));
}
if ((axisHeight - 0.5 * ruleWidth) - (denom.height - denomShift) <
clearance) {
denomShift +=
clearance - ((axisHeight - 0.5 * ruleWidth) -
(denom.height - denomShift));
}
var mid = makeSpan(
[options.style.reset(), Style.TEXT.cls(), "frac-line"]);
// Manually set the height of the line because its height is
// created in CSS
mid.height = ruleWidth;
var midShift = -(axisHeight - 0.5 * ruleWidth);
frac = buildCommon.makeVList([
{type: "elem", elem: denomreset, shift: denomShift},
{type: "elem", elem: mid, shift: midShift},
{type: "elem", elem: numerreset, shift: -numShift}
], "individualShift", null, options);
}
// Since we manually change the style sometimes (with \dfrac or \tfrac),
// account for the possible size change here.
frac.height *= fstyle.sizeMultiplier / options.style.sizeMultiplier;
frac.depth *= fstyle.sizeMultiplier / options.style.sizeMultiplier;
// Rule 15e
var delimSize;
if (fstyle.size === Style.DISPLAY.size) {
delimSize = fontMetrics.metrics.delim1;
} else {
delimSize = fontMetrics.metrics.getDelim2(fstyle);
}
var leftDelim, rightDelim;
if (group.value.leftDelim == null) {
leftDelim = makeNullDelimiter(options);
} else {
leftDelim = delimiter.customSizedDelim(
group.value.leftDelim, delimSize, true,
options.withStyle(fstyle), group.mode);
}
if (group.value.rightDelim == null) {
rightDelim = makeNullDelimiter(options);
} else {
rightDelim = delimiter.customSizedDelim(
group.value.rightDelim, delimSize, true,
options.withStyle(fstyle), group.mode);
}
return makeSpan(
["mord", options.style.reset(), fstyle.cls()],
[leftDelim, makeSpan(["mfrac"], [frac]), rightDelim],
options.getColor());
},
array: function(group, options, prev) {
var r, c;
var nr = group.value.body.length;
var nc = 0;
var body = new Array(nr);
// Horizontal spacing
var pt = 1 / fontMetrics.metrics.ptPerEm;
var arraycolsep = 5 * pt; // \arraycolsep in article.cls
// Vertical spacing
var baselineskip = 12 * pt; // see size10.clo
// Default \arraystretch from lttab.dtx
// TODO(gagern): may get redefined once we have user-defined macros
var arraystretch = utils.deflt(group.value.arraystretch, 1);
var arrayskip = arraystretch * baselineskip;
var arstrutHeight = 0.7 * arrayskip; // \strutbox in ltfsstrc.dtx and
var arstrutDepth = 0.3 * arrayskip; // \@arstrutbox in lttab.dtx
var totalHeight = 0;
for (r = 0; r < group.value.body.length; ++r) {
var inrow = group.value.body[r];
var height = arstrutHeight; // \@array adds an \@arstrut
var depth = arstrutDepth; // to each tow (via the template)
if (nc < inrow.length) {
nc = inrow.length;
}
var outrow = new Array(inrow.length);
for (c = 0; c < inrow.length; ++c) {
var elt = buildGroup(inrow[c], options);
if (depth < elt.depth) {
depth = elt.depth;
}
if (height < elt.height) {
height = elt.height;
}
outrow[c] = elt;
}
var gap = 0;
if (group.value.rowGaps[r]) {
gap = group.value.rowGaps[r].value;
switch (gap.unit) {
case "em":
gap = gap.number;
break;
case "ex":
gap = gap.number * fontMetrics.metrics.emPerEx;
break;
default:
console.error("Can't handle unit " + gap.unit);
gap = 0;
}
if (gap > 0) { // \@argarraycr
gap += arstrutDepth;
if (depth < gap) {
depth = gap; // \@xargarraycr
}
gap = 0;
}
}
outrow.height = height;
outrow.depth = depth;
totalHeight += height;
outrow.pos = totalHeight;
totalHeight += depth + gap; // \@yargarraycr
body[r] = outrow;
}
var offset = totalHeight / 2 + fontMetrics.metrics.axisHeight;
var coldescriptions = group.value.cols || [];
var cols = [];
var colsep;
for (c = 0; c < nc; ++c) {
var coldescr = coldescriptions[c] || {};
var sepwidth;
if (c > 0 || group.value.hskipBeforeAndAfter) {
sepwidth = utils.deflt(coldescr.pregap, arraycolsep);
if (sepwidth !== 0) {
colsep = makeSpan(["arraycolsep"], []);
colsep.style.width = sepwidth + "em";
cols.push(colsep);
}
}
var col = [];
for (r = 0; r < nr; ++r) {
var row = body[r];
var elem = row[c];
if (!elem) {
continue;
}
var shift = row.pos - offset;
elem.depth = row.depth;
elem.height = row.height;
col.push({type: "elem", elem: elem, shift: shift});
}
col = buildCommon.makeVList(col, "individualShift", null, options);
col = makeSpan(
["col-align-" + (coldescr.align || "c")],
[col]);
cols.push(col);
if (c < nc - 1 || group.value.hskipBeforeAndAfter) {
sepwidth = utils.deflt(coldescr.postgap, arraycolsep);
if (sepwidth !== 0) {
colsep = makeSpan(["arraycolsep"], []);
colsep.style.width = sepwidth + "em";
cols.push(colsep);
}
}
}
body = makeSpan(["mtable"], cols);
return makeSpan(["mord"], [body], options.getColor());
},
spacing: function(group, options, prev) {
if (group.value === "\\ " || group.value === "\\space" ||
group.value === " " || group.value === "~") {
// Spaces are generated by adding an actual space. Each of these
// things has an entry in the symbols table, so these will be turned
// into appropriate outputs.
return makeSpan(
["mord", "mspace"],
[buildCommon.mathsym(group.value, group.mode)]
);
} else {
// Other kinds of spaces are of arbitrary width. We use CSS to
// generate these.
return makeSpan(
["mord", "mspace",
buildCommon.spacingFunctions[group.value].className]);
}
},
llap: function(group, options, prev) {
var inner = makeSpan(
["inner"], [buildGroup(group.value.body, options.reset())]);
var fix = makeSpan(["fix"], []);
return makeSpan(
["llap", options.style.cls()], [inner, fix]);
},
rlap: function(group, options, prev) {
var inner = makeSpan(
["inner"], [buildGroup(group.value.body, options.reset())]);
var fix = makeSpan(["fix"], []);
return makeSpan(
["rlap", options.style.cls()], [inner, fix]);
},
op: function(group, options, prev) {
// Operators are handled in the TeXbook pg. 443-444, rule 13(a).
var supGroup;
var subGroup;
var hasLimits = false;
if (group.type === "supsub" ) {
// If we have limits, supsub will pass us its group to handle. Pull
// out the superscript and subscript and set the group to the op in
// its base.
supGroup = group.value.sup;
subGroup = group.value.sub;
group = group.value.base;
hasLimits = true;
}
// Most operators have a large successor symbol, but these don't.
var noSuccessor = [
"\\smallint"
];
var large = false;
if (options.style.size === Style.DISPLAY.size &&
group.value.symbol &&
!utils.contains(noSuccessor, group.value.body)) {
// Most symbol operators get larger in displaystyle (rule 13)
large = true;
}
var base;
var baseShift = 0;
var slant = 0;
if (group.value.symbol) {
// If this is a symbol, create the symbol.
var style = large ? "Size2-Regular" : "Size1-Regular";
base = buildCommon.makeSymbol(
group.value.body, style, "math", options.getColor(),
["op-symbol", large ? "large-op" : "small-op", "mop"]);
// Shift the symbol so its center lies on the axis (rule 13). It
// appears that our fonts have the centers of the symbols already
// almost on the axis, so these numbers are very small. Note we
// don't actually apply this here, but instead it is used either in
// the vlist creation or separately when there are no limits.
baseShift = (base.height - base.depth) / 2 -
fontMetrics.metrics.axisHeight *
options.style.sizeMultiplier;
// The slant of the symbol is just its italic correction.
slant = base.italic;
} else {
// Otherwise, this is a text operator. Build the text from the
// operator's name.
// TODO(emily): Add a space in the middle of some of these
// operators, like \limsup
var output = [];
for (var i = 1; i < group.value.body.length; i++) {
output.push(buildCommon.mathsym(group.value.body[i], group.mode));
}
base = makeSpan(["mop"], output, options.getColor());
}
if (hasLimits) {
// IE 8 clips \int if it is in a display: inline-block. We wrap it
// in a new span so it is an inline, and works.
base = makeSpan([], [base]);
var supmid, supKern, submid, subKern;
// We manually have to handle the superscripts and subscripts. This,
// aside from the kern calculations, is copied from supsub.
if (supGroup) {
var sup = buildGroup(
supGroup, options.withStyle(options.style.sup()));
supmid = makeSpan(
[options.style.reset(), options.style.sup().cls()], [sup]);
supKern = Math.max(
fontMetrics.metrics.bigOpSpacing1,
fontMetrics.metrics.bigOpSpacing3 - sup.depth);
}
if (subGroup) {
var sub = buildGroup(
subGroup, options.withStyle(options.style.sub()));
submid = makeSpan(
[options.style.reset(), options.style.sub().cls()],
[sub]);
subKern = Math.max(
fontMetrics.metrics.bigOpSpacing2,
fontMetrics.metrics.bigOpSpacing4 - sub.height);
}
// Build the final group as a vlist of the possible subscript, base,
// and possible superscript.
var finalGroup, top, bottom;
if (!supGroup) {
top = base.height - baseShift;
finalGroup = buildCommon.makeVList([
{type: "kern", size: fontMetrics.metrics.bigOpSpacing5},
{type: "elem", elem: submid},
{type: "kern", size: subKern},
{type: "elem", elem: base}
], "top", top, options);
// Here, we shift the limits by the slant of the symbol. Note
// that we are supposed to shift the limits by 1/2 of the slant,
// but since we are centering the limits adding a full slant of
// margin will shift by 1/2 that.
finalGroup.children[0].style.marginLeft = -slant + "em";
} else if (!subGroup) {
bottom = base.depth + baseShift;
finalGroup = buildCommon.makeVList([
{type: "elem", elem: base},
{type: "kern", size: supKern},
{type: "elem", elem: supmid},
{type: "kern", size: fontMetrics.metrics.bigOpSpacing5}
], "bottom", bottom, options);
// See comment above about slants
finalGroup.children[1].style.marginLeft = slant + "em";
} else if (!supGroup && !subGroup) {
// This case probably shouldn't occur (this would mean the
// supsub was sending us a group with no superscript or
// subscript) but be safe.
return base;
} else {
bottom = fontMetrics.metrics.bigOpSpacing5 +
submid.height + submid.depth +
subKern +
base.depth + baseShift;
finalGroup = buildCommon.makeVList([
{type: "kern", size: fontMetrics.metrics.bigOpSpacing5},
{type: "elem", elem: submid},
{type: "kern", size: subKern},
{type: "elem", elem: base},
{type: "kern", size: supKern},
{type: "elem", elem: supmid},
{type: "kern", size: fontMetrics.metrics.bigOpSpacing5}
], "bottom", bottom, options);
// See comment above about slants
finalGroup.children[0].style.marginLeft = -slant + "em";
finalGroup.children[2].style.marginLeft = slant + "em";
}
return makeSpan(["mop", "op-limits"], [finalGroup]);
} else {
if (group.value.symbol) {
base.style.top = baseShift + "em";
}
return base;
}
},
katex: function(group, options, prev) {
// The KaTeX logo. The offsets for the K and a were chosen to look
// good, but the offsets for the T, E, and X were taken from the
// definition of \TeX in TeX (see TeXbook pg. 356)
var k = makeSpan(
["k"], [buildCommon.mathsym("K", group.mode)]);
var a = makeSpan(
["a"], [buildCommon.mathsym("A", group.mode)]);
a.height = (a.height + 0.2) * 0.75;
a.depth = (a.height - 0.2) * 0.75;
var t = makeSpan(
["t"], [buildCommon.mathsym("T", group.mode)]);
var e = makeSpan(
["e"], [buildCommon.mathsym("E", group.mode)]);
e.height = (e.height - 0.2155);
e.depth = (e.depth + 0.2155);
var x = makeSpan(
["x"], [buildCommon.mathsym("X", group.mode)]);
return makeSpan(
["katex-logo", "mord"], [k, a, t, e, x], options.getColor());
},
overline: function(group, options, prev) {
// Overlines are handled in the TeXbook pg 443, Rule 9.
// Build the inner group in the cramped style.
var innerGroup = buildGroup(group.value.body,
options.withStyle(options.style.cramp()));
var ruleWidth = fontMetrics.metrics.defaultRuleThickness /
options.style.sizeMultiplier;
// Create the line above the body
var line = makeSpan(
[options.style.reset(), Style.TEXT.cls(), "overline-line"]);
line.height = ruleWidth;
line.maxFontSize = 1.0;
// Generate the vlist, with the appropriate kerns
var vlist = buildCommon.makeVList([
{type: "elem", elem: innerGroup},
{type: "kern", size: 3 * ruleWidth},
{type: "elem", elem: line},
{type: "kern", size: ruleWidth}
], "firstBaseline", null, options);
return makeSpan(["overline", "mord"], [vlist], options.getColor());
},
sqrt: function(group, options, prev) {
// Square roots are handled in the TeXbook pg. 443, Rule 11.
// First, we do the same steps as in overline to build the inner group
// and line
var inner = buildGroup(group.value.body,
options.withStyle(options.style.cramp()));
var ruleWidth = fontMetrics.metrics.defaultRuleThickness /
options.style.sizeMultiplier;
var line = makeSpan(
[options.style.reset(), Style.TEXT.cls(), "sqrt-line"], [],
options.getColor());
line.height = ruleWidth;
line.maxFontSize = 1.0;
var phi = ruleWidth;
if (options.style.id < Style.TEXT.id) {
phi = fontMetrics.metrics.xHeight;
}
// Calculate the clearance between the body and line
var lineClearance = ruleWidth + phi / 4;
var innerHeight =
(inner.height + inner.depth) * options.style.sizeMultiplier;
var minDelimiterHeight = innerHeight + lineClearance + ruleWidth;
// Create a \surd delimiter of the required minimum size
var delim = makeSpan(["sqrt-sign"], [
delimiter.customSizedDelim("\\surd", minDelimiterHeight,
false, options, group.mode)],
options.getColor());
var delimDepth = (delim.height + delim.depth) - ruleWidth;
// Adjust the clearance based on the delimiter size
if (delimDepth > inner.height + inner.depth + lineClearance) {
lineClearance =
(lineClearance + delimDepth - inner.height - inner.depth) / 2;
}
// Shift the delimiter so that its top lines up with the top of the line
var delimShift = -(inner.height + lineClearance + ruleWidth) + delim.height;
delim.style.top = delimShift + "em";
delim.height -= delimShift;
delim.depth += delimShift;
// We add a special case here, because even when `inner` is empty, we
// still get a line. So, we use a simple heuristic to decide if we
// should omit the body entirely. (note this doesn't work for something
// like `\sqrt{\rlap{x}}`, but if someone is doing that they deserve for
// it not to work.
var body;
if (inner.height === 0 && inner.depth === 0) {
body = makeSpan();
} else {
body = buildCommon.makeVList([
{type: "elem", elem: inner},
{type: "kern", size: lineClearance},
{type: "elem", elem: line},
{type: "kern", size: ruleWidth}
], "firstBaseline", null, options);
}
if (!group.value.index) {
return makeSpan(["sqrt", "mord"], [delim, body]);
} else {
// Handle the optional root index
// The index is always in scriptscript style
var root = buildGroup(
group.value.index,
options.withStyle(Style.SCRIPTSCRIPT));
var rootWrap = makeSpan(
[options.style.reset(), Style.SCRIPTSCRIPT.cls()],
[root]);
// Figure out the height and depth of the inner part
var innerRootHeight = Math.max(delim.height, body.height);
var innerRootDepth = Math.max(delim.depth, body.depth);
// The amount the index is shifted by. This is taken from the TeX
// source, in the definition of `\r@@t`.
var toShift = 0.6 * (innerRootHeight - innerRootDepth);
// Build a VList with the superscript shifted up correctly
var rootVList = buildCommon.makeVList(
[{type: "elem", elem: rootWrap}],
"shift", -toShift, options);
// Add a class surrounding it so we can add on the appropriate
// kerning
var rootVListWrap = makeSpan(["root"], [rootVList]);
return makeSpan(["sqrt", "mord"], [rootVListWrap, delim, body]);
}
},
sizing: function(group, options, prev) {
// Handle sizing operators like \Huge. Real TeX doesn't actually allow
// these functions inside of math expressions, so we do some special
// handling.
var inner = buildExpression(group.value.value,
options.withSize(group.value.size), prev);
var span = makeSpan(["mord"],
[makeSpan(["sizing", "reset-" + options.size, group.value.size,
options.style.cls()],
inner)]);
// Calculate the correct maxFontSize manually
var fontSize = buildCommon.sizingMultiplier[group.value.size];
span.maxFontSize = fontSize * options.style.sizeMultiplier;
return span;
},
styling: function(group, options, prev) {
// Style changes are handled in the TeXbook on pg. 442, Rule 3.
// Figure out what style we're changing to.
var style = {
"display": Style.DISPLAY,
"text": Style.TEXT,
"script": Style.SCRIPT,
"scriptscript": Style.SCRIPTSCRIPT
};
var newStyle = style[group.value.style];
// Build the inner expression in the new style.
var inner = buildExpression(
group.value.value, options.withStyle(newStyle), prev);
return makeSpan([options.style.reset(), newStyle.cls()], inner);
},
font: function(group, options, prev) {
var font = group.value.font;
return buildGroup(group.value.body, options.withFont(font), prev);
},
delimsizing: function(group, options, prev) {
var delim = group.value.value;
if (delim === ".") {
// Empty delimiters still count as elements, even though they don't
// show anything.
return makeSpan([groupToType[group.value.delimType]]);
}
// Use delimiter.sizedDelim to generate the delimiter.
return makeSpan(
[groupToType[group.value.delimType]],
[delimiter.sizedDelim(
delim, group.value.size, options, group.mode)]);
},
leftright: function(group, options, prev) {
// Build the inner expression
var inner = buildExpression(group.value.body, options.reset());
var innerHeight = 0;
var innerDepth = 0;
// Calculate its height and depth
for (var i = 0; i < inner.length; i++) {
innerHeight = Math.max(inner[i].height, innerHeight);
innerDepth = Math.max(inner[i].depth, innerDepth);
}
// The size of delimiters is the same, regardless of what style we are
// in. Thus, to correctly calculate the size of delimiter we need around
// a group, we scale down the inner size based on the size.
innerHeight *= options.style.sizeMultiplier;
innerDepth *= options.style.sizeMultiplier;
var leftDelim;
if (group.value.left === ".") {
// Empty delimiters in \left and \right make null delimiter spaces.
leftDelim = makeNullDelimiter(options);
} else {
// Otherwise, use leftRightDelim to generate the correct sized
// delimiter.
leftDelim = delimiter.leftRightDelim(
group.value.left, innerHeight, innerDepth, options,
group.mode);
}
// Add it to the beginning of the expression
inner.unshift(leftDelim);
var rightDelim;
// Same for the right delimiter
if (group.value.right === ".") {
rightDelim = makeNullDelimiter(options);
} else {
rightDelim = delimiter.leftRightDelim(
group.value.right, innerHeight, innerDepth, options,
group.mode);
}
// Add it to the end of the expression.
inner.push(rightDelim);
return makeSpan(
["minner", options.style.cls()], inner, options.getColor());
},
rule: function(group, options, prev) {
// Make an empty span for the rule
var rule = makeSpan(["mord", "rule"], [], options.getColor());
// Calculate the shift, width, and height of the rule, and account for units
var shift = 0;
if (group.value.shift) {
shift = group.value.shift.number;
if (group.value.shift.unit === "ex") {
shift *= fontMetrics.metrics.xHeight;
}
}
var width = group.value.width.number;
if (group.value.width.unit === "ex") {
width *= fontMetrics.metrics.xHeight;
}
var height = group.value.height.number;
if (group.value.height.unit === "ex") {
height *= fontMetrics.metrics.xHeight;
}
// The sizes of rules are absolute, so make it larger if we are in a
// smaller style.
shift /= options.style.sizeMultiplier;
width /= options.style.sizeMultiplier;
height /= options.style.sizeMultiplier;
// Style the rule to the right size
rule.style.borderRightWidth = width + "em";
rule.style.borderTopWidth = height + "em";
rule.style.bottom = shift + "em";
// Record the height and width
rule.width = width;
rule.height = height + shift;
rule.depth = -shift;
return rule;
},
accent: function(group, options, prev) {
// Accents are handled in the TeXbook pg. 443, rule 12.
var base = group.value.base;
var supsubGroup;
if (group.type === "supsub") {
// If our base is a character box, and we have superscripts and
// subscripts, the supsub will defer to us. In particular, we want
// to attach the superscripts and subscripts to the inner body (so
// that the position of the superscripts and subscripts won't be
// affected by the height of the accent). We accomplish this by
// sticking the base of the accent into the base of the supsub, and
// rendering that, while keeping track of where the accent is.
// The supsub group is the group that was passed in
var supsub = group;
// The real accent group is the base of the supsub group
group = supsub.value.base;
// The character box is the base of the accent group
base = group.value.base;
// Stick the character box into the base of the supsub group
supsub.value.base = base;
// Rerender the supsub group with its new base, and store that
// result.
supsubGroup = buildGroup(
supsub, options.reset(), prev);
}
// Build the base group
var body = buildGroup(
base, options.withStyle(options.style.cramp()));
// Calculate the skew of the accent. This is based on the line "If the
// nucleus is not a single character, let s = 0; otherwise set s to the
// kern amount for the nucleus followed by the \skewchar of its font."
// Note that our skew metrics are just the kern between each character
// and the skewchar.
var skew;
if (isCharacterBox(base)) {
// If the base is a character box, then we want the skew of the
// innermost character. To do that, we find the innermost character:
var baseChar = getBaseElem(base);
// Then, we render its group to get the symbol inside it
var baseGroup = buildGroup(
baseChar, options.withStyle(options.style.cramp()));
// Finally, we pull the skew off of the symbol.
skew = baseGroup.skew;
// Note that we now throw away baseGroup, because the layers we
// removed with getBaseElem might contain things like \color which
// we can't get rid of.
// TODO(emily): Find a better way to get the skew
} else {
skew = 0;
}
// calculate the amount of space between the body and the accent
var clearance = Math.min(body.height, fontMetrics.metrics.xHeight);
// Build the accent
var accent = buildCommon.makeSymbol(
group.value.accent, "Main-Regular", "math", options.getColor());
// Remove the italic correction of the accent, because it only serves to
// shift the accent over to a place we don't want.
accent.italic = 0;
// The \vec character that the fonts use is a combining character, and
// thus shows up much too far to the left. To account for this, we add a
// specific class which shifts the accent over to where we want it.
// TODO(emily): Fix this in a better way, like by changing the font
var vecClass = group.value.accent === "\\vec" ? "accent-vec" : null;
var accentBody = makeSpan(["accent-body", vecClass], [
makeSpan([], [accent])]);
accentBody = buildCommon.makeVList([
{type: "elem", elem: body},
{type: "kern", size: -clearance},
{type: "elem", elem: accentBody}
], "firstBaseline", null, options);
// Shift the accent over by the skew. Note we shift by twice the skew
// because we are centering the accent, so by adding 2*skew to the left,
// we shift it to the right by 1*skew.
accentBody.children[1].style.marginLeft = 2 * skew + "em";
var accentWrap = makeSpan(["mord", "accent"], [accentBody]);
if (supsubGroup) {
// Here, we replace the "base" child of the supsub with our newly
// generated accent.
supsubGroup.children[0] = accentWrap;
// Since we don't rerun the height calculation after replacing the
// accent, we manually recalculate height.
supsubGroup.height = Math.max(accentWrap.height, supsubGroup.height);
// Accents should always be ords, even when their innards are not.
supsubGroup.classes[0] = "mord";
return supsubGroup;
} else {
return accentWrap;
}
},
phantom: function(group, options, prev) {
var elements = buildExpression(
group.value.value,
options.withPhantom(),
prev
);
// \phantom isn't supposed to affect the elements it contains.
// See "color" for more details.
return new buildCommon.makeFragment(elements);
}
};
/**
* buildGroup is the function that takes a group and calls the correct groupType
* function for it. It also handles the interaction of size and style changes
* between parents and children.
*/
var buildGroup = function(group, options, prev) {
if (!group) {
return makeSpan();
}
if (groupTypes[group.type]) {
// Call the groupTypes function
var groupNode = groupTypes[group.type](group, options, prev);
var multiplier;
// If the style changed between the parent and the current group,
// account for the size difference
if (options.style !== options.parentStyle) {
multiplier = options.style.sizeMultiplier /
options.parentStyle.sizeMultiplier;
groupNode.height *= multiplier;
groupNode.depth *= multiplier;
}
// If the size changed between the parent and the current group, account
// for that size difference.
if (options.size !== options.parentSize) {
multiplier = buildCommon.sizingMultiplier[options.size] /
buildCommon.sizingMultiplier[options.parentSize];
groupNode.height *= multiplier;
groupNode.depth *= multiplier;
}
return groupNode;
} else {
throw new ParseError(
"Got group of unknown type: '" + group.type + "'");
}
};
/**
* Take an entire parse tree, and build it into an appropriate set of HTML
* nodes.
*/
var buildHTML = function(tree, settings) {
// buildExpression is destructive, so we need to make a clone
// of the incoming tree so that it isn't accidentally changed
tree = JSON.parse(JSON.stringify(tree));
var startStyle = Style.TEXT;
if (settings.displayMode) {
startStyle = Style.DISPLAY;
}
// Setup the default options
var options = new Options({
style: startStyle,
size: "size5"
});
// Build the expression contained in the tree
var expression = buildExpression(tree, options);
var body = makeSpan(["base", options.style.cls()], expression);
// Add struts, which ensure that the top of the HTML element falls at the
// height of the expression, and the bottom of the HTML element falls at the
// depth of the expression.
var topStrut = makeSpan(["strut"]);
var bottomStrut = makeSpan(["strut", "bottom"]);
topStrut.style.height = body.height + "em";
bottomStrut.style.height = (body.height + body.depth) + "em";
// We'd like to use `vertical-align: top` but in IE 9 this lowers the
// baseline of the box to the bottom of this strut (instead staying in the
// normal place) so we use an absolute value for vertical-align instead
bottomStrut.style.verticalAlign = -body.depth + "em";
// Wrap the struts and body together
var htmlNode = makeSpan(["katex-html"], [topStrut, bottomStrut, body]);
htmlNode.setAttribute("aria-hidden", "true");
return htmlNode;
};
module.exports = buildHTML;
|
// track page views
var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
var currIcon = 0;
updateState(null);
// updates icon image
function updateIcon() {
currIcon = (currIcon + 1) % 2;
chrome.browserAction.setIcon({path: "./../icons/ticker_sticker_" + currIcon + ".png"});
}
// turning extension on and off
chrome.browserAction.onClicked.addListener(function(tab) {
updateState(tab);
});
function updateState(tab) {
updateIcon();
chrome.storage.sync.set({'state': currIcon}, function() {
//message('Toggled on/off');e
});
}
|
(() => {
'use strict';
angular
.module('app')
.service('TokenService', TokenService);
function TokenService($localStorage) {
this.get = get;
this.save = save;
this.clean = clean;
////
function get() {
return $localStorage.token;
}
function save(token) {
return $localStorage.token = token;
}
function clean() {
delete $localStorage.token;
}
}
})();
|
import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Wrapper from '../components/wrapper'
import Articles from '../components/articles'
import Nav from '../components/nav'
import Hero from '../components/hero'
import Footer from '../components/footer'
import DocumentMeta from 'react-document-meta'
export default class BlogIndex extends React.Component {
render() {
const meta = {
title: 'Wanderlust - A blog about digital nomad lifestyle',
description: 'Digital nomads travel the world and work location independent.',
canonical: 'https://wanderlust.tech/en/',
locale: 'en'
}
this.props.route.path = '/en/'
this.props.route.page.data = {
locale: 'EN'
}
return (
<div>
<DocumentMeta {...meta} />
<Nav route={this.props.route} />
<Hero route={this.props.route} />
<Wrapper>
<Articles route={this.props.route} />
</Wrapper>
<Footer />
</div>
)
}
}
|
'use strict';
exports.command = function( ) {
const SauceLabs = require( 'saucelabs' );
const saucelabs = new SauceLabs({
username: process.env.SAUCE_USERNAME,
password: process.env.SAUCE_ACCESS_KEY
});
const sessionid = this.capabilities[ 'webdriver.remote.sessionid' ];
saucelabs.updateJob( sessionid, {
passed: this.currentTest.results.failed === 0
}, () => {});
return this;
};
|
/*
* Clearest Framework
* Provided under MIT License.
* Copyright (c) 2012-2015 Illya Kokshenev <sou@illya.com.br>
*/
/**
* Created by M0nZDeRR on 30/10/2015.
*/
var chai = require("chai"),
expect = chai.expect,
commons = require("../../core/commons"),
inside = commons.inside,
Serializer = require("../../tool/serializer.js");
describe("tool / serializer", function(){
it("should serialize simple elements",function(){
var ser = new Serializer();
expect(ser.serialize(undefined)).to.be.equal("undefined");
expect(ser.serialize(null)).to.be.equal("null");
expect(ser.serialize(42)).to.be.equal('42');
expect(ser.serialize('foo')).to.be.equal('"foo"');
});
it("should serialize objects, functions and call custom serializers",function(){
var ser = new Serializer();
var f = function (a,b,c){return a+b+c};
expect(ser.serialize(f)).to.be.equal(f.toString());
expect(ser.serialize({})).to.be.equal('{}');
expect(ser.serialize({foo:42})).to.be.equal('{foo:42}');
expect(ser.serialize({foo:"42"})).to.be.equal('{foo:"42"}');
var o={};
inside(o).serialize = function(ser){return ser.serialize('custom!');}
expect(ser.serialize(o)).to.be.equal('"custom!"');
});
//it("should serialize recursive references ")
});
|
angular.module('checkoutModule')
.controller('checkoutAccordionController', [
'$scope',
'$location',
'$q',
'$timeout',
'_',
'checkoutApiService',
'visitorLoginService',
'cartService',
'commonUtilService',
'checkoutService',
'giftcardsApiService',
function (
$scope,
$location,
$q,
$timeout,
_,
checkoutApiService,
visitorLoginService,
cartService,
commonUtilService,
checkoutService,
giftcardsApiService
) {
var isValidSteps = {
'billingAddress': false,
'shippingAddress': false,
'shippingMethod': false,
'paymentMethod': false,
'discounts': true
};
// General
$scope.checkoutService = checkoutService;
$scope.cart = cartService;
$scope.checkout = {};
$scope.isGuestCheckout = false;
$scope.getOptionLabel = commonUtilService.getOptionLabel;
// Accordion navigation
$scope.back = back;
$scope.next = next;
$scope.save = save;
// Addresses
$scope.addressSettings = {
useShippingAsBilling: true
};
$scope.newBilling = newBilling;
$scope.newShipping = newShipping;
$scope.choiceBilling = choiceBilling;
$scope.choiceShipping = choiceShipping;
// Shipping method
$scope.shippingMethod = {
selected: false
};
$scope.shippingMethods = []; // REFACTOR: nest under shippingMethod as options
// Billing Method
$scope.paymentMethod = {
selected: false
};
$scope.paymentMethods = []; // REFACTOR: nest under paymentMethod as options
// Discounts and Giftcards
$scope.discounts = {
apply: applyDiscount,
remove: removeDiscount,
code: '',
isVisible: false,
message: false,
isApplying: false,
};
$scope.canRemoveDiscount = canRemoveDiscount;
activate();
/////////////////////
function activate() {
// Load checkout, and refresh cart
info();
// Load the user
visitorLoginService.isLoggedIn().then(function(isLoggedIn){
// Show the first step
if (isLoggedIn) {
$('#shippingAddress .panel-body').show();
}
// Guest checkout isn't enabled, and they aren't logged in, bounce 'em
if (!isGuestCheckoutEnabled() && !isLoggedIn) {
commonUtilService.addFlashMessage('Please log in or register to enter checkout.', 'info');
return $location.path('/registration');
}
$scope.isGuestCheckout = (isLoggedIn === false);
// They are logged in, check if we have any addresses on file
getAddresses();
});
checkoutService.loadSavedCC().then(function( res ){
if (res !== null){
var result = _.uniq(res, 'ID');
$scope.paymentMethods = $scope.paymentMethods.concat(result);
}
});
// Load payment methods
checkoutService.loadPaymentMethods().then(function(methods){
//merge payment methods and tokens;
$scope.paymentMethods = methods.concat($scope.paymentMethods);
});
$scope.$emit('add-breadcrumbs', {'label': 'Checkout', 'url': '/checkout'});
}
/**
* Gets checkout information, makes sure the cart is up to date
* @return {promise}
*/
function info() {
return checkoutService.update().then(function (checkout) {
$scope.checkout = checkout;
initAddressesData();
return cartService.reload().then(function(){
// If they don't have any items in cart redirect to the empty cart page
if (cartService.getCountItems() === 0) {
return $location.path('/cart');
}
});
});
function initAddressesData() {
if ($scope.checkout.shipping_address === null) {
$scope.checkout.shipping_address = getDefaultAddress();
}
if ($scope.checkout.billing_address === null) {
$scope.checkout.billing_address = getDefaultAddress();
}
}
}
function getDefaultAddress() {
return {
'street': '',
'city': '',
'state': '',
'phone': '',
'zip_code': '',
'company': '',
'first_name': '',
'last_name': '',
'address_line1': '',
'address_line2': '',
'country': 'US'
};
}
function isGuestCheckoutEnabled() {
return angular.appConfig.hasGuestCheckout;
}
/**
* Gets visitor addresses
*/
function getAddresses() {
return checkoutApiService.getAddresses().$promise
.then(function (response) {
var result = response.result || [];
$scope.addresses = result;
});
}
// REFACTOR: we should just be able to use the $scope.paymentMethod.selected object
function getPaymentInfo() {
var info = {
'method': null,
'form': null
};
info.method = $scope.paymentMethod.selected;
info.form = $scope.paymentMethod.selected.form;
return info;
}
function newBilling() {
// Sets a flag of form is not valid
isValidSteps.billingAddress = false;
// Initialise address by default
$scope.checkout.billing_address = getDefaultAddress();
$scope.addressSettings.useShippingAsBilling = false;
for (var field in $scope.checkout.billing_address) {
if ($scope.billingAddress.hasOwnProperty(field)) {
$scope.billingAddress[field].$pristine = true;
$scope.billingAddress[field].$invalid = false;
}
}
}
function newShipping() {
// Sets a flag of form is not valid
isValidSteps.shippingAddress = false;
// Initialise address by default
$scope.checkout.shipping_address = getDefaultAddress();
for (var field in $scope.checkout.shipping_address) {
if ($scope.shippingAddress.hasOwnProperty(field)) {
$scope.shippingAddress[field].$pristine = true;
$scope.shippingAddress[field].$invalid = false;
}
}
}
// REFACTOR: This is currently only used for saved addresses, and probably isn't needed
function choiceBilling(billingId) {
// TODO: [aknox] these top level conditions can't be right,
// why would we look at the shippingAddress form validity
if ($scope.isGuestCheckout && $scope.shippingAddress.$valid) {
checkoutService.saveBillingAddress($scope.checkout.shipping_address).then(
function (response) {
if (response.error === null) {
isValidSteps.billingAddress = true;
}
}
);
} else if ($scope.checkout.billing_address !== null && $scope.checkout.billing_address._id !== billingId && typeof billingId === 'string' && billingId !== '') {
// Sets existing address as billing
checkoutService.saveBillingAddress({'id': billingId}).then(
function (response) {
if (response.error === null) {
isValidSteps.billingAddress = true;
}
}
);
} else {
if ($scope.shippingAddress.$valid) {
checkoutService.saveBillingAddress($scope.checkout.shipping_address).then(
function (response) {
if (response.error === null) {
isValidSteps.billingAddress = true;
}
}
);
}
}
}
// REFACTOR: This is currently only used for saved addresses, and probably isn't needed
function choiceShipping (shippingId) {
if ($scope.isGuestCheckout) {
checkoutService.saveShippingAddress($scope.checkout.shipping_address).then(
function (response) {
// update checkout
info().then(function () {
// if all ok, must update allowed shipping methods list
// and must set billing address if set appropriate checkbox
if (response.error === null) {
checkoutService.loadShippingMethods().then(function (methods) {
$scope.shippingMethods = methods;
$scope.shippingMethod.selected = $scope.shippingMethods[0]; // select first option
});
// sets billing address
if ($scope.addressSettings.useShippingAsBilling) {
$scope.choiceBilling(response.result);
}
}
});
}
);
} else if (($scope.checkout.shipping_address !== null && $scope.checkout.shipping_address._id !== shippingId) || Boolean(shippingId)) {
// Sets existing address as shipping
checkoutService.saveShippingAddress({'id': shippingId}).then(
function (response) {
// update checkout
info().then(function () {
// if all ok, must update allowed shipping methods list
// and must set billing address if set appropriate checkbox
if (response.error === null) {
isValidSteps.shippingAddress = true;
checkoutService.loadShippingMethods().then(function (methods) {
$scope.shippingMethods = methods;
$scope.shippingMethod.selected = $scope.shippingMethods[0]; // select first option
});
// sets billing address
if ($scope.addressSettings.useShippingAsBilling) {
$scope.choiceBilling(response.result._id);
}
} else {
isValidSteps.billingAddress = false;
}
});
}
);
}
}
var _scrollTo = function($step){
$('html, body').animate({
scrollTop: $step.offset().top
}, 100);
};
function back(step) {
var $thisStep = $('#' + step);
var $lastStep = $thisStep.prev('.panel');
// We can start scrolling to the panel before animations finish because the
// distance from the top won't change
_scrollTo($lastStep);
$thisStep.find('.panel-body').slideUp(500);
$lastStep.find('.panel-body').slideDown(500);
}
function next(step) {
var _accordionAnimation = function(step, skipOneStep) {
var $thisStep = $('#' + step);
var $nextStep = $thisStep.next('.panel');
if (skipOneStep) {
$nextStep = $thisStep.next('.panel').next('.panel');
}
$thisStep.find('.panel-body').slideUp(600, function(){
_scrollTo($nextStep);
});
$nextStep.find('.panel-body').slideDown(500);
};
var actionBillingAddress = function () {
if ($scope.billingAddress.$valid) {
isValidSteps.billingAddress = true;
// REFACTOR: this condition could be worded better
if (
(
!Boolean($scope.checkout.billing_address._id) &&
!$scope.isGuestCheckout
) ||
$scope.isGuestCheckout
) {
checkoutService.saveBillingAddress($scope.checkout.billing_address)
.then(function () {
getAddresses(); //TODO: not sure this is necessary
// update checkout
info();
_accordionAnimation(step);
});
} else {
//TODO: Confirm that this is expected
_accordionAnimation(step);
}
}
};
var actionShippingAddress = function () {
if ($scope.shippingAddress.$valid) {
isValidSteps.shippingAddress = true;
//always persist shipping address in case there are shipping notes
checkoutService.saveShippingAddress($scope.checkout.shipping_address)
.then(function () {
getAddresses(); //TODO: not sure this is necessary
checkoutService.loadShippingMethods().then(function (methods) {
$scope.shippingMethods = methods;
// select first option
$scope.shippingMethod.selected = $scope.shippingMethods[0];
});
if ($scope.addressSettings.useShippingAsBilling) {
checkoutService.saveBillingAddress($scope.checkout.shipping_address)
.then(function (response) {
if (response.error === null) {
isValidSteps.billingAddress = true;
}
// update checkout
info();
// skip billing address step
var skipOneStep = true;
_accordionAnimation(step, skipOneStep);
});
} else {
// update checkout
info();
// open billing address
_accordionAnimation(step);
}
});
}
};
var actionShippingMethod = function() {
checkoutService.saveShippingMethod({
'method': $scope.shippingMethod.selected.Method,
'rate': $scope.shippingMethod.selected.Rate
}).then(function (response) {
if (response.result === 'ok') {
// update checkout
info();
isValidSteps.shippingMethod = true;
_accordionAnimation(step);
}
});
};
var actionPaymentMethod = function () {
isValidSteps.paymentMethod = false;
// Zero dollar, proceed
if ($scope.checkout.grandtotal <= 0) {
isValidSteps.paymentMethod = true;
info();
_accordionAnimation(step);
}
if ($scope.paymentMethod.selected) {
if ($scope.paymentMethod.selected.isCreditCard) {
var payment = getPaymentInfo();
payment.method.form.$submitted = true;
if (payment.method.form.$valid) {
// Save off the method name
checkoutService.savePaymentMethod({
method: $scope.paymentMethod.selected.Code
});
// Save off the cc form
checkoutService.saveAdditionalInfo({'cc': payment.method.cc})
.then(function(resp){
if (resp.result === 'ok') {
// Update the checkout object and proceed
isValidSteps.paymentMethod = true;
info();
_accordionAnimation(step);
}
});
}
} else if ($scope.paymentMethod.selected.ID){ //if method is saved token
var payment = getPaymentInfo();
// Save off the method name
checkoutService.savePaymentMethod({
method: $scope.paymentMethod.selected.Desc
});
// Save off the cc form
checkoutService.saveAdditionalInfo({
'cc': {
'id': $scope.paymentMethod.selected.ID
}
}).then(function(resp){
if (resp.result === 'ok') {
// Update the checkout object and proceed
isValidSteps.paymentMethod = true;
info();
_accordionAnimation(step);
}
});
} else {
// not a cc just continue
checkoutService.savePaymentMethod({
method: $scope.paymentMethod.selected.Code
})
.then(function(resp){
// update the checkout object and proceed
if (resp.result === 'ok') {
isValidSteps.paymentMethod = true;
info();
_accordionAnimation(step);
}
});
}
}
};
var actionCustomerAdditionalInfo = function () {
// isValidSteps isn't used for this step
if ($scope.isGuestCheckout && $scope.customerInfo.$valid) {
checkoutService.saveAdditionalInfo({
'customer_email': $scope.checkout.info.customer_email,
'customer_name': $scope.checkout.info.customer_name
}).then(function () {
info();
_accordionAnimation(step);
});
}
};
var actionDefault = function () {
if (isValidSteps[step]) {
_accordionAnimation(step);
}
};
switch (step) {
case 'billingAddress':
actionBillingAddress();
break;
case 'shippingAddress':
actionShippingAddress();
break;
case 'shippingMethod':
actionShippingMethod();
break;
case 'paymentMethod':
actionPaymentMethod();
break;
case 'customerInfo':
actionCustomerAdditionalInfo();
break;
default:
actionDefault();
}
}// jshint ignore:line
/**
* Saves checkout
*/
function save() {
$scope.isProcessingOrder = true;
var payment, isValid, sendPostForm;
$scope.message = '';
isValid = function () {
var result, message, getErrorMsg;
message = '';
result = {
status: true,
message: '',
};
getErrorMsg = function (step) {
/*jshint maxcomplexity:6 */
var msg = 'Please fill all required fields';
switch (step) {
case 'billingAddress':
msg = 'Please fill all required fields in billing section <br />';
break;
case 'shippingAddress':
msg = 'Please fill all required fields in shipping section <br />';
break;
case 'shippingMethod':
msg = 'Please choose shipping method <br />';
break;
case 'paymentMethod':
msg = 'Please choose payment method <br />';
break;
case 'additionalInfo':
msg = 'Please fill all required fields in additional section <br />';
break;
}
return msg;
};
for (var step in isValidSteps) {
if (isValidSteps.hasOwnProperty(step) && !isValidSteps[step]) {
message += getErrorMsg(step);
result = {
status: false,
message: message
};
}
}
return result;
};
sendPostForm = function (method, response) {
var form;
form = "<div class='hidden' id='auth_net_form'>" + response.result + '</div>';
form = form.replace('$CC_NUM', method.cc.number);
form = form.replace('$CC_MONTH', method.cc.expire_month);
form = form.replace('$CC_YEAR', method.cc.expire_year);
$('body').append(form);
$('#auth_net_form').find('form').submit();
$('#auth_net_form').remove();
};
payment = getPaymentInfo();
if (payment.form !== null && typeof payment.form !== 'undefined') {
payment.form.submited = true;
}
info().then(function () {
var checkoutValid = isValid();
if (checkoutValid.status) {
$(this).parents('.confirm').css('display', 'none');
$('#processing').modal('show');
checkoutApiService.save().$promise
.then(function(response) {
if (response.error === null) {
var isRemote = (null !== payment.method && payment.method.Type === 'remote' && response.result === 'redirect');
var isPostCC = (null !== payment.method && payment.method.Type === 'post_cc');
if (isRemote) {
// PayPal Express
window.location.replace(response.redirect);
$scope.isProcessingOrder = false;
} else if (isPostCC) {
// Auth.net
sendPostForm(payment.method, response);
$scope.isProcessingOrder = false;
} else {
// All Others; Zero Dollar, PayFlow Pro
info().then(function() {
var purchase = response.result || {};
//TODO: clean this up with angular modals and promises
$('#processing').modal('hide');
$timeout(function() {
$scope.isProcessingOrder = false;
$location.path('/checkout/success/' + purchase._id);
}, 600);
});
}
} else {
// Errors from server
$(this).parents('.confirm').css('display', 'block');
$('#processing').modal('hide');
$scope.message = commonUtilService.getMessage(response);
$scope.isProcessingOrder = false;
}
});
} else {
$(this).parents('.confirm').css('display', 'block');
$('#processing').modal('hide');
$scope.message = commonUtilService.getMessage(null, 'danger', checkoutValid.message);
}
});
}
function applyDiscount() {
var errorMessage = 'The coupon code or giftcard code entered is not valid at this time.';
var validationMessage = 'Please enter a coupon code or a giftcard code.';
var code = $scope.discounts.code;
var promises = [];
// Clear old messaging
$scope.discounts.message = false;
if (!code) {
$scope.discounts.message = commonUtilService.getMessage(null, 'danger', validationMessage);
return;
}
// Prevent double submission
if ($scope.discounts.isApplying) {
return;
}
$scope.discounts.isApplying = true;
// Apply this as a giftcard and a coupon
promises.push(giftcardsApiService.apply({'giftcode': code}));
promises.push(checkoutService.discountApply({'code': code}));
allResolved(promises).then(function(responses){
$scope.discounts.isApplying = false;
var respSuccess = _.filter(responses, {'error': null});
if (respSuccess.length) {
$scope.discounts.code = '';
info();
} else {
$scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage);
}
});
// NOTE: $q.all will reject if one of the promises is bad, so we can't use it here
// and have instead replicateed $Q.allResolved
function allResolved(promises) {
var deferred = $q.defer(),
counter = 0,
results = [];
angular.forEach(promises, function(promise, key) {
counter++;
$q.when(promise).then(function(value) {
if (results.hasOwnProperty(key)) {
return;
}
results[key] = value;
if (!(--counter)) {
deferred.resolve(results);
}
}, function(reason) {
if (results.hasOwnProperty(key)) {
return;
}
results[key] = reason.data;
if (!(--counter)) {
deferred.resolve(results);
}
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
}
function canRemoveDiscount(discount) {
if (!discount || !discount.Labels || !discount.Labels[0]) return false;
var removableDiscountTypes = {
'D': true,
'GC': true
};
return discount.Labels[0] in removableDiscountTypes;
}
function removeDiscount(discount){
if (!discount.Labels || !discount.Labels[0]) return;
var discountType = discount.Labels[0];
var errorMessage = 'Removing of coupon code or giftcard code is not avalable at this time.';
var giftcardMessage = 'Your giftcard was removed successfully!';
var couponMessage = 'Your coupon code was removed successfully!';
switch(discountType) {
// type Discount
case 'D':
checkoutApiService.removeDiscount({'code': discount.Code}).$promise
.then(function(response) {
if (response.error === null) {
info();
$scope.discounts.code = '';
$scope.discounts.message = commonUtilService.getMessage(null, 'success', couponMessage);
} else {
$scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage);
}
});
break;
// type gift-card
case 'GC':
giftcardsApiService.remove({'giftcode': discount.Code}).$promise
.then(function(response) {
if (response.error === null) {
info();
$scope.discounts.code = '';
$scope.discounts.message = commonUtilService.getMessage(null, 'success', giftcardMessage);
} else {
$scope.discounts.message = commonUtilService.getMessage(null, 'danger', errorMessage);
}
});
break;
}
}
}
]);
|
const router = require("express").Router();
const Category = require("../model/Category");
const { categoryValidation } = require("../validation");
const verify = require("./verifyToken");
router.post("/", verify, async (req, res) => {
const { error } = categoryValidation(req.body);
if (error) return res.status(400).send(error.details[0].message);
const category = new Category({
name: req.body.name,
icon: req.body.icon,
color: req.body.color,
owner: req.user._id
});
try {
const savedCategory = await category.save();
res.send(savedCategory);
} catch (err) {
res.status(400).send(err);
}
});
router.get("/", verify, async (req, res) => {
let query = {};
if (req.user.role !== "admin") {
query.owner = req.user._id;
}
try {
const allCategories = await Category.find(query);
res.send(allCategories);
} catch (err) {
res.status(400).send(err);
}
});
router.get("/:id", verify, async (req, res) => {
let query = {};
if (req.user.role !== "admin") {
query.owner = req.user._id;
}
try {
const categoryDetails = await Category.findById(
req.params.id,
(err, detail) => {
var opts = [{ path: "category", match: { owner: req.user._id } }];
Category.populate(detail, opts, function(err, details) {
console.log(details);
});
}
);
res.send(categoryDetails);
} catch (err) {
res.status(400).send(err);
}
});
router.put("/:id", async (req, res) => {
try {
Category.findOneAndUpdate(
{
_id: req.params.id
},
{
name: req.body.name,
icon: req.body.icon
},
err => {
if (err) {
return res.send(err);
}
return res.send("Successfully updated!");
}
);
} catch (err) {
res.status(400).send(err);
}
});
router.delete("/:id", async (req, res) => {
try {
const data = await Category.deleteOne({ _id: req.params.id });
if (data.ok === 1) {
return res.send("Successfully deleted!");
}
} catch (err) {
res.status(400).send(err);
}
});
module.exports = router;
|
//Wrapped in an outer function to preserve global this
(function (root) { var amdExports; define(['bootstrap/bootstrap-transition','bootstrap/bootstrap-tooltip'], function () { (function () {
/* ===========================================================
* bootstrap-popover.js v2.3.1
* http://twitter.github.com/bootstrap/javascript.html#popovers
* ===========================================================
* Copyright 2012 Twitter, Inc.
*
* 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.
* =========================================================== */
!function ($) {
"use strict"; // jshint ;_;
/* POPOVER PUBLIC CLASS DEFINITION
* =============================== */
var Popover = function (element, options) {
this.init('popover', element, options)
}
/* NOTE: POPOVER EXTENDS BOOTSTRAP-TOOLTIP.js
========================================== */
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
constructor: Popover
, setContent: function () {
var $tip = this.tip()
, title = this.getTitle()
, content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content')[this.options.html ? 'html' : 'text'](content)
$tip.removeClass('fade top bottom left right in')
}
, hasContent: function () {
return this.getTitle() || this.getContent()
}
, getContent: function () {
var content
, $e = this.$element
, o = this.options
content = (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
|| $e.attr('data-content')
return content
}
, tip: function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
}
return this.$tip
}
, destroy: function () {
this.hide().$element.off('.' + this.type).removeData(this.type)
}
})
/* POPOVER PLUGIN DEFINITION
* ======================= */
var old = $.fn.popover
$.fn.popover = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('popover')
, options = typeof option == 'object' && option
if (!data) $this.data('popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
$.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
placement: 'right'
, trigger: 'click'
, content: ''
, template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
/* POPOVER NO CONFLICT
* =================== */
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(window.jQuery);
}.call(root));
return amdExports;
}); }(this));
|
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../../actions/itemActions';
import FilterList from '../../components/FilterList/FilterList';
export const Filters = (props) => {
return (
<FilterList
changeShop={props.actions.changeShop}
shop={props.shop} />
);
};
Filters.propTypes = {
actions: PropTypes.object.isRequired,
shop: PropTypes.oneOf([
'side',
'secret',
'basics',
'upgrades'
])
};
function mapStateToProps(state) {
return {
shop: state.layout.shop
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Filters);
|
var priceCount;
var priceCountS;
window.onload = function(){
initContentList(1);
//$("#addContentBtn").bind("click",function(){
// window.location = "csicrmmgr.do?page=11";
//});
$("#query").bind("click",function(){initContentList(1);});
};
$(".colors a").live({
mouseover: (function(){
$(this).css("color","blue");
}),
mouseout:(function(){
$(this).css("color","red");
})
});
function initContentList(currPage){
var pageSize =15;
var data = {};
var form = ((currPage=currPage==0?1:currPage)-1)*pageSize;
data.from = form;
data.pageSize = pageSize;
data.memberId = $("#memberId").val();
data.orderId = $("#orderId").val();
data.state = $("#state option:selected").val();
data.sdate = $("#sdate").val();
data.edate = $("#edate").val();
if(data.edate!=null&&data.sdate!=null){
var totalMonth = getMct(data.sdate,data.edate,'-');
if(totalMonth>=6){
jAlert("查询日期范围不能大于半年","提示");
return;
}
}
var jsonData = JSON.stringify(data);
$.post("Orderstatis.do?method=getsalesList",{data:jsonData},function(json){
if(json!=null && json.returnState == true){
var data=json.data[0];
var context=$("#dataList");
context.html('');
if (data != null && data.length > 0) {
priceCount = json.data[1];
priceCountS = json.data[2];
$("#dataTips").hide();
var h=new Array();
for(var i=0;i<data.length;i++){
var bean=data[i];
h.push("<tr>");
h.push("<td>"+bean.recordId+"</td>");
h.push("<td class='colors'>"+bean.orderId+"</td>");
h.push("<td>"+bean.name+"</td>");
h.push("<td>"+bean.orderNum+"</td>");
h.push("<td>"+bean.unitPrice+"</td>");
h.push("<td>"+stateInfo(bean.state)+"</td>");
h.push("<td>"+bean.createTime+"</td>");
h.push("</tr>");
}
h.push("<tr class='tb td1'><td style='text-align: left;' colspan='6'>总订单金额:"+priceCount+"元 成功订单金额:"+priceCountS+"元 成效率:"+toDecimal(priceCountS/priceCount*100)+"%</td></tr>");
context.append(h.join(''));
}else{
$("#dataTips").show();
}
}
page(json.total,pageSize,currPage,"pageInfo","initContentList");
},"json");
}
//获取两个日期之间的月份差距
function getMct(beginTime,endTime,sign){
var beginDate = beginTime.split(sign);// 拆分开始日期的年月日
var endDate = endTime.split(sign);// 拆分开始日期的年月日
var bMonth = parseInt(beginDate[0]) * 12 + parseInt(beginDate[1]);// 得到开 始日期的月数
var eMonth = parseInt(endDate[0]) * 12 + parseInt(endDate[1]);// 得到结束日 期的月数
var totalMonth = Math.abs(eMonth - bMonth);// 获取月数
return totalMonth;
}
/**查看订单详情**/
function showTxt(memberId){
window.location ="Membermanage.do?page=12&memberId="+memberId;
}
/**设置操作栏按钮**/
function stateBut(bean){
if('1'==bean.state){
return "<input type='button' id='topay' value='已支付' class='bt_1' onclick=topay('"+bean.memberId+"','"+bean.currency+"','"+bean.totalAmount+"','"+bean.orderId+"');>";
}else if('2'==bean.state){
return "<input type='button' id='backpay' value='已发货' class='bt_1'>";
}
}
/**设置状态**/
function stateInfo(state){
if('1'==state){
return '待支付';
}
if('2'==state){
return '已支付';
}
if('3'==state){
return '已发货';
}
if('4'==state){
return '已接收';
}
if('5'==state){
return '已结案';
}
if('6'==state){
return '异常';
}
if('7'==state){
return '退货';
}
}
/**确认支付**/
function topay(memberId,currency,totalAmount,orderId){
jConfirm("您确认用户已经付款?", "提示", function (r) {
if (r) {
var data={};
data.memberId=memberId;
data.orderId=orderId;
data.currency=currency;
data.totalAmount=totalAmount;
var jsonData=JSON.stringify(data);
$.post("Ordermanage.do?method=toPayforOrder",{data:jsonData},function(json){
if(json!=null && json.returnState == true){
var message=json.message; //提示信息:0,币种不同 1,操作成功 2,余额不足 3,系统错误
if('0'==message){
jAlert("币种不同,无法支付!!","提示");
}else if('1'==message){
jAlert("操作成功!!","提示",function(){
initContentList(1);
});
}else if('2'==message){
jAlert("用户账户余额不足,不能执行'已支付'动作!!","提示");
}else if('3'==message){
jAlert("操作失败,请重试!!","提示");
}
}else{
jAlert("操作失败,请重试!!","提示");
}
},"json");
}
});
}
function toDecimal(x) {
var f = parseFloat(x);
if (isNaN(f)) {
return;
}
f = Math.round(x*100)/100;
return f;
}
|
// @flow
/**
* CommonFashionista: provides utilities to help manage Fashions
* (which are * object-representations of CSS styles).
*
* @module internal/fashionistas/common
*/
import Debug from 'debug'
import chroma from 'chroma-js'
import type {
CalcFashion,
ColorFashion,
CompositeFashion,
Fashion,
NumberFashion,
StaticFashion,
UnitFashion,
} from '../flow-types'
import {
ALL_COMMAS_REGEX,
NUMBER_REGEX,
NON_NUMER_REGEX,
makeError,
} from '../utils'
import {
BOX_SHADOW,
TRANSFORM,
TRANSFORM_DELIMITER,
} from '../constants'
const EMPTY_UNIT: string = '0px';
const debug = Debug('react-animatronics:fashionistas:common');
const isCommaString = (str: string): boolean => {
return (
typeof str === 'string'
&& str.includes(',')
&& !str.includes('rgb')
&& !str.includes('hsl')
);
}
export const isColorString = (str: string): boolean => {
let color;
try {
color = chroma(str);
} catch (e) {
color = false;
}
return !!color;
}
// NOTE: replace decimals and negative signs otherwise it'll get caught by the
// NON_NUMBER_REGEX
// TODO: why is the NON_NUMBER_REGEX check in here?
export const isNumberString = (str: string): boolean => (
!isNaN(parseFloat(str))
&& !NON_NUMER_REGEX.test(str.replace('.', '').replace('-', ''))
);
// FIXME: can have false positives
export const isUnitString = (str: string): boolean => (
NUMBER_REGEX.test(str)
);
export const createColorFashion = (raw: string): ColorFashion => ({
isBasicType: true,
isColorType: true,
value: chroma(raw).hex(),
});
export const createStaticFashion = (raw: string): StaticFashion => ({
isBasicType: true,
isStaticType: true,
value: raw,
});
export const createNumberFashion = (raw: string|number): NumberFashion => ({
isBasicType: true,
isNumberType: true,
value: parseFloat(raw),
});
// EXPERIMENT: Perhaps departing from implicit returns since they make
// debugging more difficult.
export const createUnitFashion = (raw: string): UnitFashion => {
debug('creating unit fashion for "%s"', raw);
return {
isBasicType: true,
isUnitType: true,
value: parseFloat(NUMBER_REGEX.exec(raw)[0]),
unit: raw.slice(NUMBER_REGEX.exec(raw)[0].length),
};
};
export const createCalcFashion = (raw: string): CalcFashion => {
debug('creating calc fashion fro "%s"', raw);
return {
isBasicType: true,
isCalcType: true,
value: raw,
};
};
export const parseTransformName = (transform: string): string => {
return transform.slice(0, transform.indexOf('('));
};
// TODO: Better function names
const removeLastChar = (str: string) => {
return str.substr(0, str.length - 1);
};
const butLast = (array: any[]) => {
return array.slice(0, array.length - 1);
}
const last = (array: any[]) => {
return array[array.length - 1];
}
// FIXME: Lots of imperative code here, there must be a better way. To goal is
// to correctly split any valid CSS transforms, which can have nested parens
// e.g. "translateX(100px) translateY(calc((100% - 40px) * -1))"
export const splitTransforms = (transforms: string) => {
let openParenCount = 0;
const startingCharIndexes = [];
const chars = transforms.split('');
const splits = [];
for (let i = 0; i < chars.length; ++i) {
const c = chars[i];
if (c === ' ') {
continue;
} else if (startingCharIndexes.length === 0) {
startingCharIndexes.push(i);
} else if (c === '(') {
openParenCount += 1;
} else if (c === ')') {
if (openParenCount === 1) {
splits.push(
chars
.slice(startingCharIndexes.pop(), i + 1)
.join('')
);
openParenCount -= 1;
} else if (openParenCount > 1) {
openParenCount -= 1;
}
}
}
return splits;
}
/**
* @param string value e.g. "translateX(100x)", "translateY(calc(100% - 40px))"
* @returns string e.g. "100px", "calc(100% - 40px)"
*/
export const parseInnerTransformValue = (value: string): string => {
const [_, ...inner] = value.split('(');
return butLast(inner)
.concat(removeLastChar(last(inner)))
.join('(');
}
const parseTransformStyle = (transform: string): Fashion => {
return parseStyle(parseInnerTransformValue(transform));
}
export const createTransformFashion = (raw: string): CompositeFashion => ({
isCompositeType: true,
names: splitTransforms(raw).map(parseTransformName),
styles: splitTransforms(raw).map(parseTransformStyle),
});
/**
* @param raw - e.g. "6px 12px" (margin/padding shorthand)
* @returns CompositeFashion
*/
export const createSpacingFashion = (raw: string, name: string): CompositeFashion => {
const segments = raw.split(' ');
const numSegments = segments.filter(s => !!s).length;
if (numSegments < 1 || numSegments > 4) {
throw makeError(
`Received an invalid style for ${ name || "margin/padding" }: "${ raw }".`,
`Margins/paddings should have between 1 to 4 values (no less than 1 and`,
`no more than 4).`
);
}
const parsed = segments.map(createUnitFashion);
return {
isCompositeType: true,
styles: numSegments === 1 ?
[parsed[0], parsed[0], parsed[0], parsed[0]]
: numSegments === 2 ?
[parsed[0], parsed[1], parsed[0], parsed[1]]
: numSegments === 3 ?
[parsed[0], parsed[1], parsed[2], parsed[1]]
: // numSegments === 4
[parsed[0], parsed[1], parsed[2], parsed[3]]
};
};
export const createCommaFashion = (raw: string, name: ?string): CompositeFashion => ({
isCompositeType: true,
isCommaType: true,
styles: raw
.split(',')
.map(s => s.trim())
.map(style => parseStyle(style, name)),
});
export const createBoxShadowFashion = (raw: string): CompositeFashion => {
const segments = raw.split(' ');
const numSegments = segments.filter(s => !!s).length;
if (numSegments < 3 || numSegments > 5) {
throw makeError(
`Received an invalid style for box-shadow: "${ raw }".`,
`Box-shadows should have between 3 to 5 values:`,
`https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow`
);
}
// Possible formats:
// offset-x | offset-y | color
// offset-x | offset-y | blur-radius | color
// offset-x | offset-y | blur-radius | spread-radius | color
// inset | offset-x | offset-y | color
// Target format:
// offset-x | offset-y | blur-radius | spread-radius | color
return {
isCompositeType: true,
styles: numSegments === 3 ?
[
createUnitFashion(segments[0]),
createUnitFashion(segments[1]),
createUnitFashion(EMPTY_UNIT),
createUnitFashion(EMPTY_UNIT),
createColorFashion(segments[2])
]
: (numSegments === 4 && segments[0] === 'inset') ?
[
createStaticFashion(segments[0]),
createUnitFashion(segments[1]),
createUnitFashion(segments[2]),
createColorFashion(segments[3])
]
: (numSegments === 4) ?
[
createUnitFashion(segments[0]),
createUnitFashion(segments[1]),
createUnitFashion(segments[2]),
createUnitFashion(EMPTY_UNIT),
createColorFashion(segments[3])
]
: // numSegments === 5
[
createUnitFashion(segments[0]),
createUnitFashion(segments[1]),
createUnitFashion(segments[2]),
createUnitFashion(segments[3]),
createColorFashion(segments[4])
]
};
}
export const parseStyle = (raw: string|number, name: ?string): Fashion => {
return typeof raw === 'number' ?
createNumberFashion(raw)
: isNumberString(raw) ?
createNumberFashion(raw)
: typeof raw === 'string' && name === TRANSFORM ?
createTransformFashion(raw)
: typeof raw === 'string' && (raw.includes('calc') || raw.includes('matrix')) ?
createCalcFashion(raw)
: typeof name === 'string' && (name.includes('margin') || name.includes('padding')) ?
createSpacingFashion(raw, name)
: isCommaString(raw) ?
createCommaFashion(raw, name)
: name === BOX_SHADOW ?
createBoxShadowFashion(raw)
: isColorString(raw) ?
createColorFashion(raw)
: isUnitString(raw) ?
createUnitFashion(raw)
:
createStaticFashion(raw)
};
export const stringifyCalc = (calc: CalcFashion) => calc.value;
export const stringifyColor = (color: ColorFashion) => `${ chroma(color.value).hex() }`;
export const stringifyNumber = (number: NumberFashion) => `${ number.value }`;
export const stringifyUnit = (style: UnitFashion) => `${ style.value }${ style.unit }`;
export const stringifyComposite = (composite: CompositeFashion) => composite.styles
.reduce((arr: string[], style: Fashion, index: number) => {
const name: ?string = composite.names && composite.names[index];
return arr.concat(
name
? `${ name }(${ stringifyFashion(style) })`
: stringifyFashion(style)
);
}, [])
.join(composite.isCommaType ? ', ' : ' ');
const stringifyBasic = (fashion: Fashion): string => {
debug('stringifying basic fashion %o', fashion);
return fashion.isColorType ?
stringifyColor(fashion)
: fashion.isNumberType ?
stringifyNumber(fashion)
: fashion.isUnitType ?
stringifyUnit(fashion)
: fashion.isCalcType ?
stringifyCalc(fashion)
:
''
};
export const stringifyFashion = (style: Fashion): string => (
style.isCompositeType ?
stringifyComposite(style)
: // default: unknown style
stringifyBasic(style)
);
// IMPROVE: By default, all "transforms" will be converted, even if they have
// the same units. We can be more efficient about this, but it's unclear if
// that's worth it right now.
export const haveConvertibleUnits = (
rawA: string,
rawB: string,
styleName: string
): boolean => {
if (styleName === TRANSFORM) return true;
const fashionA = parseStyle(rawA, styleName);
const fashionB = parseStyle(rawB, styleName);
return (fashionA.isCalcType || fashionB.isCalcType) ?
true
: (fashionA.unit && fashionB.unit) ?
fashionA.unit !== fashionB.unit
:
false
};
const lastChar = (s: string) => s[s.length - 1];
export const separateTransformNames = (transform: string) => {
const separated = splitTransforms(transform)
.map(parseTransformName);
return separated;
}
export const parseTransformsSeparately = (transforms: string) => {
return splitTransforms(transforms)
.sort()
.reduce((result, transform) => {
const name = parseTransformName(transform);
result[name] = transform;
return result;
}, {})
};
export const pluckTransforms = (
styles: Object,
transformations: string[]
) => {
return Object.keys(styles)
.map(transformName => {
return transformations.includes(transformName) ? styles[transformName] : '';
})
.filter(t => !!t)
.join(' ');
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.