code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
import $ from 'jquery';
module.exports = function(root) {
root = root ? root : global;
root.expect = root.chai.expect;
root.$ = $;
beforeEach(() => {
// Using these globally-available Sinon features is preferrable, as they're
// automatically restored for you in the subsequent `afterEach`
root.sandbox = root.sinon.sandbox.create();
root.stub = root.sandbox.stub.bind(root.sandbox);
root.spy = root.sandbox.spy.bind(root.sandbox);
root.mock = root.sandbox.mock.bind(root.sandbox);
root.useFakeTimers = root.sandbox.useFakeTimers.bind(root.sandbox);
root.useFakeXMLHttpRequest = root.sandbox.useFakeXMLHttpRequest.bind(root.sandbox);
root.useFakeServer = root.sandbox.useFakeServer.bind(root.sandbox);
});
afterEach(() => {
delete root.stub;
delete root.spy;
root.sandbox.restore();
});
};
| atd/cartodb.js | test/setup/setup.js | JavaScript | mit | 855 |
const mongoose = require('mongoose');
const UserModel = mongoose.model('User');
module.exports = {
login: (email, password) => {
return UserModel.findOne({email, password});
}
}; | Spardevil/angular-crm | server/server/services/auth.service.js | JavaScript | mit | 184 |
module.exports = {
login: function(user, req)
{
// Parse detailed information from user-agent string
var r = require('ua-parser').parse(req.headers['user-agent']);
// Create new UserLogin row to database
sails.models.loglogin.create({
ip: req.ip,
host: req.host,
agent: req.headers['user-agent'],
browser: r.ua.toString(),
browserVersion: r.ua.toVersionString(),
browserFamily: r.ua.family,
os: r.os.toString(),
osVersion: r.os.toVersionString(),
osFamily: r.os.family,
device: r.device.family,
user: user.id
})
.exec(function(err, created) {
if(err) sails.log(err);
created.user = user;
sails.models.loglogin.publishCreate(created);
});
},
request: function(log, req, resp)
{
//var userId = -1;
// if (req.token) {
// userId = req.token;
// } else {
// userId = -1;
// }
sails.models.logrequest.create({
ip: log.ip,
protocol: log.protocol,
method: log.method,
url: log.diagnostic.url,
headers: req.headers || {},
parameters: log.diagnostic.routeParams,
body: log.diagnostic.bodyParams,
query: log.diagnostic.queryParams,
responseTime: log.responseTime || 0,
middlewareLatency: log.diagnostic.middlewareLatency || 0,
user: req.token || 0
})
.exec(function(err, created) {
if(err) sails.log(err);
sails.models.logrequest.publishCreate(created);
});
}
};
| modulr/modulr | api/api/services/LogService.js | JavaScript | mit | 1,506 |
const isObjectId = objectId => objectId && /^[0-9a-fA-F]{24}$/.test(objectId)
const isEmail = email => email && /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email.trim())
const isNick = nick => nick && /^[\u4E00-\u9FA5\uF900-\uFA2DA-Za-z0-9\-\_]{2,40}$/.test(nick.trim())
const isUrl = url => url && /^(http(?:|s)\:)*\/\/([^\/]+)/.test(url.trim())
export {
isObjectId,
isEmail,
isNick,
isUrl
}
| S-mohan/mblog | src/utils/validate.js | JavaScript | mit | 406 |
var Command = require("../Command");
var RealDirection = require("../../RealDirection");
var MessageCategory = require("../../MessageCategory");
var _dir = RealDirection.NORTHEAST;
class Northeast extends Command{
constructor(){
super();
this.rule = /^n(?:orth)?e(?:ast)?$/g;
}
exec(){
if(this.step(_dir)){
this.showRoom();
} else {
this.sendMessage("Alas, you can't go that way.", MessageCategory.COMMAND);
}
}
}
module.exports = Northeast;
| jackindisguise/node-mud | src/handle/command/Northeast.js | JavaScript | mit | 465 |
import VueRouter from 'vue-router'
import { mount } from '@vue/test-utils'
import { waitNT, waitRAF } from '../../../tests/utils'
import { Vue } from '../../vue'
import { BPaginationNav } from './pagination-nav'
Vue.use(VueRouter)
// The majority of tests for the core of pagination mixin are performed
// in pagination.spec.js. Here we just test the differences that
// <pagination-nav> has
// We use a (currently) undocumented wrapper method `destroy()` at the end
// of each test to remove the VM and DOM from the JSDOM document, as
// the wrapper's and instances remain after each test completes
describe('pagination-nav', () => {
it('renders with correct basic structure for root elements', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 1,
value: 1
}
})
await waitNT(wrapper.vm)
await waitRAF()
// <pagination-nav> has an outer wrapper of nav
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// NAV Attributes
expect(wrapper.attributes('aria-hidden')).toBe('false')
expect(wrapper.attributes('aria-label')).toBe('Pagination')
// UL Classes
expect($ul.classes()).toContain('pagination')
expect($ul.classes()).toContain('b-pagination')
expect($ul.classes()).not.toContain('pagination-sm')
expect($ul.classes()).not.toContain('pagination-lg')
expect($ul.classes()).not.toContain('justify-content-center')
expect($ul.classes()).not.toContain('justify-content-end')
// UL Attributes
expect($ul.attributes('role')).not.toBe('menubar')
expect($ul.attributes('aria-disabled')).toBe('false')
expect($ul.attributes('aria-label')).not.toBe('Pagination')
wrapper.destroy()
})
it('renders with correct default HREF', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/1')
expect($links.at(1).attributes('href')).toBe('/2')
expect($links.at(2).attributes('href')).toBe('/1')
expect($links.at(3).attributes('href')).toBe('/2')
expect($links.at(4).attributes('href')).toBe('/3')
expect($links.at(5).attributes('href')).toBe('/4')
expect($links.at(6).attributes('href')).toBe('/5')
expect($links.at(7).attributes('href')).toBe('/4')
expect($links.at(8).attributes('href')).toBe('/5')
wrapper.destroy()
})
it('renders with correct default page button text', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
expect($links.at(2).text()).toBe('1')
expect($links.at(3).text()).toBe('2')
expect($links.at(4).text()).toBe('3')
expect($links.at(5).text()).toBe('4')
expect($links.at(6).text()).toBe('5')
wrapper.destroy()
})
it('disabled renders correct', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 1,
value: 1,
disabled: true
}
})
await waitNT(wrapper.vm)
await waitRAF()
// <pagination-nav> has an outer wrapper of nav
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// NAV Attributes
expect(wrapper.attributes('aria-hidden')).toBe('true')
expect(wrapper.attributes('aria-disabled')).toBe('true')
// UL Classes
expect($ul.classes()).toContain('pagination')
expect($ul.classes()).toContain('b-pagination')
// UL Attributes
expect($ul.attributes('role')).not.toBe('menubar')
expect($ul.attributes('aria-disabled')).toBe('true')
// LI classes
expect(wrapper.findAll('li').length).toBe(5)
expect(wrapper.findAll('li.page-item').length).toBe(5)
expect(wrapper.findAll('li.disabled').length).toBe(5)
// LI Inner should be span elements
expect(wrapper.findAll('li > span').length).toBe(5)
expect(wrapper.findAll('li > span.page-link').length).toBe(5)
expect(wrapper.findAll('li > span[aria-disabled="true"').length).toBe(5)
wrapper.destroy()
})
it('reacts to changes in number-of-pages', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 3,
value: 2,
limit: 10
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
let $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(7)
await wrapper.setProps({
numberOfPages: 5
})
await waitNT(wrapper.vm)
$links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
wrapper.destroy()
})
it('renders with correct HREF when base-url specified', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
baseUrl: '/foo/'
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/foo/1')
expect($links.at(1).attributes('href')).toBe('/foo/2')
expect($links.at(2).attributes('href')).toBe('/foo/1')
expect($links.at(3).attributes('href')).toBe('/foo/2')
expect($links.at(4).attributes('href')).toBe('/foo/3')
expect($links.at(5).attributes('href')).toBe('/foo/4')
expect($links.at(6).attributes('href')).toBe('/foo/5')
expect($links.at(7).attributes('href')).toBe('/foo/4')
expect($links.at(8).attributes('href')).toBe('/foo/5')
wrapper.destroy()
})
it('renders with correct HREF when link-gen function provided', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
linkGen: page => `?${page}`
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('?1')
expect($links.at(1).attributes('href')).toBe('?2')
expect($links.at(2).attributes('href')).toBe('?1')
expect($links.at(3).attributes('href')).toBe('?2')
expect($links.at(4).attributes('href')).toBe('?3')
expect($links.at(5).attributes('href')).toBe('?4')
expect($links.at(6).attributes('href')).toBe('?5')
expect($links.at(7).attributes('href')).toBe('?4')
expect($links.at(8).attributes('href')).toBe('?5')
wrapper.destroy()
})
it('renders with correct HREF when link-gen function returns object', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
linkGen: page => ({ path: `/baz?${page}` })
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
wrapper.destroy()
})
it('renders with correct page button text when page-gen function provided', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 5,
value: 3,
limit: 10,
pageGen: page => `Page ${page}`
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
expect($links.at(2).text()).toBe('Page 1')
expect($links.at(3).text()).toBe('Page 2')
expect($links.at(4).text()).toBe('Page 3')
expect($links.at(5).text()).toBe('Page 4')
expect($links.at(6).text()).toBe('Page 5')
wrapper.destroy()
})
it('renders with correct HREF when array of links set via pages prop', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 3,
limit: 10,
pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4', '/baz?5']
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
// Page buttons have correct content
expect($links.at(2).text()).toBe('1')
expect($links.at(3).text()).toBe('2')
expect($links.at(4).text()).toBe('3')
expect($links.at(5).text()).toBe('4')
expect($links.at(6).text()).toBe('5')
wrapper.destroy()
})
it('renders with correct HREF when array of links and text set via pages prop', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 3,
limit: 10,
pages: [
{ link: '/baz?1', text: 'one' },
{ link: '/baz?2', text: 'two' },
{ link: '/baz?3', text: 'three' },
{ link: '/baz?4', text: 'four' },
{ link: '/baz?5', text: 'five' }
]
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
const $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(9)
// Default base URL is '/', and link will be the page number
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?2')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?5')
expect($links.at(7).attributes('href')).toBe('/baz?4')
expect($links.at(8).attributes('href')).toBe('/baz?5')
// Page buttons have correct content
expect($links.at(2).text()).toBe('one')
expect($links.at(3).text()).toBe('two')
expect($links.at(4).text()).toBe('three')
expect($links.at(5).text()).toBe('four')
expect($links.at(6).text()).toBe('five')
wrapper.destroy()
})
it('reacts to changes in pages array length', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
value: 2,
limit: 10,
pages: ['/baz?1', '/baz?2', '/baz?3']
}
})
await waitNT(wrapper.vm)
await waitRAF()
expect(wrapper.element.tagName).toBe('NAV')
let $links = wrapper.findAll('a.page-link')
expect($links.length).toBe(7)
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?1')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?3')
expect($links.at(6).attributes('href')).toBe('/baz?3')
// Add extra page
await wrapper.setProps({
pages: ['/baz?1', '/baz?2', '/baz?3', '/baz?4']
})
await waitNT(wrapper.vm)
$links = wrapper.findAll('a.page-link')
expect($links.length).toBe(8)
expect($links.at(0).attributes('href')).toBe('/baz?1')
expect($links.at(1).attributes('href')).toBe('/baz?1')
expect($links.at(2).attributes('href')).toBe('/baz?1')
expect($links.at(3).attributes('href')).toBe('/baz?2')
expect($links.at(4).attributes('href')).toBe('/baz?3')
expect($links.at(5).attributes('href')).toBe('/baz?4')
expect($links.at(6).attributes('href')).toBe('/baz?3')
expect($links.at(7).attributes('href')).toBe('/baz?4')
wrapper.destroy()
})
it('clicking buttons updates the v-model', async () => {
const App = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
methods: {
onPageClick(bvEvent, page) {
// Prevent 3rd page from being selected
if (page === 3) {
bvEvent.preventDefault()
}
}
},
render(h) {
return h(BPaginationNav, {
props: {
baseUrl: '#', // Needed to prevent JSDOM errors
numberOfPages: 5,
value: 1,
limit: 10
},
on: { 'page-click': this.onPageClick }
})
}
}
const wrapper = mount(App)
expect(wrapper).toBeDefined()
const paginationNav = wrapper.findComponent(BPaginationNav)
expect(paginationNav).toBeDefined()
expect(paginationNav.element.tagName).toBe('NAV')
// Grab the page links
const lis = paginationNav.findAll('li')
expect(lis.length).toBe(9)
expect(paginationNav.vm.computedCurrentPage).toBe(1)
expect(paginationNav.emitted('input')).toBeUndefined()
expect(paginationNav.emitted('change')).toBeUndefined()
expect(paginationNav.emitted('page-click')).toBeUndefined()
// Click on current (1st) page link (does nothing)
await lis
.at(2)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(1)
expect(paginationNav.emitted('input')).toBeUndefined()
expect(paginationNav.emitted('change')).toBeUndefined()
expect(paginationNav.emitted('page-click')).toBeUndefined()
// Click on 2nd page link
await lis
.at(3)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(2)
expect(paginationNav.emitted('input')).toBeDefined()
expect(paginationNav.emitted('change')).toBeDefined()
expect(paginationNav.emitted('page-click')).toBeDefined()
expect(paginationNav.emitted('input')[0][0]).toBe(2)
expect(paginationNav.emitted('change')[0][0]).toBe(2)
expect(paginationNav.emitted('page-click').length).toBe(1)
// Click goto last page link
await lis
.at(8)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(5)
expect(paginationNav.emitted('input')[1][0]).toBe(5)
expect(paginationNav.emitted('change')[1][0]).toBe(5)
expect(paginationNav.emitted('page-click').length).toBe(2)
// Click prev page link
await lis
.at(1)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(4)
expect(paginationNav.emitted('input')[2][0]).toBe(4)
expect(paginationNav.emitted('change')[2][0]).toBe(4)
expect(paginationNav.emitted('page-click').length).toBe(3)
// Click on 3rd page link (prevented)
await lis
.at(4)
.find('a')
.trigger('click')
await waitRAF()
expect(paginationNav.vm.computedCurrentPage).toBe(4)
expect(paginationNav.emitted('input').length).toBe(3)
expect(paginationNav.emitted('change').length).toBe(3)
expect(paginationNav.emitted('page-click').length).toBe(4)
wrapper.destroy()
})
describe('auto-detect page', () => {
// Note: JSDOM only works with hash URL updates out of the box
beforeEach(() => {
// Make sure theJSDOM is at '/', as JSDOM instances for each test!
window.history.pushState({}, '', '/')
})
it('detects current page without $router', async () => {
const wrapper = mount(BPaginationNav, {
propsData: {
numberOfPages: 3,
value: null,
linkGen: page => (page === 2 ? '/' : `/#${page}`)
}
})
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
expect(wrapper.vm.$router).toBeUndefined()
expect(wrapper.vm.$route).toBeUndefined()
expect(wrapper.element.tagName).toBe('NAV')
const $ul = wrapper.find('ul.pagination')
expect($ul.exists()).toBe(true)
// Emitted current page (2)
expect(wrapper.emitted('input')).toBeDefined()
expect(wrapper.emitted('input').length).toBe(1)
expect(wrapper.emitted('input')[0][0]).toBe(2) // Page 2, URL = ''
wrapper.destroy()
})
it('works with $router to detect path and linkGen returns location object', async () => {
const App = {
compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' },
components: { BPaginationNav },
methods: {
linkGen(page) {
// We make page #2 "home" for testing
// We return a to prop to auto trigger use of $router
// if using strings, we would need to set use-router=true
return page === 2 ? { path: '/' } : { path: '/' + page }
}
},
template: `
<div>
<b-pagination-nav :number-of-pages="3" :link-gen="linkGen"></b-pagination-nav>
<router-view></router-view>
</div>
`
}
// Our router view component
const FooRoute = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
render(h) {
return h('div', { class: 'foo-content' }, ['stub'])
}
}
// Create router instance
const router = new VueRouter({
routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }]
})
const wrapper = mount(App, { router })
expect(wrapper).toBeDefined()
// Wait for the router to initialize
await new Promise(resolve => router.onReady(resolve))
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 2
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2)
// Push router to a new page
wrapper.vm.$router.push('/3')
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 3
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3)
wrapper.destroy()
})
it('works with $router to detect path and use-router set and linkGen returns string', async () => {
const App = {
compatConfig: { MODE: 3, COMPONENT_FUNCTIONAL: 'suppress-warning' },
components: { BPaginationNav },
methods: {
linkGen(page) {
// We make page #2 "home" for testing
// We return a to prop to auto trigger use of $router
// if using strings, we would need to set use-router=true
return page === 2 ? '/' : `/${page}`
}
},
template: `
<div>
<b-pagination-nav :number-of-pages="3" :link-gen="linkGen" use-router></b-pagination-nav>
<router-view></router-view>
</div>
`
}
// Our router view component
const FooRoute = {
compatConfig: { MODE: 3, RENDER_FUNCTION: 'suppress-warning' },
render(h) {
return h('div', { class: 'foo-content' }, ['stub'])
}
}
// Create router instance
const router = new VueRouter({
routes: [{ path: '/', component: FooRoute }, { path: '/:page', component: FooRoute }]
})
const wrapper = mount(App, { router })
expect(wrapper).toBeDefined()
// Wait for the router to initialize
await new Promise(resolve => router.onReady(resolve))
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The <pagination-nav> component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 2
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(2)
// Push router to a new page
wrapper.vm.$router.push('/3')
// Wait for the guessCurrentPage to complete
await waitNT(wrapper.vm)
await waitRAF()
await waitNT(wrapper.vm)
// The pagination-nav component should exist
expect(wrapper.findComponent(BPaginationNav).exists()).toBe(true)
// And should be on page 3
expect(wrapper.findComponent(BPaginationNav).vm.currentPage).toBe(3)
wrapper.destroy()
})
})
})
| bootstrap-vue/bootstrap-vue | src/components/pagination-nav/pagination-nav.spec.js | JavaScript | mit | 22,231 |
module.exports = (name, node) => (
name === "apply" &&
node.type === "CallExpression" &&
node.callee.type === "Identifier");
| lachrist/aran | test/dead/apply/pointcut.js | JavaScript | mit | 131 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016-2017 The Regents of the University of California
* Author: Jim Robinson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import {loadIndex} from "./indexFactory.js"
import AlignmentContainer from "./alignmentContainer.js"
import BamUtils from "./bamUtils.js"
import {BGZip, igvxhr} from "../../node_modules/igv-utils/src/index.js"
import {buildOptions} from "../util/igvUtils.js"
/**
* Class for reading a bam file
*
* @param config
* @constructor
*/
class BamReader {
constructor(config, genome) {
this.config = config
this.genome = genome
this.bamPath = config.url
this.baiPath = config.indexURL
BamUtils.setReaderDefaults(this, config)
}
async readAlignments(chr, bpStart, bpEnd) {
const chrToIndex = await this.getChrIndex()
const queryChr = this.chrAliasTable.hasOwnProperty(chr) ? this.chrAliasTable[chr] : chr
const chrId = chrToIndex[queryChr]
const alignmentContainer = new AlignmentContainer(chr, bpStart, bpEnd, this.config)
if (chrId === undefined) {
return alignmentContainer
} else {
const bamIndex = await this.getIndex()
const chunks = bamIndex.blocksForRange(chrId, bpStart, bpEnd)
if (!chunks || chunks.length === 0) {
return alignmentContainer
}
let counter = 1
for (let c of chunks) {
let lastBlockSize
if (c.maxv.offset === 0) {
lastBlockSize = 0 // Don't need to read the last block.
} else {
const bsizeOptions = buildOptions(this.config, {range: {start: c.maxv.block, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
lastBlockSize = BGZip.bgzBlockSize(abuffer)
}
const fetchMin = c.minv.block
const fetchMax = c.maxv.block + lastBlockSize
const range = {start: fetchMin, size: fetchMax - fetchMin + 1}
const compressed = await igvxhr.loadArrayBuffer(this.bamPath, buildOptions(this.config, {range: range}))
var ba = BGZip.unbgzf(compressed) //new Uint8Array(BGZip.unbgzf(compressed)); //, c.maxv.block - c.minv.block + 1));
const done = BamUtils.decodeBamRecords(ba, c.minv.offset, alignmentContainer, this.indexToChr, chrId, bpStart, bpEnd, this.filter)
if (done) {
// console.log(`Loaded ${counter} chunks out of ${chunks.length}`);
break
}
counter++
}
alignmentContainer.finish()
return alignmentContainer
}
}
async getHeader() {
if (!this.header) {
const genome = this.genome
const index = await this.getIndex()
let start
let len
if (index.firstBlockPosition) {
const bsizeOptions = buildOptions(this.config, {range: {start: index.firstBlockPosition, size: 26}})
const abuffer = await igvxhr.loadArrayBuffer(this.bamPath, bsizeOptions)
const bsize = BGZip.bgzBlockSize(abuffer)
len = index.firstBlockPosition + bsize // Insure we get the complete compressed block containing the header
} else {
len = 64000
}
const options = buildOptions(this.config, {range: {start: 0, size: len}})
this.header = await BamUtils.readHeader(this.bamPath, options, genome)
}
return this.header
}
async getIndex() {
const genome = this.genome
if (!this.index) {
this.index = await loadIndex(this.baiPath, this.config, genome)
}
return this.index
}
async getChrIndex() {
if (this.chrToIndex) {
return this.chrToIndex
} else {
const header = await this.getHeader()
this.chrToIndex = header.chrToIndex
this.indexToChr = header.chrNames
this.chrAliasTable = header.chrAliasTable
return this.chrToIndex
}
}
}
export default BamReader
| igvteam/igv.js | js/bam/bamReader.js | JavaScript | mit | 5,347 |
var should = require("should");
var Mat3x3 = require("./Mat3x3");
var Barycentric3 = require("./Barycentric3");
var Logger = require("./Logger");
(function(exports) {
var verboseLogger = new Logger({
logLevel: "debug"
});
////////////////// constructor
function XYZ(x, y, z, options) {
var that = this;
if (typeof x === "number") {
that.x = x;
that.y = y;
that.z = z;
should &&
y.should.Number &&
z.should.Number &&
isNaN(x).should.False &&
isNaN(y).should.False &&
isNaN(z).should.False;
} else {
var xyz = x;
should &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
that.x = xyz.x;
that.y = xyz.y;
that.z = xyz.z;
if (options == null) {
options = y;
}
}
options = options || {};
if (options.verbose) {
that.verbose = options.verbose;
}
return that;
}
XYZ.prototype.nearest = function(a, b) {
var that = this;
var adx = a.x - that.x;
var ady = a.y - that.y;
var adz = a.z - that.z;
var bdx = b.x - that.x;
var bdy = b.y - that.y;
var bdz = b.z - that.z;
var ad2 = adx * adx + ady * ady + adz * adz;
var bd2 = bdx * bdx + bdy * bdy + bdz * bdz;
return ad2 <= bd2 ? a : b;
}
XYZ.prototype.dot = function(xyz) {
var that = this;
return that.x * xyz.x + that.y * xyz.y + that.z * xyz.z;
}
XYZ.prototype.cross = function(xyz) {
var that = this;
return new XYZ(
that.y * xyz.z - that.z * xyz.y, -(that.x * xyz.z - that.z * xyz.x),
that.x * xyz.y - that.y * xyz.x,
that);
}
XYZ.prototype.interpolate = function(xyz, p) {
var that = this;
p = p == null ? 0.5 : p;
var p1 = 1 - p;
should &&
xyz.should.exist &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
return new XYZ(
p * xyz.x + p1 * that.x,
p * xyz.y + p1 * that.y,
p * xyz.z + p1 * that.z,
that);
}
XYZ.prototype.invalidate = function() {
var that = this;
delete that._norm;
}
XYZ.prototype.normSquared = function() {
var that = this;
return that.x * that.x + that.y * that.y + that.z * that.z;
}
XYZ.prototype.norm = function() {
var that = this;
if (that._norm == null) {
that._norm = Math.sqrt(that.normSquared());
}
return that._norm;
}
XYZ.prototype.minus = function(value) {
var that = this;
should &&
value.x.should.Number &&
value.y.should.Number &&
value.z.should.Number;
return new XYZ(that.x - value.x, that.y - value.y, that.z - value.z, that);
}
XYZ.prototype.plus = function(value) {
var that = this;
should &&
value.x.should.Number &&
value.y.should.Number &&
value.z.should.Number;
return new XYZ(that.x + value.x, that.y + value.y, that.z + value.z, that);
}
XYZ.prototype.equal = function(value, tolerance) {
var that = this;
if (value == null) {
that.verbose && console.log("XYZ.equal(null) => false");
return false;
}
if (value.x == null) {
that.verbose && console.log("XYZ.equal(value.x is null) => false");
return false;
}
if (value.y == null) {
that.verbose && console.log("XYZ.equal(value.y is null) => false");
return false;
}
if (value.z == null) {
that.verbose && console.log("XYZ.equal(value.z is null) => false");
return false;
}
tolerance = tolerance || 0;
var result = value.x - tolerance <= that.x && that.x <= value.x + tolerance &&
value.y - tolerance <= that.y && that.y <= value.y + tolerance &&
value.z - tolerance <= that.z && that.z <= value.z + tolerance;
that.verbose && !result && verboseLogger.debug("XYZ", that, ".equal(", value, ") => false");
return result;
}
XYZ.prototype.toString = function() {
var that = this;
var scale = 1000;
return "[" + Math.round(that.x * scale) / scale +
"," + Math.round(that.y * scale) / scale +
"," + Math.round(that.z * scale) / scale +
"]";
}
XYZ.prototype.multiply = function(m) {
var that = this;
if (m instanceof Mat3x3) {
return new XYZ(
m.get(0, 0) * that.x + m.get(0, 1) * that.y + m.get(0, 2) * that.z,
m.get(1, 0) * that.x + m.get(1, 1) * that.y + m.get(1, 2) * that.z,
m.get(2, 0) * that.x + m.get(2, 1) * that.y + m.get(2, 2) * that.z,
that);
}
should && m.should.Number;
return new XYZ(
m * that.x,
m * that.y,
m * that.z,
that);
}
/////////// class
XYZ.of = function(xyz, options) {
options = options || {};
if (xyz instanceof XYZ) {
return xyz;
}
if (options.strict) {
should &&
xyz.x.should.Number &&
xyz.y.should.Number &&
xyz.z.should.Number;
} else {
if (!xyz.x instanceof Number) {
return null;
}
if (!xyz.y instanceof Number) {
return null;
}
if (!xyz.z instanceof Number) {
return null;
}
}
return new XYZ(xyz.x, xyz.y, xyz.z, options);
}
XYZ.precisionDriftComparator = function(v1, v2) {
// comparator order will reveal
// any long-term precision drift
// as a horizontal visual break along x-axis
var s1 = v1.y < 0 ? -1 : 1;
var s2 = v2.y < 0 ? -1 : 1;
var cmp = s1 - s2;
cmp === 0 && (cmp = Math.round(v2.y) - Math.round(v1.y));
if (cmp === 0) {
var v1x = Math.round(v1.x);
var v2x = Math.round(v2.x);
cmp = v1.y < 0 ? v1x - v2x : v2x - v1x;
}
cmp === 0 && (cmp = v1.z - v2.z);
return cmp;
}
module.exports = exports.XYZ = XYZ;
})(typeof exports === "object" ? exports : (exports = {}));
// mocha -R min --inline-diffs *.js
(typeof describe === 'function') && describe("XYZ", function() {
var XYZ = require("./XYZ");
var options = {
verbose: true
};
it("XYZ(1,2,3) should create an XYZ coordinate", function() {
var xyz = new XYZ(1, 2, 3);
xyz.should.instanceOf(XYZ);
xyz.x.should.equal(1);
xyz.y.should.equal(2);
xyz.z.should.equal(3);
})
it("XYZ({x:1,y:2,z:3) should create an XYZ coordinate", function() {
var xyz = new XYZ(1, 2, 3);
var xyz2 = new XYZ(xyz);
xyz2.should.instanceOf(XYZ);
xyz2.x.should.equal(1);
xyz2.y.should.equal(2);
xyz2.z.should.equal(3);
var xyz3 = new XYZ({
x: 1,
y: 2,
z: 3
});
xyz2.should.instanceOf(XYZ);
xyz2.x.should.equal(1);
xyz2.y.should.equal(2);
xyz2.z.should.equal(3);
})
it("equal(value, tolerance) should return true if coordinates are same within tolerance", function() {
var xyz = new XYZ(1, 2, 3);
var xyz2 = new XYZ(xyz);
xyz.equal(xyz2).should.True;
xyz2.x = xyz.x - 0.00001;
xyz.equal(xyz2).should.False;
xyz.equal(xyz2, 0.00001).should.True;
xyz.equal(xyz2, 0.000001).should.False;
xyz2.x = xyz.x + 0.00001;
xyz.equal(xyz2).should.False;
xyz.equal(xyz2, 0.00001).should.True;
xyz.equal(xyz2, 0.000001).should.False;
})
it("norm() should return true the vector length", function() {
var e = 0.000001;
new XYZ(1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(-1, 2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, -2, 3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, -2, -3).norm().should.within(3.741657 - e, 3.741657 + e);
new XYZ(1, 0, 1).norm().should.within(1.414213 - e, 1.414213 + e);
new XYZ(0, 1, 1).norm().should.within(1.414213 - e, 1.414213 + e);
new XYZ(1, 1, 0).norm().should.within(1.414213 - e, 1.414213 + e);
})
it("normSquared() should return norm squared", function() {
var xyz = new XYZ(1, 2, 3);
xyz.norm().should.equal(Math.sqrt(xyz.normSquared()));
})
it("minus(value) should return vector difference", function() {
var xyz1 = new XYZ(1, 2, 3);
var xyz2 = new XYZ(10, 20, 30);
var xyz3 = xyz1.minus(xyz2);
xyz3.equal({
x: -9,
y: -18,
z: -27
}).should.True;
})
it("plus(value) should return vector sum", function() {
var xyz1 = new XYZ(1, 2, 3);
var xyz2 = new XYZ(10, 20, 30);
var xyz3 = xyz1.plus(xyz2);
xyz3.equal({
x: 11,
y: 22,
z: 33
}).should.True;
})
it("interpolate(xyz,p) should interpolate to given point for p[0,1]", function() {
var pt1 = new XYZ(1, 1, 1, {
verbose: true
});
var pt2 = new XYZ(10, 20, 30, {
verbose: true
});
pt1.interpolate(pt2, 0).equal(pt1).should.True;
pt1.interpolate(pt2, 1).equal(pt2).should.True;
pt1.interpolate(pt2, 0.1).equal({
x: 1.9,
y: 2.9,
z: 3.9
}).should.True;
});
it("XYZ.of(pt) should return an XYZ object for given point", function() {
var xyz = XYZ.of({
x: 1,
y: 2,
z: 3
});
xyz.should.instanceOf.XYZ;
var xyz2 = XYZ.of(xyz);
xyz2.should.equal(xyz);
});
it("cross(xyz) returns cross product with xyz", function() {
var v1 = new XYZ(1, 2, 3, options);
var v2 = new XYZ(4, 5, 6, options);
var cross = v1.cross(v2);
var e = 0;
cross.equal({
x: -3,
y: 6,
z: -3,
e
}).should.True;
});
it("teString() returns concise string representation", function() {
new XYZ(1, 2, 3).toString().should.equal("[1,2,3]");
new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]");
new XYZ(1.001, 2.0001, -3.001).toString().should.equal("[1.001,2,-3.001]");
})
it("dot(xyz) returns dot product with xyz", function() {
var v1 = new XYZ(1, 2, 3, options);
var v2 = new XYZ(4, 5, 6, options);
var dot = v1.dot(v2);
dot.should.equal(32);
});
it("nearest(a,b) returns nearest point", function() {
var vx = new XYZ(1, 0, 0);
var vy = new XYZ(0, 1, 0);
var vz = new XYZ(0, 0, 1);
new XYZ(2, 0, 0).nearest(vx, vy).should.equal(vx);
new XYZ(0, 0, 2).nearest(vx, vy).should.equal(vx);
new XYZ(0, 2, 0).nearest(vx, vy).should.equal(vy);
new XYZ(0, 2, 0).nearest(vz, vy).should.equal(vy);
new XYZ(0, 0, 2).nearest(vy, vz).should.equal(vz);
new XYZ(0, 0, 2).nearest(vx, vz).should.equal(vz);
});
it("precisionDriftComparator(v1,v2) sorts scanned vertices to reveal long-term precision drift", function() {
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 2, 3)).should.equal(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -2, 3)).should.equal(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, 2, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, -2, 3)).should.above(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(1, -3, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, -2, 3), new XYZ(2, -2, 3)).should.below(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(2, 2, 3)).should.above(0);
XYZ.precisionDriftComparator(new XYZ(1, 2, 3), new XYZ(1, 3, 3)).should.above(0);
});
})
| firepick1/firenodejs | www/js/shared/XYZ.js | JavaScript | mit | 12,537 |
/**
* This file is part of the Unit.js testing framework.
*
* (c) Nicolas Tallefourtane <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code
* or visit {@link http://unitjs.com|Unit.js}.
*
* @author Nicolas Tallefourtane <[email protected]>
*/
'use strict';
var test = require('../../../');
describe('Asserter object()', function(){
describe('object() behavior', function(){
it('Does not contains assertions from the assertions containers', function(){
test
.value(test.object({}).hasHeader)
.isUndefined()
.value(test.object({}).isError)
.isUndefined()
.value(test.object({}).hasMessage)
.isUndefined()
.value(test.object({}).isInfinite)
.isUndefined()
;
});
it('Assert that the tested value is an `object`', function(){
var Foo = function Foo(){};
test
.object({})
.object([])
.object(new Date())
.object(new RegExp())
.object(new Foo())
.case('Test failure', function(){
test
.exception(function(){
test.object('Foo');
})
.exception(function(){
test.object(Foo);
})
.exception(function(){
test.object(1);
})
.exception(function(){
test.object(undefined);
})
.exception(function(){
test.object(true);
})
.exception(function(){
test.object(false);
})
.exception(function(){
test.object(null);
})
.exception(function(){
test.object(function(){});
})
;
})
;
});
});
describe('Assertions of object()', function(){
it('is(expected)', function(){
test
.object({fluent: 'is awesome', deep: [0, 1]})
.is({fluent: 'is awesome', deep: [0, 1]})
.exception(function(){
test.object({fluent: 'is awesome', deep: [0, 1]})
.is({fluent: 'is awesome', deep: [0, 2]});
})
;
});
it('isNot(expected)', function(){
test
.object({fluent: 'is awesome', deep: [0, 1]})
.isNot({fluent: 'is awesome', deep: [0, '1']})
.exception(function(){
test.object({fluent: 'is awesome', deep: [0, 1]})
.isNot({fluent: 'is awesome', deep: [0, 1]});
})
;
});
it('isIdenticalTo(expected)', function(){
var
obj = {},
obj2 = obj
;
test
.object(obj)
.isIdenticalTo(obj2)
.exception(function(){
test.object(obj).isIdenticalTo({});
})
;
});
it('isNotIdenticalTo(expected)', function(){
var
obj = {},
obj2 = obj
;
test
.object(obj)
.isNotIdenticalTo({})
.exception(function(){
test.object(obj).isNotIdenticalTo(obj2);
})
;
});
it('isEqualTo(expected)', function(){
var
obj = {},
obj2 = obj
;
test
.object(obj)
.isEqualTo(obj2)
.exception(function(){
test.object(obj).isEqualTo({});
})
;
});
it('isNotEqualTo(expected)', function(){
var
obj = {foo: 'bar'},
obj2 = obj
;
test
.object(obj)
.isNotEqualTo({foo: 'bar', baz: 'bar'})
.exception(function(){
test.object(obj).isNotEqualTo(obj2);
})
;
});
it('match(expected)', function(){
test
.object({hello: 'world'})
.match(function(obj){
return obj.hello == 'world';
})
.exception(function(){
test.object({hello: 'world'})
.match(function(obj){
return obj.hello == 'foo';
});
})
;
});
it('notMatch(expected)', function(){
test
.object({hello: 'world'})
.notMatch(function(obj){
return obj.hello == 'E.T';
})
.exception(function(){
test.object({hello: 'world'})
.notMatch(function(obj){
return obj.hello == 'world';
})
})
;
});
it('isValid(expected)', function(){
test
.object({hello: 'world'})
.isValid(function(obj){
return obj.hello == 'world';
})
.exception(function(){
test.object({hello: 'world'})
.isValid(function(obj){
return obj.hello == 'foo';
});
})
;
});
it('isNotValid(expected)', function(){
test
.object({hello: 'world'})
.isNotValid(function(obj){
return obj.hello == 'E.T';
})
.exception(function(){
test.object({hello: 'world'})
.isNotValid(function(obj){
return obj.hello == 'world';
})
})
;
});
it('matchEach(expected)', function(){
test
.object({foo: 'bar', hey: 'you', joker:1})
.matchEach(function(it, key) {
if(key == 'joker'){
return (typeof it == 'number');
}
return (typeof it == 'string');
})
.exception(function(){
// error if one or several does not match
test.object({foo: 'bar', hey: 'you', joker:1})
.matchEach(function(it, key) {
return (typeof it == 'string');
})
})
;
});
it('notMatchEach(expected)', function(){
test
.object({foo: 'bar', hey: 'you', joker:1})
.notMatchEach(function(it, key) {
if(key == 'other'){
return true;
}
})
.exception(function(){
// error if one or several does not match
test.object({foo: 'bar', hey: 'you', joker:1})
.notMatchEach(function(it, key) {
if(key == 'foo'){
return true;
}
})
})
.exception(function(){
// error if one or several does not match
test.object({foo: 'bar', hey: 'you', joker:1})
.notMatchEach(function(it, key) {
return (typeof it == 'string');
})
})
;
});
it('isArray()', function(){
test
.object([])
.isArray()
.exception(function(){
test.object({}).isArray();
})
.exception(function(){
test.object(new Date()).isArray();
})
;
});
it('isRegExp()', function(){
test
.object(/[0-9]+/)
.isRegExp()
.exception(function(){
test.object({}).isRegExp();
})
.exception(function(){
test.object(new Date()).isRegExp();
})
;
});
it('isNotRegExp()', function(){
test
.object(new Date())
.isNotRegExp()
.exception(function(){
test.object(/[0-9]+/).isNotRegExp();
})
;
});
it('isDate()', function(){
test
.object(new Date())
.isDate()
.exception(function(){
test.object({}).isDate();
})
.exception(function(){
test.object(/[0-9]+/).isDate();
})
;
});
it('isNotDate()', function(){
test
.object(/[0-9]+/)
.isNotDate()
.exception(function(){
test.object(new Date()).isNotDate();
})
;
});
it('isArguments()', function(){
var fn = function(){
var args = arguments;
test.object(arguments).isArguments();
test.object(args).isArguments();
};
fn(1, 2, 3);
test.exception(function(){
test.object({0: 'a'}).isArguments();
});
});
it('isNotArguments()', function(){
var fn = function(){
test
.object(arguments)
.isArguments()
.object([1, 2, 3])
.isNotArguments()
.object({0:1, 1:2, 2:3})
.isNotArguments()
;
};
fn(1, 2, 3);
test.exception(function(){
test.object(arguments).isNotArguments();
});
});
it('isEmpty()', function(){
test
.object({})
.isEmpty()
.exception(function(){
test.object({0: 'a'}).isEmpty();
})
;
});
it('isNotEmpty()', function(){
test
.object({hello: 'Nico'})
.isNotEmpty()
.exception(function(){
test.object({}).isNotEmpty();
})
;
});
it('hasLength(expected)', function(){
test
.object({foo: 'bar', other: 'baz'})
.hasLength(2)
.exception(function(){
test.object({foo: 'bar', other: 'baz'})
.hasLength(3);
})
;
});
it('hasNotLength(expected)', function(){
test
.object({foo: 'bar', other: 'baz'})
.hasNotLength(4)
.exception(function(){
test.object({foo: 'bar', other: 'baz'})
.hasNotLength(2);
})
;
});
it('isEnumerable(property)', function(){
test
.object({prop: 'foobar'})
.isEnumerable('prop')
.exception(function(){
test.object({prop: 'foobar'})
.isEnumerable('length');
})
;
});
it('isNotEnumerable(property)', function(){
test
.object(Object.create({}, {prop: {enumerable: 0}}))
.isNotEnumerable('prop')
.exception(function(){
test.object({prop: 'foobar'})
.isNotEnumerable('prop');
})
;
});
it('isFrozen()', function(){
test
.object(Object.freeze({}))
.isFrozen()
.exception(function(){
test.object({})
.isFrozen();
})
;
});
it('isNotFrozen()', function(){
test
.object({})
.isNotFrozen()
.exception(function(){
test.object(Object.freeze({}))
.isNotFrozen();
})
;
});
it('isInstanceOf(expected)', function(){
test
.object(new Date())
.isInstanceOf(Date)
.exception(function(){
test.object(new Date())
.isInstanceOf(Error);
})
;
});
it('isNotInstanceOf(expected)', function(){
test
.object(new Date())
.isNotInstanceOf(RegExp)
.exception(function(){
test.object(new Date())
.isNotInstanceOf(Object);
})
.exception(function(){
test.object(new Date())
.isNotInstanceOf(Date);
})
;
});
it('hasProperty(property [, value])', function(){
test
.object({foo: 'bar'})
.hasProperty('foo')
.object({foo: 'bar'})
.hasProperty('foo', 'bar')
.exception(function(){
test.object({foo: 'bar'})
.hasProperty('bar');
})
.exception(function(){
test.object({foo: 'bar'})
.hasProperty('foo', 'ba');
})
;
});
it('hasNotProperty(property [, value])', function(){
test
.object({foo: 'bar'})
.hasNotProperty('bar')
.object({foo: 'bar'})
.hasNotProperty('foo', 'baz')
.exception(function(){
test.object({foo: 'bar'})
.hasNotProperty('foo');
})
.exception(function(){
test.object({foo: 'bar'})
.hasNotProperty('foo', 'bar');
})
;
});
it('hasOwnProperty(property [, value])', function(){
test
.object({foo: 'bar'})
.hasOwnProperty('foo')
.object({foo: 'bar'})
.hasOwnProperty('foo', 'bar')
.exception(function(){
test.object({foo: 'bar'})
.hasOwnProperty('bar');
})
.exception(function(){
test.object({foo: 'bar'})
.hasOwnProperty('foo', 'ba');
})
;
});
it('hasNotOwnProperty(property [, value])', function(){
test
.object({foo: 'bar'})
.hasNotOwnProperty('bar')
.object({foo: 'bar'})
.hasNotOwnProperty('foo', 'baz')
.exception(function(){
test.object({foo: 'bar'})
.hasNotOwnProperty('foo');
})
.exception(function(){
test.object({foo: 'bar'})
.hasNotOwnProperty('foo', 'bar');
})
;
});
it('hasProperties(properties)', function(){
test
.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasProperties(['other', 'bar', 'foo'])
.exception(function(){
test.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasProperties(['other', 'bar']);
})
;
});
it('hasNotProperties(properties)', function(){
test
.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasNotProperties(['other', 'foo'])
.exception(function(){
test.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasNotProperties(['bar', 'other', 'foo']);
})
;
});
it('hasOwnProperties(properties)', function(){
test
.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasOwnProperties(['other', 'bar', 'foo'])
.exception(function(){
test.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasOwnProperties(['other', 'bar']);
})
;
});
it('hasKey(key [, value])', function(){
test
.object({foo: 'bar'})
.hasKey('foo')
.object({foo: 'bar'})
.hasKey('foo', 'bar')
.exception(function(){
test.object({foo: 'bar'})
.hasKey('bar');
})
.exception(function(){
test.object({foo: 'bar'})
.hasKey('foo', 'ba');
})
;
});
it('notHasKey(key [, value])', function(){
test
.object({foo: 'bar'})
.notHasKey('bar')
.object({foo: 'bar'})
.notHasKey('foo', 'baz')
.exception(function(){
test.object({foo: 'bar'})
.notHasKey('foo');
})
.exception(function(){
test.object({foo: 'bar'})
.notHasKey('foo', 'bar');
})
;
});
it('hasKeys(keys)', function(){
test
.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasKeys(['other', 'bar', 'foo'])
.exception(function(){
test.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.hasKeys(['other', 'bar']);
})
;
});
it('notHasKeys(keys)', function(){
test
.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.notHasKeys(['other', 'foo'])
.exception(function(){
test.object({foo: 'bar', bar: 'huhu', other: 'vroom'})
.notHasKeys(['bar', 'other', 'foo']);
})
;
});
it('hasValue(expected)', function(){
test
.object({life: 42, love: 69})
.hasValue(42)
.exception(function(){
test.object({life: 42, love: 69})
.hasValue('42');
})
;
});
it('notHasValue(expected)', function(){
test
.object({life: 42, love: 69})
.notHasValue(4)
.exception(function(){
test.object({life: 42, love: 69})
.notHasValue(42);
})
;
});
it('hasValues(expected)', function(){
test
.object({life: 42, love: 69})
.hasValues([42, 69])
.exception(function(){
test.object([1, 42, 3])
.hasValues([42, 3.01]);
})
;
});
it('notHasValues(expected)', function(){
test
.object({life: 42, love: 69})
.notHasValues([43, 68])
.exception(function(){
test.object([1, 42, 3])
.notHasValues([1, 42, 3]);
})
;
});
it('contains(expected [, ...])', function(){
test
.object({ a: { b: 10 }, b: { c: 10, d: 11, a: { b: 10, c: 11} }})
.contains({ a: { b: 10 }, b: { c: 10, a: { c: 11 }}})
.object({a: 'a', b: {c: 'c'}})
.contains({b: {c: 'c'}})
.contains({b: {c: 'c'}}, {a: 'a'})
.exception(function(){
test.object({foo: {a: 'a'}, bar: {b: 'b', c: 'c'}})
.contains({foo: {a: 'a'}}, {bar: {b: 'c'}});
})
;
});
it('notContains(expected [, ...])', function(){
test
.object({a: 'a'}, {b: 'b', c: 'c'})
.notContains({c: 'b'})
.exception(function(){
test.object({foo: {a: 'a'}, bar: {b: 'b', c: 'c'}})
.notContains({foo: {a: 'a'}, bar: {c: 'c'}});
})
;
});
it('hasName(expected)', function(){
test
.object(new Date(2010, 5, 28))
.hasName('Date')
.exception(function(){
test.object(new Date(2010, 5, 28))
.hasName('date');
})
;
});
});
}); | johanasplund/coffeefuck | node_modules/unit.js/test/lib/asserters/object.js | JavaScript | mit | 17,594 |
var mongoose = require('mongoose');
var Shape = require('./Shape');
var User = require('./User');
// Create a session model, _id will be assigned by Mongoose
var CanvasSessionSchema = new mongoose.Schema(
{
_id: String,
users: [User],
dateCreated: Date,
dateUpdated: Date,
// canDraw: Boolean,
// canChat: Boolean,
// maxUsers: Number,
sessionProperties: {
canDraw: Boolean,
canChat: Boolean,
maxUsers: Number
},
//canvasModel: { type: Object },
canvasShapes: { type: Array, unique: true, index: true },
messages: Array
},
{ autoIndex: false }
);
// Make Session available to rest of the application
module.exports = mongoose.model('Session', CanvasSessionSchema);
| OpenSketch-Application/OpenSketch | server/db/models/Session.js | JavaScript | mit | 740 |
import config from '../components/configLoader';
import { addToDefaultPluginDOM } from '../components/helpers';
const pluginConfig = config.plugins.find(obj => obj.name === 'age');
// DOM setup
const pluginId = 'js-plugin-age';
addToDefaultPluginDOM(pluginId);
const ageDOM = document.getElementById(pluginId);
const renderAge = () => {
const { birthday, goal } = pluginConfig;
// Inspired by:
// Alex MacCaw https://github.com/maccman/motivation
const now = new Date();
const age = (now - new Date(birthday)) / 3.1556952e+10; // divided by 1 year in ms
let remainder = 100 - (age / goal * 100);
let goalPrefix = 'left until';
if (remainder < 0) {
goalPrefix = 'over goal of';
remainder = -remainder;
}
ageDOM.innerHTML = `Age: ${age.toFixed(5)}, ${remainder.toFixed(2)}% ${goalPrefix} ${goal}`;
};
// Initialize plugin
export const init = () => renderAge(); // eslint-disable-line import/prefer-default-export
| michaelx/Launchbot | src/js/plugins/age.js | JavaScript | mit | 950 |
Meteor.startup(function () {
});
Deps.autorun(function(){
Meteor.subscribe('userData');
}); | nikhilpi/klick | client/startup/default.js | JavaScript | mit | 94 |
// will this be needed?
var getMotionEventName = function(type) {
var t;
var el = document.createElement('fakeelement');
var map = {};
if (type == 'transition') {
map = {
'transition': 'transitionend',
'OTransition': 'oTransitionEnd',
'MozTransition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd'
};
} else if (type == 'animation') {
map = {
'animation': 'animationend',
'OAnimation': 'oAnimationEnd',
'MozAnimation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd'
};
};
for (t in map) {
if (el.style[t] !== undefined) {
return map[t];
}
}
};
| mwyatt/dialogue | js/getMotionEventName.js | JavaScript | mit | 710 |
// Include gulp
import gulp from 'gulp';
import fs from 'fs';
// Include Our Plugins
import eslint from 'gulp-eslint';
import mocha from 'gulp-mocha';
import browserSyncJs from 'browser-sync';
import sassJs from 'gulp-sass';
import sassCompiler from 'sass';
import rename from "gulp-rename";
import uglify from 'gulp-uglify';
import postcss from 'gulp-postcss';
import replace from 'gulp-replace';
import autoprefixer from 'autoprefixer';
import gulpStylelint from '@ronilaukkarinen/gulp-stylelint';
const browserSync = browserSyncJs.create();
const pkg = JSON.parse(fs.readFileSync('./package.json'));
const sass = sassJs(sassCompiler);
const doEslint = function() {
return gulp.src(
[
'*.js',
pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
// .pipe(eslint.failAfterError())
;
};
const doMocha = function() {
return gulp.src(pkg.directories.test + '/**/*.js', {read: false})
.pipe(mocha({
reporter: 'dot'
}))
;
};
const buildJs = function() {
return gulp.src(pkg.directories.theme + '/**/js-src/*.js')
.pipe(eslint())
.pipe(eslint.format())
//.pipe(eslint.failAfterError())
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/js-src/, 'js');
}))
.pipe(uglify({output: {
max_line_len: 9000
}}))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const buildCss = function() {
return gulp.src(pkg.directories.theme + '/**/*.scss')
.pipe(gulpStylelint({
reporters: [
{formatter: 'string', console: true}
]
}))
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer()
]))
.pipe(rename(function(path){
path.dirname = path.dirname.replace(/sass/, 'css');
}))
.pipe(replace(/(\n)\s*\n/g, '$1'))
.pipe(gulp.dest(pkg.directories.theme))
;
};
const serve = function() {
browserSync.init({
server: pkg.directories.htdocs,
port: 8080
});
gulp.watch(pkg.directories.htdocs + '/**/*').on('change', browserSync.reload);
};
// Watch Files For Changes
const watch = function() {
gulp.watch(['gulpfile.js', 'package.json'], process.exit);
gulp.watch(
[
'*.js', pkg.directories.bin + '/**/*',
pkg.directories.lib + '/**/*.js',
pkg.directories.test + '/**/*.js'
],
test
);
gulp.watch(pkg.directories.theme + '/**/*.js', buildJs);
gulp.watch(pkg.directories.theme + '/**/*.scss', buildCss);
};
// Bundle tasks
const test = gulp.parallel(doEslint, doMocha);
const build = gulp.parallel(buildJs, buildCss);
const defaultTask = gulp.parallel(serve, watch);
// Expose tasks
export {doEslint, doMocha, buildJs, buildCss, serve, watch, test, build};
export default defaultTask;
| fboes/blogophon | gulpfile.js | JavaScript | mit | 2,874 |
//
// Jala Project [http://opensvn.csie.org/traccgi/jala]
//
// Copyright 2004 ORF Online und Teletext GmbH
//
// 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.
//
// $Revision: 213 $
// $LastChangedBy: tobi $
// $LastChangedDate: 2007-05-08 16:12:32 +0200 (Die, 08 Mai 2007) $
// $HeadURL: http://dev.orf.at/source/jala/trunk/code/AsyncRequest.js $
//
/**
* @fileoverview Fields and methods of the jala.AsyncRequest class.
*/
// Define the global namespace for Jala modules
if (!global.jala) {
global.jala = {};
}
/**
* Creates a new AsyncRequest instance.
* @class This class is used to create requests of type "INTERNAL"
* (like cron-jobs) that are processed in a separate thread and
* therefor asynchronous.
* @param {Object} obj Object in whose context the method should be called
* @param {String} funcName Name of the function to call
* @param {Array} args Array containing the arguments that should be passed
* to the function (optional). This option is <em>deprecated</em>, instead
* pass the arguments directly to the {@link #run} method.
* @constructor
* @returns A new instance of AsyncRequest
* @type AsyncRequest
* @deprecated Use the {@link http://helma.zumbrunn.net/reference/core/app.html#invokeAsync
* app.invokeAsync} method instead (built-in into Helma as
* of version 1.6)
*/
jala.AsyncRequest = function(obj, funcName, args) {
app.logger.warn("Use of jala.AsyncRequest is deprecated in this version.");
app.logger.warn("This module will probably be removed in a " +
"future version of Jala.");
/**
* Contains a reference to the thread started by this AsyncRequest
* @type java.lang.Thread
* @private
*/
var thread;
/**
* Contains the timeout defined for this AsyncRequest (in milliseconds)
* @type Number
* @private
*/
var timeout;
/**
* Contains the number of milliseconds to wait before starting
* the asynchronous request.
* @type Number
* @private
*/
var delay;
/**
* Run method necessary to implement java.lang.Runnable.
* @private
*/
var runner = function() {
// evaluator that will handle the request
var ev = app.__app__.getEvaluator();
if (delay != null) {
java.lang.Thread.sleep(delay);
}
try {
if (args === undefined || args === null || args.constructor != Array) {
args = [];
}
if (timeout != null) {
ev.invokeInternal(obj, funcName, args, timeout);
} else {
ev.invokeInternal(obj, funcName, args);
}
} catch (e) {
// ignore it, but log it
app.log("[Runner] Caught Exception: " + e);
} finally {
// release the ev in any case
app.__app__.releaseEvaluator(ev);
// remove reference to underlying thread
thread = null;
}
return;
};
/**
* Sets the timeout of this asynchronous request.
* @param {Number} seconds Thread-timeout.
*/
this.setTimeout = function(seconds) {
timeout = seconds * 1000;
return;
};
/**
* Defines the delay to wait before evaluating this asynchronous request.
* @param {Number} millis Milliseconds to wait
*/
this.setDelay = function(millis) {
delay = millis;
return;
};
/**
* Starts this asynchronous request. Any arguments passed to
* this method will be passed to the method executed by
* this AsyncRequest instance.
*/
this.run = function() {
if (arguments.length > 0) {
// convert arguments object into array
args = Array.prototype.slice.call(arguments, 0, arguments.length);
}
thread = (new java.lang.Thread(new java.lang.Runnable({"run": runner})));
thread.start();
return;
};
/**
* Starts this asynchronous request.
* @deprecated Use {@link #run} instead
*/
this.evaluate = function() {
this.run.apply(this, arguments);
return;
};
/**
* Returns true if the underlying thread is alive
* @returns True if the underlying thread is alive,
* false otherwise.
* @type Boolean
*/
this.isAlive = function() {
return thread != null && thread.isAlive();
}
/** @ignore */
this.toString = function() {
return "[jala.AsyncRequest]";
};
/**
* Main constructor body
*/
if (!obj || !funcName)
throw "jala.AsyncRequest: insufficient arguments.";
return this;
}
| hankly/frizione | Frizione/modules/jala/code/AsyncRequest.js | JavaScript | mit | 5,028 |
const OFF = 0;
const WARN = 1;
const ERROR = 2;
module.exports = {
extends: "../.eslintrc.js",
rules: {
"max-len": [ ERROR, 100 ],
},
env: {
"es6": true,
"node": true,
"mocha": true,
},
};
| deadcee/horizon | cli/.eslintrc.js | JavaScript | mit | 216 |
const webdriver = require('selenium-webdriver');
const setupDriver = (browser) => {
const driver = new webdriver
.Builder()
.usingServer('http://localhost:9515/')
.withCapabilities({
browserName: browser,
})
.build();
return driver;
};
module.exports = { setupDriver };
| TeamYAGNI/BonanzaAlgorithmsCatalogue | tests/browser/utils/setup-driver.js | JavaScript | mit | 333 |
'use strict';
module.exports = function(grunt) {
// Please see the Grunt documentation for more information regarding task
// creation: http://gruntjs.com/creating-tasks
function random(min, max) {
min = min || 0;
max = max || 1;
var result;
if(min === 0 && max === 1) {
result = Math.random();
} else {
result = Math.floor((Math.random() * max) + min);
}
return result;
}
grunt.registerMultiTask('random', 'Your task description goes here.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({min:0,max:1});
grunt.log.writeln('Random: ' + random(options.min, options.max));
});
}; | doowb/lessbuilder | tasks/random.js | JavaScript | mit | 744 |
'use strict';
angular
.module('facebookMe', [
])
;
| codealchemist/insight | app/facebook-me/facebook-me.js | JavaScript | mit | 55 |
/**
* interact.js v1.1.2
*
* Copyright (c) 2012, 2013, 2014 Taye Adeyemi <[email protected]>
* Open source under the MIT License.
* https://raw.github.com/taye/interact.js/master/LICENSE
*/
(function () {
'use strict';
var document = window.document,
SVGElement = window.SVGElement || blank,
SVGSVGElement = window.SVGSVGElement || blank,
SVGElementInstance = window.SVGElementInstance || blank,
HTMLElement = window.HTMLElement || window.Element,
PointerEvent = (window.PointerEvent || window.MSPointerEvent),
pEventTypes,
hypot = Math.hypot || function (x, y) { return Math.sqrt(x * x + y * y); },
tmpXY = {}, // reduce object creation in getXY()
documents = [], // all documents being listened to
interactables = [], // all set interactables
interactions = [], // all interactions
dynamicDrop = false,
// {
// type: {
// selectors: ['selector', ...],
// contexts : [document, ...],
// listeners: [[listener, useCapture], ...]
// }
// }
delegatedEvents = {},
defaultOptions = {
draggable : false,
dragAxis : 'xy',
dropzone : false,
accept : null,
dropOverlap : 'pointer',
resizable : false,
squareResize: false,
resizeAxis : 'xy',
gesturable : false,
// no more than this number of actions can target the Interactable
dragMax : 1,
resizeMax : 1,
gestureMax: 1,
// no more than this number of actions can target the same
// element of this Interactable simultaneously
dragMaxPerElement : 1,
resizeMaxPerElement : 1,
gestureMaxPerElement: 1,
pointerMoveTolerance: 1,
actionChecker: null,
styleCursor: true,
preventDefault: 'auto',
// aww snap
snap: {
mode : 'grid',
endOnly : false,
actions : ['drag'],
range : Infinity,
grid : { x: 100, y: 100 },
gridOffset : { x: 0, y: 0 },
anchors : [],
paths : [],
elementOrigin: null,
arrayTypes : /^anchors$|^paths$|^actions$/,
objectTypes : /^grid$|^gridOffset$|^elementOrigin$/,
stringTypes : /^mode$/,
numberTypes : /^range$/,
boolTypes : /^endOnly$/
},
snapEnabled: false,
restrict: {
drag: null,
resize: null,
gesture: null,
endOnly: false
},
restrictEnabled: false,
autoScroll: {
container : null, // the item that is scrolled (Window or HTMLElement)
margin : 60,
speed : 300, // the scroll speed in pixels per second
numberTypes : /^margin$|^speed$/
},
autoScrollEnabled: false,
inertia: {
resistance : 10, // the lambda in exponential decay
minSpeed : 100, // target speed must be above this for inertia to start
endSpeed : 10, // the speed at which inertia is slow enough to stop
allowResume : true, // allow resuming an action in inertia phase
zeroResumeDelta : false, // if an action is resumed after launch, set dx/dy to 0
smoothEndDuration: 300, // animate to snap/restrict endOnly if there's no inertia
actions : ['drag', 'resize'], // allow inertia on these actions. gesture might not work
numberTypes: /^resistance$|^minSpeed$|^endSpeed$|^smoothEndDuration$/,
arrayTypes : /^actions$/,
boolTypes : /^(allowResume|zeroResumeDelta)$/
},
inertiaEnabled: false,
origin : { x: 0, y: 0 },
deltaSource : 'page',
},
// Things related to autoScroll
autoScroll = {
interaction: null,
i: null, // the handle returned by window.setInterval
x: 0, y: 0, // Direction each pulse is to scroll in
// scroll the window by the values in scroll.x/y
scroll: function () {
var options = autoScroll.interaction.target.options.autoScroll,
container = options.container || getWindow(autoScroll.interaction.element),
now = new Date().getTime(),
// change in time in seconds
dt = (now - autoScroll.prevTime) / 1000,
// displacement
s = options.speed * dt;
if (s >= 1) {
if (isWindow(container)) {
container.scrollBy(autoScroll.x * s, autoScroll.y * s);
}
else if (container) {
container.scrollLeft += autoScroll.x * s;
container.scrollTop += autoScroll.y * s;
}
autoScroll.prevTime = now;
}
if (autoScroll.isScrolling) {
cancelFrame(autoScroll.i);
autoScroll.i = reqFrame(autoScroll.scroll);
}
},
edgeMove: function (event) {
var interaction,
target,
doAutoscroll = false;
for (var i = 0; i < interactions.length; i++) {
interaction = interactions[i];
target = interaction.target;
if (target && target.options.autoScrollEnabled
&& (interaction.dragging || interaction.resizing)) {
doAutoscroll = true;
break;
}
}
if (!doAutoscroll) { return; }
var top,
right,
bottom,
left,
options = target.options.autoScroll,
container = options.container || getWindow(interaction.element);
if (isWindow(container)) {
left = event.clientX < autoScroll.margin;
top = event.clientY < autoScroll.margin;
right = event.clientX > container.innerWidth - autoScroll.margin;
bottom = event.clientY > container.innerHeight - autoScroll.margin;
}
else {
var rect = getElementRect(container);
left = event.clientX < rect.left + autoScroll.margin;
top = event.clientY < rect.top + autoScroll.margin;
right = event.clientX > rect.right - autoScroll.margin;
bottom = event.clientY > rect.bottom - autoScroll.margin;
}
autoScroll.x = (right ? 1: left? -1: 0);
autoScroll.y = (bottom? 1: top? -1: 0);
if (!autoScroll.isScrolling) {
// set the autoScroll properties to those of the target
autoScroll.margin = options.margin;
autoScroll.speed = options.speed;
autoScroll.start(interaction);
}
},
isScrolling: false,
prevTime: 0,
start: function (interaction) {
autoScroll.isScrolling = true;
cancelFrame(autoScroll.i);
autoScroll.interaction = interaction;
autoScroll.prevTime = new Date().getTime();
autoScroll.i = reqFrame(autoScroll.scroll);
},
stop: function () {
autoScroll.isScrolling = false;
cancelFrame(autoScroll.i);
}
},
// Does the browser support touch input?
supportsTouch = (('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch),
// Does the browser support PointerEvents
supportsPointerEvent = !!PointerEvent,
// Less Precision with touch input
margin = supportsTouch || supportsPointerEvent? 20: 10,
// for ignoring browser's simulated mouse events
prevTouchTime = 0,
// Allow this many interactions to happen simultaneously
maxInteractions = 1,
actionCursors = {
drag : 'move',
resizex : 'e-resize',
resizey : 's-resize',
resizexy: 'se-resize',
gesture : ''
},
actionIsEnabled = {
drag : true,
resize : true,
gesture: true
},
// because Webkit and Opera still use 'mousewheel' event type
wheelEvent = 'onmousewheel' in document? 'mousewheel': 'wheel',
eventTypes = [
'dragstart',
'dragmove',
'draginertiastart',
'dragend',
'dragenter',
'dragleave',
'dropactivate',
'dropdeactivate',
'dropmove',
'drop',
'resizestart',
'resizemove',
'resizeinertiastart',
'resizeend',
'gesturestart',
'gesturemove',
'gestureinertiastart',
'gestureend',
'down',
'move',
'up',
'cancel',
'tap',
'doubletap',
'hold'
],
globalEvents = {},
// Opera Mobile must be handled differently
isOperaMobile = navigator.appName == 'Opera' &&
supportsTouch &&
navigator.userAgent.match('Presto'),
// scrolling doesn't change the result of
// getBoundingClientRect/getClientRects on iOS <=7 but it does on iOS 8
isIOS7orLower = (/iP(hone|od|ad)/.test(navigator.platform)
&& /OS [1-7][^\d]/.test(navigator.appVersion)),
// prefix matchesSelector
prefixedMatchesSelector = 'matchesSelector' in Element.prototype?
'matchesSelector': 'webkitMatchesSelector' in Element.prototype?
'webkitMatchesSelector': 'mozMatchesSelector' in Element.prototype?
'mozMatchesSelector': 'oMatchesSelector' in Element.prototype?
'oMatchesSelector': 'msMatchesSelector',
// will be polyfill function if browser is IE8
ie8MatchesSelector,
// native requestAnimationFrame or polyfill
reqFrame = window.requestAnimationFrame,
cancelFrame = window.cancelAnimationFrame,
// Events wrapper
events = (function () {
var useAttachEvent = ('attachEvent' in window) && !('addEventListener' in window),
addEvent = useAttachEvent? 'attachEvent': 'addEventListener',
removeEvent = useAttachEvent? 'detachEvent': 'removeEventListener',
on = useAttachEvent? 'on': '',
elements = [],
targets = [],
attachedListeners = [];
function add (element, type, listener, useCapture) {
var elementIndex = indexOf(elements, element),
target = targets[elementIndex];
if (!target) {
target = {
events: {},
typeCount: 0
};
elementIndex = elements.push(element) - 1;
targets.push(target);
attachedListeners.push((useAttachEvent ? {
supplied: [],
wrapped : [],
useCount: []
} : null));
}
if (!target.events[type]) {
target.events[type] = [];
target.typeCount++;
}
if (!contains(target.events[type], listener)) {
var ret;
if (useAttachEvent) {
var listeners = attachedListeners[elementIndex],
listenerIndex = indexOf(listeners.supplied, listener);
var wrapped = listeners.wrapped[listenerIndex] || function (event) {
if (!event.immediatePropagationStopped) {
event.target = event.srcElement;
event.currentTarget = element;
event.preventDefault = event.preventDefault || preventDef;
event.stopPropagation = event.stopPropagation || stopProp;
event.stopImmediatePropagation = event.stopImmediatePropagation || stopImmProp;
if (/mouse|click/.test(event.type)) {
event.pageX = event.clientX + element.ownerDdocument.documentElement.scrollLeft;
event.pageY = event.clientY + element.ownerDdocument.documentElement.scrollTop;
}
listener(event);
}
};
ret = element[addEvent](on + type, wrapped, Boolean(useCapture));
if (listenerIndex === -1) {
listeners.supplied.push(listener);
listeners.wrapped.push(wrapped);
listeners.useCount.push(1);
}
else {
listeners.useCount[listenerIndex]++;
}
}
else {
ret = element[addEvent](type, listener, useCapture || false);
}
target.events[type].push(listener);
return ret;
}
}
function remove (element, type, listener, useCapture) {
var i,
elementIndex = indexOf(elements, element),
target = targets[elementIndex],
listeners,
listenerIndex,
wrapped = listener;
if (!target || !target.events) {
return;
}
if (useAttachEvent) {
listeners = attachedListeners[elementIndex];
listenerIndex = indexOf(listeners.supplied, listener);
wrapped = listeners.wrapped[listenerIndex];
}
if (type === 'all') {
for (type in target.events) {
if (target.events.hasOwnProperty(type)) {
remove(element, type, 'all');
}
}
return;
}
if (target.events[type]) {
var len = target.events[type].length;
if (listener === 'all') {
for (i = 0; i < len; i++) {
remove(element, type, target.events[type][i], Boolean(useCapture));
}
} else {
for (i = 0; i < len; i++) {
if (target.events[type][i] === listener) {
element[removeEvent](on + type, wrapped, useCapture || false);
target.events[type].splice(i, 1);
if (useAttachEvent && listeners) {
listeners.useCount[listenerIndex]--;
if (listeners.useCount[listenerIndex] === 0) {
listeners.supplied.splice(listenerIndex, 1);
listeners.wrapped.splice(listenerIndex, 1);
listeners.useCount.splice(listenerIndex, 1);
}
}
break;
}
}
}
if (target.events[type] && target.events[type].length === 0) {
target.events[type] = null;
target.typeCount--;
}
}
if (!target.typeCount) {
targets.splice(elementIndex);
elements.splice(elementIndex);
attachedListeners.splice(elementIndex);
}
}
function preventDef () {
this.returnValue = false;
}
function stopProp () {
this.cancelBubble = true;
}
function stopImmProp () {
this.cancelBubble = true;
this.immediatePropagationStopped = true;
}
return {
add: add,
remove: remove,
useAttachEvent: useAttachEvent,
_elements: elements,
_targets: targets,
_attachedListeners: attachedListeners
};
}());
function blank () {}
function isElement (o) {
if (!o || (typeof o !== 'object')) { return false; }
var _window = getWindow(o) || window;
return (/object|function/.test(typeof _window.Element)
? o instanceof _window.Element //DOM2
: o.nodeType === 1 && typeof o.nodeName === "string");
}
function isWindow (thing) { return !!(thing && thing.Window) && (thing instanceof thing.Window); }
function isArray (thing) {
return isObject(thing)
&& (typeof thing.length !== undefined)
&& isFunction(thing.splice);
}
function isObject (thing) { return !!thing && (typeof thing === 'object'); }
function isFunction (thing) { return typeof thing === 'function'; }
function isNumber (thing) { return typeof thing === 'number' ; }
function isBool (thing) { return typeof thing === 'boolean' ; }
function isString (thing) { return typeof thing === 'string' ; }
function trySelector (value) {
if (!isString(value)) { return false; }
// an exception will be raised if it is invalid
document.querySelector(value);
return true;
}
function extend (dest, source) {
for (var prop in source) {
dest[prop] = source[prop];
}
return dest;
}
function copyCoords (dest, src) {
dest.page = dest.page || {};
dest.page.x = src.page.x;
dest.page.y = src.page.y;
dest.client = dest.client || {};
dest.client.x = src.client.x;
dest.client.y = src.client.y;
dest.timeStamp = src.timeStamp;
}
function setEventXY (targetObj, pointer, interaction) {
if (!pointer) {
if (interaction.pointerIds.length > 1) {
pointer = touchAverage(interaction.pointers);
}
else {
pointer = interaction.pointers[0];
}
}
getPageXY(pointer, tmpXY, interaction);
targetObj.page.x = tmpXY.x;
targetObj.page.y = tmpXY.y;
getClientXY(pointer, tmpXY, interaction);
targetObj.client.x = tmpXY.x;
targetObj.client.y = tmpXY.y;
targetObj.timeStamp = new Date().getTime();
}
function setEventDeltas (targetObj, prev, cur) {
targetObj.page.x = cur.page.x - prev.page.x;
targetObj.page.y = cur.page.y - prev.page.y;
targetObj.client.x = cur.client.x - prev.client.x;
targetObj.client.y = cur.client.y - prev.client.y;
targetObj.timeStamp = new Date().getTime() - prev.timeStamp;
// set pointer velocity
var dt = Math.max(targetObj.timeStamp / 1000, 0.001);
targetObj.page.speed = hypot(targetObj.page.x, targetObj.page.y) / dt;
targetObj.page.vx = targetObj.page.x / dt;
targetObj.page.vy = targetObj.page.y / dt;
targetObj.client.speed = hypot(targetObj.client.x, targetObj.page.y) / dt;
targetObj.client.vx = targetObj.client.x / dt;
targetObj.client.vy = targetObj.client.y / dt;
}
// Get specified X/Y coords for mouse or event.touches[0]
function getXY (type, pointer, xy) {
xy = xy || {};
type = type || 'page';
xy.x = pointer[type + 'X'];
xy.y = pointer[type + 'Y'];
return xy;
}
function getPageXY (pointer, page, interaction) {
page = page || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
interaction = interaction || pointer.interaction;
extend(page, interaction.inertiaStatus.upCoords.page);
page.x += interaction.inertiaStatus.sx;
page.y += interaction.inertiaStatus.sy;
}
else {
page.x = pointer.pageX;
page.y = pointer.pageY;
}
}
// Opera Mobile handles the viewport and scrolling oddly
else if (isOperaMobile) {
getXY('screen', pointer, page);
page.x += window.scrollX;
page.y += window.scrollY;
}
else {
getXY('page', pointer, page);
}
return page;
}
function getClientXY (pointer, client, interaction) {
client = client || {};
if (pointer instanceof InteractEvent) {
if (/inertiastart/.test(pointer.type)) {
extend(client, interaction.inertiaStatus.upCoords.client);
client.x += interaction.inertiaStatus.sx;
client.y += interaction.inertiaStatus.sy;
}
else {
client.x = pointer.clientX;
client.y = pointer.clientY;
}
}
else {
// Opera Mobile handles the viewport and scrolling oddly
getXY(isOperaMobile? 'screen': 'client', pointer, client);
}
return client;
}
function getScrollXY (win) {
win = win || window;
return {
x: win.scrollX || win.document.documentElement.scrollLeft,
y: win.scrollY || win.document.documentElement.scrollTop
};
}
function getPointerId (pointer) {
return isNumber(pointer.pointerId)? pointer.pointerId : pointer.identifier;
}
function getActualElement (element) {
return (element instanceof SVGElementInstance
? element.correspondingUseElement
: element);
}
function getWindow (node) {
if (isWindow(node)) {
return node;
}
var rootNode = (node.ownerDocument || node);
return rootNode.defaultView || rootNode.parentWindow;
}
function getElementRect (element) {
var scroll = isIOS7orLower
? { x: 0, y: 0 }
: getScrollXY(getWindow(element)),
clientRect = (element instanceof SVGElement)?
element.getBoundingClientRect():
element.getClientRects()[0];
return clientRect && {
left : clientRect.left + scroll.x,
right : clientRect.right + scroll.x,
top : clientRect.top + scroll.y,
bottom: clientRect.bottom + scroll.y,
width : clientRect.width || clientRect.right - clientRect.left,
height: clientRect.heigh || clientRect.bottom - clientRect.top
};
}
function getTouchPair (event) {
var touches = [];
// array of touches is supplied
if (isArray(event)) {
touches[0] = event[0];
touches[1] = event[1];
}
// an event
else {
if (event.type === 'touchend') {
if (event.touches.length === 1) {
touches[0] = event.touches[0];
touches[1] = event.changedTouches[0];
}
else if (event.touches.length === 0) {
touches[0] = event.changedTouches[0];
touches[1] = event.changedTouches[1];
}
}
else {
touches[0] = event.touches[0];
touches[1] = event.touches[1];
}
}
return touches;
}
function touchAverage (event) {
var touches = getTouchPair(event);
return {
pageX: (touches[0].pageX + touches[1].pageX) / 2,
pageY: (touches[0].pageY + touches[1].pageY) / 2,
clientX: (touches[0].clientX + touches[1].clientX) / 2,
clientY: (touches[0].clientY + touches[1].clientY) / 2
};
}
function touchBBox (event) {
if (!event.length && !(event.touches && event.touches.length > 1)) {
return;
}
var touches = getTouchPair(event),
minX = Math.min(touches[0].pageX, touches[1].pageX),
minY = Math.min(touches[0].pageY, touches[1].pageY),
maxX = Math.max(touches[0].pageX, touches[1].pageX),
maxY = Math.max(touches[0].pageY, touches[1].pageY);
return {
x: minX,
y: minY,
left: minX,
top: minY,
width: maxX - minX,
height: maxY - minY
};
}
function touchDistance (event, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event);
var dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY];
return hypot(dx, dy);
}
function touchAngle (event, prevAngle, deltaSource) {
deltaSource = deltaSource || defaultOptions.deltaSource;
var sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
touches = getTouchPair(event),
dx = touches[0][sourceX] - touches[1][sourceX],
dy = touches[0][sourceY] - touches[1][sourceY],
angle = 180 * Math.atan(dy / dx) / Math.PI;
if (isNumber(prevAngle)) {
var dr = angle - prevAngle,
drClamped = dr % 360;
if (drClamped > 315) {
angle -= 360 + (angle / 360)|0 * 360;
}
else if (drClamped > 135) {
angle -= 180 + (angle / 360)|0 * 360;
}
else if (drClamped < -315) {
angle += 360 + (angle / 360)|0 * 360;
}
else if (drClamped < -135) {
angle += 180 + (angle / 360)|0 * 360;
}
}
return angle;
}
function getOriginXY (interactable, element) {
var origin = interactable
? interactable.options.origin
: defaultOptions.origin;
if (origin === 'parent') {
origin = element.parentNode;
}
else if (origin === 'self') {
origin = interactable.getRect(element);
}
else if (trySelector(origin)) {
origin = closest(element, origin) || { x: 0, y: 0 };
}
if (isFunction(origin)) {
origin = origin(interactable && element);
}
if (isElement(origin)) {
origin = getElementRect(origin);
}
origin.x = ('x' in origin)? origin.x : origin.left;
origin.y = ('y' in origin)? origin.y : origin.top;
return origin;
}
// http://stackoverflow.com/a/5634528/2280888
function _getQBezierValue(t, p1, p2, p3) {
var iT = 1 - t;
return iT * iT * p1 + 2 * iT * t * p2 + t * t * p3;
}
function getQuadraticCurvePoint(startX, startY, cpX, cpY, endX, endY, position) {
return {
x: _getQBezierValue(position, startX, cpX, endX),
y: _getQBezierValue(position, startY, cpY, endY)
};
}
// http://gizma.com/easing/
function easeOutQuad (t, b, c, d) {
t /= d;
return -c * t*(t-2) + b;
}
function nodeContains (parent, child) {
while ((child = child.parentNode)) {
if (child === parent) {
return true;
}
}
return false;
}
function closest (child, selector) {
var parent = child.parentNode;
while (isElement(parent)) {
if (matchesSelector(parent, selector)) { return parent; }
parent = parent.parentNode;
}
return null;
}
function inContext (interactable, element) {
return interactable._context === element.ownerDocument
|| nodeContains(interactable._context, element);
}
function testIgnore (interactable, interactableElement, element) {
var ignoreFrom = interactable.options.ignoreFrom;
if (!ignoreFrom
// limit test to the interactable's element and its children
|| !isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(ignoreFrom)) {
return matchesSelector(element, ignoreFrom) || testIgnore(interactable, element.parentNode);
}
else if (isElement(ignoreFrom)) {
return element === ignoreFrom || nodeContains(ignoreFrom, element);
}
return false;
}
function testAllow (interactable, interactableElement, element) {
var allowFrom = interactable.options.allowFrom;
if (!allowFrom) { return true; }
// limit test to the interactable's element and its children
if (!isElement(element) || element === interactableElement.parentNode) {
return false;
}
if (isString(allowFrom)) {
return matchesSelector(element, allowFrom) || testAllow(interactable, element.parentNode);
}
else if (isElement(allowFrom)) {
return element === allowFrom || nodeContains(allowFrom, element);
}
return false;
}
function checkAxis (axis, interactable) {
if (!interactable) { return false; }
var thisAxis = interactable.options.dragAxis;
return (axis === 'xy' || thisAxis === 'xy' || thisAxis === axis);
}
function checkSnap (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return action !== 'gesture' && options.snapEnabled && contains(options.snap.actions, action);
}
function checkRestrict (interactable, action) {
var options = interactable.options;
if (/^resize/.test(action)) {
action = 'resize';
}
return options.restrictEnabled && options.restrict[action];
}
function withinInteractionLimit (interactable, element, action) {
action = /resize/.test(action)? 'resize': action;
var options = interactable.options,
maxActions = options[action + 'Max'],
maxPerElement = options[action + 'MaxPerElement'],
activeInteractions = 0,
targetCount = 0,
targetElementCount = 0;
for (var i = 0, len = interactions.length; i < len; i++) {
var interaction = interactions[i],
otherAction = /resize/.test(interaction.prepared)? 'resize': interaction.prepared,
active = interaction.interacting();
if (!active) { continue; }
activeInteractions++;
if (activeInteractions >= maxInteractions) {
return false;
}
if (interaction.target !== interactable) { continue; }
targetCount += (otherAction === action)|0;
if (targetCount >= maxActions) {
return false;
}
if (interaction.element === element) {
targetElementCount++;
if (otherAction !== action || targetElementCount >= maxPerElement) {
return false;
}
}
}
return maxInteractions > 0;
}
// Test for the element that's "above" all other qualifiers
function indexOfDeepestElement (elements) {
var dropzone,
deepestZone = elements[0],
index = deepestZone? 0: -1,
parent,
deepestZoneParents = [],
dropzoneParents = [],
child,
i,
n;
for (i = 1; i < elements.length; i++) {
dropzone = elements[i];
// an element might belong to multiple selector dropzones
if (!dropzone || dropzone === deepestZone) {
continue;
}
if (!deepestZone) {
deepestZone = dropzone;
index = i;
continue;
}
// check if the deepest or current are document.documentElement or document.rootElement
// - if the current dropzone is, do nothing and continue
if (dropzone.parentNode === dropzone.ownerDocument) {
continue;
}
// - if deepest is, update with the current dropzone and continue to next
else if (deepestZone.parentNode === dropzone.ownerDocument) {
deepestZone = dropzone;
index = i;
continue;
}
if (!deepestZoneParents.length) {
parent = deepestZone;
while (parent.parentNode && parent.parentNode !== parent.ownerDocument) {
deepestZoneParents.unshift(parent);
parent = parent.parentNode;
}
}
// if this element is an svg element and the current deepest is
// an HTMLElement
if (deepestZone instanceof HTMLElement
&& dropzone instanceof SVGElement
&& !(dropzone instanceof SVGSVGElement)) {
if (dropzone === deepestZone.parentNode) {
continue;
}
parent = dropzone.ownerSVGElement;
}
else {
parent = dropzone;
}
dropzoneParents = [];
while (parent.parentNode !== parent.ownerDocument) {
dropzoneParents.unshift(parent);
parent = parent.parentNode;
}
n = 0;
// get (position of last common ancestor) + 1
while (dropzoneParents[n] && dropzoneParents[n] === deepestZoneParents[n]) {
n++;
}
var parents = [
dropzoneParents[n - 1],
dropzoneParents[n],
deepestZoneParents[n]
];
child = parents[0].lastChild;
while (child) {
if (child === parents[1]) {
deepestZone = dropzone;
index = i;
deepestZoneParents = [];
break;
}
else if (child === parents[2]) {
break;
}
child = child.previousSibling;
}
}
return index;
}
function Interaction () {
this.target = null; // current interactable being interacted with
this.element = null; // the target element of the interactable
this.dropTarget = null; // the dropzone a drag target might be dropped into
this.dropElement = null; // the element at the time of checking
this.prevDropTarget = null; // the dropzone that was recently dragged away from
this.prevDropElement = null; // the element at the time of checking
this.prepared = null; // Action that's ready to be fired on next move event
this.matches = []; // all selectors that are matched by target element
this.matchElements = []; // corresponding elements
this.inertiaStatus = {
active : false,
smoothEnd : false,
startEvent: null,
upCoords: {},
xe: 0, ye: 0,
sx: 0, sy: 0,
t0: 0,
vx0: 0, vys: 0,
duration: 0,
resumeDx: 0,
resumeDy: 0,
lambda_v0: 0,
one_ve_v0: 0,
i : null
};
if (isFunction(Function.prototype.bind)) {
this.boundInertiaFrame = this.inertiaFrame.bind(this);
this.boundSmoothEndFrame = this.smoothEndFrame.bind(this);
}
else {
var that = this;
this.boundInertiaFrame = function () { return that.inertiaFrame(); };
this.boundSmoothEndFrame = function () { return that.smoothEndFrame(); };
}
this.activeDrops = {
dropzones: [], // the dropzones that are mentioned below
elements : [], // elements of dropzones that accept the target draggable
rects : [] // the rects of the elements mentioned above
};
// keep track of added pointers
this.pointers = [];
this.pointerIds = [];
this.downTargets = [];
this.downTimes = [];
this.holdTimers = [];
// Previous native pointer move event coordinates
this.prevCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// current native pointer move event coordinates
this.curCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Starting InteractEvent pointer coordinates
this.startCoords = {
page : { x: 0, y: 0 },
client : { x: 0, y: 0 },
timeStamp: 0
};
// Change in coordinates and time of the pointer
this.pointerDelta = {
page : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
client : { x: 0, y: 0, vx: 0, vy: 0, speed: 0 },
timeStamp: 0
};
this.downEvent = null; // pointerdown/mousedown/touchstart event
this.downPointer = {};
this.prevEvent = null; // previous action event
this.tapTime = 0; // time of the most recent tap event
this.prevTap = null;
this.startOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.restrictOffset = { left: 0, right: 0, top: 0, bottom: 0 };
this.snapOffset = { x: 0, y: 0};
this.gesture = {
start: { x: 0, y: 0 },
startDistance: 0, // distance between two touches of touchStart
prevDistance : 0,
distance : 0,
scale: 1, // gesture.distance / gesture.startDistance
startAngle: 0, // angle of line joining two touches
prevAngle : 0 // angle of the previous gesture event
};
this.snapStatus = {
x : 0, y : 0,
dx : 0, dy : 0,
realX : 0, realY : 0,
snappedX: 0, snappedY: 0,
anchors : [],
paths : [],
locked : false,
changed : false
};
this.restrictStatus = {
dx : 0, dy : 0,
restrictedX: 0, restrictedY: 0,
snap : null,
restricted : false,
changed : false
};
this.restrictStatus.snap = this.snapStatus;
this.pointerIsDown = false;
this.pointerWasMoved = false;
this.gesturing = false;
this.dragging = false;
this.resizing = false;
this.resizeAxes = 'xy';
this.mouse = false;
interactions.push(this);
}
Interaction.prototype = {
getPageXY : function (pointer, xy) { return getPageXY(pointer, xy, this); },
getClientXY: function (pointer, xy) { return getClientXY(pointer, xy, this); },
setEventXY : function (target, ptr) { return setEventXY(target, ptr, this); },
pointerOver: function (pointer, event, eventTarget) {
if (this.prepared || !this.mouse) { return; }
var curMatches = [],
curMatchElements = [],
prevTargetElement = this.element;
this.addPointer(pointer);
if (this.target
&& (testIgnore(this.target, this.element, eventTarget)
|| !testAllow(this.target, this.element, eventTarget)
|| !withinInteractionLimit(this.target, this.element, this.prepared))) {
// if the eventTarget should be ignored or shouldn't be allowed
// clear the previous target
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
var elementInteractable = interactables.get(eventTarget),
elementAction = (elementInteractable
&& !testIgnore(elementInteractable, eventTarget, eventTarget)
&& testAllow(elementInteractable, eventTarget, eventTarget)
&& validateAction(
elementInteractable.getAction(pointer, this, eventTarget),
elementInteractable));
elementAction = elementInteractable && withinInteractionLimit(elementInteractable, eventTarget, elementAction)
? elementAction
: null;
function pushCurMatches (interactable, selector) {
if (interactable
&& inContext(interactable, eventTarget)
&& !testIgnore(interactable, eventTarget, eventTarget)
&& testAllow(interactable, eventTarget, eventTarget)
&& matchesSelector(eventTarget, selector)) {
curMatches.push(interactable);
curMatchElements.push(eventTarget);
}
}
if (elementAction) {
this.target = elementInteractable;
this.element = eventTarget;
this.matches = [];
this.matchElements = [];
}
else {
interactables.forEachSelector(pushCurMatches);
if (this.validateSelector(pointer, curMatches, curMatchElements)) {
this.matches = curMatches;
this.matchElements = curMatchElements;
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else if (this.target) {
if (nodeContains(prevTargetElement, eventTarget)) {
this.pointerHover(pointer, event, this.matches, this.matchElements);
events.add(this.element,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
else {
this.target = null;
this.element = null;
this.matches = [];
this.matchElements = [];
}
}
}
},
// Check what action would be performed on pointerMove target if a mouse
// button were pressed and change the cursor accordingly
pointerHover: function (pointer, event, eventTarget, curEventTarget, matches, matchElements) {
var target = this.target;
if (!this.prepared && this.mouse) {
var action;
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (matches) {
action = this.validateSelector(pointer, matches, matchElements);
}
else if (target) {
action = validateAction(target.getAction(this.pointers[0], this, this.element), this.target);
}
if (target && target.options.styleCursor) {
if (action) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
else {
target._doc.documentElement.style.cursor = '';
}
}
}
else if (this.prepared) {
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerOut: function (pointer, event, eventTarget) {
if (this.prepared) { return; }
// Remove temporary event listeners for selector Interactables
if (!interactables.get(eventTarget)) {
events.remove(eventTarget,
PointerEvent? pEventTypes.move : 'mousemove',
listeners.pointerHover);
}
if (this.target && this.target.options.styleCursor && !this.interacting()) {
this.target._doc.documentElement.style.cursor = '';
}
},
selectorDown: function (pointer, event, eventTarget, curEventTarget) {
var that = this,
element = eventTarget,
pointerIndex = this.addPointer(pointer),
action;
this.collectEventTargets(pointer, event, eventTarget, 'down');
this.holdTimers[pointerIndex] = window.setTimeout(function () {
that.pointerHold(pointer, event, eventTarget, curEventTarget);
}, 600);
this.pointerIsDown = true;
// Check if the down event hits the current inertia target
if (this.inertiaStatus.active && this.target.selector) {
// climb up the DOM tree from the event target
while (element && element !== element.ownerDocument) {
// if this element is the current inertia target element
if (element === this.element
// and the prospective action is the same as the ongoing one
&& validateAction(this.target.getAction(pointer, this, this.element), this.target) === this.prepared) {
// stop inertia so that the next move will be a normal one
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
return;
}
element = element.parentNode;
}
}
// do nothing if interacting
if (this.interacting()) {
return;
}
function pushMatches (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)) {
that.matches.push(interactable);
that.matchElements.push(element);
}
}
// update pointer coords for defaultActionChecker to use
this.setEventXY(this.curCoords, pointer);
if (this.matches.length && this.mouse) {
action = this.validateSelector(pointer, this.matches, this.matchElements);
}
else {
while (element && element !== element.ownerDocument && !action) {
this.matches = [];
this.matchElements = [];
interactables.forEachSelector(pushMatches);
action = this.validateSelector(pointer, this.matches, this.matchElements);
element = element.parentNode;
}
}
if (action) {
this.prepared = action;
return this.pointerDown(pointer, event, eventTarget, curEventTarget, action);
}
else {
// do these now since pointerDown isn't being called from here
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
copyCoords(this.prevCoords, this.curCoords);
this.pointerWasMoved = false;
}
},
// Determine action to be performed on next pointerMove and add appropriate
// style and event Listeners
pointerDown: function (pointer, event, eventTarget, curEventTarget, forceAction) {
if (!forceAction && !this.inertiaStatus.active && this.pointerWasMoved && this.prepared) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
this.pointerIsDown = true;
var pointerIndex = this.addPointer(pointer),
action;
// If it is the second touch of a multi-touch gesture, keep the target
// the same if a target was set by the first touch
// Otherwise, set the target if there is no action prepared
if ((this.pointerIds.length < 2 && !this.target) || !this.prepared) {
var interactable = interactables.get(curEventTarget);
if (interactable
&& !testIgnore(interactable, curEventTarget, eventTarget)
&& testAllow(interactable, curEventTarget, eventTarget)
&& (action = validateAction(forceAction || interactable.getAction(pointer, this), interactable, eventTarget))
&& withinInteractionLimit(interactable, curEventTarget, action)) {
this.target = interactable;
this.element = curEventTarget;
}
}
var target = this.target,
options = target && target.options;
if (target && !this.interacting()) {
action = action || validateAction(forceAction || target.getAction(pointer, this), target, this.element);
this.setEventXY(this.startCoords);
if (!action) { return; }
if (options.styleCursor) {
target._doc.documentElement.style.cursor = actionCursors[action];
}
this.resizeAxes = action === 'resizexy'?
'xy':
action === 'resizex'?
'x':
action === 'resizey'?
'y':
'';
if (action === 'gesture' && this.pointerIds.length < 2) {
action = null;
}
this.prepared = action;
this.snapStatus.snappedX = this.snapStatus.snappedY =
this.restrictStatus.restrictedX = this.restrictStatus.restrictedY = NaN;
this.downTimes[pointerIndex] = new Date().getTime();
this.downTargets[pointerIndex] = eventTarget;
this.downEvent = event;
extend(this.downPointer, pointer);
this.setEventXY(this.prevCoords);
this.pointerWasMoved = false;
this.checkAndPreventDefault(event, target, this.element);
}
// if inertia is active try to resume action
else if (this.inertiaStatus.active
&& curEventTarget === this.element
&& validateAction(target.getAction(pointer, this, this.element), target) === this.prepared) {
cancelFrame(this.inertiaStatus.i);
this.inertiaStatus.active = false;
this.checkAndPreventDefault(event, target, this.element);
}
},
pointerMove: function (pointer, event, eventTarget, curEventTarget, preEnd) {
this.recordPointer(pointer);
this.setEventXY(this.curCoords, (pointer instanceof InteractEvent)
? this.inertiaStatus.startEvent
: undefined);
var duplicateMove = (this.curCoords.page.x === this.prevCoords.page.x
&& this.curCoords.page.y === this.prevCoords.page.y
&& this.curCoords.client.x === this.prevCoords.client.x
&& this.curCoords.client.y === this.prevCoords.client.y);
var dx, dy,
pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// register movement greater than pointerMoveTolerance
if (this.pointerIsDown && !this.pointerWasMoved) {
dx = this.curCoords.client.x - this.startCoords.client.x;
dy = this.curCoords.client.y - this.startCoords.client.y;
this.pointerWasMoved = hypot(dx, dy) > defaultOptions.pointerMoveTolerance;
}
if (!duplicateMove && (!this.pointerIsDown || this.pointerWasMoved)) {
if (this.pointerIsDown) {
window.clearTimeout(this.holdTimers[pointerIndex]);
}
this.collectEventTargets(pointer, event, eventTarget, 'move');
}
if (!this.pointerIsDown) { return; }
if (duplicateMove && this.pointerWasMoved && !preEnd) {
this.checkAndPreventDefault(event, this.target, this.element);
return;
}
// set pointer coordinate, time changes and speeds
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
if (!this.prepared) { return; }
if (this.pointerWasMoved
// ignore movement while inertia is active
&& (!this.inertiaStatus.active || (pointer instanceof InteractEvent && /inertiastart/.test(pointer.type)))) {
// if just starting an action, calculate the pointer speed now
if (!this.interacting()) {
setEventDeltas(this.pointerDelta, this.prevCoords, this.curCoords);
// check if a drag is in the correct axis
if (this.prepared === 'drag') {
var absX = Math.abs(dx),
absY = Math.abs(dy),
targetAxis = this.target.options.dragAxis,
axis = (absX > absY ? 'x' : absX < absY ? 'y' : 'xy');
// if the movement isn't in the axis of the interactable
if (axis !== 'xy' && targetAxis !== 'xy' && targetAxis !== axis) {
// cancel the prepared action
this.prepared = null;
// then try to get a drag from another ineractable
var element = eventTarget;
// check element interactables
while (element && element !== element.ownerDocument) {
var elementInteractable = interactables.get(element);
if (elementInteractable
&& elementInteractable !== this.target
&& elementInteractable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, elementInteractable)) {
this.prepared = 'drag';
this.target = elementInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
// if there's no drag from element interactables,
// check the selector interactables
if (!this.prepared) {
var getDraggable = function (interactable, selector, context) {
var elements = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable === this.target) { return; }
if (inContext(interactable, eventTarget)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, elements)
&& interactable.getAction(this.downPointer, this, element) === 'drag'
&& checkAxis(axis, interactable)
&& withinInteractionLimit(interactable, element, 'drag')) {
return interactable;
}
};
element = eventTarget;
while (element && element !== element.ownerDocument) {
var selectorInteractable = interactables.forEachSelector(getDraggable);
if (selectorInteractable) {
this.prepared = 'drag';
this.target = selectorInteractable;
this.element = element;
break;
}
element = element.parentNode;
}
}
}
}
}
var starting = !!this.prepared && !this.interacting();
if (starting && !withinInteractionLimit(this.target, this.element, this.prepared)) {
this.stop();
return;
}
if (this.prepared && this.target) {
var target = this.target,
shouldMove = true,
shouldSnap = checkSnap(target, this.prepared) && (!target.options.snap.endOnly || preEnd),
shouldRestrict = checkRestrict(target, this.prepared) && (!target.options.restrict.endOnly || preEnd);
if (starting) {
var rect = target.getRect(this.element),
snap = target.options.snap,
restrict = target.options.restrict,
width, height;
if (rect) {
this.startOffset.left = this.startCoords.page.x - rect.left;
this.startOffset.top = this.startCoords.page.y - rect.top;
this.startOffset.right = rect.right - this.startCoords.page.x;
this.startOffset.bottom = rect.bottom - this.startCoords.page.y;
if ('width' in rect) { width = rect.width; }
else { width = rect.right - rect.left; }
if ('height' in rect) { height = rect.height; }
else { height = rect.bottom - rect.top; }
}
else {
this.startOffset.left = this.startOffset.top = this.startOffset.right = this.startOffset.bottom = 0;
}
if (rect && snap.elementOrigin) {
this.snapOffset.x = this.startOffset.left - (width * snap.elementOrigin.x);
this.snapOffset.y = this.startOffset.top - (height * snap.elementOrigin.y);
}
else {
this.snapOffset.x = this.snapOffset.y = 0;
}
if (rect && restrict.elementRect) {
this.restrictOffset.left = this.startOffset.left - (width * restrict.elementRect.left);
this.restrictOffset.top = this.startOffset.top - (height * restrict.elementRect.top);
this.restrictOffset.right = this.startOffset.right - (width * (1 - restrict.elementRect.right));
this.restrictOffset.bottom = this.startOffset.bottom - (height * (1 - restrict.elementRect.bottom));
}
else {
this.restrictOffset.left = this.restrictOffset.top = this.restrictOffset.right = this.restrictOffset.bottom = 0;
}
}
var snapCoords = starting? this.startCoords.page : this.curCoords.page;
if (shouldSnap ) { this.setSnapping (snapCoords); } else { this.snapStatus .locked = false; }
if (shouldRestrict) { this.setRestriction(snapCoords); } else { this.restrictStatus.restricted = false; }
if (shouldSnap && this.snapStatus.locked && !this.snapStatus.changed) {
shouldMove = shouldRestrict && this.restrictStatus.restricted && this.restrictStatus.changed;
}
else if (shouldRestrict && this.restrictStatus.restricted && !this.restrictStatus.changed) {
shouldMove = false;
}
// move if snapping or restriction doesn't prevent it
if (shouldMove) {
var action = /resize/.test(this.prepared)? 'resize': this.prepared;
if (starting) {
var dragStartEvent = this[action + 'Start'](this.downEvent);
this.prevEvent = dragStartEvent;
// reset active dropzones
this.activeDrops.dropzones = [];
this.activeDrops.elements = [];
this.activeDrops.rects = [];
if (!this.dynamicDrop) {
this.setActiveDrops(this.element);
}
var dropEvents = this.getDropEvents(event, dragStartEvent);
if (dropEvents.activate) {
this.fireActiveDrops(dropEvents.activate);
}
snapCoords = this.curCoords.page;
// set snapping and restriction for the move event
if (shouldSnap ) { this.setSnapping (snapCoords); }
if (shouldRestrict) { this.setRestriction(snapCoords); }
}
this.prevEvent = this[action + 'Move'](event);
}
this.checkAndPreventDefault(event, this.target, this.element);
}
}
copyCoords(this.prevCoords, this.curCoords);
if (this.dragging || this.resizing) {
autoScroll.edgeMove(event);
}
},
dragStart: function (event) {
var dragEvent = new InteractEvent(this, event, 'drag', 'start', this.element);
this.dragging = true;
this.target.fire(dragEvent);
return dragEvent;
},
dragMove: function (event) {
var target = this.target,
dragEvent = new InteractEvent(this, event, 'drag', 'move', this.element),
draggableElement = this.element,
drop = this.getDrop(dragEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, dragEvent);
target.fire(dragEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.move ) { this.dropTarget.fire(dropEvents.move ); }
this.prevDropTarget = this.dropTarget;
this.prevDropElement = this.dropElement;
return dragEvent;
},
resizeStart: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'start', this.element);
this.target.fire(resizeEvent);
this.resizing = true;
return resizeEvent;
},
resizeMove: function (event) {
var resizeEvent = new InteractEvent(this, event, 'resize', 'move', this.element);
this.target.fire(resizeEvent);
return resizeEvent;
},
gestureStart: function (event) {
var gestureEvent = new InteractEvent(this, event, 'gesture', 'start', this.element);
gestureEvent.ds = 0;
this.gesture.startDistance = this.gesture.prevDistance = gestureEvent.distance;
this.gesture.startAngle = this.gesture.prevAngle = gestureEvent.angle;
this.gesture.scale = 1;
this.gesturing = true;
this.target.fire(gestureEvent);
return gestureEvent;
},
gestureMove: function (event) {
if (!this.pointerIds.length) {
return this.prevEvent;
}
var gestureEvent;
gestureEvent = new InteractEvent(this, event, 'gesture', 'move', this.element);
gestureEvent.ds = gestureEvent.scale - this.gesture.scale;
this.target.fire(gestureEvent);
this.gesture.prevAngle = gestureEvent.angle;
this.gesture.prevDistance = gestureEvent.distance;
if (gestureEvent.scale !== Infinity &&
gestureEvent.scale !== null &&
gestureEvent.scale !== undefined &&
!isNaN(gestureEvent.scale)) {
this.gesture.scale = gestureEvent.scale;
}
return gestureEvent;
},
pointerHold: function (pointer, event, eventTarget) {
this.collectEventTargets(pointer, event, eventTarget, 'hold');
},
pointerUp: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'up' );
this.collectEventTargets(pointer, event, eventTarget, 'tap');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
this.removePointer(pointer);
},
pointerCancel: function (pointer, event, eventTarget, curEventTarget) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
window.clearTimeout(this.holdTimers[pointerIndex]);
this.collectEventTargets(pointer, event, eventTarget, 'cancel');
this.pointerEnd(pointer, event, eventTarget, curEventTarget);
},
// End interact move events and stop auto-scroll unless inertia is enabled
pointerEnd: function (pointer, event, eventTarget, curEventTarget) {
var endEvent,
target = this.target,
options = target && target.options,
inertiaOptions = options && options.inertia,
inertiaStatus = this.inertiaStatus;
if (this.interacting()) {
if (inertiaStatus.active) { return; }
var pointerSpeed,
now = new Date().getTime(),
inertiaPossible = false,
inertia = false,
smoothEnd = false,
endSnap = checkSnap(target, this.prepared) && options.snap.endOnly,
endRestrict = checkRestrict(target, this.prepared) && options.restrict.endOnly,
dx = 0,
dy = 0,
startEvent;
if (this.dragging) {
if (options.dragAxis === 'x' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vx); }
else if (options.dragAxis === 'y' ) { pointerSpeed = Math.abs(this.pointerDelta.client.vy); }
else /*options.dragAxis === 'xy'*/{ pointerSpeed = this.pointerDelta.client.speed; }
}
// check if inertia should be started
inertiaPossible = (options.inertiaEnabled
&& this.prepared !== 'gesture'
&& contains(inertiaOptions.actions, this.prepared)
&& event !== inertiaStatus.startEvent);
inertia = (inertiaPossible
&& (now - this.curCoords.timeStamp) < 50
&& pointerSpeed > inertiaOptions.minSpeed
&& pointerSpeed > inertiaOptions.endSpeed);
if (inertiaPossible && !inertia && (endSnap || endRestrict)) {
var snapRestrict = {};
snapRestrict.snap = snapRestrict.restrict = snapRestrict;
if (endSnap) {
this.setSnapping(this.curCoords.page, snapRestrict);
if (snapRestrict.locked) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (endRestrict) {
this.setRestriction(this.curCoords.page, snapRestrict);
if (snapRestrict.restricted) {
dx += snapRestrict.dx;
dy += snapRestrict.dy;
}
}
if (dx || dy) {
smoothEnd = true;
}
}
if (inertia || smoothEnd) {
copyCoords(inertiaStatus.upCoords, this.curCoords);
this.pointers[0] = inertiaStatus.startEvent = startEvent =
new InteractEvent(this, event, this.prepared, 'inertiastart', this.element);
inertiaStatus.t0 = now;
target.fire(inertiaStatus.startEvent);
if (inertia) {
inertiaStatus.vx0 = this.pointerDelta.client.vx;
inertiaStatus.vy0 = this.pointerDelta.client.vy;
inertiaStatus.v0 = pointerSpeed;
this.calcInertia(inertiaStatus);
var page = extend({}, this.curCoords.page),
origin = getOriginXY(target, this.element),
statusObject;
page.x = page.x + inertiaStatus.xe - origin.x;
page.y = page.y + inertiaStatus.ye - origin.y;
statusObject = {
useStatusXY: true,
x: page.x,
y: page.y,
dx: 0,
dy: 0,
snap: null
};
statusObject.snap = statusObject;
dx = dy = 0;
if (endSnap) {
var snap = this.setSnapping(this.curCoords.page, statusObject);
if (snap.locked) {
dx += snap.dx;
dy += snap.dy;
}
}
if (endRestrict) {
var restrict = this.setRestriction(this.curCoords.page, statusObject);
if (restrict.restricted) {
dx += restrict.dx;
dy += restrict.dy;
}
}
inertiaStatus.modifiedXe += dx;
inertiaStatus.modifiedYe += dy;
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.smoothEnd = true;
inertiaStatus.xe = dx;
inertiaStatus.ye = dy;
inertiaStatus.sx = inertiaStatus.sy = 0;
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
inertiaStatus.active = true;
return;
}
if (endSnap || endRestrict) {
// fire a move event at the snapped coordinates
this.pointerMove(pointer, event, eventTarget, curEventTarget, true);
}
}
if (this.dragging) {
endEvent = new InteractEvent(this, event, 'drag', 'end', this.element);
var draggableElement = this.element,
drop = this.getDrop(endEvent, draggableElement);
this.dropTarget = drop.dropzone;
this.dropElement = drop.element;
var dropEvents = this.getDropEvents(event, endEvent);
if (dropEvents.leave) { this.prevDropTarget.fire(dropEvents.leave); }
if (dropEvents.enter) { this.dropTarget.fire(dropEvents.enter); }
if (dropEvents.drop ) { this.dropTarget.fire(dropEvents.drop ); }
if (dropEvents.deactivate) {
this.fireActiveDrops(dropEvents.deactivate);
}
target.fire(endEvent);
}
else if (this.resizing) {
endEvent = new InteractEvent(this, event, 'resize', 'end', this.element);
target.fire(endEvent);
}
else if (this.gesturing) {
endEvent = new InteractEvent(this, event, 'gesture', 'end', this.element);
target.fire(endEvent);
}
this.stop(event);
},
collectDrops: function (element) {
var drops = [],
elements = [],
i;
element = element || this.element;
// collect all dropzones and their elements which qualify for a drop
for (i = 0; i < interactables.length; i++) {
if (!interactables[i].options.dropzone) { continue; }
var current = interactables[i];
// test the draggable element against the dropzone's accept setting
if ((isElement(current.options.accept) && current.options.accept !== element)
|| (isString(current.options.accept)
&& !matchesSelector(element, current.options.accept))) {
continue;
}
// query for new elements if necessary
var dropElements = current.selector? current._context.querySelectorAll(current.selector) : [current._element];
for (var j = 0, len = dropElements.length; j < len; j++) {
var currentElement = dropElements[j];
if (currentElement === element) {
continue;
}
drops.push(current);
elements.push(currentElement);
}
}
return {
dropzones: drops,
elements: elements
};
},
fireActiveDrops: function (event) {
var i,
current,
currentElement,
prevElement;
// loop through all active dropzones and trigger event
for (i = 0; i < this.activeDrops.dropzones.length; i++) {
current = this.activeDrops.dropzones[i];
currentElement = this.activeDrops.elements [i];
// prevent trigger of duplicate events on same element
if (currentElement !== prevElement) {
// set current element as event target
event.target = currentElement;
current.fire(event);
}
prevElement = currentElement;
}
},
// Collect a new set of possible drops and save them in activeDrops.
// setActiveDrops should always be called when a drag has just started or a
// drag event happens while dynamicDrop is true
setActiveDrops: function (dragElement) {
// get dropzones and their elements that could receive the draggable
var possibleDrops = this.collectDrops(dragElement, true);
this.activeDrops.dropzones = possibleDrops.dropzones;
this.activeDrops.elements = possibleDrops.elements;
this.activeDrops.rects = [];
for (var i = 0; i < this.activeDrops.dropzones.length; i++) {
this.activeDrops.rects[i] = this.activeDrops.dropzones[i].getRect(this.activeDrops.elements[i]);
}
},
getDrop: function (event, dragElement) {
var validDrops = [];
if (dynamicDrop) {
this.setActiveDrops(dragElement);
}
// collect all dropzones and their elements which qualify for a drop
for (var j = 0; j < this.activeDrops.dropzones.length; j++) {
var current = this.activeDrops.dropzones[j],
currentElement = this.activeDrops.elements [j],
rect = this.activeDrops.rects [j];
validDrops.push(current.dropCheck(this.pointers[0], this.target, dragElement, currentElement, rect)
? currentElement
: null);
}
// get the most appropriate dropzone based on DOM depth and order
var dropIndex = indexOfDeepestElement(validDrops),
dropzone = this.activeDrops.dropzones[dropIndex] || null,
element = this.activeDrops.elements [dropIndex] || null;
return {
dropzone: dropzone,
element: element
};
},
getDropEvents: function (pointerEvent, dragEvent) {
var dragLeaveEvent = null,
dragEnterEvent = null,
dropActivateEvent = null,
dropDeactivateEvent = null,
dropMoveEvent = null,
dropEvent = null;
if (this.dropElement !== this.prevDropElement) {
// if there was a prevDropTarget, create a dragleave event
if (this.prevDropTarget) {
dragLeaveEvent = new InteractEvent(this, pointerEvent, 'drag', 'leave', this.prevDropElement, dragEvent.target);
dragLeaveEvent.draggable = dragEvent.interactable;
dragEvent.dragLeave = this.prevDropElement;
dragEvent.prevDropzone = this.prevDropTarget;
}
// if the dropTarget is not null, create a dragenter event
if (this.dropTarget) {
dragEnterEvent = new InteractEvent(this, pointerEvent, 'drag', 'enter', this.dropElement, dragEvent.target);
dragEnterEvent.draggable = dragEvent.interactable;
dragEvent.dragEnter = this.dropElement;
dragEvent.dropzone = this.dropTarget;
}
}
if (dragEvent.type === 'dragend' && this.dropTarget) {
dropEvent = new InteractEvent(this, pointerEvent, 'drop', null, this.dropElement, dragEvent.target);
dropEvent.draggable = dragEvent.interactable;
dragEvent.dropzone = this.dropTarget;
}
if (dragEvent.type === 'dragstart') {
dropActivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'activate', this.element, dragEvent.target);
dropActivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragend') {
dropDeactivateEvent = new InteractEvent(this, pointerEvent, 'drop', 'deactivate', this.element, dragEvent.target);
dropDeactivateEvent.draggable = dragEvent.interactable;
}
if (dragEvent.type === 'dragmove' && this.dropTarget) {
dropMoveEvent = {
target : this.dropElement,
relatedTarget: dragEvent.target,
draggable : dragEvent.interactable,
dragmove : dragEvent,
type : 'dropmove',
timeStamp : dragEvent.timeStamp
};
dragEvent.dropzone = this.dropTarget;
}
return {
enter : dragEnterEvent,
leave : dragLeaveEvent,
activate : dropActivateEvent,
deactivate : dropDeactivateEvent,
move : dropMoveEvent,
drop : dropEvent
};
},
currentAction: function () {
return (this.dragging && 'drag') || (this.resizing && 'resize') || (this.gesturing && 'gesture') || null;
},
interacting: function () {
return this.dragging || this.resizing || this.gesturing;
},
clearTargets: function () {
if (this.target && !this.target.selector) {
this.target = this.element = null;
}
this.dropTarget = this.dropElement = this.prevDropTarget = this.prevDropElement = null;
},
stop: function (event) {
if (this.interacting()) {
autoScroll.stop();
this.matches = [];
this.matchElements = [];
var target = this.target;
if (target.options.styleCursor) {
target._doc.documentElement.style.cursor = '';
}
// prevent Default only if were previously interacting
if (event && isFunction(event.preventDefault)) {
this.checkAndPreventDefault(event, target, this.element);
}
if (this.dragging) {
this.activeDrops.dropzones = this.activeDrops.elements = this.activeDrops.rects = null;
}
this.clearTargets();
}
this.pointerIsDown = this.snapStatus.locked = this.dragging = this.resizing = this.gesturing = false;
this.prepared = this.prevEvent = null;
this.inertiaStatus.resumeDx = this.inertiaStatus.resumeDy = 0;
this.pointerIds .splice(0);
this.pointers .splice(0);
this.downTargets.splice(0);
this.downTimes .splice(0);
this.holdTimers .splice(0);
// delete interaction if it's not the only one
if (interactions.length > 1) {
interactions.splice(indexOf(interactions, this), 1);
}
},
inertiaFrame: function () {
var inertiaStatus = this.inertiaStatus,
options = this.target.options.inertia,
lambda = options.resistance,
t = new Date().getTime() / 1000 - inertiaStatus.t0;
if (t < inertiaStatus.te) {
var progress = 1 - (Math.exp(-lambda * t) - inertiaStatus.lambda_v0) / inertiaStatus.one_ve_v0;
if (inertiaStatus.modifiedXe === inertiaStatus.xe && inertiaStatus.modifiedYe === inertiaStatus.ye) {
inertiaStatus.sx = inertiaStatus.xe * progress;
inertiaStatus.sy = inertiaStatus.ye * progress;
}
else {
var quadPoint = getQuadraticCurvePoint(
0, 0,
inertiaStatus.xe, inertiaStatus.ye,
inertiaStatus.modifiedXe, inertiaStatus.modifiedYe,
progress);
inertiaStatus.sx = quadPoint.x;
inertiaStatus.sy = quadPoint.y;
}
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundInertiaFrame);
}
else {
inertiaStatus.sx = inertiaStatus.modifiedXe;
inertiaStatus.sy = inertiaStatus.modifiedYe;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
smoothEndFrame: function () {
var inertiaStatus = this.inertiaStatus,
t = new Date().getTime() - inertiaStatus.t0,
duration = this.target.options.inertia.smoothEndDuration;
if (t < duration) {
inertiaStatus.sx = easeOutQuad(t, 0, inertiaStatus.xe, duration);
inertiaStatus.sy = easeOutQuad(t, 0, inertiaStatus.ye, duration);
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.i = reqFrame(this.boundSmoothEndFrame);
}
else {
inertiaStatus.sx = inertiaStatus.xe;
inertiaStatus.sy = inertiaStatus.ye;
this.pointerMove(inertiaStatus.startEvent, inertiaStatus.startEvent);
inertiaStatus.active = false;
inertiaStatus.smoothEnd = false;
this.pointerEnd(inertiaStatus.startEvent, inertiaStatus.startEvent);
}
},
addPointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) {
index = this.pointerIds.length;
this.pointerIds.push(id);
}
this.pointers[index] = pointer;
return index;
},
removePointer: function (pointer) {
var id = getPointerId(pointer),
index = this.mouse? 0 : indexOf(this.pointerIds, id);
if (index === -1) { return; }
this.pointerIds .splice(index, 1);
this.pointers .splice(index, 1);
this.downTargets.splice(index, 1);
this.downTimes .splice(index, 1);
this.holdTimers .splice(index, 1);
},
recordPointer: function (pointer) {
// Do not update pointers while inertia is active.
// The inertia start event should be this.pointers[0]
if (this.inertiaStatus.active) { return; }
var index = this.mouse? 0: indexOf(this.pointerIds, getPointerId(pointer));
if (index === -1) { return; }
this.pointers[index] = pointer;
},
collectEventTargets: function (pointer, event, eventTarget, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(this.pointerIds, getPointerId(pointer));
// do not fire a tap event if the pointer was moved before being lifted
if (eventType === 'tap' && (this.pointerWasMoved
// or if the pointerup target is different to the pointerdown target
|| !(this.downTargets[pointerIndex] && this.downTargets[pointerIndex] === eventTarget))) {
return;
}
var targets = [],
elements = [],
element = eventTarget;
function collectSelectors (interactable, selector, context) {
var els = ie8MatchesSelector
? context.querySelectorAll(selector)
: undefined;
if (interactable._iEvents[eventType]
&& isElement(element)
&& inContext(interactable, element)
&& !testIgnore(interactable, element, eventTarget)
&& testAllow(interactable, element, eventTarget)
&& matchesSelector(element, selector, els)) {
targets.push(interactable);
elements.push(element);
}
}
while (element) {
if (interact.isSet(element) && interact(element)._iEvents[eventType]) {
targets.push(interact(element));
elements.push(element);
}
interactables.forEachSelector(collectSelectors);
element = element.parentNode;
}
if (targets.length) {
this.firePointers(pointer, event, targets, elements, eventType);
}
},
firePointers: function (pointer, event, targets, elements, eventType) {
var pointerIndex = this.mouse? 0 : indexOf(getPointerId(pointer)),
pointerEvent = {},
i,
// for tap events
interval, dbl;
extend(pointerEvent, event);
if (event !== pointer) {
extend(pointerEvent, pointer);
}
pointerEvent.preventDefault = preventOriginalDefault;
pointerEvent.stopPropagation = InteractEvent.prototype.stopPropagation;
pointerEvent.stopImmediatePropagation = InteractEvent.prototype.stopImmediatePropagation;
pointerEvent.interaction = this;
pointerEvent.timeStamp = new Date().getTime();
pointerEvent.originalEvent = event;
pointerEvent.type = eventType;
pointerEvent.pointerId = getPointerId(pointer);
pointerEvent.pointerType = this.mouse? 'mouse' : !supportsPointerEvent? 'touch'
: isString(pointer.pointerType)
? pointer.pointerType
: [,,'touch', 'pen', 'mouse'][pointer.pointerType];
if (eventType === 'tap') {
pointerEvent.dt = pointerEvent.timeStamp - this.downTimes[pointerIndex];
interval = pointerEvent.timeStamp - this.tapTime;
dbl = (this.prevTap && this.prevTap.type !== 'doubletap'
&& this.prevTap.target === pointerEvent.target
&& interval < 500);
this.tapTime = pointerEvent.timeStamp;
}
for (i = 0; i < targets.length; i++) {
pointerEvent.currentTarget = elements[i];
pointerEvent.interactable = targets[i];
targets[i].fire(pointerEvent);
if (pointerEvent.immediatePropagationStopped
||(pointerEvent.propagationStopped && elements[i + 1] !== pointerEvent.currentTarget)) {
break;
}
}
if (dbl) {
var doubleTap = {};
extend(doubleTap, pointerEvent);
doubleTap.dt = interval;
doubleTap.type = 'doubletap';
for (i = 0; i < targets.length; i++) {
doubleTap.currentTarget = elements[i];
doubleTap.interactable = targets[i];
targets[i].fire(doubleTap);
if (doubleTap.immediatePropagationStopped
||(doubleTap.propagationStopped && elements[i + 1] !== doubleTap.currentTarget)) {
break;
}
}
this.prevTap = doubleTap;
}
else if (eventType === 'tap') {
this.prevTap = pointerEvent;
}
},
validateSelector: function (pointer, matches, matchElements) {
for (var i = 0, len = matches.length; i < len; i++) {
var match = matches[i],
matchElement = matchElements[i],
action = validateAction(match.getAction(pointer, this, matchElement), match);
if (action && withinInteractionLimit(match, matchElement, action)) {
this.target = match;
this.element = matchElement;
return action;
}
}
},
setSnapping: function (pageCoords, status) {
var snap = this.target.options.snap,
anchors = snap.anchors,
page,
closest,
range,
inRange,
snapChanged,
dx,
dy,
distance,
i, len;
status = status || this.snapStatus;
if (status.useStatusXY) {
page = { x: status.x, y: status.y };
}
else {
var origin = getOriginXY(this.target, this.element);
page = extend({}, pageCoords);
page.x -= origin.x;
page.y -= origin.y;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.realX = page.x;
status.realY = page.y;
// change to infinite range when range is negative
if (snap.range < 0) { snap.range = Infinity; }
// create an anchor representative for each path's returned point
if (snap.mode === 'path') {
anchors = [];
for (i = 0, len = snap.paths.length; i < len; i++) {
var path = snap.paths[i];
if (isFunction(path)) {
path = path(page.x, page.y);
}
anchors.push({
x: isNumber(path.x) ? path.x : page.x,
y: isNumber(path.y) ? path.y : page.y,
range: isNumber(path.range)? path.range: snap.range
});
}
}
if ((snap.mode === 'anchor' || snap.mode === 'path') && anchors.length) {
closest = {
anchor: null,
distance: 0,
range: 0,
dx: 0,
dy: 0
};
for (i = 0, len = anchors.length; i < len; i++) {
var anchor = anchors[i];
range = isNumber(anchor.range)? anchor.range: snap.range;
dx = anchor.x - page.x + this.snapOffset.x;
dy = anchor.y - page.y + this.snapOffset.y;
distance = hypot(dx, dy);
inRange = distance < range;
// Infinite anchors count as being out of range
// compared to non infinite ones that are in range
if (range === Infinity && closest.inRange && closest.range !== Infinity) {
inRange = false;
}
if (!closest.anchor || (inRange?
// is the closest anchor in range?
(closest.inRange && range !== Infinity)?
// the pointer is relatively deeper in this anchor
distance / range < closest.distance / closest.range:
//the pointer is closer to this anchor
distance < closest.distance:
// The other is not in range and the pointer is closer to this anchor
(!closest.inRange && distance < closest.distance))) {
if (range === Infinity) {
inRange = true;
}
closest.anchor = anchor;
closest.distance = distance;
closest.range = range;
closest.inRange = inRange;
closest.dx = dx;
closest.dy = dy;
status.range = range;
}
}
inRange = closest.inRange;
snapChanged = (closest.anchor.x !== status.x || closest.anchor.y !== status.y);
status.snappedX = closest.anchor.x;
status.snappedY = closest.anchor.y;
status.dx = closest.dx;
status.dy = closest.dy;
}
else if (snap.mode === 'grid') {
var gridx = Math.round((page.x - snap.gridOffset.x - this.snapOffset.x) / snap.grid.x),
gridy = Math.round((page.y - snap.gridOffset.y - this.snapOffset.y) / snap.grid.y),
newX = gridx * snap.grid.x + snap.gridOffset.x + this.snapOffset.x,
newY = gridy * snap.grid.y + snap.gridOffset.y + this.snapOffset.y;
dx = newX - page.x;
dy = newY - page.y;
distance = hypot(dx, dy);
inRange = distance < snap.range;
snapChanged = (newX !== status.snappedX || newY !== status.snappedY);
status.snappedX = newX;
status.snappedY = newY;
status.dx = dx;
status.dy = dy;
status.range = snap.range;
}
status.changed = (snapChanged || (inRange && !status.locked));
status.locked = inRange;
return status;
},
setRestriction: function (pageCoords, status) {
var target = this.target,
action = /resize/.test(this.prepared)? 'resize' : this.prepared,
restrict = target && target.options.restrict,
restriction = restrict && restrict[action],
page;
if (!restriction) {
return status;
}
status = status || this.restrictStatus;
page = status.useStatusXY
? page = { x: status.x, y: status.y }
: page = extend({}, pageCoords);
if (status.snap && status.snap.locked) {
page.x += status.snap.dx || 0;
page.y += status.snap.dy || 0;
}
page.x -= this.inertiaStatus.resumeDx;
page.y -= this.inertiaStatus.resumeDy;
status.dx = 0;
status.dy = 0;
status.restricted = false;
var rect, restrictedX, restrictedY;
if (isString(restriction)) {
if (restriction === 'parent') {
restriction = this.element.parentNode;
}
else if (restriction === 'self') {
restriction = target.getRect(this.element);
}
else {
restriction = closest(this.element, restriction);
}
if (!restriction) { return status; }
}
if (isFunction(restriction)) {
restriction = restriction(page.x, page.y, this.element);
}
if (isElement(restriction)) {
restriction = getElementRect(restriction);
}
rect = restriction;
// object is assumed to have
// x, y, width, height or
// left, top, right, bottom
if ('x' in restriction && 'y' in restriction) {
restrictedX = Math.max(Math.min(rect.x + rect.width - this.restrictOffset.right , page.x), rect.x + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.y + rect.height - this.restrictOffset.bottom, page.y), rect.y + this.restrictOffset.top );
}
else {
restrictedX = Math.max(Math.min(rect.right - this.restrictOffset.right , page.x), rect.left + this.restrictOffset.left);
restrictedY = Math.max(Math.min(rect.bottom - this.restrictOffset.bottom, page.y), rect.top + this.restrictOffset.top );
}
status.dx = restrictedX - page.x;
status.dy = restrictedY - page.y;
status.changed = status.restrictedX !== restrictedX || status.restrictedY !== restrictedY;
status.restricted = !!(status.dx || status.dy);
status.restrictedX = restrictedX;
status.restrictedY = restrictedY;
return status;
},
checkAndPreventDefault: function (event, interactable, element) {
if (!(interactable = interactable || this.target)) { return; }
var options = interactable.options,
prevent = options.preventDefault;
if (prevent === 'auto' && element && !/^input$|^textarea$/i.test(element.nodeName)) {
// do not preventDefault on pointerdown if the prepared action is a drag
// and dragging can only start from a certain direction - this allows
// a touch to pan the viewport if a drag isn't in the right direction
if (/down|start/i.test(event.type)
&& this.prepared === 'drag' && options.dragAxis !== 'xy') {
return;
}
event.preventDefault();
return;
}
if (prevent === true) {
event.preventDefault();
return;
}
},
calcInertia: function (status) {
var inertiaOptions = this.target.options.inertia,
lambda = inertiaOptions.resistance,
inertiaDur = -Math.log(inertiaOptions.endSpeed / status.v0) / lambda;
status.x0 = this.prevEvent.pageX;
status.y0 = this.prevEvent.pageY;
status.t0 = status.startEvent.timeStamp / 1000;
status.sx = status.sy = 0;
status.modifiedXe = status.xe = (status.vx0 - inertiaDur) / lambda;
status.modifiedYe = status.ye = (status.vy0 - inertiaDur) / lambda;
status.te = inertiaDur;
status.lambda_v0 = lambda / status.v0;
status.one_ve_v0 = 1 - inertiaOptions.endSpeed / status.v0;
}
};
function getInteractionFromPointer (pointer, eventType, eventTarget) {
var i = 0, len = interactions.length,
mouseEvent = (/mouse/i.test(pointer.pointerType || eventType)
// MSPointerEvent.MSPOINTER_TYPE_MOUSE
|| pointer.pointerType === 4),
interaction;
var id = getPointerId(pointer);
// try to resume inertia with a new pointer
if (/down|start/i.test(eventType)) {
for (i = 0; i < len; i++) {
interaction = interactions[i];
var element = eventTarget;
if (interaction.inertiaStatus.active && interaction.target.options.inertia.allowResume
&& (interaction.mouse === mouseEvent)) {
while (element) {
// if the element is the interaction element
if (element === interaction.element) {
// update the interaction's pointer
interaction.removePointer(interaction.pointers[0]);
interaction.addPointer(pointer);
return interaction;
}
element = element.parentNode;
}
}
}
}
// if it's a mouse interaction
if (mouseEvent || !(supportsTouch || supportsPointerEvent)) {
// find a mouse interaction that's not in inertia phase
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !interactions[i].inertiaStatus.active) {
return interactions[i];
}
}
// find any interaction specifically for mouse.
// if the eventType is a mousedown, and inertia is active
// ignore the interaction
for (i = 0; i < len; i++) {
if (interactions[i].mouse && !(/down/.test(eventType) && interactions[i].inertiaStatus.active)) {
return interaction;
}
}
// create a new interaction for mouse
interaction = new Interaction();
interaction.mouse = true;
return interaction;
}
// get interaction that has this pointer
for (i = 0; i < len; i++) {
if (contains(interactions[i].pointerIds, id)) {
return interactions[i];
}
}
// at this stage, a pointerUp should not return an interaction
if (/up|end|out/i.test(eventType)) {
return null;
}
// get first idle interaction
for (i = 0; i < len; i++) {
interaction = interactions[i];
if ((!interaction.prepared || (interaction.target.gesturable()))
&& !interaction.interacting()
&& !(!mouseEvent && interaction.mouse)) {
interaction.addPointer(pointer);
return interaction;
}
}
return new Interaction();
}
function doOnInteractions (method) {
return (function (event) {
var interaction,
eventTarget = getActualElement(event.target),
curEventTarget = getActualElement(event.currentTarget),
i;
if (supportsTouch && /touch/.test(event.type)) {
prevTouchTime = new Date().getTime();
for (i = 0; i < event.changedTouches.length; i++) {
var pointer = event.changedTouches[i];
interaction = getInteractionFromPointer(pointer, event.type, eventTarget);
if (!interaction) { continue; }
interaction[method](pointer, event, eventTarget, curEventTarget);
}
}
else {
if (!supportsPointerEvent && /mouse/.test(event.type)) {
// ignore mouse events while touch interactions are active
for (i = 0; i < interactions.length; i++) {
if (!interactions[i].mouse && interactions[i].pointerIsDown) {
return;
}
}
// try to ignore mouse events that are simulated by the browser
// after a touch event
if (new Date().getTime() - prevTouchTime < 500) {
return;
}
}
interaction = getInteractionFromPointer(event, event.type, eventTarget);
if (!interaction) { return; }
interaction[method](event, event, eventTarget, curEventTarget);
}
});
}
function InteractEvent (interaction, event, action, phase, element, related) {
var client,
page,
target = interaction.target,
snapStatus = interaction.snapStatus,
restrictStatus = interaction.restrictStatus,
pointers = interaction.pointers,
deltaSource = (target && target.options || defaultOptions).deltaSource,
sourceX = deltaSource + 'X',
sourceY = deltaSource + 'Y',
options = target? target.options: defaultOptions,
origin = getOriginXY(target, element),
starting = phase === 'start',
ending = phase === 'end',
coords = starting? interaction.startCoords : interaction.curCoords;
element = element || interaction.element;
page = extend({}, coords.page);
client = extend({}, coords.client);
page.x -= origin.x;
page.y -= origin.y;
client.x -= origin.x;
client.y -= origin.y;
if (checkSnap(target, action) && !(starting && options.snap.elementOrigin)) {
this.snap = {
range : snapStatus.range,
locked : snapStatus.locked,
x : snapStatus.snappedX,
y : snapStatus.snappedY,
realX : snapStatus.realX,
realY : snapStatus.realY,
dx : snapStatus.dx,
dy : snapStatus.dy
};
if (snapStatus.locked) {
page.x += snapStatus.dx;
page.y += snapStatus.dy;
client.x += snapStatus.dx;
client.y += snapStatus.dy;
}
}
if (checkRestrict(target, action) && !(starting && options.restrict.elementRect) && restrictStatus.restricted) {
page.x += restrictStatus.dx;
page.y += restrictStatus.dy;
client.x += restrictStatus.dx;
client.y += restrictStatus.dy;
this.restrict = {
dx: restrictStatus.dx,
dy: restrictStatus.dy
};
}
this.pageX = page.x;
this.pageY = page.y;
this.clientX = client.x;
this.clientY = client.y;
this.x0 = interaction.startCoords.page.x;
this.y0 = interaction.startCoords.page.y;
this.clientX0 = interaction.startCoords.client.x;
this.clientY0 = interaction.startCoords.client.y;
this.ctrlKey = event.ctrlKey;
this.altKey = event.altKey;
this.shiftKey = event.shiftKey;
this.metaKey = event.metaKey;
this.button = event.button;
this.target = element;
this.t0 = interaction.downTimes[0];
this.type = action + (phase || '');
this.interaction = interaction;
this.interactable = target;
var inertiaStatus = interaction.inertiaStatus;
if (inertiaStatus.active) {
this.detail = 'inertia';
}
if (related) {
this.relatedTarget = related;
}
// end event dx, dy is difference between start and end points
if (ending || action === 'drop') {
if (deltaSource === 'client') {
this.dx = client.x - interaction.startCoords.client.x;
this.dy = client.y - interaction.startCoords.client.y;
}
else {
this.dx = page.x - interaction.startCoords.page.x;
this.dy = page.y - interaction.startCoords.page.y;
}
}
else if (starting) {
this.dx = 0;
this.dy = 0;
}
// copy properties from previousmove if starting inertia
else if (phase === 'inertiastart') {
this.dx = interaction.prevEvent.dx;
this.dy = interaction.prevEvent.dy;
}
else {
if (deltaSource === 'client') {
this.dx = client.x - interaction.prevEvent.clientX;
this.dy = client.y - interaction.prevEvent.clientY;
}
else {
this.dx = page.x - interaction.prevEvent.pageX;
this.dy = page.y - interaction.prevEvent.pageY;
}
}
if (interaction.prevEvent && interaction.prevEvent.detail === 'inertia'
&& !inertiaStatus.active && options.inertia.zeroResumeDelta) {
inertiaStatus.resumeDx += this.dx;
inertiaStatus.resumeDy += this.dy;
this.dx = this.dy = 0;
}
if (action === 'resize') {
if (options.squareResize || event.shiftKey) {
if (interaction.resizeAxes === 'y') {
this.dx = this.dy;
}
else {
this.dy = this.dx;
}
this.axes = 'xy';
}
else {
this.axes = interaction.resizeAxes;
if (interaction.resizeAxes === 'x') {
this.dy = 0;
}
else if (interaction.resizeAxes === 'y') {
this.dx = 0;
}
}
}
else if (action === 'gesture') {
this.touches = [pointers[0], pointers[1]];
if (starting) {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = 1;
this.ds = 0;
this.angle = touchAngle(pointers, undefined, deltaSource);
this.da = 0;
}
else if (ending || event instanceof InteractEvent) {
this.distance = interaction.prevEvent.distance;
this.box = interaction.prevEvent.box;
this.scale = interaction.prevEvent.scale;
this.ds = this.scale - 1;
this.angle = interaction.prevEvent.angle;
this.da = this.angle - interaction.gesture.startAngle;
}
else {
this.distance = touchDistance(pointers, deltaSource);
this.box = touchBBox(pointers);
this.scale = this.distance / interaction.gesture.startDistance;
this.angle = touchAngle(pointers, interaction.gesture.prevAngle, deltaSource);
this.ds = this.scale - interaction.gesture.prevScale;
this.da = this.angle - interaction.gesture.prevAngle;
}
}
if (starting) {
this.timeStamp = interaction.downTimes[0];
this.dt = 0;
this.duration = 0;
this.speed = 0;
this.velocityX = 0;
this.velocityY = 0;
}
else if (phase === 'inertiastart') {
this.timeStamp = interaction.prevEvent.timeStamp;
this.dt = interaction.prevEvent.dt;
this.duration = interaction.prevEvent.duration;
this.speed = interaction.prevEvent.speed;
this.velocityX = interaction.prevEvent.velocityX;
this.velocityY = interaction.prevEvent.velocityY;
}
else {
this.timeStamp = new Date().getTime();
this.dt = this.timeStamp - interaction.prevEvent.timeStamp;
this.duration = this.timeStamp - interaction.downTimes[0];
if (event instanceof InteractEvent) {
var dx = this[sourceX] - interaction.prevEvent[sourceX],
dy = this[sourceY] - interaction.prevEvent[sourceY],
dt = this.dt / 1000;
this.speed = hypot(dx, dy) / dt;
this.velocityX = dx / dt;
this.velocityY = dy / dt;
}
// if normal move or end event, use previous user event coords
else {
// speed and velocity in pixels per second
this.speed = interaction.pointerDelta[deltaSource].speed;
this.velocityX = interaction.pointerDelta[deltaSource].vx;
this.velocityY = interaction.pointerDelta[deltaSource].vy;
}
}
if ((ending || phase === 'inertiastart')
&& interaction.prevEvent.speed > 600 && this.timeStamp - interaction.prevEvent.timeStamp < 150) {
var angle = 180 * Math.atan2(interaction.prevEvent.velocityY, interaction.prevEvent.velocityX) / Math.PI,
overlap = 22.5;
if (angle < 0) {
angle += 360;
}
var left = 135 - overlap <= angle && angle < 225 + overlap,
up = 225 - overlap <= angle && angle < 315 + overlap,
right = !left && (315 - overlap <= angle || angle < 45 + overlap),
down = !up && 45 - overlap <= angle && angle < 135 + overlap;
this.swipe = {
up : up,
down : down,
left : left,
right: right,
angle: angle,
speed: interaction.prevEvent.speed,
velocity: {
x: interaction.prevEvent.velocityX,
y: interaction.prevEvent.velocityY
}
};
}
}
InteractEvent.prototype = {
preventDefault: blank,
stopImmediatePropagation: function () {
this.immediatePropagationStopped = this.propagationStopped = true;
},
stopPropagation: function () {
this.propagationStopped = true;
}
};
function preventOriginalDefault () {
this.originalEvent.preventDefault();
}
function defaultActionChecker (pointer, interaction, element) {
var rect = this.getRect(element),
right,
bottom,
action = null,
page = extend({}, interaction.curCoords.page),
options = this.options;
if (!rect) { return null; }
if (actionIsEnabled.resize && options.resizable) {
right = options.resizeAxis !== 'y' && page.x > (rect.right - margin);
bottom = options.resizeAxis !== 'x' && page.y > (rect.bottom - margin);
}
interaction.resizeAxes = (right?'x': '') + (bottom?'y': '');
action = (interaction.resizeAxes)?
'resize' + interaction.resizeAxes:
actionIsEnabled.drag && options.draggable?
'drag':
null;
if (actionIsEnabled.gesture
&& interaction.pointerIds.length >=2
&& !(interaction.dragging || interaction.resizing)) {
action = 'gesture';
}
return action;
}
// Check if action is enabled globally and the current target supports it
// If so, return the validated action. Otherwise, return null
function validateAction (action, interactable) {
if (!isString(action)) { return null; }
var actionType = action.search('resize') !== -1? 'resize': action,
options = interactable;
if (( (actionType === 'resize' && options.resizable )
|| (action === 'drag' && options.draggable )
|| (action === 'gesture' && options.gesturable))
&& actionIsEnabled[actionType]) {
if (action === 'resize' || action === 'resizeyx') {
action = 'resizexy';
}
return action;
}
return null;
}
var listeners = {},
interactionListeners = [
'dragStart', 'dragMove', 'resizeStart', 'resizeMove', 'gestureStart', 'gestureMove',
'pointerOver', 'pointerOut', 'pointerHover', 'selectorDown',
'pointerDown', 'pointerMove', 'pointerUp', 'pointerCancel', 'pointerEnd',
'addPointer', 'removePointer', 'recordPointer',
];
for (var i = 0, len = interactionListeners.length; i < len; i++) {
var name = interactionListeners[i];
listeners[name] = doOnInteractions(name);
}
// bound to the interactable context when a DOM event
// listener is added to a selector interactable
function delegateListener (event, useCapture) {
var fakeEvent = {},
delegated = delegatedEvents[event.type],
element = event.target;
useCapture = useCapture? true: false;
// duplicate the event so that currentTarget can be changed
for (var prop in event) {
fakeEvent[prop] = event[prop];
}
fakeEvent.originalEvent = event;
fakeEvent.preventDefault = preventOriginalDefault;
// climb up document tree looking for selector matches
while (element && (element.ownerDocument && element !== element.ownerDocument)) {
for (var i = 0; i < delegated.selectors.length; i++) {
var selector = delegated.selectors[i],
context = delegated.contexts[i];
if (matchesSelector(element, selector)
&& nodeContains(context, event.target)
&& nodeContains(context, element)) {
var listeners = delegated.listeners[i];
fakeEvent.currentTarget = element;
for (var j = 0; j < listeners.length; j++) {
if (listeners[j][1] === useCapture) {
listeners[j][0](fakeEvent);
}
}
}
}
element = element.parentNode;
}
}
function delegateUseCapture (event) {
return delegateListener.call(this, event, true);
}
interactables.indexOfElement = function indexOfElement (element, context) {
context = context || document;
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if ((interactable.selector === element
&& (interactable._context === context))
|| (!interactable.selector && interactable._element === element)) {
return i;
}
}
return -1;
};
interactables.get = function interactableGet (element, options) {
return this[this.indexOfElement(element, options && options.context)];
};
interactables.forEachSelector = function (callback) {
for (var i = 0; i < this.length; i++) {
var interactable = this[i];
if (!interactable.selector) {
continue;
}
var ret = callback(interactable, interactable.selector, interactable._context, i, this);
if (ret !== undefined) {
return ret;
}
}
};
/*\
* interact
[ method ]
*
* The methods of this variable can be used to set elements as
* interactables and also to change various default settings.
*
* Calling it as a function and passing an element or a valid CSS selector
* string returns an Interactable object which has various methods to
* configure it.
*
- element (Element | string) The HTML or SVG Element to interact with or CSS selector
= (object) An @Interactable
*
> Usage
| interact(document.getElementById('draggable')).draggable(true);
|
| var rectables = interact('rect');
| rectables
| .gesturable(true)
| .on('gesturemove', function (event) {
| // something cool...
| })
| .autoScroll(true);
\*/
function interact (element, options) {
return interactables.get(element, options) || new Interactable(element, options);
}
// A class for easy inheritance and setting of an Interactable's options
function IOptions (options) {
for (var option in defaultOptions) {
if (options.hasOwnProperty(option)
&& typeof options[option] === typeof defaultOptions[option]) {
this[option] = options[option];
}
}
}
IOptions.prototype = defaultOptions;
/*\
* Interactable
[ property ]
**
* Object type returned by @interact
\*/
function Interactable (element, options) {
this._element = element;
this._iEvents = this._iEvents || {};
var _window;
if (trySelector(element)) {
this.selector = element;
var context = options && options.context;
_window = context? getWindow(context) : window;
if (context && (_window.Node
? context instanceof _window.Node
: (isElement(context) || context === _window.document))) {
this._context = context;
}
}
else {
_window = getWindow(element);
if (isElement(element, _window)) {
if (PointerEvent) {
events.add(this._element, pEventTypes.down, listeners.pointerDown );
events.add(this._element, pEventTypes.move, listeners.pointerHover);
}
else {
events.add(this._element, 'mousedown' , listeners.pointerDown );
events.add(this._element, 'mousemove' , listeners.pointerHover);
events.add(this._element, 'touchstart', listeners.pointerDown );
events.add(this._element, 'touchmove' , listeners.pointerHover);
}
}
}
this._doc = _window.document;
if (!contains(documents, this._doc)) {
listenToDocument(this._doc);
}
interactables.push(this);
this.set(options);
}
Interactable.prototype = {
setOnEvents: function (action, phases) {
if (action === 'drop') {
var drop = phases.ondrop || phases.onDrop || phases.drop,
dropactivate = phases.ondropactivate || phases.onDropActivate || phases.dropactivate
|| phases.onactivate || phases.onActivate || phases.activate,
dropdeactivate = phases.ondropdeactivate || phases.onDropDeactivate || phases.dropdeactivate
|| phases.ondeactivate || phases.onDeactivate || phases.deactivate,
dragenter = phases.ondragenter || phases.onDropEnter || phases.dragenter
|| phases.onenter || phases.onEnter || phases.enter,
dragleave = phases.ondragleave || phases.onDropLeave || phases.dragleave
|| phases.onleave || phases.onLeave || phases.leave,
dropmove = phases.ondropmove || phases.onDropMove || phases.dropmove
|| phases.onmove || phases.onMove || phases.move;
if (isFunction(drop) ) { this.ondrop = drop ; }
if (isFunction(dropactivate) ) { this.ondropactivate = dropactivate ; }
if (isFunction(dropdeactivate)) { this.ondropdeactivate = dropdeactivate; }
if (isFunction(dragenter) ) { this.ondragenter = dragenter ; }
if (isFunction(dragleave) ) { this.ondragleave = dragleave ; }
if (isFunction(dropmove) ) { this.ondropmove = dropmove ; }
}
else {
var start = phases.onstart || phases.onStart || phases.start,
move = phases.onmove || phases.onMove || phases.move,
end = phases.onend || phases.onEnd || phases.end,
inertiastart = phases.oninertiastart || phases.onInertiaStart || phases.inertiastart;
action = 'on' + action;
if (isFunction(start) ) { this[action + 'start' ] = start ; }
if (isFunction(move) ) { this[action + 'move' ] = move ; }
if (isFunction(end) ) { this[action + 'end' ] = end ; }
if (isFunction(inertiastart)) { this[action + 'inertiastart' ] = inertiastart ; }
}
return this;
},
/*\
* Interactable.draggable
[ method ]
*
* Gets or sets whether drag actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of drag events
| var isDraggable = interact('ul li').draggable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on drag events (object makes the Interactable draggable)
= (object) This Interactable
| interact(element).draggable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // the axis in which the first movement must be
| // for the drag sequence to start
| // 'xy' by default - any direction
| axis: 'x' || 'y' || 'xy',
|
| // max number of drags that can happen concurrently
| // with elements of this Interactable. 1 by default
| max: Infinity,
|
| // max number of drags that can target the same element
| // 1 by default
| maxPerElement: 2
| });
\*/
draggable: function (options) {
if (isObject(options)) {
this.options.draggable = true;
this.setOnEvents('drag', options);
if (isNumber(options.max)) {
this.options.dragMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.dragMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.dragAxis = options.axis;
}
else if (options.axis === null) {
delete this.options.dragAxis;
}
return this;
}
if (isBool(options)) {
this.options.draggable = options;
return this;
}
if (options === null) {
delete this.options.draggable;
return this;
}
return this.options.draggable;
},
/*\
* Interactable.dropzone
[ method ]
*
* Returns or sets whether elements can be dropped onto this
* Interactable to trigger drop events
*
* Dropzones can receive the following events:
* - `dragactivate` and `dragdeactivate` when an acceptable drag starts and ends
* - `dragenter` and `dragleave` when a draggable enters and leaves the dropzone
* - `drop` when a draggable is dropped into this dropzone
*
* Use the `accept` option to allow only elements that match the given CSS selector or element.
*
* Use the `overlap` option to set how drops are checked for. The allowed values are:
* - `'pointer'`, the pointer must be over the dropzone (default)
* - `'center'`, the draggable element's center must be over the dropzone
* - a number from 0-1 which is the `(intersection area) / (draggable area)`.
* e.g. `0.5` for drop to happen when half of the area of the
* draggable is over the dropzone
*
- options (boolean | object | null) #optional The new value to be set.
| interact('.drop').dropzone({
| accept: '.can-drop' || document.getElementById('single-drop'),
| overlap: 'pointer' || 'center' || zeroToOne
| }
= (boolean | object) The current setting or this Interactable
\*/
dropzone: function (options) {
if (isObject(options)) {
this.options.dropzone = true;
this.setOnEvents('drop', options);
this.accept(options.accept);
if (/^(pointer|center)$/.test(options.overlap)) {
this.options.dropOverlap = options.overlap;
}
else if (isNumber(options.overlap)) {
this.options.dropOverlap = Math.max(Math.min(1, options.overlap), 0);
}
return this;
}
if (isBool(options)) {
this.options.dropzone = options;
return this;
}
if (options === null) {
delete this.options.dropzone;
return this;
}
return this.options.dropzone;
},
/*\
* Interactable.dropCheck
[ method ]
*
* The default function to determine if a dragend event occured over
* this Interactable's element. Can be overridden using
* @Interactable.dropChecker.
*
- pointer (MouseEvent | PointerEvent | Touch) The event that ends a drag
- draggable (Interactable) The Interactable being dragged
- draggableElement (Element) The actual element that's being dragged
- dropElement (Element) The dropzone element
- rect (object) #optional The rect of dropElement
= (boolean) whether the pointer was over this Interactable
\*/
dropCheck: function (pointer, draggable, draggableElement, dropElement, rect) {
if (!(rect = rect || this.getRect(dropElement))) {
return false;
}
var dropOverlap = this.options.dropOverlap;
if (dropOverlap === 'pointer') {
var page = getPageXY(pointer),
origin = getOriginXY(draggable, draggableElement),
horizontal,
vertical;
page.x += origin.x;
page.y += origin.y;
horizontal = (page.x > rect.left) && (page.x < rect.right);
vertical = (page.y > rect.top ) && (page.y < rect.bottom);
return horizontal && vertical;
}
var dragRect = draggable.getRect(draggableElement);
if (dropOverlap === 'center') {
var cx = dragRect.left + dragRect.width / 2,
cy = dragRect.top + dragRect.height / 2;
return cx >= rect.left && cx <= rect.right && cy >= rect.top && cy <= rect.bottom;
}
if (isNumber(dropOverlap)) {
var overlapArea = (Math.max(0, Math.min(rect.right , dragRect.right ) - Math.max(rect.left, dragRect.left))
* Math.max(0, Math.min(rect.bottom, dragRect.bottom) - Math.max(rect.top , dragRect.top ))),
overlapRatio = overlapArea / (dragRect.width * dragRect.height);
return overlapRatio >= dropOverlap;
}
},
/*\
* Interactable.dropChecker
[ method ]
*
* Gets or sets the function used to check if a dragged element is
* over this Interactable. See @Interactable.dropCheck.
*
- checker (function) #optional
* The checker is a function which takes a mouseUp/touchEnd event as a
* parameter and returns true or false to indicate if the the current
* draggable can be dropped into this Interactable
*
= (Function | Interactable) The checker function or this Interactable
\*/
dropChecker: function (checker) {
if (isFunction(checker)) {
this.dropCheck = checker;
return this;
}
return this.dropCheck;
},
/*\
* Interactable.accept
[ method ]
*
* Gets or sets the Element or CSS selector match that this
* Interactable accepts if it is a dropzone.
*
- newValue (Element | string | null) #optional
* If it is an Element, then only that element can be dropped into this dropzone.
* If it is a string, the element being dragged must match it as a selector.
* If it is null, the accept options is cleared - it accepts any element.
*
= (string | Element | null | Interactable) The current accept option if given `undefined` or this Interactable
\*/
accept: function (newValue) {
if (isElement(newValue)) {
this.options.accept = newValue;
return this;
}
// test if it is a valid CSS selector
if (trySelector(newValue)) {
this.options.accept = newValue;
return this;
}
if (newValue === null) {
delete this.options.accept;
return this;
}
return this.options.accept;
},
/*\
* Interactable.resizable
[ method ]
*
* Gets or sets whether resize actions can be performed on the
* Interactable
*
= (boolean) Indicates if this can be the target of resize elements
| var isResizeable = interact('input[type=text]').resizable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on resize events (object makes the Interactable resizable)
= (object) This Interactable
| interact(element).resizable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| axis : 'x' || 'y' || 'xy' // default is 'xy',
|
| // limit multiple resizes.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
resizable: function (options) {
if (isObject(options)) {
this.options.resizable = true;
this.setOnEvents('resize', options);
if (isNumber(options.max)) {
this.options.resizeMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.resizeMaxPerElement = options.maxPerElement;
}
if (/^x$|^y$|^xy$/.test(options.axis)) {
this.options.resizeAxis = options.axis;
}
else if (options.axis === null) {
this.options.resizeAxis = defaultOptions.resizeAxis;
}
return this;
}
if (isBool(options)) {
this.options.resizable = options;
return this;
}
return this.options.resizable;
},
// misspelled alias
resizeable: blank,
/*\
* Interactable.squareResize
[ method ]
*
* Gets or sets whether resizing is forced 1:1 aspect
*
= (boolean) Current setting
*
* or
*
- newValue (boolean) #optional
= (object) this Interactable
\*/
squareResize: function (newValue) {
if (isBool(newValue)) {
this.options.squareResize = newValue;
return this;
}
if (newValue === null) {
delete this.options.squareResize;
return this;
}
return this.options.squareResize;
},
/*\
* Interactable.gesturable
[ method ]
*
* Gets or sets whether multitouch gestures can be performed on the
* Interactable's element
*
= (boolean) Indicates if this can be the target of gesture events
| var isGestureable = interact(element).gesturable();
* or
- options (boolean | object) #optional true/false or An object with event listeners to be fired on gesture events (makes the Interactable gesturable)
= (object) this Interactable
| interact(element).gesturable({
| onstart: function (event) {},
| onmove : function (event) {},
| onend : function (event) {},
|
| // limit multiple gestures.
| // See the explanation in @Interactable.draggable example
| max: 1,
| maxPerElement: 1,
| });
\*/
gesturable: function (options) {
if (isObject(options)) {
this.options.gesturable = true;
this.setOnEvents('gesture', options);
if (isNumber(options.max)) {
this.options.gestureMax = options.max;
}
if (isNumber(options.maxPerElement)) {
this.options.gestureMaxPerElement = options.maxPerElement;
}
return this;
}
if (isBool(options)) {
this.options.gesturable = options;
return this;
}
if (options === null) {
delete this.options.gesturable;
return this;
}
return this.options.gesturable;
},
// misspelled alias
gestureable: blank,
/*\
* Interactable.autoScroll
[ method ]
*
* Returns or sets whether or not any actions near the edges of the
* window/container trigger autoScroll for this Interactable
*
= (boolean | object)
* `false` if autoScroll is disabled; object with autoScroll properties
* if autoScroll is enabled
*
* or
*
- options (object | boolean | null) #optional
* options can be:
* - an object with margin, distance and interval properties,
* - true or false to enable or disable autoScroll or
* - null to use default settings
= (Interactable) this Interactable
\*/
autoScroll: function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
var autoScroll = this.options.autoScroll;
if (autoScroll === defaults) {
autoScroll = this.options.autoScroll = {
margin : defaults.margin,
distance : defaults.distance,
interval : defaults.interval,
container: defaults.container
};
}
autoScroll.margin = this.validateSetting('autoScroll', 'margin', options.margin);
autoScroll.speed = this.validateSetting('autoScroll', 'speed' , options.speed);
autoScroll.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
this.options.autoScrollEnabled = true;
this.options.autoScroll = autoScroll;
return this;
}
if (isBool(options)) {
this.options.autoScrollEnabled = options;
return this;
}
if (options === null) {
delete this.options.autoScrollEnabled;
delete this.options.autoScroll;
return this;
}
return (this.options.autoScrollEnabled
? this.options.autoScroll
: false);
},
/*\
* Interactable.snap
[ method ]
**
* Returns or sets if and how action coordinates are snapped. By
* default, snapping is relative to the pointer coordinates. You can
* change this by setting the
* [`elementOrigin`](https://github.com/taye/interact.js/pull/72).
**
= (boolean | object) `false` if snap is disabled; object with snap properties if snap is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| interact('.handle').snap({
| mode : 'grid', // event coords should snap to the corners of a grid
| range : Infinity, // the effective distance of snap points
| grid : { x: 100, y: 100 }, // the x and y spacing of the grid points
| gridOffset : { x: 0, y: 0 }, // the offset of the grid points
| });
|
| interact('.handle').snap({
| mode : 'anchor', // snap to specified points
| anchors : [
| { x: 100, y: 100, range: 25 }, // a point with x, y and a specific range
| { x: 200, y: 200 } // a point with x and y. it uses the default range
| ]
| });
|
| interact(document.querySelector('#thing')).snap({
| mode : 'path',
| paths: [
| { // snap to points on these x and y axes
| x: 100,
| y: 100,
| range: 25
| },
| // give this function the x and y page coords and snap to the object returned
| function (x, y) {
| return {
| x: x,
| y: (75 + 50 * Math.sin(x * 0.04)),
| range: 40
| };
| }]
| })
|
| interact(element).snap({
| // do not snap during normal movement.
| // Instead, trigger only one snapped move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementOrigin: { x: 0, y: 0 }
| });
\*/
snap: function (options) {
var defaults = defaultOptions.snap;
if (isObject(options)) {
var snap = this.options.snap;
if (snap === defaults) {
snap = {};
}
snap.mode = this.validateSetting('snap', 'mode' , options.mode);
snap.endOnly = this.validateSetting('snap', 'endOnly' , options.endOnly);
snap.actions = this.validateSetting('snap', 'actions' , options.actions);
snap.range = this.validateSetting('snap', 'range' , options.range);
snap.paths = this.validateSetting('snap', 'paths' , options.paths);
snap.grid = this.validateSetting('snap', 'grid' , options.grid);
snap.gridOffset = this.validateSetting('snap', 'gridOffset' , options.gridOffset);
snap.anchors = this.validateSetting('snap', 'anchors' , options.anchors);
snap.elementOrigin = this.validateSetting('snap', 'elementOrigin', options.elementOrigin);
this.options.snapEnabled = true;
this.options.snap = snap;
return this;
}
if (isBool(options)) {
this.options.snapEnabled = options;
return this;
}
if (options === null) {
delete this.options.snapEnabled;
delete this.options.snap;
return this;
}
return (this.options.snapEnabled
? this.options.snap
: false);
},
/*\
* Interactable.inertia
[ method ]
**
* Returns or sets if and how events continue to run after the pointer is released
**
= (boolean | object) `false` if inertia is disabled; `object` with inertia properties if inertia is enabled
**
* or
**
- options (object | boolean | null) #optional
= (Interactable) this Interactable
> Usage
| // enable and use default settings
| interact(element).inertia(true);
|
| // enable and use custom settings
| interact(element).inertia({
| // value greater than 0
| // high values slow the object down more quickly
| resistance : 16,
|
| // the minimum launch speed (pixels per second) that results in inertia start
| minSpeed : 200,
|
| // inertia will stop when the object slows down to this speed
| endSpeed : 20,
|
| // boolean; should actions be resumed when the pointer goes down during inertia
| allowResume : true,
|
| // boolean; should the jump when resuming from inertia be ignored in event.dx/dy
| zeroResumeDelta: false,
|
| // if snap/restrict are set to be endOnly and inertia is enabled, releasing
| // the pointer without triggering inertia will animate from the release
| // point to the snaped/restricted point in the given amount of time (ms)
| smoothEndDuration: 300,
|
| // an array of action types that can have inertia (no gesture)
| actions : ['drag', 'resize']
| });
|
| // reset custom settings and use all defaults
| interact(element).inertia(null);
\*/
inertia: function (options) {
var defaults = defaultOptions.inertia;
if (isObject(options)) {
var inertia = this.options.inertia;
if (inertia === defaults) {
inertia = this.options.inertia = {
resistance : defaults.resistance,
minSpeed : defaults.minSpeed,
endSpeed : defaults.endSpeed,
actions : defaults.actions,
allowResume : defaults.allowResume,
zeroResumeDelta : defaults.zeroResumeDelta,
smoothEndDuration: defaults.smoothEndDuration
};
}
inertia.resistance = this.validateSetting('inertia', 'resistance' , options.resistance);
inertia.minSpeed = this.validateSetting('inertia', 'minSpeed' , options.minSpeed);
inertia.endSpeed = this.validateSetting('inertia', 'endSpeed' , options.endSpeed);
inertia.actions = this.validateSetting('inertia', 'actions' , options.actions);
inertia.allowResume = this.validateSetting('inertia', 'allowResume' , options.allowResume);
inertia.zeroResumeDelta = this.validateSetting('inertia', 'zeroResumeDelta' , options.zeroResumeDelta);
inertia.smoothEndDuration = this.validateSetting('inertia', 'smoothEndDuration', options.smoothEndDuration);
this.options.inertiaEnabled = true;
this.options.inertia = inertia;
return this;
}
if (isBool(options)) {
this.options.inertiaEnabled = options;
return this;
}
if (options === null) {
delete this.options.inertiaEnabled;
delete this.options.inertia;
return this;
}
return (this.options.inertiaEnabled
? this.options.inertia
: false);
},
getAction: function (pointer, interaction, element) {
var action = this.defaultActionChecker(pointer, interaction, element);
if (this.options.actionChecker) {
action = this.options.actionChecker(pointer, action, this, element, interaction);
}
return action;
},
defaultActionChecker: defaultActionChecker,
/*\
* Interactable.actionChecker
[ method ]
*
* Gets or sets the function used to check action to be performed on
* pointerDown
*
- checker (function | null) #optional A function which takes a pointer event, defaultAction string and an interactable as parameters and returns 'drag' 'resize[axes]' or 'gesture' or null.
= (Function | Interactable) The checker function or this Interactable
\*/
actionChecker: function (newValue) {
if (isFunction(newValue)) {
this.options.actionChecker = newValue;
return this;
}
if (newValue === null) {
delete this.options.actionChecker;
return this;
}
return this.options.actionChecker;
},
/*\
* Interactable.getRect
[ method ]
*
* The default function to get an Interactables bounding rect. Can be
* overridden using @Interactable.rectChecker.
*
- element (Element) #optional The element to measure. Meant to be used for selector Interactables which don't have a specific element.
= (object) The object's bounding rectangle.
o {
o top : 0,
o left : 0,
o bottom: 0,
o right : 0,
o width : 0,
o height: 0
o }
\*/
getRect: function rectCheck (element) {
element = element || this._element;
if (this.selector && !(isElement(element))) {
element = this._context.querySelector(this.selector);
}
return getElementRect(element);
},
/*\
* Interactable.rectChecker
[ method ]
*
* Returns or sets the function used to calculate the interactable's
* element's rectangle
*
- checker (function) #optional A function which returns this Interactable's bounding rectangle. See @Interactable.getRect
= (function | object) The checker function or this Interactable
\*/
rectChecker: function (checker) {
if (isFunction(checker)) {
this.getRect = checker;
return this;
}
if (checker === null) {
delete this.options.getRect;
return this;
}
return this.getRect;
},
/*\
* Interactable.styleCursor
[ method ]
*
* Returns or sets whether the action that would be performed when the
* mouse on the element are checked on `mousemove` so that the cursor
* may be styled appropriately
*
- newValue (boolean) #optional
= (boolean | Interactable) The current setting or this Interactable
\*/
styleCursor: function (newValue) {
if (isBool(newValue)) {
this.options.styleCursor = newValue;
return this;
}
if (newValue === null) {
delete this.options.styleCursor;
return this;
}
return this.options.styleCursor;
},
/*\
* Interactable.preventDefault
[ method ]
*
* Returns or sets whether to prevent the browser's default behaviour
* in response to pointer events. Can be set to
* - `true` to always prevent
* - `false` to never prevent
* - `'auto'` to allow interact.js to try to guess what would be best
* - `null` to set to the default ('auto')
*
- newValue (boolean | string | null) #optional `true`, `false` or `'auto'`
= (boolean | string | Interactable) The current setting or this Interactable
\*/
preventDefault: function (newValue) {
if (isBool(newValue) || newValue === 'auto') {
this.options.preventDefault = newValue;
return this;
}
if (newValue === null) {
delete this.options.preventDefault;
return this;
}
return this.options.preventDefault;
},
/*\
* Interactable.origin
[ method ]
*
* Gets or sets the origin of the Interactable's element. The x and y
* of the origin will be subtracted from action event coordinates.
*
- origin (object | string) #optional An object eg. { x: 0, y: 0 } or string 'parent', 'self' or any CSS selector
* OR
- origin (Element) #optional An HTML or SVG Element whose rect will be used
**
= (object) The current origin or this Interactable
\*/
origin: function (newValue) {
if (trySelector(newValue)) {
this.options.origin = newValue;
return this;
}
else if (isObject(newValue)) {
this.options.origin = newValue;
return this;
}
if (newValue === null) {
delete this.options.origin;
return this;
}
return this.options.origin;
},
/*\
* Interactable.deltaSource
[ method ]
*
* Returns or sets the mouse coordinate types used to calculate the
* movement of the pointer.
*
- newValue (string) #optional Use 'client' if you will be scrolling while interacting; Use 'page' if you want autoScroll to work
= (string | object) The current deltaSource or this Interactable
\*/
deltaSource: function (newValue) {
if (newValue === 'page' || newValue === 'client') {
this.options.deltaSource = newValue;
return this;
}
if (newValue === null) {
delete this.options.deltaSource;
return this;
}
return this.options.deltaSource;
},
/*\
* Interactable.restrict
[ method ]
**
* Returns or sets the rectangles within which actions on this
* interactable (after snap calculations) are restricted. By default,
* restricting is relative to the pointer coordinates. You can change
* this by setting the
* [`elementRect`](https://github.com/taye/interact.js/pull/72).
**
- newValue (object) #optional an object with keys drag, resize, and/or gesture whose values are rects, Elements, CSS selectors, or 'parent' or 'self'
= (object) The current restrictions object or this Interactable
**
| interact(element).restrict({
| // the rect will be `interact.getElementRect(element.parentNode)`
| drag: element.parentNode,
|
| // x and y are relative to the the interactable's origin
| resize: { x: 100, y: 100, width: 200, height: 200 }
| })
|
| interact('.draggable').restrict({
| // the rect will be the selected element's parent
| drag: 'parent',
|
| // do not restrict during normal movement.
| // Instead, trigger only one restricted move event
| // immediately before the end event.
| endOnly: true,
|
| // https://github.com/taye/interact.js/pull/72#issue-41813493
| elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
| });
\*/
restrict: function (newValue) {
if (newValue === undefined) {
return this.options.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
var newRestrictions = {};
if (isObject(newValue.drag) || trySelector(newValue.drag)) {
newRestrictions.drag = newValue.drag;
}
if (isObject(newValue.resize) || trySelector(newValue.resize)) {
newRestrictions.resize = newValue.resize;
}
if (isObject(newValue.gesture) || trySelector(newValue.gesture)) {
newRestrictions.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
newRestrictions.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
newRestrictions.elementRect = newValue.elementRect;
}
this.options.restrictEnabled = true;
this.options.restrict = newRestrictions;
}
else if (newValue === null) {
delete this.options.restrict;
delete this.options.restrictEnabled;
}
return this;
},
/*\
* Interactable.context
[ method ]
*
* Get's the selector context Node of the Interactable. The default is `window.document`.
*
= (Node) The context Node of this Interactable
**
\*/
context: function () {
return this._context;
},
_context: document,
/*\
* Interactable.ignoreFrom
[ method ]
*
* If the target of the `mousedown`, `pointerdown` or `touchstart`
* event or any of it's parents match the given CSS selector or
* Element, no drag/resize/gesture is started.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to not ignore any elements
= (string | Element | object) The current ignoreFrom value or this Interactable
**
| interact(element, { ignoreFrom: document.getElementById('no-action') });
| // or
| interact(element).ignoreFrom('input, textarea, a');
\*/
ignoreFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.ignoreFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.ignoreFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.ignoreFrom;
return this;
}
return this.options.ignoreFrom;
},
/*\
* Interactable.allowFrom
[ method ]
*
* A drag/resize/gesture is started only If the target of the
* `mousedown`, `pointerdown` or `touchstart` event or any of it's
* parents match the given CSS selector or Element.
*
- newValue (string | Element | null) #optional a CSS selector string, an Element or `null` to allow from any element
= (string | Element | object) The current allowFrom value or this Interactable
**
| interact(element, { allowFrom: document.getElementById('drag-handle') });
| // or
| interact(element).allowFrom('.handle');
\*/
allowFrom: function (newValue) {
if (trySelector(newValue)) { // CSS selector to match event.target
this.options.allowFrom = newValue;
return this;
}
if (isElement(newValue)) { // specific element
this.options.allowFrom = newValue;
return this;
}
if (newValue === null) {
delete this.options.allowFrom;
return this;
}
return this.options.allowFrom;
},
/*\
* Interactable.validateSetting
[ method ]
*
- context (string) eg. 'snap', 'autoScroll'
- option (string) The name of the value being set
- value (any type) The value being validated
*
= (typeof value) A valid value for the give context-option pair
* - null if defaultOptions[context][value] is undefined
* - value if it is the same type as defaultOptions[context][value],
* - this.options[context][value] if it is the same type as defaultOptions[context][value],
* - or defaultOptions[context][value]
\*/
validateSetting: function (context, option, value) {
var defaults = defaultOptions[context],
current = this.options[context];
if (defaults !== undefined && defaults[option] !== undefined) {
if ('objectTypes' in defaults && defaults.objectTypes.test(option)) {
if (isObject(value)) { return value; }
else {
return (option in current && isObject(current[option])
? current [option]
: defaults[option]);
}
}
if ('arrayTypes' in defaults && defaults.arrayTypes.test(option)) {
if (isArray(value)) { return value; }
else {
return (option in current && isArray(current[option])
? current[option]
: defaults[option]);
}
}
if ('stringTypes' in defaults && defaults.stringTypes.test(option)) {
if (isString(value)) { return value; }
else {
return (option in current && isString(current[option])
? current[option]
: defaults[option]);
}
}
if ('numberTypes' in defaults && defaults.numberTypes.test(option)) {
if (isNumber(value)) { return value; }
else {
return (option in current && isNumber(current[option])
? current[option]
: defaults[option]);
}
}
if ('boolTypes' in defaults && defaults.boolTypes.test(option)) {
if (isBool(value)) { return value; }
else {
return (option in current && isBool(current[option])
? current[option]
: defaults[option]);
}
}
if ('elementTypes' in defaults && defaults.elementTypes.test(option)) {
if (isElement(value)) { return value; }
else {
return (option in current && isElement(current[option])
? current[option]
: defaults[option]);
}
}
}
return null;
},
/*\
* Interactable.element
[ method ]
*
* If this is not a selector Interactable, it returns the element this
* interactable represents
*
= (Element) HTML / SVG Element
\*/
element: function () {
return this._element;
},
/*\
* Interactable.fire
[ method ]
*
* Calls listeners for the given InteractEvent type bound globally
* and directly to this Interactable
*
- iEvent (InteractEvent) The InteractEvent object to be fired on this Interactable
= (Interactable) this Interactable
\*/
fire: function (iEvent) {
if (!(iEvent && iEvent.type) || !contains(eventTypes, iEvent.type)) {
return this;
}
var listeners,
i,
len,
onEvent = 'on' + iEvent.type,
funcName = '';
// Interactable#on() listeners
if (iEvent.type in this._iEvents) {
listeners = this._iEvents[iEvent.type];
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
// interactable.onevent listener
if (isFunction(this[onEvent])) {
funcName = this[onEvent].name;
this[onEvent](iEvent);
}
// interact.on() listeners
if (iEvent.type in globalEvents && (listeners = globalEvents[iEvent.type])) {
for (i = 0, len = listeners.length; i < len && !iEvent.immediatePropagationStopped; i++) {
funcName = listeners[i].name;
listeners[i](iEvent);
}
}
return this;
},
/*\
* Interactable.on
[ method ]
*
* Binds a listener for an InteractEvent or DOM event.
*
- eventType (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) This Interactable
\*/
on: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.on(eventType[i], listener, useCapture);
}
return this;
}
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// convert to boolean
useCapture = useCapture? true: false;
if (contains(eventTypes, eventType)) {
// if this type of event was never bound to this Interactable
if (!(eventType in this._iEvents)) {
this._iEvents[eventType] = [listener];
}
else {
this._iEvents[eventType].push(listener);
}
}
// delegated event for selector
else if (this.selector) {
if (!delegatedEvents[eventType]) {
delegatedEvents[eventType] = {
selectors: [],
contexts : [],
listeners: []
};
// add delegate listener functions
for (i = 0; i < documents.length; i++) {
events.add(documents[i], eventType, delegateListener);
events.add(documents[i], eventType, delegateUseCapture, true);
}
}
var delegated = delegatedEvents[eventType],
index;
for (index = delegated.selectors.length - 1; index >= 0; index--) {
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
break;
}
}
if (index === -1) {
index = delegated.selectors.length;
delegated.selectors.push(this.selector);
delegated.contexts .push(this._context);
delegated.listeners.push([]);
}
// keep listener and useCapture flag
delegated.listeners[index].push([listener, useCapture]);
}
else {
events.add(this._element, eventType, listener, useCapture);
}
return this;
},
/*\
* Interactable.off
[ method ]
*
* Removes an InteractEvent or DOM event listener
*
- eventType (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) This Interactable
\*/
off: function (eventType, listener, useCapture) {
var i;
if (isArray(eventType)) {
for (i = 0; i < eventType.length; i++) {
this.off(eventType[i], listener, useCapture);
}
return this;
}
var eventList,
index = -1;
// convert to boolean
useCapture = useCapture? true: false;
if (eventType === 'wheel') {
eventType = wheelEvent;
}
// if it is an action event type
if (contains(eventTypes, eventType)) {
eventList = this._iEvents[eventType];
if (eventList && (index = indexOf(eventList, listener)) !== -1) {
this._iEvents[eventType].splice(index, 1);
}
}
// delegated event
else if (this.selector) {
var delegated = delegatedEvents[eventType],
matchFound = false;
if (!delegated) { return this; }
// count from last index of delegated to 0
for (index = delegated.selectors.length - 1; index >= 0; index--) {
// look for matching selector and context Node
if (delegated.selectors[index] === this.selector
&& delegated.contexts[index] === this._context) {
var listeners = delegated.listeners[index];
// each item of the listeners array is an array: [function, useCaptureFlag]
for (i = listeners.length - 1; i >= 0; i--) {
var fn = listeners[i][0],
useCap = listeners[i][1];
// check if the listener functions and useCapture flags match
if (fn === listener && useCap === useCapture) {
// remove the listener from the array of listeners
listeners.splice(i, 1);
// if all listeners for this interactable have been removed
// remove the interactable from the delegated arrays
if (!listeners.length) {
delegated.selectors.splice(index, 1);
delegated.contexts .splice(index, 1);
delegated.listeners.splice(index, 1);
// remove delegate function from context
events.remove(this._context, eventType, delegateListener);
events.remove(this._context, eventType, delegateUseCapture, true);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[eventType] = null;
}
}
// only remove one listener
matchFound = true;
break;
}
}
if (matchFound) { break; }
}
}
}
// remove listener from this Interatable's element
else {
events.remove(this, listener, useCapture);
}
return this;
},
/*\
* Interactable.set
[ method ]
*
* Reset the options of this Interactable
- options (object) The new settings to apply
= (object) This Interactablw
\*/
set: function (options) {
if (!options || !isObject(options)) {
options = {};
}
this.options = new IOptions(options);
this.draggable ('draggable' in options? options.draggable : this.options.draggable );
this.dropzone ('dropzone' in options? options.dropzone : this.options.dropzone );
this.resizable ('resizable' in options? options.resizable : this.options.resizable );
this.gesturable('gesturable' in options? options.gesturable: this.options.gesturable);
var settings = [
'accept', 'actionChecker', 'allowFrom', 'autoScroll', 'deltaSource',
'dropChecker', 'ignoreFrom', 'inertia', 'origin', 'preventDefault',
'rectChecker', 'restrict', 'snap', 'styleCursor'
];
for (var i = 0, len = settings.length; i < len; i++) {
var setting = settings[i];
if (setting in options) {
this[setting](options[setting]);
}
}
return this;
},
/*\
* Interactable.unset
[ method ]
*
* Remove this interactable from the list of interactables and remove
* it's drag, drop, resize and gesture capabilities
*
= (object) @interact
\*/
unset: function () {
events.remove(this, 'all');
if (!isString(this.selector)) {
events.remove(this, 'all');
if (this.options.styleCursor) {
this._element.style.cursor = '';
}
}
else {
// remove delegated events
for (var type in delegatedEvents) {
var delegated = delegatedEvents[type];
for (var i = 0; i < delegated.selectors.length; i++) {
if (delegated.selectors[i] === this.selector
&& delegated.contexts[i] === this._context) {
delegated.selectors.splice(i, 1);
delegated.contexts .splice(i, 1);
delegated.listeners.splice(i, 1);
// remove the arrays if they are empty
if (!delegated.selectors.length) {
delegatedEvents[type] = null;
}
}
events.remove(this._context, type, delegateListener);
events.remove(this._context, type, delegateUseCapture, true);
break;
}
}
}
this.dropzone(false);
interactables.splice(indexOf(interactables, this), 1);
return interact;
}
};
Interactable.prototype.gestureable = Interactable.prototype.gesturable;
Interactable.prototype.resizeable = Interactable.prototype.resizable;
/*\
* interact.isSet
[ method ]
*
* Check if an element has been set
- element (Element) The Element being searched for
= (boolean) Indicates if the element or CSS selector was previously passed to interact
\*/
interact.isSet = function(element, options) {
return interactables.indexOfElement(element, options && options.context) !== -1;
};
/*\
* interact.on
[ method ]
*
* Adds a global listener for an InteractEvent or adds a DOM event to
* `document`
*
- type (string | array) The type of event or array of types to listen for
- listener (function) The function to be called on the given event(s)
- useCapture (boolean) #optional useCapture flag for addEventListener
= (object) interact
\*/
interact.on = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.on(type[i], listener, useCapture);
}
return interact;
}
// if it is an InteractEvent type, add listener to globalEvents
if (contains(eventTypes, type)) {
// if this type of event was never bound
if (!globalEvents[type]) {
globalEvents[type] = [listener];
}
else {
globalEvents[type].push(listener);
}
}
// If non InteractEvent type, addEventListener to document
else {
events.add(document, type, listener, useCapture);
}
return interact;
};
/*\
* interact.off
[ method ]
*
* Removes a global InteractEvent listener or DOM event from `document`
*
- type (string | array) The type of event or array of types that were listened for
- listener (function) The listener function to be removed
- useCapture (boolean) #optional useCapture flag for removeEventListener
= (object) interact
\*/
interact.off = function (type, listener, useCapture) {
if (isArray(type)) {
for (var i = 0; i < type.length; i++) {
interact.off(type[i], listener, useCapture);
}
return interact;
}
if (!contains(eventTypes, type)) {
events.remove(document, type, listener, useCapture);
}
else {
var index;
if (type in globalEvents
&& (index = indexOf(globalEvents[type], listener)) !== -1) {
globalEvents[type].splice(index, 1);
}
}
return interact;
};
/*\
* interact.simulate
[ method ]
*
* Simulate pointer down to begin to interact with an interactable element
- action (string) The action to be performed - drag, resize, etc.
- element (Element) The DOM Element to resize/drag
- pointerEvent (object) #optional Pointer event whose pageX/Y coordinates will be the starting point of the interact drag/resize
= (object) interact
\*/
interact.simulate = function (action, element, pointerEvent) {
var event = {},
clientRect;
if (action === 'resize') {
action = 'resizexy';
}
// return if the action is not recognised
if (!/^(drag|resizexy|resizex|resizey)$/.test(action)) {
return interact;
}
if (pointerEvent) {
extend(event, pointerEvent);
}
else {
clientRect = (element instanceof SVGElement)
? element.getBoundingClientRect()
: clientRect = element.getClientRects()[0];
if (action === 'drag') {
event.pageX = clientRect.left + clientRect.width / 2;
event.pageY = clientRect.top + clientRect.height / 2;
}
else {
event.pageX = clientRect.right;
event.pageY = clientRect.bottom;
}
}
event.target = event.currentTarget = element;
event.preventDefault = event.stopPropagation = blank;
listeners.pointerDown(event, action);
return interact;
};
/*\
* interact.enableDragging
[ method ]
*
* Returns or sets whether dragging is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableDragging = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.drag = newValue;
return interact;
}
return actionIsEnabled.drag;
};
/*\
* interact.enableResizing
[ method ]
*
* Returns or sets whether resizing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableResizing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.resize = newValue;
return interact;
}
return actionIsEnabled.resize;
};
/*\
* interact.enableGesturing
[ method ]
*
* Returns or sets whether gesturing is enabled for any Interactables
*
- newValue (boolean) #optional `true` to allow the action; `false` to disable action for all Interactables
= (boolean | object) The current setting or interact
\*/
interact.enableGesturing = function (newValue) {
if (newValue !== null && newValue !== undefined) {
actionIsEnabled.gesture = newValue;
return interact;
}
return actionIsEnabled.gesture;
};
interact.eventTypes = eventTypes;
/*\
* interact.debug
[ method ]
*
* Returns debugging data
= (object) An object with properties that outline the current state and expose internal functions and variables
\*/
interact.debug = function () {
var interaction = interactions[0] || new Interaction();
return {
interactions : interactions,
target : interaction.target,
dragging : interaction.dragging,
resizing : interaction.resizing,
gesturing : interaction.gesturing,
prepared : interaction.prepared,
matches : interaction.matches,
matchElements : interaction.matchElements,
prevCoords : interaction.prevCoords,
startCoords : interaction.startCoords,
pointerIds : interaction.pointerIds,
pointers : interaction.pointers,
addPointer : listeners.addPointer,
removePointer : listeners.removePointer,
recordPointer : listeners.recordPointer,
snap : interaction.snapStatus,
restrict : interaction.restrictStatus,
inertia : interaction.inertiaStatus,
downTime : interaction.downTimes[0],
downEvent : interaction.downEvent,
downPointer : interaction.downPointer,
prevEvent : interaction.prevEvent,
Interactable : Interactable,
IOptions : IOptions,
interactables : interactables,
pointerIsDown : interaction.pointerIsDown,
defaultOptions : defaultOptions,
defaultActionChecker : defaultActionChecker,
actionCursors : actionCursors,
dragMove : listeners.dragMove,
resizeMove : listeners.resizeMove,
gestureMove : listeners.gestureMove,
pointerUp : listeners.pointerUp,
pointerDown : listeners.pointerDown,
pointerMove : listeners.pointerMove,
pointerHover : listeners.pointerHover,
events : events,
globalEvents : globalEvents,
delegatedEvents : delegatedEvents
};
};
// expose the functions used to calculate multi-touch properties
interact.getTouchAverage = touchAverage;
interact.getTouchBBox = touchBBox;
interact.getTouchDistance = touchDistance;
interact.getTouchAngle = touchAngle;
interact.getElementRect = getElementRect;
interact.matchesSelector = matchesSelector;
interact.closest = closest;
/*\
* interact.margin
[ method ]
*
* Returns or sets the margin for autocheck resizing used in
* @Interactable.getAction. That is the distance from the bottom and right
* edges of an element clicking in which will start resizing
*
- newValue (number) #optional
= (number | interact) The current margin value or interact
\*/
interact.margin = function (newvalue) {
if (isNumber(newvalue)) {
margin = newvalue;
return interact;
}
return margin;
};
/*\
* interact.styleCursor
[ styleCursor ]
*
* Returns or sets whether the cursor style of the document is changed
* depending on what action is being performed
*
- newValue (boolean) #optional
= (boolean | interact) The current setting of interact
\*/
interact.styleCursor = function (newValue) {
if (isBool(newValue)) {
defaultOptions.styleCursor = newValue;
return interact;
}
return defaultOptions.styleCursor;
};
/*\
* interact.autoScroll
[ method ]
*
* Returns or sets whether or not actions near the edges of the window or
* specified container element trigger autoScroll by default
*
- options (boolean | object) true or false to simply enable or disable or an object with margin, distance, container and interval properties
= (object) interact
* or
= (boolean | object) `false` if autoscroll is disabled and the default autoScroll settings if it is enabled
\*/
interact.autoScroll = function (options) {
var defaults = defaultOptions.autoScroll;
if (isObject(options)) {
defaultOptions.autoScrollEnabled = true;
if (isNumber(options.margin)) { defaults.margin = options.margin;}
if (isNumber(options.speed) ) { defaults.speed = options.speed ;}
defaults.container =
(isElement(options.container) || isWindow(options.container)
? options.container
: defaults.container);
return interact;
}
if (isBool(options)) {
defaultOptions.autoScrollEnabled = options;
return interact;
}
// return the autoScroll settings if autoScroll is enabled
// otherwise, return false
return defaultOptions.autoScrollEnabled? defaults: false;
};
/*\
* interact.snap
[ method ]
*
* Returns or sets whether actions are constrained to a grid or a
* collection of coordinates
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object with some of the following properties
o {
o mode : 'grid', 'anchor' or 'path',
o range : the distance within which snapping to a point occurs,
o actions: ['drag', 'resizex', 'resizey', 'resizexy'], an array of action types that can snapped (['drag'] by default) (no gesture)
o grid : {
o x, y: the distances between the grid lines,
o },
o gridOffset: {
o x, y: the x/y-axis values of the grid origin
o },
o anchors: [
o {
o x: x coordinate to snap to,
o y: y coordinate to snap to,
o range: optional range for this anchor
o }
o {
o another anchor
o }
o ]
o }
*
= (object | interact) The default snap settings object or interact
\*/
interact.snap = function (options) {
var snap = defaultOptions.snap;
if (isObject(options)) {
defaultOptions.snapEnabled = true;
if (isString(options.mode) ) { snap.mode = options.mode; }
if (isBool (options.endOnly) ) { snap.endOnly = options.endOnly; }
if (isNumber(options.range) ) { snap.range = options.range; }
if (isArray (options.actions) ) { snap.actions = options.actions; }
if (isArray (options.anchors) ) { snap.anchors = options.anchors; }
if (isObject(options.grid) ) { snap.grid = options.grid; }
if (isObject(options.gridOffset) ) { snap.gridOffset = options.gridOffset; }
if (isObject(options.elementOrigin)) { snap.elementOrigin = options.elementOrigin; }
return interact;
}
if (isBool(options)) {
defaultOptions.snapEnabled = options;
return interact;
}
return defaultOptions.snapEnabled;
};
/*\
* interact.inertia
[ method ]
*
* Returns or sets inertia settings.
*
* See @Interactable.inertia
*
- options (boolean | object) #optional New settings
* `true` or `false` to simply enable or disable
* or an object of inertia options
= (object | interact) The default inertia settings object or interact
\*/
interact.inertia = function (options) {
var inertia = defaultOptions.inertia;
if (isObject(options)) {
defaultOptions.inertiaEnabled = true;
if (isNumber(options.resistance) ) { inertia.resistance = options.resistance ; }
if (isNumber(options.minSpeed) ) { inertia.minSpeed = options.minSpeed ; }
if (isNumber(options.endSpeed) ) { inertia.endSpeed = options.endSpeed ; }
if (isNumber(options.smoothEndDuration)) { inertia.smoothEndDuration = options.smoothEndDuration; }
if (isBool (options.allowResume) ) { inertia.allowResume = options.allowResume ; }
if (isBool (options.zeroResumeDelta) ) { inertia.zeroResumeDelta = options.zeroResumeDelta ; }
if (isArray (options.actions) ) { inertia.actions = options.actions ; }
return interact;
}
if (isBool(options)) {
defaultOptions.inertiaEnabled = options;
return interact;
}
return {
enabled: defaultOptions.inertiaEnabled,
resistance: inertia.resistance,
minSpeed: inertia.minSpeed,
endSpeed: inertia.endSpeed,
actions: inertia.actions,
allowResume: inertia.allowResume,
zeroResumeDelta: inertia.zeroResumeDelta
};
};
/*\
* interact.supportsTouch
[ method ]
*
= (boolean) Whether or not the browser supports touch input
\*/
interact.supportsTouch = function () {
return supportsTouch;
};
/*\
* interact.supportsPointerEvent
[ method ]
*
= (boolean) Whether or not the browser supports PointerEvents
\*/
interact.supportsPointerEvent = function () {
return supportsPointerEvent;
};
/*\
* interact.currentAction
[ method ]
*
= (string) What action is currently being performed
\*/
interact.currentAction = function () {
for (var i = 0, len = interactions.length; i < len; i++) {
var action = interactions[i].currentAction();
if (action) { return action; }
}
return null;
};
/*\
* interact.stop
[ method ]
*
* Cancels the current interaction
*
- event (Event) An event on which to call preventDefault()
= (object) interact
\*/
interact.stop = function (event) {
for (var i = interactions.length - 1; i > 0; i--) {
interactions[i].stop(event);
}
return interact;
};
/*\
* interact.dynamicDrop
[ method ]
*
* Returns or sets whether the dimensions of dropzone elements are
* calculated on every dragmove or only on dragstart for the default
* dropChecker
*
- newValue (boolean) #optional True to check on each move. False to check only before start
= (boolean | interact) The current setting or interact
\*/
interact.dynamicDrop = function (newValue) {
if (isBool(newValue)) {
//if (dragging && dynamicDrop !== newValue && !newValue) {
//calcRects(dropzones);
//}
dynamicDrop = newValue;
return interact;
}
return dynamicDrop;
};
/*\
* interact.deltaSource
[ method ]
* Returns or sets weather pageX/Y or clientX/Y is used to calculate dx/dy.
*
* See @Interactable.deltaSource
*
- newValue (string) #optional 'page' or 'client'
= (string | Interactable) The current setting or interact
\*/
interact.deltaSource = function (newValue) {
if (newValue === 'page' || newValue === 'client') {
defaultOptions.deltaSource = newValue;
return this;
}
return defaultOptions.deltaSource;
};
/*\
* interact.restrict
[ method ]
*
* Returns or sets the default rectangles within which actions (after snap
* calculations) are restricted.
*
* See @Interactable.restrict
*
- newValue (object) #optional an object with keys drag, resize, and/or gesture and rects or Elements as values
= (object) The current restrictions object or interact
\*/
interact.restrict = function (newValue) {
var defaults = defaultOptions.restrict;
if (newValue === undefined) {
return defaultOptions.restrict;
}
if (isBool(newValue)) {
defaultOptions.restrictEnabled = newValue;
}
else if (isObject(newValue)) {
if (isObject(newValue.drag) || /^parent$|^self$/.test(newValue.drag)) {
defaults.drag = newValue.drag;
}
if (isObject(newValue.resize) || /^parent$|^self$/.test(newValue.resize)) {
defaults.resize = newValue.resize;
}
if (isObject(newValue.gesture) || /^parent$|^self$/.test(newValue.gesture)) {
defaults.gesture = newValue.gesture;
}
if (isBool(newValue.endOnly)) {
defaults.endOnly = newValue.endOnly;
}
if (isObject(newValue.elementRect)) {
defaults.elementRect = newValue.elementRect;
}
defaultOptions.restrictEnabled = true;
}
else if (newValue === null) {
defaults.drag = defaults.resize = defaults.gesture = null;
defaults.endOnly = false;
}
return this;
};
/*\
* interact.pointerMoveTolerance
[ method ]
* Returns or sets the distance the pointer must be moved before an action
* sequence occurs. This also affects tolerance for tap events.
*
- newValue (number) #optional The movement from the start position must be greater than this value
= (number | Interactable) The current setting or interact
\*/
interact.pointerMoveTolerance = function (newValue) {
if (isNumber(newValue)) {
defaultOptions.pointerMoveTolerance = newValue;
return this;
}
return defaultOptions.pointerMoveTolerance;
};
/*\
* interact.maxInteractions
[ method ]
**
* Returns or sets the maximum number of concurrent interactions allowed.
* By default only 1 interaction is allowed at a time (for backwards
* compatibility). To allow multiple interactions on the same Interactables
* and elements, you need to enable it in the draggable, resizable and
* gesturable `'max'` and `'maxPerElement'` options.
**
- newValue (number) #optional Any number. newValue <= 0 means no interactions.
\*/
interact.maxInteractions = function (newValue) {
if (isNumber(newValue)) {
maxInteractions = newValue;
return this;
}
return maxInteractions;
};
function endAllInteractions (event) {
for (var i = 0; i < interactions.length; i++) {
interactions[i].pointerEnd(event, event);
}
}
function listenToDocument (doc) {
if (contains(documents, doc)) { return; }
var win = doc.defaultView || doc.parentWindow;
// add delegate event listener
for (var eventType in delegatedEvents) {
events.add(doc, eventType, delegateListener);
events.add(doc, eventType, delegateUseCapture, true);
}
if (PointerEvent) {
if (PointerEvent === win.MSPointerEvent) {
pEventTypes = {
up: 'MSPointerUp', down: 'MSPointerDown', over: 'mouseover',
out: 'mouseout', move: 'MSPointerMove', cancel: 'MSPointerCancel' };
}
else {
pEventTypes = {
up: 'pointerup', down: 'pointerdown', over: 'pointerover',
out: 'pointerout', move: 'pointermove', cancel: 'pointercancel' };
}
events.add(doc, pEventTypes.down , listeners.selectorDown );
events.add(doc, pEventTypes.move , listeners.pointerMove );
events.add(doc, pEventTypes.over , listeners.pointerOver );
events.add(doc, pEventTypes.out , listeners.pointerOut );
events.add(doc, pEventTypes.up , listeners.pointerUp );
events.add(doc, pEventTypes.cancel, listeners.pointerCancel);
// autoscroll
events.add(doc, pEventTypes.move, autoScroll.edgeMove);
}
else {
events.add(doc, 'mousedown', listeners.selectorDown);
events.add(doc, 'mousemove', listeners.pointerMove );
events.add(doc, 'mouseup' , listeners.pointerUp );
events.add(doc, 'mouseover', listeners.pointerOver );
events.add(doc, 'mouseout' , listeners.pointerOut );
events.add(doc, 'touchstart' , listeners.selectorDown );
events.add(doc, 'touchmove' , listeners.pointerMove );
events.add(doc, 'touchend' , listeners.pointerUp );
events.add(doc, 'touchcancel', listeners.pointerCancel);
// autoscroll
events.add(doc, 'mousemove', autoScroll.edgeMove);
events.add(doc, 'touchmove', autoScroll.edgeMove);
}
events.add(win, 'blur', endAllInteractions);
try {
if (win.frameElement) {
var parentDoc = win.frameElement.ownerDocument,
parentWindow = parentDoc.defaultView;
events.add(parentDoc , 'mouseup' , listeners.pointerEnd);
events.add(parentDoc , 'touchend' , listeners.pointerEnd);
events.add(parentDoc , 'touchcancel' , listeners.pointerEnd);
events.add(parentDoc , 'pointerup' , listeners.pointerEnd);
events.add(parentDoc , 'MSPointerUp' , listeners.pointerEnd);
events.add(parentWindow, 'blur' , endAllInteractions );
}
}
catch (error) {
interact.windowParentError = error;
}
// For IE's lack of Event#preventDefault
if (events.useAttachEvent) {
events.add(doc, 'selectstart', function (event) {
var interaction = interactions[0];
if (interaction.currentAction()) {
interaction.checkAndPreventDefault(event);
}
});
}
documents.push(doc);
}
listenToDocument(document);
function indexOf (array, target) {
for (var i = 0, len = array.length; i < len; i++) {
if (array[i] === target) {
return i;
}
}
return -1;
}
function contains (array, target) {
return indexOf(array, target) !== -1;
}
function matchesSelector (element, selector, nodeList) {
if (ie8MatchesSelector) {
return ie8MatchesSelector(element, selector, nodeList);
}
return element[prefixedMatchesSelector](selector);
}
// For IE8's lack of an Element#matchesSelector
// taken from http://tanalin.com/en/blog/2012/12/matches-selector-ie8/ and modified
if (!(prefixedMatchesSelector in Element.prototype) || !isFunction(Element.prototype[prefixedMatchesSelector])) {
ie8MatchesSelector = function (element, selector, elems) {
elems = elems || element.parentNode.querySelectorAll(selector);
for (var i = 0, len = elems.length; i < len; i++) {
if (elems[i] === element) {
return true;
}
}
return false;
};
}
// requestAnimationFrame polyfill
(function() {
var lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
reqFrame = window[vendors[x]+'RequestAnimationFrame'];
cancelFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!reqFrame) {
reqFrame = function(callback) {
var currTime = new Date().getTime(),
timeToCall = Math.max(0, 16 - (currTime - lastTime)),
id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!cancelFrame) {
cancelFrame = function(id) {
clearTimeout(id);
};
}
}());
/* global exports: true, module, define */
// http://documentcloud.github.io/underscore/docs/underscore.html#section-11
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = interact;
}
exports.interact = interact;
}
// AMD
else if (typeof define === 'function' && define.amd) {
define('interact', function() {
return interact;
});
}
else {
window.interact = interact;
}
} ());
| emilkje/interact.js | interact.js | JavaScript | mit | 210,270 |
var base64url = require('urlsafe-base64')
, After = require('json-list-response').After
, inherits = require('util').inherits
module.exports = DateAfter
function DateAfter(value, options) {
After.call(this, value, options)
this.skip = 0
this.value = 0
if (value) {
value = base64url.decode(value)
if (value.length === 9) {
this.value = value.readDoubleBE(0)
this.skip = value.readUInt8(8)
}
}
}
inherits(DateAfter, After)
DateAfter.prototype.add = function (row) {
var value = row[this.key]
if (!value) return
if (+this.value === +value) {
this.skip++
} else {
this.skip = 0
this.value = value
}
}
DateAfter.prototype.toString = function () {
if (!this.value) return ''
var buf = new Buffer(9)
buf.writeDoubleBE(+this.value || 0, 0)
buf.writeUInt8(this.skip, 8)
return base64url.encode(buf)
}
DateAfter.prototype.mongoSorting = function (list, sorting) {
var obj = {}
obj[sorting.key] = {}
obj[sorting.key][sorting.descending ? '$lte' : '$gte'] = new Date(this.value)
list.selector.$and.push(obj)
list.cursor.skip(this.skip + 1)
}
| tellnes/mongo-list | lib/after/date.js | JavaScript | mit | 1,122 |
export goCommand from './goCommand'
export goReducer from './goReducer'
export parseBestmove from './parseBestmove'
export parseId from './parseId'
export parseInfo from './parseInfo'
export parseOption from './parseOption'
export initReducer from './initReducer'
| ebemunk/node-uci | src/parseUtil/index.js | JavaScript | mit | 264 |
exports.translate = function(tag) {
return this.import("riot").compile(tag);
};
| lixiaoyan/jspm-plugin-riot | riot.js | JavaScript | mit | 82 |
en.resources.define("audio",{
name: "Engine",
src: "./audio/ship_engine.ogg",
}, function(content, callback){
var sound = client.audio.createSound();
sound.load(content.src, function(sound){
content.sound = sound;
callback(content.type, content);
});
}, function(content){
return content.sound;
}); | thehink/GLWars | client/assets_types/audio.js | JavaScript | mit | 319 |
var express = require("express");
var Pusher = require("pusher");
var bodyParser = require("body-parser");
var env = require("node-env-file");
var app = express();
app.use(bodyParser.urlencoded());
try {
env(__dirname + "/.env");
} catch (_error) {
error = _error;
console.log(error);
}
var pusher = new Pusher({
appId: process.env.PUSHER_APP_ID,
key: process.env.PUSHER_APP_KEY,
secret: process.env.PUSHER_APP_SECRET
});
app.use('/', express["static"]('dist'));
app.post("/pusher/auth", function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var auth = pusher.authenticate(socketId, channel);
res.send(auth);
});
var port = process.env.PORT || 5000;
app.listen(port);
| adambutler/geo-pusher | server.js | JavaScript | mit | 735 |
var app = angular.module("ethics-app");
// User create controller
app.controller("userCreateController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $authenticationService, $userService, $universityService, $instituteService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [description]
* @param {[type]} former_status [description]
* @return {[type]} [description]
*/
$scope.getGroupName = function(former_status){
if(former_status){
return $filter('translate')('FORMER_INSTITUTES');
} else {
return $filter('translate')('INSTITUTES');
}
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.createUserForm.$invalid) {
// Update UI
$scope.createUserForm.email_address.$pristine = false;
$scope.createUserForm.title.$pristine = false;
$scope.createUserForm.first_name.$pristine = false;
$scope.createUserForm.last_name.$pristine = false;
$scope.createUserForm.institute_id.$pristine = false;
$scope.createUserForm.blocked.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('CREATING_NEW_USER') };
// Create new user
$userService.create($scope.new_user)
.then(function onSuccess(response) {
var user = response.data;
// Redirect
$scope.redirect("/users/" + user.user_id);
})
.catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [description]
* @param {[type]} related_data [description]
* @return {[type]} [description]
*/
$scope.load = function(related_data){
// Check which kind of related data needs to be requested
switch (related_data) {
case 'universities': {
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_UNIVERSITIES') };
// Load universities
$universityService.list({
orderby: 'name.asc',
limit: null,
offset: null
})
.then(function onSuccess(response) {
$scope.universities = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
break;
}
case 'institutes': {
if($scope.university_id){
if($scope.university_id !== null){
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_INSTITUTES') };
// Load related institutes
$instituteService.listByUniversity($scope.university_id, {
orderby: 'name.asc',
limit: null,
offset: null,
former: false
})
.then(function onSuccess(response) {
$scope.institutes = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
} else {
// Reset institutes
$scope.institutes = [];
$scope.new_user.institute_id = null;
}
break;
}
}
};
/*************************************************
INIT
*************************************************/
$scope.new_user = $userService.init();
$scope.authenticated_member = $authenticationService.get();
// Load universities
$scope.load('universities');
// Set default value by member
$scope.university_id = $scope.authenticated_member.university_id;
// Load related institutes
$scope.load('institutes');
// Set default value by member
$scope.new_user.institute_id = $scope.authenticated_member.institute_id;
});
| sitcomlab/Ethics-app | public/member-client/js/controllers/user/createController.js | JavaScript | mit | 5,089 |
#!/usr/bin/env node
var child_process = require('child_process');
var argv = require('yargs')
.boolean(['readability', 'open'])
.argv;
var pdfdify = require('../lib');
var srcUrl = argv._[0];
console.log("Convertering: '"+srcUrl+"'");
pdfdify.convert({
title:argv.title|| srcUrl,
readability:argv.readability,
srcUrl:srcUrl
},function (err, pdfFile) {
if (err) {
throw err;
}
console.log("Created: '"+pdfFile+"'");
if(argv.open) {
child_process.exec('open "'+pdfFile+'"');
}
}); | darvin/prince-bookmarklet | bin/pdfdify.js | JavaScript | mit | 507 |
/**
* Sizzle Engine Support v2.2.0
* http://rightjs.org/plugins/sizzle
*
* Copyright (C) 2009-2011 Nikolay Nemshilov
*/
/**
* sizzle initialization script
*
* Copyright (C) 2010-2011 Nikolay Nemshilov
*/
RightJS.Sizzle = {
version: '2.2.0'
};
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
var Sizzle = function(selector, context, results, seed) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, extra, prune = true, contextXML = Sizzle.isXML(context),
soFar = selector, ret, cur, pop, i;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec("");
m = chunker.exec(soFar);
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray(set);
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function(results){
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort(sortOrder);
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[i-1] ) {
results.splice(i--, 1);
}
}
}
}
return results;
};
Sizzle.matches = function(expr, set){
return Sizzle(expr, null, null, set);
};
Sizzle.find = function(expr, context, isXML){
var set;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice(1,1);
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && Sizzle.isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var filter = Expr.filter[ type ], found, item, left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part){
var isPartStr = typeof part === "string",
elem, i = 0, l = checkSet.length;
if ( isPartStr && !/\W/.test(part) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck, nodeCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
}
},
find: {
ID: function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function(match, context){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
return match[1].toLowerCase();
},
CHILD: function(match){
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return (/h\d/i).test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function(elem){
return (/input|select|textarea|button/i).test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 === i;
},
eq: function(elem, i, match){
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || Sizzle.getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case 'last':
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function(array, results) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch(e){
makeArray = function(array, results) {
var ret = results || [], i = 0;
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
var ap = [], bp = [], aup = a.parentNode, bup = b.parentNode,
cur = aup, al, bl;
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// If the nodes are siblings (or identical) we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
Sizzle.getText = function( elems ) {
var ret = "", elem;
for ( var i = 0; elems[i]; i++ ) {
elem = elems[i];
// Get the text from text nodes and CDATA nodes
if ( elem.nodeType === 3 || elem.nodeType === 4 ) {
ret += elem.nodeValue;
// Traverse everything else, except comment nodes
} else if ( elem.nodeType !== 8 ) {
ret += Sizzle.getText( elem.childNodes );
}
}
return ret;
};
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime();
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function(match, context, isXML){
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
}
};
Expr.filter.ID = function(elem, match){
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
root = form = null; // release memory in IE
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function(match, context){
var results = context.getElementsByTagName(match[1]);
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function(elem){
return elem.getAttribute("href", 2);
};
}
div = null; // release memory in IE
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle, div = document.createElement("div");
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function(query, context, extra, seed){
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && context.nodeType === 9 && !Sizzle.isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
div = null; // release memory in IE
})();
}
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function(match, context, isXML) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
div = null; // release memory in IE
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem.sizcache = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
while ( elem ) {
if ( elem.sizcache === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem.sizcache = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
Sizzle.contains = document.compareDocumentPosition ? function(a, b){
return !!(a.compareDocumentPosition(b) & 16);
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
Sizzle.isXML = function(elem){
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function(selector, context){
var tmpSet = [], later = "", match,
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
window.Sizzle = Sizzle;
})();
RightJS([RightJS.Document, RightJS.Element]).each('include', {
first: function(rule) {
return this.find(rule)[0];
},
find: function(rule) {
return RightJS(Sizzle(rule, this._)).map(RightJS.$);
}
});
| MadRabbit/right-rails | vendor/assets/javascripts/right/sizzle-src.js | JavaScript | mit | 30,339 |
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import getIn from '@mzvonar/getin';
import isEvent from './../utils/isEvent';
import getPath from './../utils/getPath';
import deepEqual from 'react-fast-compare';
function deleteChildren(object, children) {
let deleted = {};
for(let i = 0, length = children.length; i < length; i += 1) {
const key = children[i];
if(Object.prototype.hasOwnProperty.call(object, key)) {
deleted[key] = object[key];
delete object[key];
}
}
return deleted;
}
function cleanComponentProps(value, props) {
const componentProps = Object.assign({}, props);
const input = componentProps.input;
// const value = componentProps.value;
deleteChildren(componentProps, [
'component',
'_mrf',
'input',
'value',
'validate',
'formSubmitted',
'readOnly',
'disabled'
]);
const inputProps = {};
if(componentProps.type === 'radio') {
inputProps.checked = value === componentProps.value;
}
else if(componentProps.type === 'checkbox') {
inputProps.checked = !!value;
}
else {
inputProps.value = typeof value !== 'undefined' ? value : /*(!props.input.dirty ? props.initialValue : '') ||*/ '';
}
inputProps.id = props.id;
inputProps.readOnly = props.readOnly;
inputProps.disabled = props.disabled;
inputProps.autoComplete = props.autoComplete;
inputProps.maxLength = props.maxLength;
componentProps.input = inputProps;
return componentProps;
}
function getValue(event) {
if(isEvent(event)) {
return event.target.value;
}
else {
return event;
}
}
function generateErrorMessages(errors, errorMessages) {
const messages = [];
if(errors && errors.length > 0 && errorMessages) {
for(let i = 0, length = errors.length; i < length; i += 1) {
if(errorMessages[errors[i]]) {
messages.push(errorMessages[errors[i]]);
}
}
}
return messages;
}
const ignoreForUpdate = [
'_mrf'
];
class ConnectedInput extends React.Component {
static get propTypes() {
return {
component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired,
name: PropTypes.string.isRequired
}
}
static get defaultProps() {
return {
component: 'input',
}
}
constructor(props, context) {
super(props, context);
this.state = {
value: props.value
};
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
}
componentDidMount() {
this.props._mrf.registerInput(this.props.name, {
required: this.props.required,
validate: this.props.validate,
value: (this.props.type === 'hidden' && this.props.inputValue) ? this.props.inputValue : undefined
}, this.props.initialValue, this.props.initialErrors);
}
UNSAFE_componentWillReceiveProps(nextProps) {
if(nextProps.value !== this.props.value) {
this.setState({
value: nextProps.value
});
}
if(this.props.type === 'hidden' && nextProps.inputValue !== this.props.inputValue) {
this.props._mrf.inputChange(this.props.name, nextProps.inputValue);
}
}
componentWillUnmount() {
this.props._mrf.removeInput(this.props.name);
}
shouldComponentUpdate(nextProps, nextState) {
const nextPropsKeys = Object.keys(nextProps);
const thisPropsKeys = Object.keys(this.props);
if(nextPropsKeys.length !== thisPropsKeys.length || nextState.value !== this.state.value) {
return true;
}
for(let i = 0, length = nextPropsKeys.length; i < length; i += 1) {
const key = nextPropsKeys[i];
if(!~ignoreForUpdate.indexOf(key) && !deepEqual(this.props[key], nextProps[key])) {
return true
}
}
return false;
}
// UNSAFE_componentWillReceiveProps(nextProps) {
// if(this.props.type === 'hidden' && nextProps.value !== this.props.value) {
// this.onChange(nextProps.value);
// }
// }
onChange(e) {
const value = getValue(e);
this.setState({
value: value
});
this.props._mrf.inputChange(this.props.name, value);
if(this.props.onChange) {
this.props.onChange(e);
}
}
onBlur(e) {
this.props._mrf.inputBlur(this.props.name);
if(this.props._mrf.asyncValidate) {
this.props._mrf.asyncValidate(this.props.name, getValue(e), true, false);
}
if(this.props.onBlur) {
this.props.onBlur(e);
}
}
render() {
const formSubmitted = this.props.formSubmitted;
let componentProps = cleanComponentProps(this.state.value, this.props);
componentProps.input.onChange = this.onChange;
componentProps.input.onBlur = this.onBlur;
if(typeof this.props.component === 'string') {
return React.createElement(this.props.component, Object.assign(componentProps.input, {
type: this.props.type,
className: this.props.className
}));
}
else {
return React.createElement(this.props.component, Object.assign(componentProps, {
meta: {
pristine: this.props.input.pristine,
dirty: this.props.input.dirty,
touched: formSubmitted === true ? true : this.props.input.touched,
valid: this.props.input.valid,
errors: this.props.input.errors,
errorMessages: generateErrorMessages(this.props.input.errors, this.props.errors),
initialErrors: this.props.input.initialErrors,
asyncValidation: this.props.input.asyncValidation,
asyncErrors: this.props.input.asyncErrors,
formSubmitted: formSubmitted
}
}));
}
}
}
function mapStateToProps(state, ownProps) {
const formState = ownProps._mrf.getFormState(state);
return {
input: getIn(formState, ['inputs', ownProps.name]) || {},
value: getIn(formState, ['values', ...getPath(ownProps.name)]),
initialValue: getIn(formState, ['initialValues', ...getPath(ownProps.name)]),
initialErrors: getIn(formState, ['initialInputErrors', ownProps.name]),
inputValue: ownProps.value,
formSubmitted: getIn(formState, 'submitted', false)
}
}
const mapDispatchToProps = {};
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedInput); | mzvonar/modular-redux-form | src/components/ConnectedInput.js | JavaScript | mit | 6,941 |
import { createTest } from 'tests/test-utils'
import moment from 'moment'
import { EventTypes, Disciplines } from 'client/calendar/events/types'
import _ from 'lodash'
import ncnca2017 from '../2017-ncnca-events'
import usac2017 from '../2017-usac-events'
const events = _.concat(
// does not inlcude older events that do not comply with this requirements
ncnca2017,
usac2017
)
//TODO: make this tests event centric or test-case centric?
const test = createTest('Common events tests')
const parseDate = date => moment(date, 'MMMM DD YYYY')
const getKeyByValue = (obj, value) => Object.keys(obj).filter(key => obj[key] === value)
const getFirstKeyByValue = (obj, value) => getKeyByValue(obj, value)[0]
test('Event must have short id as part of long id and separately as "_shortId" property', t => {
events.forEach((event, i) => {
const eventId = event.id
const shortIdFromId = eventId.match(/[a-zA-Z0-9_$]+$/gm)[0] //matches part after last '-'
t.equal(event._shortId, shortIdFromId,
`#${event.name} "${event._shortId}" => "${shortIdFromId}"`)
})
t.end()
})
test('Event must have unique id across all events', t => {
const eventsById = _.groupBy(events, 'id')
_.map(eventsById, (value, key) => {
if (value.length !== 1) {
t.fail(`There are "${value.length}" events with id: "${key}", id must be unique.`)
}
})
t.end()
})
test('Event must have _shortId that only contains predefined characters', t => {
events.forEach((event, i) => {
const matches = event._shortId.match(/[a-zA-Z0-9_$]+$/gm) //matches part after last '-'
if (matches && matches.length === 1) {
t.pass(`#${event._shortId} for event "${event.name}"`)
} else {
t.fail(`Problematic _shortId: "#${event._shortId}" for event "${event.name}"`)
}
})
t.end()
})
test('Event must have id starting from "evt-"', t => {
events.forEach((event, i) => {
t.ok(event.id.startsWith(('evt-')),
`${event.name}`)
})
t.end()
})
test('Event must have date in a format "MMMM DD YYYY"', t => {
events.forEach((event, i) => {
const date = moment(event.date, 'MMMM DD YYYY')
t.ok(date.isValid(),
`${event.name}`)
})
t.end()
})
test('Event with USAC permit should have permit starting from events year', t => {
events
.filter(x => x.usacPermit)
.forEach((event, i) => {
const date = parseDate(event.date)
t.ok(event.usacPermit.startsWith(date.year() + '-'), `${event.name}`)
})
t.end()
})
test('Event with promoters', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
if (event.promoters) {
t.ok(Array.isArray(event.promoters), 'promoters should be an array')
if (event.promoters.length >= 1) {
t.ok(event.promoters.every(x => x.id),
'each promoter should have an id')
t.ok(event.promoters.every(x => x.id && x.id.startsWith('prm-')),
'each promoter\'s id should start from "prm-"')
}
}
})
t.end()
})
test('Each Event must have at least city and state set in Location', t => {
events.forEach((event, i) => {
t.comment(`${event.name}`)
t.ok(event.location, 'has location set')
t.ok(event.location.city, 'has city set')
t.ok(event.location.state, 'has state set')
})
t.end()
})
test('Each Event must have Type and Discipline set to one of the pre-defined ones', t => {
const allDisciplines = _.values(Disciplines)
const getEventTypesForDiscipline = discipline => {
const disciplineKey = getFirstKeyByValue(Disciplines, discipline)
return _.values(EventTypes[disciplineKey])
}
events.forEach((event, i) => {
t.comment(`${event.id}`)
t.ok(allDisciplines.includes(event.discipline),
'should have discipline equal to one of the pre-defined ones')
t.ok(getEventTypesForDiscipline(event.discipline).includes(event.type),
'should have type set to one that corresponds to event\'s discipline'
+ `, current one is set to: "${event.type}" which is not part of "${event.discipline}" discipline`)
})
t.end()
})
test('Event that is moved, when have "movedToEventId" should point to existing event', t => {
const eventsById = _.keyBy(events, 'id')
events
.filter(x => x.movedToEventId)
.forEach((event, i) => {
t.comment(`${event.name}`)
const movedToEvent = eventsById[event.movedToEventId]
t.ok(movedToEvent, 'moved to event id should point to existing event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(event.movedToEventId !== event.id, 'moved to event id should point to a different event')
t.comment(`Provided evnet id: ${event.movedToEventId}`)
t.ok(parseDate(movedToEvent.date) > parseDate(event.date),
'moved to event should be later than the event it is moved from')
})
t.end()
})
| Restuta/rcn.io | src/client/temp/data/tests/common-tests.js | JavaScript | mit | 4,852 |
/**
* Global Variable Configuration
* (sails.config.globals)
*
* Configure which global variables which will be exposed
* automatically by Sails.
*
* For more information on configuration, check out:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.globals.html
*/
module.exports.globals = {
/****************************************************************************
* *
* Expose the lodash installed in Sails core as a global variable. If this *
* is disabled, like any other node module you can always run npm install *
* lodash --save, then var _ = require('lodash') at the top of any file. *
* *
****************************************************************************/
// _: true,
/****************************************************************************
* *
* Expose the async installed in Sails core as a global variable. If this is *
* disabled, like any other node module you can always run npm install async *
* --save, then var async = require('async') at the top of any file. *
* *
****************************************************************************/
// async: true,
/****************************************************************************
* *
* Expose the sails instance representing your app. If this is disabled, you *
* can still get access via req._sails. *
* *
****************************************************************************/
// sails: true,
/****************************************************************************
* *
* Expose each of your app's services as global variables (using their *
* "globalId"). E.g. a service defined in api/models/NaturalLanguage.js *
* would have a globalId of NaturalLanguage by default. If this is disabled, *
* you can still access your services via sails.services.* *
* *
****************************************************************************/
// services: true,
/****************************************************************************
* *
* Expose each of your app's models as global variables (using their *
* "globalId"). E.g. a model defined in api/models/User.js would have a *
* globalId of User by default. If this is disabled, you can still access *
* your models via sails.models.*. *
* *
****************************************************************************/
// models: true
};
| dcamachoj/rauxa-code | config/globals.js | JavaScript | mit | 3,304 |
this.NesDb = this.NesDb || {};
NesDb[ '9F3DE783494F7FF30679A17B0C5B912834121095' ] = {
"$": {
"name": "Nekketsu Kouha Kunio-kun",
"altname": "熱血硬派くにおくん",
"class": "Licensed",
"catalog": "TJC-KN",
"publisher": "Technos",
"developer": "Technos",
"region": "Japan",
"players": "2",
"date": "1987-04-17"
},
"cartridge": [
{
"$": {
"system": "Famicom",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095",
"dump": "ok",
"dumper": "bootgod",
"datedumped": "2007-06-24"
},
"board": [
{
"$": {
"type": "HVC-UNROM",
"pcb": "HVC-UNROM-02",
"mapper": "2"
},
"prg": [
{
"$": {
"name": "TJC-KN-0 PRG",
"size": "128k",
"crc": "A7D3635E",
"sha1": "9F3DE783494F7FF30679A17B0C5B912834121095"
}
}
],
"vram": [
{
"$": {
"size": "8k"
}
}
],
"chip": [
{
"$": {
"type": "74xx161"
}
},
{
"$": {
"type": "74xx32"
}
}
],
"pad": [
{
"$": {
"h": "1",
"v": "0"
}
}
]
}
]
}
]
};
| peteward44/WebNES | project/js/db/9F3DE783494F7FF30679A17B0C5B912834121095.js | JavaScript | mit | 1,227 |
/**
* Interaction for the tags module
*
* @author Tijs Verkoyen <[email protected]>
*/
jsBackend.tags =
{
// init, something like a constructor
init: function()
{
$dataGridTag = $('.jsDataGrid td.tag');
if($dataGridTag.length > 0) $dataGridTag.inlineTextEdit({ params: { fork: { action: 'edit' } }, tooltip: jsBackend.locale.msg('ClickToEdit') });
}
};
$(jsBackend.tags.init);
| jlglorences/jorge_prueba | src/Backend/Modules/Tags/Js/Tags.js | JavaScript | mit | 392 |
/* global WebFont */
(function () {
'use strict';
function FontLoaderFactory () {
return {
setFonts : function () {
WebFont.load({
custom: {
families: [ 'FontAwesome','Ubuntu','Oxygen','Open Sans' ],
urls: [ '/fonts/base.css']
}
});
}
};
}
angular.module('app.core.fontloader', [])
.factory('FontLoader',FontLoaderFactory);
})();
| dlfinis/master-sigma | assets/angular/components/core/fontloader/fontloader.mdl.js | JavaScript | mit | 428 |
module.exports = handler
var debug = require('../debug').server
var fs = require('fs')
function handler (err, req, res, next) {
debug('Error page because of ' + err.message)
var ldp = req.app.locals.ldp
// If the user specifies this function
// then, they can customize the error programmatically
if (ldp.errorHandler) {
return ldp.errorHandler(err, req, res, next)
}
// If noErrorPages is set,
// then use built-in express default error handler
if (ldp.noErrorPages) {
return res
.status(err.status)
.send(err.message + '\n' || '')
}
// Check if error page exists
var errorPage = ldp.errorPages + err.status.toString() + '.html'
fs.readFile(errorPage, 'utf8', function (readErr, text) {
if (readErr) {
return res
.status(err.status)
.send(err.message || '')
}
res.status(err.status)
res.header('Content-Type', 'text/html')
res.send(text)
})
}
| nicola/ldnode | lib/handlers/error-pages.js | JavaScript | mit | 941 |
const DateTime = Jymfony.Component.DateTime.DateTime;
const DateTimeZone = Jymfony.Component.DateTime.DateTimeZone;
const TimeSpan = Jymfony.Component.DateTime.TimeSpanInterface;
const { expect } = require('chai');
describe('[DateTime] DateTime', function () {
it('should accept string on construction', () => {
const dt = new DateTime('2017-03-24T00:00:00', 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept unix timestamp on construction', () => {
const dt = new DateTime(1490313600, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
});
it('should accept a js Date object on construction', () => {
const date = new Date(1490313600000);
const dt = new DateTime(date, 'Etc/UTC');
expect(dt).to.be.instanceOf(DateTime);
expect(dt.year).to.be.equal(2017);
expect(dt.month).to.be.equal(3);
expect(dt.day).to.be.equal(24);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('today should set time to midnight', () => {
const dt = DateTime.today;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
it('yesterday should set time to midnight', () => {
const dt = DateTime.yesterday;
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
expect(dt.millisecond).to.be.equal(0);
});
let tests = [
[ '2017-01-01T00:00:00', 'P-1D', '2016-12-31T00:00:00+0000' ],
[ '2016-12-31T00:00:00', 'P+1D', '2017-01-01T00:00:00+0000' ],
[ '2016-11-30T00:00:00', 'P+1D', '2016-12-01T00:00:00+0000' ],
[ '2017-01-01T00:00:00', 'P-1Y', '2016-01-01T00:00:00+0000' ],
[ '2016-02-29T00:00:00', 'P-1Y', '2015-02-28T00:00:00+0000' ],
];
for (const t of tests) {
it('add timespan should work correctly', () => {
const [ date, span, expected ] = t;
let dt = new DateTime(date);
dt = dt.modify(new TimeSpan(span));
expect(dt.toString()).to.be.equal(expected);
});
}
it('createFromFormat should correctly parse a date', () => {
const dt = DateTime.createFromFormat(DateTime.RFC2822, 'Wed, 20 Jun 2018 10:19:32 GMT');
expect(dt.toString()).to.be.equal('2018-06-20T10:19:32+0000');
});
tests = [
[ '2020 mar 29 01:00 Europe/Rome', 3600, 1, 0 ],
[ '2020 mar 29 02:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 03:00 Europe/Rome', 7200, 3, 0 ],
[ '2020 mar 29 04:00 Europe/Rome', 7200, 4, 0 ],
[ '2020 may 04 02:00 Europe/Rome', 7200, 2, 0 ],
];
for (const index of tests.keys()) {
const t = tests[index];
it('should correctly handle timezone transitions #'+index, () => {
const dt = new DateTime(t[0]);
expect(dt.timezone).to.be.instanceOf(DateTimeZone);
expect(dt.timezone.getOffset(dt)).to.be.equal(t[1]);
expect(dt.hour).to.be.equal(t[2]);
expect(dt.minute).to.be.equal(t[3]);
});
}
it('should correctly handle timezone transitions on modify', () => {
let dt = new DateTime('2020 mar 29 01:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(0);
});
it('should correctly handle between rules', () => {
let dt = new DateTime('1866 dec 11 00:00 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
dt = new DateTime('1866 dec 11 23:59:59 Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.toString()).to.be.equal('1866-12-11T23:59:59+0049');
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
dt = new DateTime('1893 Oct 31 23:49:55', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(2996);
expect(dt.day).to.be.equal(31);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(49);
expect(dt.second).to.be.equal(55);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('1916 Jun 3 23:59:59', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(23);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.month).to.be.equal(6);
expect(dt.day).to.be.equal(4);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1H'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('PT1S'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.hour).to.be.equal(2);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(0);
dt = new DateTime('2020 Oct 25 01:59:59', 'Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
dt = dt.modify(new TimeSpan('P1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1603673999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P-1D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
dt = dt.modify(new TimeSpan('P1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1606265999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(11);
expect(dt.year).to.be.equal(2020);
dt = dt.modify(new TimeSpan('P-1M'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
dt = dt.modify(new TimeSpan('P1Y'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1635119999);
expect(dt.hour).to.be.equal(1);
expect(dt.minute).to.be.equal(59);
expect(dt.second).to.be.equal(59);
expect(dt.day).to.be.equal(25);
expect(dt.month).to.be.equal(10);
expect(dt.year).to.be.equal(2021);
dt = dt.modify(new TimeSpan('P7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.timestamp).to.be.equal(1635728399);
dt = dt.modify(new TimeSpan('P-1Y7D'));
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.timestamp).to.be.equal(1603583999);
});
it ('invalid times for timezone', () => {
let dt = new DateTime('1893 Oct 31 23:49:58', 'Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(3600);
expect(dt.year).to.be.equal(1893);
expect(dt.month).to.be.equal(11);
expect(dt.day).to.be.equal(1);
expect(dt.hour).to.be.equal(0);
expect(dt.minute).to.be.equal(0);
expect(dt.second).to.be.equal(2);
dt = new DateTime('2020 mar 29 02:01:00 Europe/Rome');
expect(dt.timezone.name).to.be.equal('Europe/Rome');
expect(dt.timezone.getOffset(dt)).to.be.equal(7200);
expect(dt.hour).to.be.equal(3);
expect(dt.minute).to.be.equal(1);
});
});
| alekitto/jymfony | src/Component/DateTime/test/DateTimeTest.js | JavaScript | mit | 9,292 |
module.exports = function () {
var modules = [];
var creeps = Game.creeps;
var spawn = Game.spawns.Spawn1;
var score = spawn ? spawn.room.survivalInfo.score : 0;
var minions = {
total: 0,
build: 0,
carry: 0,
harvest: 0,
guard: 0,
medic: 0,
runner: 0
};
if (score == 0 || spawn.spawning != null) return; // no action when already spawning
for (var i in creeps) {
var creep = creeps[i];
minions.total++;
minions[creep.memory.module]++;
}
var getTough = function (amount) {
var modules = [];
amount += Math.round(score / 250);
for (var i = 0; i < amount; i++) {
modules.push(TOUGH);
}
return modules;
};
var spawnCreep = function (modules, memory) {
var creep = spawn.createCreep(modules, undefined, memory);
if (typeof creep != 'number') {
console.log('created ' + memory.module, modules);
}
return creep;
};
if (minions.harvest < 2) {
spawnCreep([WORK, WORK, WORK, CARRY, MOVE], {module: 'harvest'});
}
else if (minions.carry < 2) {
spawnCreep([CARRY, MOVE, MOVE], {module: 'carry'});
}
else if (score > 1000 && minions.runner < 1 || score > 2000 && minions.runner < 2) {
spawnCreep([CARRY, MOVE, MOVE, CARRY, MOVE], {module: 'runner'});
}
else if (minions.medic < minions.guard / 2) {
modules = [];
modules.push(HEAL, HEAL, HEAL, HEAL, MOVE);
spawnCreep(modules, {module: 'medic'});
}
else if (minions.harvest > 0 && ((score < 1100 && minions.guard < 6) || (score > 1100 && score < 2100 && minions.guard < 12) || score > 2100)) {
modules = getTough(0);
modules.push(RANGED_ATTACK, RANGED_ATTACK, RANGED_ATTACK, MOVE, MOVE);
spawnCreep(modules, {module: 'guard'});
}
};
| cameroncondry/cbc-screeps | game/clock.js | JavaScript | mit | 1,928 |
/**
* @class A wrapper around WebGL.
* @name GL
* @param {HTMLCanvasElement} element A canvas element.
* @param {function} onload A callback function.
* @param {function} callbacks.onerror A callback function.
* @param {function} callbacks.onprogress A callback function.
* @param {function} callbacks.onloadstart A callback function.
* @param {function} callbacks.onremove A callback function.
* @property {WebGLRenderingContext} ctx
*/
function GL(element, callbacks) {
var ctx,
identifiers = ["webgl", "experimental-webgl"],
i,
l;
for (var i = 0, l = identifiers.length; i < l; ++i) {
try {
ctx = element.getContext(identifiers[i], {antialias: true, alpha: false/*, preserveDrawingBuffer: true*/});
} catch(e) {
}
if (ctx) {
break;
}
}
if (!ctx) {
console.error("[WebGLContext]: Failed to create a WebGLContext");
throw "[WebGLContext]: Failed to create a WebGLContext";
}
var hasVertexTexture = ctx.getParameter(ctx.MAX_VERTEX_TEXTURE_IMAGE_UNITS) > 0;
var hasFloatTexture = ctx.getExtension("OES_texture_float");
var compressedTextures = ctx.getExtension("WEBGL_compressed_texture_s3tc");
if (!hasVertexTexture) {
console.error("[WebGLContext]: No vertex shader texture support");
throw "[WebGLContext]: No vertex shader texture support";
}
if (!hasFloatTexture) {
console.error("[WebGLContext]: No float texture support");
throw "[WebGLContext]: No float texture support";
}
if (!compressedTextures) {
console.warn("[WebGLContext]: No compressed textures support");
}
var refreshViewProjectionMatrix = false;
var projectionMatrix = mat4.create();
var viewMatrix = mat4.create();
var viewProjectionMatrix = mat4.create();
var matrixStack = [];
var textureStore = {};
var textureStoreById = {};
var shaderUnitStore = {};
var shaderStore = {};
var boundShader;
var boundShaderName = "";
var boundTextures = [];
var floatPrecision = "precision mediump float;\n";
var textureHandlers = {};
ctx.viewport(0, 0, element.clientWidth, element.clientHeight);
ctx.depthFunc(ctx.LEQUAL);
ctx.enable(ctx.DEPTH_TEST);
ctx.enable(ctx.CULL_FACE);
function textureOptions(wrapS, wrapT, magFilter, minFilter) {
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_S, wrapS);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_WRAP_T, wrapT);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MAG_FILTER, magFilter);
ctx.texParameteri(ctx.TEXTURE_2D, ctx.TEXTURE_MIN_FILTER, minFilter);
}
/**
* Sets a perspective projection matrix.
*
* @memberof GL
* @instance
* @param {number} fovy
* @param {number} aspect
* @param {number} near
* @param {number} far
*/
function setPerspective(fovy, aspect, near, far) {
mat4.perspective(projectionMatrix, fovy, aspect, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Sets an orthogonal projection matrix.
*
* @memberof GL
* @instance
* @param {number} left
* @param {number} right
* @param {number} bottom
* @param {number} top
* @param {number} near
* @param {number} far
*/
function setOrtho(left, right, bottom, top, near, far) {
mat4.ortho(projectionMatrix, left, right, bottom, top, near, far);
refreshViewProjectionMatrix = true;
}
/**
* Resets the view matrix.
*
* @memberof GL
* @instance
*/
function loadIdentity() {
mat4.identity(viewMatrix);
refreshViewProjectionMatrix = true;
}
/**
* Translates the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Translation.
*/
function translate(v) {
mat4.translate(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Rotates the view matrix.
*
* @memberof GL
* @instance
* @param {number} radians Angle.
* @param {vec3} axis The rotation axis..
*/
function rotate(radians, axis) {
mat4.rotate(viewMatrix, viewMatrix, radians, axis);
refreshViewProjectionMatrix = true;
}
/**
* Scales the view matrix.
*
* @memberof GL
* @instance
* @param {vec3} v Scaling.
*/
function scale(v) {
mat4.scale(viewMatrix, viewMatrix, v);
refreshViewProjectionMatrix = true;
}
/**
* Sets the view matrix to a look-at matrix.
*
* @memberof GL
* @instance
* @param {vec3} eye
* @param {vec3} center
* @param {vec3} up
*/
function lookAt(eye, center, up) {
mat4.lookAt(viewMatrix, eye, center, up);
refreshViewProjectionMatrix = true;
}
/**
* Multiplies the view matrix by another matrix.
*
* @memberof GL
* @instance
* @param {mat4} mat.
*/
function multMat(mat) {
mat4.multiply(viewMatrix, viewMatrix, mat);
refreshViewProjectionMatrix = true;
}
/**
* Pushes the current view matrix in the matrix stack.
*
* @memberof GL
* @instance
*/
function pushMatrix() {
matrixStack.push(mat4.clone(viewMatrix));
refreshViewProjectionMatrix = true;
}
/**
* Pops the matrix stacks and sets the popped matrix to the view matrix.
*
* @memberof GL
* @instance
*/
function popMatrix() {
viewMatrix = matrixStack.pop();
refreshViewProjectionMatrix = true;
}
/**
* Gets the view-projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MVP.
*/
function getViewProjectionMatrix() {
if (refreshViewProjectionMatrix) {
mat4.multiply(viewProjectionMatrix, projectionMatrix, viewMatrix);
refreshViewProjectionMatrix = false;
}
return viewProjectionMatrix;
}
/**
* Gets the projection matrix.
*
* @memberof GL
* @instance
* @returns {mat4} P.
*/
function getProjectionMatrix() {
return projectionMatrix;
}
/**
* Gets the view matrix.
*
* @memberof GL
* @instance
* @returns {mat4} MV.
*/
function getViewMatrix() {
return viewMatrix;
}
function setProjectionMatrix(matrix) {
mat4.copy(projectionMatrix, matrix);
refreshViewProjectionMatrix = true;
}
function setViewMatrix(matrix) {
mat4.copy(viewMatrix, matrix);
refreshViewProjectionMatrix = true;
}
/**
* Creates a new {@link GL.ShaderUnit}, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} source GLSL source.
* @param {number} type Shader unit type.
* @param {string} name Owning shader's name.
* @returns {GL.ShaderUnit} The created shader unit.
*/
function createShaderUnit(source, type, name) {
var hash = String.hashCode(source);
if (!shaderUnitStore[hash]) {
shaderUnitStore[hash] = new ShaderUnit(ctx, source, type, name);
}
return shaderUnitStore[hash];
}
/**
* Creates a new {@link GL.Shader} program, or grabs it from the cache if it was previously created, and returns it.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @param {string} vertexSource Vertex shader GLSL source.
* @param {string} fragmentSource Fragment shader GLSL source.
* @param {array} defines An array of strings that will be added as #define-s to the shader source.
* @returns {GL.Shader?} The created shader, or a previously cached version, or null if it failed to compile and link.
*/
function createShader(name, vertexSource, fragmentSource, defines) {
if (!shaderStore[name]) {
defines = defines || [];
for (var i = 0; i < defines.length; i++) {
defines[i] = "#define " + defines[i];
}
defines = defines.join("\n") + "\n";
var vertexUnit = createShaderUnit(defines + vertexSource, ctx.VERTEX_SHADER, name);
var fragmentUnit = createShaderUnit(floatPrecision + defines + fragmentSource, ctx.FRAGMENT_SHADER, name);
if (vertexUnit.ready && fragmentUnit.ready) {
shaderStore[name] = new Shader(ctx, name, vertexUnit, fragmentUnit);
}
}
if (shaderStore[name] && shaderStore[name].ready) {
return shaderStore[name];
}
}
/**
* Checks if a shader is ready for use.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {boolean} The shader's status.
*/
function shaderStatus(name) {
var shader = shaderStore[name];
return shader && shader.ready;
}
/**
* Enables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function enableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.enableVertexAttribArray(i);
}
}
/**
* Disables the WebGL vertex attribute arrays in the range defined by start-end.
*
* @memberof GL
* @instance
* @param {number} start The first attribute.
* @param {number} end The last attribute.
*/
function disableVertexAttribs(start, end) {
for (var i = start; i < end; i++) {
ctx.disableVertexAttribArray(i);
}
}
/**
* Binds a shader. This automatically handles the vertex attribute arrays. Returns the currently bound shader.
*
* @memberof GL
* @instance
* @param {string} name The name of the shader.
* @returns {GL.Shader} The bound shader.
*/
function bindShader(name) {
var shader = shaderStore[name];
if (shader && (!boundShader || boundShader.id !== shader.id)) {
var oldAttribs = 0;
if (boundShader) {
oldAttribs = boundShader.attribs;
}
var newAttribs = shader.attribs;
ctx.useProgram(shader.id);
if (newAttribs > oldAttribs) {
enableVertexAttribs(oldAttribs, newAttribs);
} else if (newAttribs < oldAttribs) {
disableVertexAttribs(newAttribs, oldAttribs);
}
boundShaderName = name;
boundShader = shader;
}
return boundShader;
}
/**
* Loads a texture, with optional options that will be sent to the texture's constructor,
* If the texture was already loaded previously, it returns it.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
* @param {object} options Options.
*/
function loadTexture(source, fileType, isFromMemory, options) {
if (!textureStore[source]) {
textureStore[source] = new AsyncTexture(source, fileType, options, textureHandlers, ctx, compressedTextures, callbacks, isFromMemory);
textureStoreById[textureStore[source].id] = textureStore[source];
}
return textureStore[source];
}
/**
* Unloads a texture.
*
* @memberof GL
* @instance
* @param {string} source The texture's url.
*/
function removeTexture(source) {
if (textureStore[source]) {
callbacks.onremove(textureStore[source]);
delete textureStore[source];
}
}
function textureLoaded(source) {
var texture = textureStore[source];
return (texture && texture.loaded());
}
/**
* Binds a texture to the specified texture unit.
*
* @memberof GL
* @instance
* @param {(string|null)} object A texture source.
* @param {number} [unit] The texture unit.
*/
function bindTexture(source, unit) {
//console.log(source);
var texture;
unit = unit || 0;
if (typeof source === "string") {
texture = textureStore[source];
} else if (typeof source === "number") {
texture = textureStoreById[source];
}
if (texture && texture.impl && texture.impl.ready) {
// Only bind if actually necessary
if (!boundTextures[unit] || boundTextures[unit].id !== texture.id) {
boundTextures[unit] = texture.impl;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, texture.impl.id);
}
} else {
boundTextures[unit] = null;
ctx.activeTexture(ctx.TEXTURE0 + unit);
ctx.bindTexture(ctx.TEXTURE_2D, null);
}
}
/**
* Creates a new {@link GL.Rect} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} hw Half of the width.
* @param {number} hh Half of the height.
* @param {number} stscale A scale that is applied to the texture coordinates.
* @returns {GL.Rect} The rectangle.
*/
function createRect(x, y, z, hw, hh, stscale) {
return new Rect(ctx, x, y, z, hw, hh, stscale);
}
/**
* Creates a new {@link GL.Cube} and returns it.
*
* @memberof GL
* @instance
* @param {number} x1 Minimum X coordinate.
* @param {number} y1 Minimum Y coordinate.
* @param {number} z1 Minimum Z coordinate.
* @param {number} x2 Maximum X coordinate.
* @param {number} y2 Maximum Y coordinate.
* @param {number} z2 Maximum Z coordinate.
* @returns {GL.Cube} The cube.
*/
function createCube(x1, y1, z1, x2, y2, z2) {
return new Cube(ctx, x1, y1, z1, x2, y2, z2);
}
/**
* Creates a new {@link GL.Sphere} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} latitudeBands Latitude bands.
* @param {number} longitudeBands Longitude bands.
* @param {number} radius The sphere radius.
* @returns {GL.Sphere} The sphere.
*/
function createSphere(x, y, z, latitudeBands, longitudeBands, radius) {
return new Sphere(ctx, x, y, z, latitudeBands, longitudeBands, radius);
}
/**
* Creates a new {@link GL.Cylinder} and returns it.
*
* @memberof GL
* @instance
* @param {number} x X coordinate.
* @param {number} y Y coordinate.
* @param {number} z Z coordinate.
* @param {number} r The cylinder radius.
* @param {number} h The cylinder height.
* @param {number} bands Number of bands..
* @returns {GL.Cylinder} The cylinder.
*/
function createCylinder(x, y, z, r, h, bands) {
return new Cylinder(ctx, x, y, z, r, h, bands);
}
/**
* Registers an external handler for an unsupported texture type.
*
* @memberof GL
* @instance
* @param {string} fileType The file format the handler handles.
* @param {function} textureHandler
*/
function registerTextureHandler(fileType, textureHandler) {
textureHandlers[fileType] = textureHandler;
}
textureHandlers[".png"] = NativeTexture;
textureHandlers[".gif"] = NativeTexture;
textureHandlers[".jpg"] = NativeTexture;
return {
setPerspective: setPerspective,
setOrtho: setOrtho,
loadIdentity: loadIdentity,
translate: translate,
rotate: rotate,
scale: scale,
lookAt: lookAt,
multMat: multMat,
pushMatrix: pushMatrix,
popMatrix: popMatrix,
createShader: createShader,
shaderStatus: shaderStatus,
bindShader: bindShader,
getViewProjectionMatrix: getViewProjectionMatrix,
getProjectionMatrix: getProjectionMatrix,
getViewMatrix: getViewMatrix,
setProjectionMatrix: setProjectionMatrix,
setViewMatrix: setViewMatrix,
loadTexture: loadTexture,
removeTexture: removeTexture,
textureLoaded: textureLoaded,
textureOptions: textureOptions,
bindTexture: bindTexture,
createRect: createRect,
createSphere: createSphere,
createCube: createCube,
createCylinder: createCylinder,
ctx: ctx,
registerTextureHandler: registerTextureHandler
};
}
| emnh/mdx-m3-viewer | src/gl/gl.js | JavaScript | mit | 15,053 |
import hotkeys from "hotkeys-js";
export default class HotkeyHandler {
constructor(hotkeyRegistry) {
this.hotkeyRegistry = hotkeyRegistry;
hotkeys("*", { keyup: true, keydown: false }, event => {
event.preventDefault();
this.hotkeyRegistry.resetLastPressedKeyCodes();
return false;
});
hotkeys("*", { keyup: false, keydown: true }, event => {
event.preventDefault();
const pressed = hotkeys.getPressedKeyCodes();
this.hotkeyRegistry.onKeyPressed(pressed);
return false;
});
}
dispose() {
hotkeys.deleteScope("all");
}
}
| UnderNotic/KeyJitsu | src/game/HotkeyRegistry/index.js | JavaScript | mit | 602 |
$(function(){
BrowserDetect.init();
$('.minifyme').on("navminified", function() {
// $('td.expand,th.expand').toggle();
});
// Activate all popovers (if NOT mobile)
if ( !BrowserDetect.isMobile() ) {
$('[data-toggle="popover"]').popover();
}
});
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
function ensureHeightOfSidebar() {
$('#left-panel').css('height',$('#main').height());
}
BrowserDetect =
// From http://stackoverflow.com/questions/13478303/correct-way-to-use-modernizr-to-detect-ie
{
init: function ()
{
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
isMobile: function ()
{
if (navigator.userAgent.search(/(Android|Touch|iPhone|iPad)/) == -1) {
return false;
} else {
return true;
}
},
searchString: function (data)
{
for (var i=0 ; i < data.length ; i++)
{
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) != -1)
{
return data[i].identity;
}
}
},
searchVersion: function (dataString)
{
var index = dataString.indexOf(this.versionSearchString);
if (index == -1) return;
return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
},
dataBrowser:
[
{ string: navigator.userAgent, subString: "Chrome", identity: "Chrome" },
{ string: navigator.userAgent, subString: "MSIE", identity: "Explorer" },
{ string: navigator.userAgent, subString: "Firefox", identity: "Firefox" },
{ string: navigator.userAgent, subString: "Safari", identity: "Safari" },
{ string: navigator.userAgent, subString: "Opera", identity: "Opera" }
]
}; | empath-io/empath | app/assets/javascripts/main.js | JavaScript | mit | 2,251 |
/*
Author: Gerard Lamusse
Created: 08/2015
Version: 1.0
URL: https://github.com/u12206050/jsonZipper
*/
var jsonZipper = (function(){
var jz = function(_jsonObj, _options) {
var Z = this;
var MAP = [];
var opts = _options && typeof(_options) !== "boolean" ? _options : {};
/* Public Functions */
Z.zip = function() {
if (Z.status === "zipable") {
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
compress(Z.JO[x++]);
}
} else {
compress(Z.JO);
}
Z.status = "zipped";
return {M:MAP,D:Z.JO,O:Z.uzOpts};
} return false;
};
Z.unzip = function() {
if (Z.status === "unzipable") {
if (Z.isArray) {
var x = 0;
var y = Z.JO.length;
while (x < y) {
extract(Z.JO[x++]);
}
} else {
extract(Z.JO);
}
Z.status = "unzipped";
return Z.JO;
} return false;
};
Z.compress = function(obj) {
if (Z.status === "compressing") {
Z.JO.push(obj);
compress(obj);
} else if (Z.status === "ready to load object") {
Z.isArray = true;
Z.uzOpts = {I:[],A:Z.isArray,eC:[],iC:[]};
Z.status = "compressing";
Z.JO = [];
Z.JO.push(obj);
compress(obj);
} else return false;
return {M:MAP,D:Z.JO,O:Z.uzOpts};
};
var prevExtractIndex = false;
var extracted = [];
Z.extract = function(i) {
if (Z.status === "unzipable" || Z.status === "zipped") {
if (extracted.indexOf(i) > -1) {
prev = Z.JO[i];
} else {
if (!prevExtractIndex || prevExtractIndex+1 !== i) {
setPrev(i);
}
extract(Z.JO[i]);
extracted.push(i);
}
prevExtractIndex = i;
}
return Z.JO[i];
};
Z.length = function() {
return JSON.stringify(Z.JO).length + (MAP ? JSON.stringify(MAP).length : 0);
};
Z.options = function(opts,isArray) {
/* []: An array of key names that will be used as identifiers.
WARGING: Should be within every object, but repeating, NO Booleans or Integers allowed.
Hint: Most common values that can be guessed/used from previous objects */
Z.identifiers = opts.identifiers || [];
/* boolean: If _jsonObj is an array or not */
Z.isArray = opts.isArray || isArray;
/* []: An array of key names not to map or zip */
Z.exclude = opts.exclude || [];
/* []: An array of key names which values to include in mapping will need identifiers */
Z.include = opts.include || [];
/* []: An array of key names to be removed from the object */
Z.remove = opts.remove || false;
/* {}: An object containing key(s) to add, with function(s) which return the value */
Z.add = opts.add || false;
}
Z.load = function(_jsonObj, isJZobj) {
Z.startLength = 0;
MAP = [];
try {
var stringIT = JSON.stringify(_jsonObj);
Z.startLength = stringIT.length;
Z.JO = JSON.parse(stringIT);
}
catch (err) {
throw "The json object has recursive references or is too big to load into memory";
}
Z.status = "zipable";
if (isJZobj) {
if (Z.JO.D && Z.JO.O && Z.JO.M) {
MAP = Z.JO.M;
Z.identifiers = Z.JO.O.I || [];
Z.isArray = Z.JO.O.A;
Z.exclude = Z.JO.O.eC || false;
Z.include = Z.JO.O.iC || false;
Z.JO = Z.JO.D;
Z.remove = false;
Z.add = false;
Z.status = "unzipable";
} else
Z.options(isJZobj,_jsonObj.constructor === Array);
}
prev = false;
prevID = false;
};
/* Private Functions */
var getID = function(key, value) {
var mI = MAP.indexOf(key);
if (mI < 0) {
if (value) {
return MAP.push(key) - 1;
}
if (Z.exclude.indexOf(key) > -1) {
Z.uzOpts.eC.push(key);
return key;
} else {
mI = MAP.push(key) - 1;
if (Z.identifiers.indexOf(key) > -1) {
Z.uzOpts.I.push(mI);
}
if (Z.include.indexOf(key) > -1) {
Z.uzOpts.iC.push(mI);
}
}
}
return mI;
};
/* Compress the given object, taking note of the previous object */
var prev = false;
var prevID = false;
var compress = function(J) {
add(J);
var keys = Object.keys(J);
var prevSame = prev ? true : false;
var id = '';
var i=0;
for (xend=Z.identifiers.length; i<xend; i++) {
var ikey = Z.identifiers[i];
J[ikey] = getID(J[ikey],1);
id += J[ikey];
}
if (!prevSame || !prevID || prevID !== id) {
prevSame = false;
prev = J;
prevID = id;
}
i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
var mI = getID(key);
if (prevSame && (MAP[prev[mI]] === J[key] || prev[mI] === J[key]))
delete J[key];
else if (Z.include.indexOf(key) > -1) {
if (Z.identifiers.indexOf(key) > -1)
J[mI] = J[key];
else J[mI] = getID(J[key],1);
delete J[key];
} else if (mI !== key) {
J[mI] = J[key];
delete J[key];
}
}
}
};
/* Extract the given object, taking note of the previous object */
var extract = function(J) {
if (J === prev)
return;
add(J);
var prevSame = Z.isArray ? isSame(prev, J) : false;
var keys = Object.keys(J);
if (prevSame)
extend(prev,J);
else if (Z.identifiers) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var ikey = Z.identifiers[x];
J[ikey] = MAP[J[ikey]];
}
}
var i=0;
for (iend=keys.length; i<iend; i++) {
var key = keys[i]*1;
var value = J[key];
if (Z.remove && Z.remove.indexOf(key) > -1)
delete J[key];
else {
if (Z.exclude.indexOf(key) > -1) {
J[key] = J[key];
if (Z.include.indexOf(key) > -1)
J[key] = MAP[J[key]];
} else {
if (Z.include.indexOf(key) > -1)
J[MAP[key]] = MAP[J[key]];
else
J[MAP[key]] = J[key];
delete J[key];
}
}
}
prev = J;
};
/* Add the additional keys and values to the given object */
var add = function(J) {
if (Z.add) {
for (var key in Z.add) {
if('undefined' !== typeof Z.add[key]){
if (typeof(Z.add[key]) === "function")
J[key] = Z.add[key](J);
else
J[key] = Z.add[key];
}
}
}
};
/* Set the previous full object from the current index, incl. */
var setPrev = function(i) {
if (i > 0) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
if ('undefined' === typeof Z.JO[i][Z.identifiers[x]]) {
setPrev(i-1);
return;
}
}
extract(Z.JO[i]);
} else
extract(Z.JO[0]);
};
/* Checks if identiifiers match */
var isSame = function(obj1, obj2) {
if (Z.identifiers && obj1 && obj2 && obj1 !== obj2) {
var x=0;
for (xend=Z.identifiers.length; x<xend; x++) {
var key = Z.identifiers[x];
var mKey = MAP[Z.identifiers[x]];
if ('undefined' === typeof obj1[mKey] || ('undefined' !== typeof obj2[key] && MAP[obj2[key]] !== obj1[mKey]))
return false;
}
} else return false;
return true;
};
/* Merges an object by reference into the first one, replacing values from the second object into the first if duplicate keys exist */
var merge = function(obj1,obj2) {
for (var key in obj2) {
if('undefined' !== typeof obj2[key]) {
obj1[key] = obj2[key];
}
}
};
/* Adds all keys and values from the base to obj2 for each key that does not exist in obj2 */
var extend = function(base,obj2) {
for (var key in base) {
if('undefined' === typeof obj2[key]) {
obj2[key] = base[key];
}
}
};
Z.setID = opts.setID || false;
Z.options(opts,_jsonObj.constructor === Array)
Z.status = "ready to load object";
/* Check if object is given and if options is object or 'compressed' flag */
if (_jsonObj && typeof(_jsonObj) === "object") {
/* When unzipping an object ensure _options is true and not an object, once loaded, you can set the options */
if (_options && typeof(_options) === "boolean") {
Z.load(_jsonObj,true);
} else {
Z.load(_jsonObj,false);
}
}
};
return jz;
})(); | mboulette/incendie | javascript/jsonZipper.js | JavaScript | mit | 8,405 |
// (The MIT License)
//
// Copyright Michał Czapracki, [email protected]
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/**
* @fileoverview
* @author Michał Czapracki
*
* An extended config example
*
* Try invoking this file like:
* node simple --config=./myvars
* or
* node examples/simple --config=./examples/myvars --no-all-fixes-global --all-fixes-heap --quiet=
*/
var path = require('path');
var flatconfig = require('flatconfig'),
args = flatconfig.parseArgs(process.argv.slice(2));
if (!args['config']) {
console.log('Usage: ' + process.argv.slice(0, 2).join(' ')
+ ' --config=path/to/config');
process.exit(1);
}
var cfgpath = args['config'][0];
delete args['config'];
var config = flatconfig.load(__dirname + '/cfg.js',
path.resolve(process.cwd(), cfgpath),
args),
flat = flatconfig.flatten(config);
if (!config.quiet) {
console.log('The configuration resolved to: ');
for (var k in flat) {
console.log(' ', k, '=', JSON.stringify(flat[k]));
}
console.log('');
console.log('The resulting JSON is: ');
}
console.log(JSON.stringify(config));
| MichalCz/node-flat-config | examples/advanced/test.js | JavaScript | mit | 2,206 |
'use strict';
(function() {
// ProductAppliers Controller Spec
describe('ProductAppliersController', function() {
// Initialize global variables
var ProductAppliersController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the ProductAppliers controller.
ProductAppliersController = $controller('ProductAppliersController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one productApplier object fetched from XHR', inject(function(ProductAppliers) {
// Create sample productApplier using the ProductAppliers service
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productAppliers array that includes the new productApplier
var sampleProductAppliers = [sampleProductApplier];
// Set GET response
$httpBackend.expectGET('productAppliers').respond(sampleProductAppliers);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.productAppliers).toEqualData(sampleProductAppliers);
}));
it('$scope.findOne() should create an array with one productApplier object fetched from XHR using a productApplierId URL parameter', inject(function(ProductAppliers) {
// Define a sample productApplier object
var sampleProductApplier = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Set the URL parameter
$stateParams.productApplierId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/productAppliers\/([0-9a-fA-F]{24})$/).respond(sampleProductApplier);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.productApplier).toEqualData(sampleProductApplier);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(ProductAppliers) {
// Create a sample productApplier object
var sampleProductApplierPostData = new ProductAppliers({
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Create a sample productApplier response
var sampleProductApplierResponse = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN rocks!'
});
// Fixture mock form input values
scope.title = 'An ProductApplier about MEAN';
scope.content = 'MEAN rocks!';
// Set POST response
$httpBackend.expectPOST('productAppliers', sampleProductApplierPostData).respond(sampleProductApplierResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.title).toEqual('');
expect(scope.content).toEqual('');
// Test URL redirection after the productApplier was created
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierResponse._id);
}));
it('$scope.update() should update a valid productApplier', inject(function(ProductAppliers) {
// Define a sample productApplier put data
var sampleProductApplierPutData = new ProductAppliers({
_id: '525cf20451979dea2c000001',
title: 'An ProductApplier about MEAN',
content: 'MEAN Rocks!'
});
// Mock productApplier in scope
scope.productApplier = sampleProductApplierPutData;
// Set PUT response
$httpBackend.expectPUT(/productAppliers\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/productAppliers/' + sampleProductApplierPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid productApplierId and remove the productApplier from the scope', inject(function(ProductAppliers) {
// Create new productApplier object
var sampleProductApplier = new ProductAppliers({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new productAppliers array and include the productApplier
scope.productAppliers = [sampleProductApplier];
// Set expected DELETE response
$httpBackend.expectDELETE(/productAppliers\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleProductApplier);
$httpBackend.flush();
// Test array after successful delete
expect(scope.productAppliers.length).toBe(0);
}));
});
}());
| lawliet467/backend-mean | public/modules/productAppliers/tests/products.client.controller.test.js | JavaScript | mit | 5,896 |
/* global expect */
describe('outputFormat', () => {
describe('when given a format', () => {
it('decides the output that will be used for serializing errors', () => {
expect(
function () {
const clonedExpect = expect.clone().outputFormat('html');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
htmlMessage:
'<div style="font-family: monospace; white-space: nowrap">' +
'<div><span style="color: red; font-weight: bold">expected</span> <span style="color: #0086b3">42</span> <span style="color: red; font-weight: bold">to equal</span> <span style="color: #0086b3">24</span></div>' +
'</div>',
}
);
expect(
function () {
const clonedExpect = expect.clone().outputFormat('ansi');
clonedExpect(42, 'to equal', 24);
},
'to throw',
{
message:
'\n\x1b[31m\x1b[1mexpected\x1b[22m\x1b[39m 42 \x1b[31m\x1b[1mto equal\x1b[22m\x1b[39m 24\n',
}
);
});
});
});
| unexpectedjs/unexpected | test/api/outputFormat.spec.js | JavaScript | mit | 1,096 |
'use strict';
const fs = require('fs');
const remote = require('electron').remote;
const mainProcess = remote.require('./main');
module.exports = {
template: `
<v-list dense class="pt-0">
<v-list-tile to="recent-projects" :router="true">
<v-list-tile-action>
<v-icon>list</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="recent-projects">Recent projects</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="existingProject">
<v-list-tile-action>
<v-icon>folder_open</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-project">Add existing project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="create-project" :router="true">
<v-list-tile-action>
<v-icon>create_new_folder</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="create-project">Create new project</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile @click="globalProject" v-if="globalComposerFileExists">
<v-list-tile-action>
<v-icon>public</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="global-composer">Global composer</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
<v-list-tile to="settings" :router="true">
<v-list-tile-action>
<v-icon>settings</v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title id="open-settings">Settings</v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</v-list>
`,
computed: {
globalComposerFileExists() {
return fs.existsSync(remote.app.getPath('home') + '/.composer');
}
},
methods: {
existingProject: () => {
mainProcess.openDirectory();
},
globalProject: () => {
mainProcess.openProject(remote.app.getPath('home') + '/.composer');
},
}
}
| mglaman/conductor | src/components/MainNavigation.js | JavaScript | mit | 1,947 |
var sys = require("sys"),
my_http = require("http"),
path = require("path"),
url = require("url"),
filesys = require("fs");
my_http.createServer(function(request,response){
var my_path = url.parse(request.url).pathname;
var full_path = path.join(process.cwd(),my_path);
path.exists(full_path,function(exists){
if(!exists){
response.writeHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
}
else{
filesys.readFile(full_path, "binary", function(err, file) {
if(err) {
response.writeHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
}
else{
response.writeHeader(200);
response.write(file, "binary");
response.end();
}
});
}
});
}).listen(8080);
sys.puts("Server Running on 8080");
| mark-hahn/node-ide | test.js | JavaScript | mit | 914 |
var path = require('path');
var fs = require('fs');
var Writer = require('broccoli-writer');
var Handlebars = require('handlebars');
var walkSync = require('walk-sync');
var RSVP = require('rsvp');
var helpers = require('broccoli-kitchen-sink-helpers');
var mkdirp = require('mkdirp');
var Promise = RSVP.Promise;
var EXTENSIONS_REGEX = new RegExp('.(hbs|handlebars)');
var HandlebarsWriter = function (inputTree, files, options) {
if (!(this instanceof HandlebarsWriter)) {
return new HandlebarsWriter(inputTree, files, options);
}
this.inputTree = inputTree;
this.files = files;
this.options = options || {};
this.context = this.options.context || {};
this.destFile = this.options.destFile || function (filename) {
return filename.replace(/(hbs|handlebars)$/, 'html');
};
this.handlebars = this.options.handlebars || Handlebars;
this.loadPartials();
this.loadHelpers();
};
HandlebarsWriter.prototype = Object.create(Writer.prototype);
HandlebarsWriter.prototype.constructor = HandlebarsWriter;
HandlebarsWriter.prototype.loadHelpers = function () {
var helpers = this.options.helpers;
if (!helpers) return;
if ('function' === typeof helpers) helpers = helpers();
if ('object' !== typeof helpers) {
throw Error('options.helpers must be an object or a function that returns an object');
}
this.handlebars.registerHelper(helpers);
};
HandlebarsWriter.prototype.loadPartials = function () {
var partials = this.options.partials;
var partialsPath;
var partialFiles;
if (!partials) return;
if ('string' !== typeof partials) {
throw Error('options.partials must be a string');
}
partialsPath = path.join(process.cwd(), partials);
partialFiles = walkSync(partialsPath).filter(EXTENSIONS_REGEX.test.bind(EXTENSIONS_REGEX));
partialFiles.forEach(function (file) {
var key = file.replace(partialsPath, '').replace(EXTENSIONS_REGEX, '');
var filePath = path.join(partialsPath, file);
this.handlebars.registerPartial(key, fs.readFileSync(filePath).toString());
}, this);
};
HandlebarsWriter.prototype.write = function (readTree, destDir) {
var self = this;
this.loadPartials();
this.loadHelpers();
return readTree(this.inputTree).then(function (sourceDir) {
var targetFiles = helpers.multiGlob(self.files, {cwd: sourceDir});
return RSVP.all(targetFiles.map(function (targetFile) {
function write (output) {
var destFilepath = path.join(destDir, self.destFile(targetFile));
mkdirp.sync(path.dirname(destFilepath));
var str = fs.readFileSync(path.join(sourceDir, targetFile)).toString();
var template = self.handlebars.compile(str);
fs.writeFileSync(destFilepath, template(output));
}
var output = ('function' !== typeof self.context) ? self.context : self.context(targetFile);
return Promise.resolve(output).then(write);
}));
});
};
module.exports = HandlebarsWriter; | michaellopez/broccoli-handlebars | index.js | JavaScript | mit | 2,973 |
var _a;
import app from './app';
import toHTML from './vdom-to-html';
import { _createEventTests, _createStateTests } from './apprun-dev-tools-tests';
app['debug'] = true;
window['_apprun-help'] = ['', () => {
Object.keys(window).forEach(cmd => {
if (cmd.startsWith('_apprun-')) {
cmd === '_apprun-help' ?
console.log('AppRun Commands:') :
console.log(`* ${cmd.substring(8)}: ${window[cmd][0]}`);
}
});
}];
function newWin(html) {
const win = window.open('', '_apprun_debug', 'toolbar=0');
win.document.write(`<html>
<title>AppRun Analyzer | ${document.location.href}</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI" }
li { margin-left: 80px; }
</style>
<body>
<div id="main">${html}</div>
</script>
</body>
</html>`);
win.document.close();
}
const get_components = () => {
const o = { components: {} };
app.run('get-components', o);
const { components } = o;
return components;
};
const viewElement = element => app.h("div", null,
element.tagName.toLowerCase(),
element.id ? '#' + element.id : '',
' ',
element.className && element.className.split(' ').map(c => '.' + c).join());
const viewComponents = state => {
const Events = ({ events }) => app.h("ul", null, events && events.filter(event => event.name !== '.').map(event => app.h("li", null, event.name)));
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name),
app.h(Events, { events: component['_actions'] }))));
return app.h("ul", null, state.map(({ element, comps }) => app.h("li", null,
app.h("div", null, viewElement(element)),
app.h(Components, { components: comps }))));
};
const viewEvents = state => {
const Components = ({ components }) => app.h("ul", null, components.map(component => app.h("li", null,
app.h("div", null, component.constructor.name))));
const Events = ({ events, global }) => app.h("ul", null, events && events
.filter(event => event.global === global && event.event !== '.')
.map(({ event, components }) => app.h("li", null,
app.h("div", null, event),
app.h(Components, { components: components }))));
return app.h("div", null,
app.h("div", null, "GLOBAL EVENTS"),
app.h(Events, { events: state, global: true }),
app.h("div", null, "LOCAL EVENTS"),
app.h(Events, { events: state, global: false }));
};
const _events = (print) => {
const global_events = app['_events'];
const events = {};
const cache = get_components();
const add_component = component => component['_actions'].forEach(event => {
events[event.name] = events[event.name] || [];
events[event.name].push(component);
});
if (cache instanceof Map) {
for (let [key, comps] of cache) {
comps.forEach(add_component);
}
}
else {
Object.keys(cache).forEach(el => cache[el].forEach(add_component));
}
const data = [];
Object.keys(events).forEach(event => {
data.push({ event, components: events[event], global: global_events[event] ? true : false });
});
data.sort(((a, b) => a.event > b.event ? 1 : -1)).map(e => e.event);
if (print) {
const vdom = viewEvents(data);
newWin(toHTML(vdom));
}
else {
console.log('=== GLOBAL EVENTS ===');
data.filter(event => event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
console.log('=== LOCAL EVENTS ===');
data.filter(event => !event.global && event.event !== '.')
.forEach(({ event, components }) => console.log({ event }, components));
}
};
const _components = (print) => {
const components = get_components();
const data = [];
if (components instanceof Map) {
for (let [key, comps] of components) {
const element = typeof key === 'string' ? document.getElementById(key) : key;
data.push({ element, comps });
}
}
else {
Object.keys(components).forEach(el => {
const element = typeof el === 'string' ? document.getElementById(el) : el;
data.push({ element, comps: components[el] });
});
}
if (print) {
const vdom = viewComponents(data);
newWin(toHTML(vdom));
}
else {
data.forEach(({ element, comps }) => console.log(element, comps));
}
};
let debugging = Number((_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.getItem('__apprun_debugging__')) || 0;
app.on('debug', p => {
if (debugging & 1 && p.event)
console.log(p);
if (debugging & 2 && p.vdom)
console.log(p);
});
window['_apprun-components'] = ['components [print]', (p) => {
_components(p === 'print');
}];
window['_apprun-events'] = ['events [print]', (p) => {
_events(p === 'print');
}];
window['_apprun-log'] = ['log [event|view] on|off', (a1, a2) => {
var _a;
if (a1 === 'on') {
debugging = 3;
}
else if (a1 === 'off') {
debugging = 0;
}
else if (a1 === 'event') {
if (a2 === 'on') {
debugging |= 1;
}
else if (a2 === 'off') {
debugging &= ~1;
}
}
else if (a1 === 'view') {
if (a2 === 'on') {
debugging |= 2;
}
else if (a2 === 'off') {
debugging &= ~2;
}
}
console.log(`* log ${a1} ${a2 || ''}`);
(_a = window === null || window === void 0 ? void 0 : window.localStorage) === null || _a === void 0 ? void 0 : _a.setItem('__apprun_debugging__', `${debugging}`);
}];
window['_apprun-create-event-tests'] = ['create-event-tests',
() => _createEventTests()
];
window['_apprun-create-state-tests'] = ['create-state-tests <start|stop>',
(p) => _createStateTests(p)
];
window['_apprun'] = (strings) => {
const [cmd, ...p] = strings[0].split(' ').filter(c => !!c);
const command = window[`_apprun-${cmd}`];
if (command)
command[1](...p);
else
window['_apprun-help'][1]();
};
console.info('AppRun DevTools 2.27: type "_apprun `help`" to list all available commands.');
const reduxExt = window['__REDUX_DEVTOOLS_EXTENSION__'];
if (reduxExt) {
let devTools_running = false;
const devTools = window['__REDUX_DEVTOOLS_EXTENSION__'].connect();
if (devTools) {
const hash = location.hash || '#';
devTools.send(hash, '');
const buf = [{ component: null, state: '' }];
console.info('Connected to the Redux DevTools');
devTools.subscribe((message) => {
if (message.type === 'START')
devTools_running = true;
else if (message.type === 'STOP')
devTools_running = false;
else if (message.type === 'DISPATCH') {
// console.log('From Redux DevTools: ', message);
const idx = message.payload.index;
if (idx === 0) {
app.run(hash);
}
else {
const { component, state } = buf[idx];
component === null || component === void 0 ? void 0 : component.setState(state);
}
}
});
const send = (component, action, state) => {
if (state == null)
return;
buf.push({ component, state });
devTools.send(action, state);
};
app.on('debug', p => {
if (devTools_running && p.event) {
const state = p.newState;
const type = p.event;
const payload = p.p;
const action = { type, payload };
const component = p.component;
if (state instanceof Promise) {
state.then(s => send(component, action, s));
}
else {
send(component, action, state);
}
}
});
}
}
//# sourceMappingURL=apprun-dev-tools.js.map | yysun/apprun | esm/apprun-dev-tools.js | JavaScript | mit | 8,440 |
import './index.css';
import React, {Component} from 'react';
import { postToggleDevice } from '../ajax';
export default class SocketDevice extends Component {
constructor() {
super();
this.state = {clicked: false, device: {}};
this.clicked = this.clicked.bind(this);
}
componentWillMount() {
var device = this.props.device;
if (device.enabled) {
this.setState({clicked: true});
}
this.setState({device: device});
}
clicked() {
var nextState = !this.state.clicked;
var id = this.state.device.id;
if (this.props.valueControl) {
this.props.valueControl(id, 'enabled', nextState);
this.setState({clicked: nextState});
} else {
this.toggle(id);
}
}
toggle() {
var id = this.state.device.id;
postToggleDevice(id, function (device) {
this.setState({clicked: device.enabled, device: device});
}.bind(this));
}
render() {
var name = this.state.device.name;
var classes = 'icon-tinted' + (this.state.clicked ? ' active' : '');
return (<div className="m-t-1">
<h4>
<a className={classes} onClick={this.clicked}><i className="fa fa-plug fa-lg"/></a> {name}
</h4>
</div>);
}
}
SocketDevice.propTypes = {
device: React.PropTypes.object.isRequired,
valueControl: React.PropTypes.func.isRequired
};
| aspic/wemo-control | src/SocketDevice/index.js | JavaScript | mit | 1,491 |
var config = {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
ceo = {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg"
},
cto = {
parent: ceo,
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg"
},
cbo = {
parent: ceo,
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg"
},
cdo = {
parent: ceo,
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg"
},
cio = {
parent: cto,
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
ciso = {
parent: cto,
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: {val: "[email protected]", href: "mailto:[email protected]"}
},
image: "../headshots/9.jpg"
},
cio2 = {
parent: cdo,
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
},
ciso2 = {
parent: cbo,
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
ciso3 = {
parent: cbo,
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
ciso4 = {
parent: cbo,
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
chart_config = [
config,
ceo,
cto,
cbo,
cdo,
cio,
ciso,
cio2,
ciso2,
ciso3,
ciso4
];
// Another approach, same result
// JSON approach
/*
var chart_config = {
chart: {
container: "#basic-example",
connectors: {
type: 'step'
},
node: {
HTMLclass: 'nodeExample1'
}
},
nodeStructure: {
text: {
name: "Mark Hill",
title: "Chief executive officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/2.jpg",
children: [
{
text:{
name: "Joe Linux",
title: "Chief Technology Officer",
},
stackChildren: true,
image: "../headshots/1.jpg",
children: [
{
text:{
name: "Ron Blomquist",
title: "Chief Information Security Officer"
},
image: "../headshots/8.jpg"
},
{
text:{
name: "Michael Rubin",
title: "Chief Innovation Officer",
contact: "[email protected]"
},
image: "../headshots/9.jpg"
}
]
},
{
stackChildren: true,
text:{
name: "Linda May",
title: "Chief Business Officer",
},
image: "../headshots/5.jpg",
children: [
{
text:{
name: "Alice Lopez",
title: "Chief Communications Officer"
},
image: "../headshots/7.jpg"
},
{
text:{
name: "Mary Johnson",
title: "Chief Brand Officer"
},
image: "../headshots/4.jpg"
},
{
text:{
name: "Kirk Douglas",
title: "Chief Business Development Officer"
},
image: "../headshots/11.jpg"
}
]
},
{
text:{
name: "John Green",
title: "Chief accounting officer",
contact: "Tel: 01 213 123 134",
},
image: "../headshots/6.jpg",
children: [
{
text:{
name: "Erica Reel",
title: "Chief Customer Officer"
},
link: {
href: "http://www.google.com"
},
image: "../headshots/10.jpg"
}
]
}
]
}
};
*/ | fperucic/treant-js | examples/basic-example/basic-example.js | JavaScript | mit | 6,298 |
require( ['build/index'] );
| pixelsnow/arkanoid-uni | scripts/index.js | JavaScript | mit | 28 |
/*
* Copyright (c) 2016 airbug Inc. http://airbug.com
*
* bugcore may be freely distributed under the MIT license.
*/
//-------------------------------------------------------------------------------
// Annotations
//-------------------------------------------------------------------------------
//@TestFile
//@Require('Class')
//@Require('Map')
//@Require('ObservableMap')
//@Require('PutChange')
//@Require('TypeUtil')
//@Require('bugdouble.BugDouble')
//@Require('bugmeta.BugMeta')
//@Require('bugunit.TestTag')
//-------------------------------------------------------------------------------
// Context
//-------------------------------------------------------------------------------
require('bugpack').context("*", function(bugpack) {
//-------------------------------------------------------------------------------
// BugPack
//-------------------------------------------------------------------------------
var Class = bugpack.require('Class');
var Map = bugpack.require('Map');
var ObservableMap = bugpack.require('ObservableMap');
var PutChange = bugpack.require('PutChange');
var TypeUtil = bugpack.require('TypeUtil');
var BugDouble = bugpack.require('bugdouble.BugDouble');
var BugMeta = bugpack.require('bugmeta.BugMeta');
var TestTag = bugpack.require('bugunit.TestTag');
//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------
var bugmeta = BugMeta.context();
var spyOnObject = BugDouble.spyOnObject;
var test = TestTag.test;
//-------------------------------------------------------------------------------
// Declare Tests
//-------------------------------------------------------------------------------
/**
* This tests...
* 1) Instantiating a ObservableMap class with no parameters
*/
var observableMapInstantiationTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testObservableMap = new ObservableMap();
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed defaults to a Map")
}
};
bugmeta.tag(observableMapInstantiationTest).with(
test().name("ObservableMap - instantiation test")
);
/**
* This tests...
* 1) Instantiating a ObservableMap class with parameters
*/
var observableMapInstantiationWithParametersTest = {
// Setup Test
//-------------------------------------------------------------------------------
setup: function() {
this.testKey = "testKey";
this.testValue = "testValue";
this.testMap = new Map();
this.testMap.put(this.testKey, this.testValue);
this.testObservableMap = new ObservableMap(this.testMap);
},
// Run Test
//-------------------------------------------------------------------------------
test: function(test) {
test.assertTrue(Class.doesExtend(this.testObservableMap.getObserved(), Map),
"Assert ObservableMap.observed was set to a Map");
test.assertEqual(this.testObservableMap.getObserved().get(this.testKey), this.testValue,
"Assert ObservableMap.observed was set correctly");
}
};
bugmeta.tag(observableMapInstantiationWithParametersTest).with(
test().name("ObservableMap - instantiation with parameters test")
);
});
| airbug/bugcore | libraries/bugcore/js/test/observe/data/ObservableMapTests.js | JavaScript | mit | 3,975 |
const app = require('../server');
const readline = require('readline');
const {
User,
Role,
RoleMapping,
} = app.models;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
Role.findOne({ where: { name: 'admin' } })
.then((role) => {
if (!role) {
console.log('No admin role found. Create fixtures first.');
process.exit();
}
const admin = {};
const fields = ['username', 'password'];
let field = fields.shift();
console.log(`${field}: `);
rl.on('line', (line) => {
admin[field] = line;
field = fields.shift();
if (!field) {
process.stdout.write('Creating the user... ');
User.create(admin)
.then(user =>
RoleMapping.create({
UserId: user.id,
RoleId: role.id,
})
)
.then(() => {
console.log('Done!\n');
process.exit(0);
})
.catch((err) => {
console.error(err);
process.exit(1);
});
return;
}
process.stdout.write(`${field}: \n`);
});
});
| oamaok/kinko | server/scripts/create-admin.js | JavaScript | mit | 1,056 |
var dbm = require('db-migrate');
var type = dbm.dataType;
exports.up = function(db, callback) {
db.addColumn("troop_type", "production_cost", "int", callback);
};
exports.down = function(db, callback) {
};
| Codes-With-Eagles-SWE2014/Server | web_server/migrations/20141116202453-troopcost.js | JavaScript | mit | 210 |
'use strict';
// you have to require the utils module and call adapter function
const utils = require('@iobroker/adapter-core'); // Get common adapter utils
const adapterName = require('./package.json').name.split('.').pop();
// include node-ssdp and node-upnp-subscription
const {Client, Server} = require('node-ssdp');
const Subscription = require('./lib/upnp-subscription');
const parseString = require('xml2js').parseString;
const DOMParser = require('xmldom').DOMParser;
const request = require('request');
const nodeSchedule = require('node-schedule');
let adapter;
let client = new Client();
const tasks = [];
let taskRunning = false;
const actions = {}; // scheduled actions
const crons = {};
const checked = {}; // store checked objects for polling
let discoveredDevices = [];
let sidPromise; // Read SIDs promise
let globalCb; // callback for last processTasks
function startCronJob(cron) {
console.log('Start cron JOB: ' + cron);
crons[cron] = nodeSchedule.scheduleJob(cron, () => pollActions(cron));
}
function stopCronJob(cron) {
if (crons[cron]) {
crons[cron].cancel();
delete crons[cron];
}
}
function pollActions(cron) {
Object.keys(actions).forEach(id =>
actions[id].cron === cron && addTask({name: 'sendCommand', id}));
processTasks();
}
function reschedule(changedId, deletedCron) {
const schedules = {};
if (changedId) {
if (!deletedCron) {
Object.keys(actions).forEach(_id => {
if (_id !== changedId) {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
}
});
if (!schedules[actions[changedId].cron]) {
// start cron job
startCronJob(actions[changedId].cron);
}
} else {
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
if (schedules[deletedCron] === 1 && crons[deletedCron]) {
// stop cron job
stopCronJob(deletedCron);
}
}
} else {
// first
Object.keys(actions).forEach(_id => {
const cron = actions[_id].cron;
schedules[cron] = schedules[cron] || 0;
schedules[cron]++;
});
Object.keys(schedules).forEach(cron => startCronJob(cron));
}
}
function startAdapter(options) {
options = options || {};
Object.assign(options, {name: adapterName, strictObjectChecks: false});
adapter = new utils.Adapter(options);
// is called when adapter shuts down - callback has to be called under any circumstances!
adapter.on('unload', callback => {
try {
server.stop(); // advertise shutting down and stop listening
adapter.log.info('cleaned everything up...');
clearAliveAndSIDStates(callback);
} catch (e) {
callback();
}
});
adapter.on('objectChange', (id, obj) => {
if (obj && obj.common && obj.common.custom &&
obj.common.custom[adapter.namespace] &&
obj.common.custom[adapter.namespace].enabled &&
obj.native && obj.native.request
) {
if (!actions[id]) {
adapter.log.info(`enabled polling of ${id} with schedule ${obj.common.custom[adapter.namespace].schedule}`);
setImmediate(() => reschedule(id));
}
actions[id] = {cron: obj.common.custom[adapter.namespace].schedule};
} else if (actions[id]) {
adapter.log.debug('Removed polling for ' + id);
setImmediate((id, cron) => reschedule(id, cron), id, actions[id].cron);
delete actions[id];
}
});
// is called if a subscribed state changes
adapter.on('stateChange', (id, state) => {
if (!state || state.ack) {
return;
}
// Subscribe to an service when its state Alive is true
if (id.match(/\.request$/)) {
// Control a device when a related object changes its value
if (checked[id] !== undefined) {
checked[id] && sendCommand(id);
} else {
adapter.getObject(id, (err, obj) => {
if (obj && obj.native && obj.native.request) {
checked[id] = true;
sendCommand(id);
} else {
checked[id] = false;
}
});
}
}
});
// is called when databases are connected and adapter received configuration.
// start here!
adapter.on('ready', () => {
main();
});
// Some message was sent to adapter instance over message box. Used by email, pushover, text2speech, ...
adapter.on('message', obj => {
if (typeof obj === 'object' && obj.message) {
if (obj.command === 'send') {
// e.g. send email or pushover or whatever
adapter.log.info('send command');
// Send response in callback if required
obj.callback && adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
}
}
});
return adapter;
}
function getValueFromArray(value) {
if (typeof value === 'object' && value instanceof Array && value[0] !== undefined) {
return value[0] !== null ? value[0].toString() : '';
} else {
return value !== null && value !== undefined ? value.toString() : '';
}
}
let foundIPs = []; // Array for the caught broadcast answers
function sendBroadcast() {
// adapter.log.debug('Send Broadcast');
// Sends a Broadcast and catch the URL with xml device description file
client.on('response', (headers, _statusCode, _rinfo) => {
let answer = (headers || {}).LOCATION;
if (answer && foundIPs.indexOf(answer) === -1) {
foundIPs.push(answer);
if (answer !== answer.match(/.*dummy.xml/g)) {
setTimeout(() => firstDevLookup(answer), 1000);
}
}
});
client.search('ssdp:all');
}
// Read the xml device description file of each upnp device the first time
function firstDevLookup(strLocation, cb) {
const originalStrLocation = strLocation;
adapter.log.debug('firstDevLookup for ' + strLocation);
request(strLocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
adapter.log.debug('Positive answer for request of the XML file for ' + strLocation);
try {
const xmlStringSerialized = new DOMParser().parseFromString((body || '').toString(), 'text/xml');
parseString(xmlStringSerialized, {explicitArray: true, mergeAttrs: true}, (err, result) => {
let path;
let xmlDeviceType;
let xmlTypeOfDevice;
let xmlUDN;
let xmlManufacturer;
adapter.log.debug('Parsing the XML file for ' + strLocation);
if (err) {
adapter.log.warn('Error: ' + err);
} else {
adapter.log.debug('Creating objects for ' + strLocation);
let i;
if (!result || !result.root || !result.root.device) {
adapter.log.debug('Error by parsing of ' + strLocation + ': Cannot find deviceType');
return;
}
path = result.root.device[0];
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceType);
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug('TypeOfDevice ' + xmlTypeOfDevice);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the port
let strPort = strLocation.replace(/\bhttp:\/\/.*\d:/ig, '');
strPort = strPort.replace(/\/.*/g, '');
if (strPort.match(/http:/ig)) {
strPort = '';
} else {
strPort = parseInt(strPort, 10);
}
// Looking for the IP of a device
strLocation = strLocation.replace(/http:\/\/|"/g, '').replace(/:\d*\/.*/ig, '');
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.UDN).replace(/"/g, '').replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${strLocation}`);
xmlUDN = '';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug('Can not read manufacturer of ' + strLocation);
xmlManufacturer = '';
}
// Extract the path to the device icon that is delivered by the device
// let i_icons = 0;
let xmlIconURL;
let xmlFN;
let xmlManufacturerURL;
let xmlModelNumber;
let xmlModelDescription;
let xmlModelName;
let xmlModelURL;
try {
// i_icons = path.iconList[0].icon.length;
xmlIconURL = getValueFromArray(path.iconList[0].icon[0].url).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not find a icon for ${strLocation}`);
xmlIconURL = '';
}
//Looking for the friendlyName of a device
try {
xmlFN = nameFilter(getValueFromArray(path.friendlyName));
} catch (err) {
adapter.log.debug(`Can not read friendlyName of ${strLocation}`);
xmlFN = 'Unknown';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.manufacturerURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${strLocation}`);
xmlManufacturerURL = '';
}
// Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.modelNumber).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${strLocation}`);
xmlModelNumber = '';
}
// Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.modelDescription).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${strLocation}`);
xmlModelDescription = '';
}
// Looking for the modelName
try {
xmlModelName = getValueFromArray(path.modelName).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelName of ${strLocation}`);
xmlModelName = '';
}
// Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.modelURL).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${strLocation}`);
xmlModelURL = '';
}
// START - Creating the root object of a device
adapter.log.debug(`Creating root element for device: ${xmlFN}`);
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlFN,
extIcon: `http://${strLocation}:${strPort}${xmlIconURL}`
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType,
manufacturer: xmlManufacturer,
manufacturerURL: xmlManufacturerURL,
modelNumber: xmlModelNumber,
modelDescription: xmlModelDescription,
modelName: xmlModelName,
modelURL: xmlModelURL,
name: xmlFN,
}
}
});
let pathRoot = result.root.device[0];
let objectName = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectName, strLocation, strPort, pathRoot);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
// START - Creating SubDevices list for a device
let lenSubDevices = 0;
let xmlfriendlyName;
if (path.deviceList && path.deviceList[0].device) {
// Counting SubDevices
lenSubDevices = path.deviceList[0].device.length;
if (lenSubDevices) {
// adapter.log.debug('Found more than one SubDevice');
for (i = lenSubDevices - 1; i >= 0; i--) {
// Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType.replace(/:\d/, '');
xmlTypeOfDevice = xmlTypeOfDevice.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceType);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].modelName);
} catch (err) {
adapter.log.debug(`Can not read modelName of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = path.deviceList[0].device[i].modelURL;
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
let pathSub = result.root.device[0].deviceList[0].device[i];
let objectNameSub = `${xmlFN}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, xmlTypeOfDevice, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
let TypeOfSubDevice = xmlTypeOfDevice;
//START - Creating SubDevices list for a sub-device
if (path.deviceList[0].device[i].deviceList && path.deviceList[0].device[i].deviceList[0].device) {
//Counting SubDevices
let i_SubSubDevices = path.deviceList[0].device[i].deviceList[0].device.length;
let i2;
if (i_SubSubDevices) {
for (i2 = i_SubSubDevices - 1; i2 >= 0; i--) {
adapter.log.debug(`Device ${i2} ` + path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType).replace(/"/g, '');
xmlTypeOfDevice = xmlDeviceType
.replace(/:\d/, '')
.replace(/.*:/, '');
xmlTypeOfDevice = nameFilter(xmlTypeOfDevice);
adapter.log.debug(`TypeOfDevice ${xmlTypeOfDevice}`);
} catch (err) {
adapter.log.debug(`Can not read deviceType of ${strLocation}`);
xmlDeviceType = '';
}
//Looking for the friendlyName of the SubDevice
try {
xmlfriendlyName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].friendlyName);
xmlFN = nameFilter(xmlfriendlyName);
} catch (err) {
adapter.log.debug(`Can not read friendlyName of SubDevice from ${xmlFN}`);
xmlfriendlyName = 'Unknown';
}
//Looking for the manufacturer of a device
try {
xmlManufacturer = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturer).replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read manufacturer of ${xmlfriendlyName}`);
xmlManufacturer = '';
}
//Looking for the manufacturerURL
try {
xmlManufacturerURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].manufacturerURL);
} catch (err) {
adapter.log.debug(`Can not read manufacturerURL of ${xmlfriendlyName}`);
xmlManufacturerURL = '';
}
//Looking for the modelNumber
try {
xmlModelNumber = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelNumber);
} catch (err) {
adapter.log.debug(`Can not read modelNumber of ${xmlfriendlyName}`);
xmlModelNumber = '';
}
//Looking for the modelDescription
try {
xmlModelDescription = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelDescription);
} catch (err) {
adapter.log.debug(`Can not read modelDescription of ${xmlfriendlyName}`);
xmlModelDescription = '';
}
//Looking for deviceType of device
try {
xmlDeviceType = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].deviceType);
} catch (err) {
adapter.log.debug('Can not read DeviceType of ' + xmlfriendlyName);
xmlDeviceType = '';
}
//Looking for the modelName
try {
xmlModelName = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelName);
} catch (err) {
adapter.log.debug(`Can not read DeviceType of ${xmlfriendlyName}`);
xmlModelName = '';
}
//Looking for the modelURL
try {
xmlModelURL = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].modelURL);
} catch (err) {
adapter.log.debug(`Can not read modelURL of ${xmlfriendlyName}`);
xmlModelURL = '';
}
//Looking for UDN of a device
try {
xmlUDN = getValueFromArray(path.deviceList[0].device[i].deviceList[0].device[i2].UDN)
.replace(/"/g, '')
.replace(/uuid:/g, '');
} catch (err) {
adapter.log.debug(`Can not read UDN of ${xmlfriendlyName}`);
xmlUDN = '';
}
//The SubDevice object
addTask({
name: 'setObjectNotExists',
id: `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`,
obj: {
type: 'device',
common: {
name: xmlfriendlyName
},
native: {
ip: strLocation,
port: strPort,
uuid: xmlUDN,
deviceType: xmlDeviceType.toString(),
manufacturer: xmlManufacturer.toString(),
manufacturerURL: xmlManufacturerURL.toString(),
modelNumber: xmlModelNumber.toString(),
modelDescription: xmlModelDescription.toString(),
modelName: xmlModelName.toString(),
modelURL: xmlModelURL.toString(),
name: xmlfriendlyName
}
}
}); //END SubDevice Object
pathSub = result.root.device[0].deviceList[0].device[i].deviceList[0].device[i2];
objectNameSub = `${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}`;
createServiceList(result, xmlFN, `${TypeOfSubDevice}.${xmlTypeOfDevice}`, objectNameSub, strLocation, strPort, pathSub);
const aliveID = `${adapter.namespace}.${xmlFN}.${TypeOfSubDevice}.${xmlTypeOfDevice}.Alive`;
addTask({
name: 'setObjectNotExists',
id: aliveID,
obj: {
type: 'state',
common: {
name: 'Alive',
type: 'boolean',
role: 'indicator.reachable',
def: false,
read: true,
write: false
},
native: {}
}
});
// Add to Alives list
getIDs()
.then(result => result.alives.indexOf(aliveID) === -1 && result.alives.push(aliveID));
}
}
}
}
}
}
}
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
});
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${strLocation}: ${error}`);
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
processTasks();
cb && cb();
}
} else {
// remove device from processed list
const pos = discoveredDevices.indexOf(originalStrLocation);
pos !== -1 && discoveredDevices.splice(pos, 1);
cb && cb();
}
});
}
function createServiceList(result, xmlFN, xmlTypeOfDevice, object, strLocation, strPort, path) {
if (!path.serviceList) {
adapter.log.debug('No service list found at ' + JSON.stringify(path));
return;
}
if (!path.serviceList[0] || !path.serviceList[0].service || !path.serviceList[0].service.length) {
adapter.log.debug('No services found in the service list');
return;
}
let i;
let xmlService;
let xmlServiceType;
let xmlServiceID;
let xmlControlURL;
let xmlEventSubURL;
let xmlSCPDURL;
let i_services = path.serviceList[0].service.length;
//Counting services
//adapter.log.debug('Number of services: ' + i_services);
for (i = i_services - 1; i >= 0; i--) {
try {
xmlService = getValueFromArray(path.serviceList[0].service[i].serviceType)
.replace(/urn:.*:service:/g, '')
.replace(/:\d/g, '')
.replace(/"/g, '');
} catch (err) {
adapter.log.debug(`Can not read service of ${xmlFN}`);
xmlService = 'Unknown';
}
try {
xmlServiceType = getValueFromArray(path.serviceList[0].service[i].serviceType);
} catch (err) {
adapter.log.debug(`Can not read serviceType of ${xmlService}`);
xmlServiceType = '';
}
try {
xmlServiceID = getValueFromArray(path.serviceList[0].service[i].serviceId);
} catch (err) {
adapter.log.debug(`Can not read serviceID of ${xmlService}`);
xmlServiceID = '';
}
try {
xmlControlURL = getValueFromArray(path.serviceList[0].service[i].controlURL);
} catch (err) {
adapter.log.debug(`Can not read controlURL of ${xmlService}`);
xmlControlURL = '';
}
try {
xmlEventSubURL = getValueFromArray(path.serviceList[0].service[i].eventSubURL);
} catch (err) {
adapter.log.debug(`Can not read eventSubURL of ${xmlService}`);
xmlEventSubURL = '';
}
try {
xmlSCPDURL = getValueFromArray(path.serviceList[0].service[i].SCPDURL);
if (!xmlSCPDURL.match(/^\//)) {
xmlSCPDURL = `/${xmlSCPDURL}`;
}
} catch (err) {
adapter.log.debug(`Can not read SCPDURL of ${xmlService}`);
xmlSCPDURL = '';
}
addTask({
name: 'setObjectNotExists',
id: `${object}.${xmlService}`,
obj: {
type: 'channel',
common: {
name: xmlService
},
native: {
serviceType: xmlServiceType,
serviceID: xmlServiceID,
controlURL: xmlControlURL,
eventSubURL: xmlEventSubURL,
SCPDURL: xmlSCPDURL,
name: xmlService
}
}
});
const sid = `${adapter.namespace}.${object}.${xmlService}.sid`;
addTask({
name: 'setObjectNotExists',
id: sid,
obj: {
type: 'state',
common: {
name: 'Subscription ID',
type: 'string',
role: 'state',
def: '',
read: true,
write: true
},
native: {}
}
});
// Add to SID list
getIDs()
.then(result => result.sids.indexOf(sid) === -1 && result.sids.push(sid));
let SCPDlocation = `http://${strLocation}:${strPort}${xmlSCPDURL}`;
let service = `${xmlFN}.${xmlTypeOfDevice}.${xmlService}`;
addTask({name: 'readSCPD', SCPDlocation, service});
}
}
// Read the SCPD File of a upnp device service
function readSCPD(SCPDlocation, service, cb) {
adapter.log.debug('readSCPD for ' + SCPDlocation);
request(SCPDlocation, (error, response, body) => {
if (!error && response.statusCode === 200) {
try {
parseString(body, {explicitArray: true}, (err, result) => {
adapter.log.debug('Parsing the SCPD XML file for ' + SCPDlocation);
if (err) {
adapter.log.warn('Error: ' + err);
cb();
} else if (!result || !result.scpd) {
adapter.log.debug('Error by parsing of ' + SCPDlocation);
cb();
} else {
createServiceStateTable(result, service);
createActionList(result, service);
processTasks();
cb();
}
}); //END function
} catch (error) {
adapter.log.debug(`Cannot parse answer from ${SCPDlocation}: ${error}`);
cb();
}
} else {
cb();
}
});
}
function createServiceStateTable(result, service) {
if (!result.scpd || !result.scpd.serviceStateTable) {
return;
}
let path = result.scpd.serviceStateTable[0] || result.scpd.serviceStateTable;
if (!path.stateVariable || !path.stateVariable.length) {
return;
}
let iStateVarLength = path.stateVariable.length;
let xmlName;
let xmlDataType;
// Counting stateVariable's
// adapter.log.debug('Number of stateVariables: ' + iStateVarLength);
try {
for (let i2 = iStateVarLength - 1; i2 >= 0; i2--) {
let stateVariableAttr;
let strAllowedValues = [];
let strMinimum;
let strMaximum;
let strDefaultValue;
let strStep;
stateVariableAttr = path.stateVariable[i2]['$'].sendEvents;
xmlName = getValueFromArray(path.stateVariable[i2].name);
xmlDataType = getValueFromArray(path.stateVariable[i2].dataType);
try {
let allowed = path.stateVariable[i2].allowedValueList[0].allowedValue;
strAllowedValues = Object.keys(allowed).map(xmlAllowedValue => allowed[xmlAllowedValue]).join(' ');
} catch (err) {
}
try {
strDefaultValue = getValueFromArray(path.stateVariable[i2].defaultValue);
} catch (err) {
}
if (path.stateVariable[i2].allowedValueRange) {
try {
strMinimum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].minimum);
} catch (err) {
}
try {
strMaximum = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].maximum);
} catch (err) {
}
try {
strStep = getValueFromArray(path.stateVariable[i2].allowedValueRange[0].step);
} catch (err) {
}
}
// Handles DataType ui2 as Number
let dataType;
if (xmlDataType.toString() === 'ui2') {
dataType = 'number';
} else {
dataType = xmlDataType.toString();
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
type: dataType,
role: 'state',
read: true,
write: true
},
native: {
name: xmlName,
sendEvents: stateVariableAttr,
allowedValues: strAllowedValues,
defaultValue: strDefaultValue,
minimum: strMinimum,
maximum: strMaximum,
step: strStep,
}
}
});
}//END for
} catch (err) {
}
//END Add serviceList for SubDevice
} //END function
function createActionList(result, service) {
if (!result || !result.scpd || !result.scpd.actionList || !result.scpd.actionList[0]) {
return;
}
let path = result.scpd.actionList[0];
if (!path.action || !path.action.length) {
return;
}
let actionLen = path.action.length;
//Counting action's
//adapter.log.debug('Number of actions: ' + actionLen);
for (let i2 = actionLen - 1; i2 >= 0; i2--) {
let xmlName = getValueFromArray(path.action[i2].name);
addTask({
name: 'setObjectNotExists',
id: `${service}.${xmlName}`,
obj: {
type: 'channel',
common: {
name: xmlName
},
native: {
name: xmlName
}
}
});
try {
createArgumentList(result, service, xmlName, i2, path);
} catch (err) {
adapter.log.debug(`There is no argument for ${xmlName}`);
}
}
}
function createArgumentList(result, service, actionName, action_number, path) {
let iLen = 0;
let action;
let _arguments;
// adapter.log.debug('Reading argumentList for ' + actionName);
action = path.action[action_number].argumentList;
if (action && action[0] && action[0].argument) {
_arguments = action[0].argument;
iLen = _arguments.length;
} else {
return;
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.request`,
obj: {
type: 'state',
common: {
name: 'Initiate poll',
role: 'button',
type: 'boolean',
def: false,
read: false,
write: true
},
native: {
actionName: actionName,
service: service,
request: true
}
}
}); //END adapter.setObject()
// Counting arguments's
for (let i2 = iLen - 1; i2 >= 0; i2--) {
let xmlName = 'Unknown';
let xmlDirection = '';
let xmlRelStateVar = '';
let argument = _arguments[i2];
try {
xmlName = getValueFromArray(argument.name);
} catch (err) {
adapter.log.debug(`Can not read argument "name" of ${actionName}`);
}
try {
xmlDirection = getValueFromArray(argument.direction);
} catch (err) {
adapter.log.debug(`Can not read direction of ${actionName}`);
}
try {
xmlRelStateVar = getValueFromArray(argument.relatedStateVariable);
} catch (err) {
adapter.log.debug(`Can not read relatedStateVariable of ${actionName}`);
}
addTask({
name: 'setObjectNotExists',
id: `${service}.${actionName}.${xmlName}`,
obj: {
type: 'state',
common: {
name: xmlName,
role: 'state.argument.' + xmlDirection,
type: 'string',
def: '',
read: true,
write: true
},
native: {
direction: xmlDirection,
relatedStateVariable: xmlRelStateVar,
argumentNumber: i2 + 1,
name: xmlName,
}
}
}); //END adapter.setObject()
}
} //END function
//END Creating argumentList
let showTimer = null;
function processTasks(cb) {
if (!taskRunning && tasks.length) {
if (cb) {
globalCb = cb; // used by unload
}
taskRunning = true;
setImmediate(_processTasks);
adapter.log.debug('Started processTasks with ' + tasks.length + ' tasks');
showTimer = setInterval(() => adapter.log.debug(`Tasks ${tasks.length}...`), 5000);
} else if (cb) {
cb();
}
}
function addTask(task) {
tasks.push(task);
}
function _processTasks() {
if (!tasks.length) {
taskRunning = false;
adapter.log.debug('All tasks processed');
clearInterval(showTimer);
if (globalCb) {
globalCb();
globalCb = null;
}
} else {
const task = tasks.shift();
if (task.name === 'sendCommand') {
sendCommand(task.id, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'firstDevLookup') {
firstDevLookup(task.location, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'subscribeEvent') {
subscribeEvent(task.deviceID, () => setTimeout(_processTasks, 0));
} else if (task.name === 'setState') {
adapter.setState(task.id, task.state, err => {
if (typeof task.cb === 'function') {
task.cb(() => setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else
if (task.name === 'valChannel') {
valChannel(task.strState, task.serviceID, () => {
writeState(task.serviceID, task.stateName, task.val, () =>
setTimeout(_processTasks, 0));
});
} else
if (task.name === 'readSCPD') {
readSCPD(task.SCPDlocation, task.service, () => setTimeout(_processTasks, 0));
} else
if (task.name === 'setObjectNotExists') {
if(task.obj.common.type){
switch (task.obj.common.type){
case 'bool':
task.obj.common.type = 'boolean';
break;
case 'i1':
case 'i2':
case 'i4':
case 'ui1':
case 'ui2':
case 'ui4':
case 'int':
case 'r4':
case 'r8':
case 'fixed.14.4':
case 'fixed':
case 'float':
task.obj.common.type = 'number';
break;
case 'char string':
case 'date':
case 'dateTime':
case 'dateTime.tz':
case 'time':
case 'time.tz':
case 'bin.base64':
case 'bin.hex':
case 'uri':
case 'uuid':
task.obj.common.type = 'string';
break;
}
if(task.obj.common.name === 'bool'){
task.obj.common.name = 'boolean';
}
}
adapter.setObjectNotExists(task.id, task.obj, () => {
if (task.obj.type === 'state' && task.id.match(/\.sid$/)) {
adapter.getState(task.id, (err, state) => {
if (!state) {
adapter.setState(task.id, false, true, (err, state) =>
setTimeout(_processTasks, 0));
} else {
setTimeout(_processTasks, 0);
}
});
} else {
setTimeout(_processTasks, 0);
}
});
} else {
adapter.log.warn('Unknown task: ' + task.name);
setTimeout(_processTasks, 0);
}
}
}
function startServer() {
//START Server for Alive and ByeBye messages
// let own_uuid = 'uuid:f40c2981-7329-40b7-8b04-27f187aecfb5'; //this string is for filter message's from upnp Adapter
let server = new Server({ssdpIp: '239.255.255.250'});
// helper variables for start adding new devices
// let devices;
// Identification of upnp Adapter/ioBroker as upnp Service and it's capabilities
// at this time there is no implementation of upnp service capabilities, it is only necessary for the server to run
server.addUSN('upnp:rootdevice');
server.addUSN('urn:schemas-upnp-org:device:IoTManagementandControlDevice:1');
server.on('advertise-alive', headers => {
let usn = getValueFromArray(headers['USN'])
.replace(/uuid:/ig, '')
.replace(/::.*/ig, '');
let nt = getValueFromArray(headers['NT']);
let location = getValueFromArray(headers['LOCATION']);
if (!usn.match(/f40c2981-7329-40b7-8b04-27f187aecfb5/)) {
if (discoveredDevices.indexOf(location) === -1) {
discoveredDevices.push(location);
adapter.getDevices((err, devices) => {
let foundUUID = false;
for (let i = 0; i < devices.length; i++) {
if (!devices[i] || !devices[i].native || !devices[i].native.uuid) continue;
const deviceUUID = devices[i].native.uuid;
const deviceUSN = devices[i].native.deviceType;
// Set object Alive for the Service true
if (deviceUUID === usn && deviceUSN === nt) {
let maxAge = getValueFromArray(headers['CACHE-CONTROL'])
.replace(/max-age.=./ig, '')
.replace(/max-age=/ig, '')
.replace(/"/g, '');
addTask({
name: 'setState',
id: `${devices[i]._id}.Alive`,
state: {val: true, ack: true, expire: parseInt(maxAge)}
});
addTask({name: 'subscribeEvent', deviceID: devices[i]._id});
}
if (deviceUUID === usn) {
foundUUID = true;
break;
}
}
if (!foundUUID && adapter.config.enableAutoDiscover) {
adapter.log.debug(`Found new device: ${location}`);
addTask({name: 'firstDevLookup', location});
} else {
const pos = discoveredDevices.indexOf(location);
pos !== -1 && discoveredDevices.splice(pos, 1);
}
processTasks();
});
}
}
});
server.on('advertise-bye', headers => {
let usn = JSON.stringify(headers['USN']);
usn = usn.toString();
usn = usn.replace(/uuid:/g, '');
try {
usn.replace(/::.*/ig, '')
} catch (err) {
}
// let nt = JSON.stringify(headers['NT']);
// let location = JSON.stringify(headers['LOCATION']);
if (!usn.match(/.*f40c2981-7329-40b7-8b04-27f187aecfb5.*/)) {
adapter.getDevices((err, devices) => {
let device;
let deviceID;
let deviceUUID;
let deviceUSN;
for (device in devices) {
if (!devices.hasOwnProperty(device)) continue;
deviceUUID = JSON.stringify(devices[device]['native']['uuid']);
deviceUSN = JSON.stringify(devices[device]['native']['deviceType']);
//Set object Alive for the Service false
if (deviceUUID === usn) {
deviceID = JSON.stringify(devices[device]._id);
deviceID = deviceID.replace(/"/ig, '');
addTask({
name: 'setState',
id: `${deviceID}.Alive`,
state: {val: false, ack: true}
});
}
}
processTasks();
}); //END adapter.getDevices()
}
});
setTimeout(() => server.start(), 15000);
}
// Subscribe to every service that is alive. Triggered by change alive from false/null to true.
async function subscribeEvent(id, cb) {
const service = id.replace(/\.Alive/ig, '');
if (adapter.config.enableAutoSubscription === true) {
adapter.getObject(service, (err, obj) => {
let deviceIP = obj.native.ip;
let devicePort = obj.native.port;
const parts = obj._id.split('.');
parts.pop();
const channelID = parts.join('.');
adapter.getChannelsOf(channelID, async (err, channels) => {
for (let x = channels.length - 1; x >= 0; x--) {
const eventUrl = getValueFromArray(channels[x].native.eventSubURL).replace(/"/g, '');
if(channels[x].native.serviceType) {
try {
const infoSub = new Subscription(deviceIP, devicePort, eventUrl, 1000);
listener(eventUrl, channels[x]._id, infoSub);
} catch (err) {
}
}
}
cb();
}); //END adapter.getChannelsOf()
}); //END adapter.getObjects()
} else {
cb();
}
}
// message handler for subscriptions
function listener(eventUrl, channelID, infoSub) {
let variableTimeout;
let resetTimeoutTimer;
infoSub.on('subscribed', data => {
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('message', data => {
adapter.log.debug('Listener message: ' + JSON.stringify(data));
variableTimeout += 5;
setTimeout(() =>
getIDs()
.then(result => lookupService(data, JSON.parse(JSON.stringify(result.sids))))
,variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
infoSub.on('error', err => {
adapter.log.debug(`Subscription error: ` + JSON.stringify(err));
// subscription.unsubscribe();
});
infoSub.on('resubscribed', data => {
// adapter.log.info('SID: ' + JSON.stringify(sid) + ' ' + eventUrl + ' ' + _channel._id);
variableTimeout += 5;
setTimeout(() => adapter.setState(channelID + '.sid', {val: ((data && data.sid) || '').toString(), ack: true}), variableTimeout);
resetTimeoutTimer && clearTimeout(resetTimeoutTimer);
resetTimeoutTimer = setTimeout(() => {
variableTimeout = 0;
resetTimeoutTimer = null;
}, 100);
});
}
function lookupService(data, SIDs, cb) {
if (!SIDs || !SIDs.length || !data || !data.sid) {
cb && cb();
} else {
const id = SIDs.shift();
adapter.getState(id, (err, state) => {
if (err || !state || typeof state !== 'object') {
adapter.log.error(`Error in lookupService: ${err || 'No object ' + id}`);
setImmediate(lookupService, data, cb);
} else {
setNewState(state, id.replace(/\.sid$/, ''), data, () =>
setImmediate(lookupService, data, cb));
}
});
}
}
function setNewState(state, serviceID, data, cb) {
adapter.log.debug('setNewState: ' + state + ' ' + JSON.stringify(data));
// Extract the value of the state
let valueSID = state.val;
if (valueSID !== null && valueSID !== undefined) {
valueSID = valueSID.toString().toLowerCase();
if (valueSID.indexOf(data.sid.toString().toLowerCase()) !== -1) {
serviceID = serviceID.replace(/\.sid$/, '');
// Select sub element with States
let newStates = data.body['e:propertyset']['e:property'];
if (newStates && newStates.LastChange && newStates.LastChange._) {
newStates = newStates.LastChange._;
adapter.log.info('Number 1: ' + newStates);
} else if (newStates) {
newStates = newStates.LastChange;
adapter.log.info('Number 2: ' + newStates);
} else {
adapter.log.info('Number 3: ' + newStates);
}
let newStates2 = JSON.stringify(newStates) || '';
// TODO: Must be refactored
if (newStates2 === undefined){
adapter.log.info('State: ' + state + ' Service ID: ' + serviceID + ' Data: ' + JSON.stringify(data));
}else if (newStates2.match(/<Event.*/ig)) {
parseString(newStates, (err, result) => {
let states = convertEventObject(result['Event']);
// split every array member into state name and value, then push it to ioBroker state
let stateName;
let val;
if (states) {
for (let x = states.length - 1; x >= 0; x--) {
let strState = states[x].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/"/i, '');
// looking for the value
val = strState.match(/val":"(\w*(:\w*|,\s\w*)*)/ig);
if (val) {
val = val[0];
val = val.replace(/val":"/ig, '');
}
addTask({name: 'valChannel', strState, serviceID, stateName, val});
}
processTasks();
}
cb();
}); //END parseString()
} else if (newStates2.match(/"\$":/ig)) {
let states = convertWM(newStates);
// split every array member into state name and value, then push it to ioBroker state
if (states) {
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
} else {
// Read all other messages and write the states to the related objects
let states = convertInitialObject(newStates);
if (states) {
// split every array member into state name and value, then push it to ioBroker state
let stateName;
for (let z = states.length - 1; z >= 0; z--) {
let strState = states[z].toString();
stateName = strState.match(/"\w*/i);
stateName = stateName ? stateName[0] : strState;
stateName = stateName.replace(/^"|"$/g, '');
addTask({name: 'valChannel', strState, serviceID, stateName, val: valLookup(strState)});
}
processTasks();
}
cb();
}
} else {
cb();
}
} else {
cb();
}
}
// write state
function writeState(sID, sname, val, cb) {
adapter.getObject(`${sID}.A_ARG_TYPE_${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.A_ARG_TYPE_${sname}`, {val: val, ack: true}, err => {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
});
} else {
adapter.getObject(`${sID}.${sname}`, (err, obj) => {
if (obj) {
if(obj.common.type === 'number'){
val = parseInt(val);
}
adapter.setState(`${sID}.${sname}`, {val: val, ack: true}, cb);
} else {
cb();
}
});
}
});
}
// looking for the value of channel
function valChannel(strState, serviceID, cb) {
//looking for the value of channel
let channel = strState.match(/channel":"(\w*(:\w*|,\s\w*)*)/ig);
if (channel) {
channel = channel.toString();
channel = channel.replace(/channel":"/ig, '');
adapter.setState(`${serviceID}.A_ARG_TYPE_Channel`, {val: channel, ack: true}, cb);
} else {
cb()
}
}
// looking for the value
function valLookup(strState) {
let val = strState.match(/\w*":"(\w*\D\w|\w*|,\s\w*|(\w*:)*(\*)*(\/)*(,)*(-)*(\.)*)*/ig);
if (val) {
val = val.toString();
val = val.replace(/"\w*":"/i, '');
val = val.replace(/"/ig, '');
val = val.replace(/\w*:/, '')
}
return val;
}
// Not used now
// function convertEvent(data){
// let change = data.replace(/<\\.*>/ig, '{"');
// change = data.replace(/</ig, '{"');
// change = change.replace(/\s/ig, '""');
// change = change.replace(/=/ig, ':');
// change = change.replace(/\\/ig, '');
// change = change.replace(/>/ig, '}');
// }
//convert the event JSON into an array
function convertEventObject(result) {
const regex = new RegExp(/"\w*":\[{"\$":{("\w*":"(\w*:\w*:\w*|(\w*,\s\w*)*|\w*)"(,"\w*":"\w*")*)}/ig);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array
function convertInitialObject(result) {
const regex = new RegExp(/"\w*":"(\w*|\w*\D\w*|(\w*-)*\w*:\w*|(\w*,\w*)*|\w*:\S*\*)"/g);
return (JSON.stringify(result) || '').match(regex);
}
//convert the initial message JSON into an array for windows media player/server
function convertWM(result) {
const regex = new RegExp(/"\w*":{".":"(\w*"|((http-get:\*:\w*\/((\w*\.)*|(\w*-)*|(\w*\.)*(\w*-)*)\w*:\w*\.\w*=\w*(,)*)*((http-get|rtsp-rtp-udp):\*:\w*\/(\w*(\.|-))*\w*:\*(,)*)*))/g);
return (JSON.stringify(result) || '').match(regex);
}
//END Event listener
// clear Alive and sid's states when Adapter stops
function clearAliveAndSIDStates(cb) {
// Clear sid
getIDs()
.then(result => {
result.sids.forEach(id => {
addTask({name: 'setState', id, state: {val: '', ack: true}});
});
result.alives.forEach(id => {
addTask({name: 'setState', id, state: {val: false, ack: true}});
});
processTasks(cb);
});
}
function getIDs() {
if (sidPromise) {
return sidPromise;
} else {
// Fill array arrSID if it is empty
sidPromise = new Promise(resolve => {
adapter.getStatesOf(`upnp.${adapter.instance}`, (err, _states) => {
const sids = [];
const alives = [];
err && adapter.log.error('Cannot get SIDs: ' + err);
if (_states) {
_states.forEach(obj => {
if (obj._id.match(/\.sid$/)) {
// if the match deliver an id of an object add them to the array
sids.push(obj._id);
} else
if (obj._id.match(/\.Alive/g)) {
alives.push(obj._id);
}
});
}
// adapter.log.debug('Array arrSID is now filled');
// When the array is filled start the search
resolve({sids, alives});
});
});
return sidPromise;
}
}
// control the devices
function sendCommand(id, cb) {
adapter.log.debug('Send Command for ' + id);
let parts = id.split('.');
parts.pop();
let actionName = parts.pop();
let service = parts.join('.');
id = id.replace('.request', '');
adapter.getObject(service, (err, obj) => {
let vServiceType = obj.native.serviceType;
let serviceName = obj.native.name;
let device = service.replace(`.${serviceName}`, '');
let vControlURL = obj.native.controlURL;
adapter.getObject(device, (err, obj) => {
let ip = obj.native.ip;
let port = obj.native.port;
let cName = JSON.stringify(obj._id);
cName = cName.replace(/\.\w*"$/g, '');
cName = cName.replace(/^"/g, '');
adapter.getStatesOf(cName, (err, _states) => {
let args = [];
for (let x = _states.length - 1; x >= 0; x--) {
let argumentsOfAction = _states[x]._id;
let obj = _states[x];
let test2 = id + '\\.';
try {
test2 = test2.replace(/\(/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\)/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/\[/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
try {
test2 = test2.replace(/ ]/gi, '.');
} catch (err) {
adapter.log.debug(err)
}
let re = new RegExp(test2, 'g');
let testResult = re.test(argumentsOfAction);
if (testResult && argumentsOfAction !== id) {
args.push(obj);
}
}
let body = '';
// get all states of the arguments as string
adapter.getStates(`${id}.*`, (err, idStates) => {
adapter.log.debug('get all states of the arguments as string ');
let helperBody = [];
let states = JSON.stringify(idStates);
states = states.replace(/,"ack":\w*,"ts":\d*,"q":\d*,"from":"(\w*\.)*(\d*)","lc":\d*/g, '');
for (let z = args.length - 1; z >= 0; z--) {
// check if the argument has to be send with the action
if (args[z].native.direction === 'in') {
let argNo = args[z].native.argumentNumber;
// check if the argument is already written to the helperBody array, if not found value and add to array
if (helperBody[argNo] == null) {
let test2 = getValueFromArray(args[z]._id);
// replace signs that could cause problems with regex
test2 = test2
.replace(/\(/gi, '.')
.replace(/\)/gi, '.')
.replace(/\[/gi, '.')
.replace(/]/gi, '.');
let test3 = test2 + '":{"val":("[^"]*|\\d*)}?';
let patt = new RegExp(test3, 'g');
let testResult2;
let testResult = states.match(patt);
testResult2 = JSON.stringify(testResult);
testResult2 = testResult2.match(/val\\":(\\"[^"]*|\d*)}?/g);
testResult2 = JSON.stringify(testResult2);
testResult2 = testResult2.replace(/\["val(\\)*":(\\)*/, '');
testResult2 = testResult2.replace(/]/, '');
testResult2 = testResult2.replace(/}"/, '');
testResult2 = testResult2.replace(/"/g, '');
//extract argument name from id string
let test1 = args[z]._id;
let argName = test1.replace(`${id}\.`, '');
helperBody[argNo] = '<' + argName + '>' + testResult2 + '</' + argName + '>';
}
}
}
//convert helperBody array to string and add it to main body string
helperBody = helperBody.toString().replace(/,/g, '');
body += helperBody;
body = `<u:${actionName} xmlns:u="${vServiceType}">${body}</u:${actionName}>`;
createMessage(vServiceType, actionName, ip, port, vControlURL, body, id, cb);
});
})
});
});
}
function readSchedules() {
return new Promise(resolve => {
adapter.getObjectView('system', 'custom', {startkey: adapter.namespace + '.', endkey: adapter.namespace + '.\uFFFF'}, (err, doc) => {
if (doc && doc.rows) {
for (let i = 0, l = doc.rows.length; i < l; i++) {
if (doc.rows[i].value) {
let id = doc.rows[i].id;
let obj = doc.rows[i].value;
if (id.startsWith(adapter.namespace) && obj[adapter.namespace] && obj[adapter.namespace].enabled && id.match(/\.request$/)) {
actions[id] = {cron: obj[adapter.namespace].schedule};
}
}
}
}
resolve();
});
});
}
// create Action message
function createMessage(sType, aName, _ip, _port, cURL, body, actionID, cb) {
const UA = 'UPnP/1.0, ioBroker.upnp';
let url = `http://${_ip}:${_port}${cURL}`;
const contentType = 'text/xml; charset="utf-8"';
let soapAction = `${sType}#${aName}`;
let postData = `
<s:Envelope s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
<s:Body>${body}</s:Body>
</s:Envelope>`;
//Options for the SOAP message
let options = {
uri: url,
headers: {
'Content-Type': contentType,
'SOAPAction': `"${soapAction}"`,
'USER-AGENT': UA
},
method: 'POST',
body: postData
};
// Send Action message to Device/Service
request(options, (err, res, body) => {
adapter.log.debug('Options for request: ' + JSON.stringify(options));
if (err) {
adapter.log.warn(`Error sending SOAP request: ${err}`);
} else {
if (res.statusCode !== 200) {
adapter.log.warn(`Unexpected answer from upnp service: ` + JSON.stringify(res) + `\n Sent message: ` + JSON.stringify(options));
} else {
//look for data in the response
// die Zusätlichen infos beim Argument namen müssen entfernt werden damit er genutzt werden kann
let foundData = body.match(/<[^\/]\w*\s*[^<]*/g);
if (foundData) {
actionID = actionID.replace(/\.request$/, '');
for (let i = foundData.length - 1; i >= 0; i--) {
let foundArgName = foundData[i].match(/<\w*>/);
let strFoundArgName;
let argValue;
if (foundArgName) {
strFoundArgName = foundArgName[0];
// TODO: must be rewritten
strFoundArgName = strFoundArgName.replace(/["\][]}/g, '');
argValue = foundData[i].replace(strFoundArgName, '');
strFoundArgName = strFoundArgName.replace(/[<>]/g, '');
} else {
foundArgName = foundData[i].match(/<\w*\s/);
if (foundArgName) {
// TODO: must be rewritten
strFoundArgName = foundArgName[0];
strFoundArgName = strFoundArgName.replace(/["[\]<]/g, '').replace(/\s+$/, '');
argValue = foundData[i].replace(/<.*>/, '');
}
}
if (strFoundArgName !== null && strFoundArgName !== undefined) {
let argID = actionID + '.' + strFoundArgName;
addTask({
name: 'setState',
id: argID,
state: {val: argValue, ack: true},
cb: cb =>
//look for relatedStateVariable and setState
syncArgument(actionID, argID, argValue, cb)
});
}
}
processTasks();
} else {
adapter.log.debug('Nothing found: ' + JSON.stringify(body));
}
}
}
cb && cb();
});
}
// Sync Argument with relatedStateVariable
function syncArgument(actionID, argID, argValue, cb) {
adapter.getObject(argID, (err, obj) => {
if (obj) {
let relatedStateVariable = obj.native.relatedStateVariable;
let serviceID = actionID.replace(/\.\w*$/, '');
let relStateVarID = serviceID + '.' + relatedStateVariable;
let val = argValue;
if(obj.common.type === 'number'){
val = parseInt(argValue);
}
adapter.setState(relStateVarID, {val: argValue, ack: true}, cb);
} else {
cb && cb();
}
});
}
function nameFilter(name) {
if (typeof name === 'object' && name[0]) {
name = name[0];
}
let signs = [
String.fromCharCode(46),
String.fromCharCode(44),
String.fromCharCode(92),
String.fromCharCode(47),
String.fromCharCode(91),
String.fromCharCode(93),
String.fromCharCode(123),
String.fromCharCode(125),
String.fromCharCode(32),
String.fromCharCode(129),
String.fromCharCode(154),
String.fromCharCode(132),
String.fromCharCode(142),
String.fromCharCode(148),
String.fromCharCode(153),
String.fromCharCode(42),
String.fromCharCode(63),
String.fromCharCode(34),
String.fromCharCode(39),
String.fromCharCode(96)
];
//46=. 44=, 92=\ 47=/ 91=[ 93=] 123={ 125=} 32=Space 129=ü 154=Ü 132=ä 142=Ä 148=ö 153=Ö 42=* 63=? 34=" 39=' 96=`
signs.forEach((item, index) => {
let count = name.split(item).length - 1;
for (let i = 0; i < count; i++) {
name = name.replace(item, '_');
}
let result = name.search(/_$/);
if (result !== -1) {
name = name.replace(/_$/, '');
}
});
name = name.replace(/[*\[\]+?]+/g, '_');
return name;
}
function main() {
adapter.subscribeStates('*');
adapter.subscribeObjects('*');
adapter.log.info('Auto discover: ' + adapter.config.enableAutoDiscover);
readSchedules()
.then(() => {
if (adapter.config.enableAutoDiscover === true) {
sendBroadcast();
}
// read SIDs and Alive IDs
getIDs()
.then(result => {
adapter.log.debug(`Read ${result.sids.length} SIDs and ${result.alives.length} alives`);
// Filtering the Device description file addresses, timeout is necessary to wait for all answers
setTimeout(() => {
adapter.log.debug(`Found ${foundIPs.length} devices`);
if (adapter.config.rootXMLurl) {
firstDevLookup(adapter.config.rootXMLurl);
}
reschedule();
}, 5000);
//start the server
startServer();
});
});
}
// If started as allInOne mode => return function to create instance
if (module.parent) {
module.exports = startAdapter;
} else {
// or start the instance directly
startAdapter();
}
| Jey-Cee/ioBroker.upnp | main.js | JavaScript | mit | 83,360 |
if(Bar.app("Início")) throw "Barra já existe!";
/*/LOADING BAR
$.get("http://hosts.medorc.org/xn--stio-vpa/json/bar.Home.json"),
function(data){
//if(Bar.app(data.name)) throw "Barra já existe!";
$('#header').bar({
toolbox: data,
callback: function(bar){
//(auto) load requested addon
(function(startHash){
if(startHash && startHash != '#!Home' && startHash != '#!Início'){
// gets bar addon (or loads addon script) before callback
Bar.getBar(Bar.urls(startHash), function(error, addon){
// error getting addon
if(error) throw error + " error getting addon " + startHash + " @bar.Home";
// route to addon (select addon tab)
Frontgate.router.route(addon.href);
//console.log('Bar.route', bar, route);
});
}
})(Remote.attr("requestHash"));
// mostrar item IE apenas se o utilizador for "daniel"
if(Situs.attr().user == "daniel") $("#isec-ei").show();
Situs.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}
});
});
/*/
//AUTO LOADING BAR
Bar.load('#header', function(bar, data){
Frontgate.router.on("#Home", function(hash){
location.hash = "Início";
});
// mostrar item IE apenas se o utilizador for "daniel"
if(Frontgate.attr().user == "daniel") $("#isec-ei").show();
Frontgate.subscribeEvent('userChange', function(attr){
if(attr.user == "daniel") $("#isec-ei").show();
else $("#isec-ei").hide();
});
}, FILE);//*/
//------------------------------------------------------------------
// BUG:
// when addon items are not hash banged (#!ToolboxItem)
// the tab is added to the navigator but the toolbox is not selected
//------------------------------------------------------------------
| vieiralisboa/ze | private/bars/bar.Home.js | JavaScript | mit | 2,099 |
System.config({
baseURL: "/",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime"
],
"stage": 1
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"angular2": "npm:[email protected]",
"babel": "npm:[email protected]",
"babel-runtime": "npm:[email protected]",
"clean-css": "npm:[email protected]",
"core-js": "npm:[email protected]",
"css": "github:systemjs/[email protected]",
"reflect-metadata": "npm:[email protected]",
"rxjs": "npm:[email protected]",
"zone.js": "npm:[email protected]",
"github:jspm/[email protected]": {
"assert": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"buffer": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"constants-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"crypto-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"events": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"Base64": "npm:[email protected]",
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]",
"url": "github:jspm/[email protected]",
"util": "github:jspm/[email protected]"
},
"github:jspm/[email protected]": {
"https-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"os-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"path-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"process": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"stream-browserify": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"string_decoder": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"url": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"util": "npm:[email protected]"
},
"github:jspm/[email protected]": {
"vm-browserify": "npm:[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]",
"module": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"crypto": "github:jspm/[email protected]",
"es6-promise": "npm:[email protected]",
"es6-shim": "npm:[email protected]",
"process": "github:jspm/[email protected]",
"reflect-metadata": "npm:[email protected]",
"rxjs": "npm:[email protected]",
"zone.js": "npm:[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"minimalistic-assert": "npm:[email protected]",
"vm": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"util": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"buffer-xor": "npm:[email protected]",
"cipher-base": "npm:[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"evp_bytestokey": "npm:[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"browserify-aes": "npm:[email protected]",
"browserify-des": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"evp_bytestokey": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"cipher-base": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"des.js": "npm:[email protected]",
"inherits": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"constants": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"browserify-rsa": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"create-hmac": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"elliptic": "npm:[email protected]",
"inherits": "npm:[email protected]",
"parse-asn1": "npm:[email protected]",
"stream": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"base64-js": "npm:[email protected]",
"child_process": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"ieee754": "npm:[email protected]",
"isarray": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]",
"string_decoder": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"commander": "npm:[email protected]",
"fs": "github:jspm/[email protected]",
"http": "github:jspm/[email protected]",
"https": "github:jspm/[email protected]",
"os": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"source-map": "npm:[email protected]",
"url": "github:jspm/[email protected]",
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"child_process": "github:jspm/[email protected]",
"events": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"graceful-readlink": "npm:[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"elliptic": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"cipher-base": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"ripemd160": "npm:[email protected]",
"sha.js": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"stream": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"browserify-cipher": "npm:[email protected]",
"browserify-sign": "npm:[email protected]",
"create-ecdh": "npm:[email protected]",
"create-hash": "npm:[email protected]",
"create-hmac": "npm:[email protected]",
"diffie-hellman": "npm:[email protected]",
"inherits": "npm:[email protected]",
"pbkdf2": "npm:[email protected]",
"public-encrypt": "npm:[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"minimalistic-assert": "npm:[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"miller-rabin": "npm:[email protected]",
"randombytes": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"brorand": "npm:[email protected]",
"hash.js": "npm:[email protected]",
"inherits": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"fs": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"inherits": "npm:[email protected]"
},
"npm:[email protected]": {
"http": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"brorand": "npm:[email protected]"
},
"npm:[email protected]": {
"os": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"asn1.js": "npm:[email protected]",
"browserify-aes": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"evp_bytestokey": "npm:[email protected]",
"pbkdf2": "npm:[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"child_process": "github:jspm/[email protected]",
"create-hmac": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"path": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]",
"systemjs-json": "github:systemjs/[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"bn.js": "npm:[email protected]",
"browserify-rsa": "npm:[email protected]",
"buffer": "github:jspm/[email protected]",
"create-hash": "npm:[email protected]",
"crypto": "github:jspm/[email protected]",
"parse-asn1": "npm:[email protected]",
"randombytes": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"crypto": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"core-util-is": "npm:[email protected]",
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"isarray": "npm:[email protected]",
"process": "github:jspm/[email protected]",
"stream-browserify": "npm:[email protected]",
"string_decoder": "npm:[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]",
"fs": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"amdefine": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"events": "github:jspm/[email protected]",
"inherits": "npm:[email protected]",
"readable-stream": "npm:[email protected]"
},
"npm:[email protected]": {
"buffer": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"assert": "github:jspm/[email protected]",
"punycode": "npm:[email protected]",
"querystring": "npm:[email protected]",
"util": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"inherits": "npm:[email protected]",
"process": "github:jspm/[email protected]"
},
"npm:[email protected]": {
"indexof": "npm:[email protected]"
},
"npm:[email protected]": {
"process": "github:jspm/[email protected]"
}
}
});
| gilAsier/angular2beta_errors | public/config.js | JavaScript | mit | 14,023 |
$(document).ready(function() {
$.getJSON('/backend/go/' + go_term['id'] + '/locus_details', function(data) {
create_go_table(data);
});
$.getJSON('/backend/go/' + go_term['id'] + '/ontology_graph', function(data) {
var cy = create_cytoscape_vis("cy", layout, graph_style, data, null, false, "goOntology");
create_cy_download_button(cy, "cy_download", go_term['display_name'] + '_ontology')
if(data['all_children'] != null && data['all_children'].length > 0) {
var children_div = document.getElementById("children");
var more_children_div = document.getElementById("children_see_more");
for(var i=0; i < data['all_children'].length; i++) {
var a = document.createElement('a');
a.innerHTML = data['all_children'][i]['display_name'];
a.href = data['all_children'][i]['link']
if(i < 20) {
children_div.appendChild(a);
}
else {
more_children_div.appendChild(a);
}
if(i != data['all_children'].length-1) {
var comma = document.createElement('span');
comma.innerHTML = ' • ';
if(i < 20) {
children_div.appendChild(comma);
}
else {
more_children_div.appendChild(comma);
}
}
}
if(data['all_children'].length <= 20) {
$("#children_see_more_button").hide();
}
}
else {
$("#children_wrapper").hide()
}
});
});
function create_go_table(data) {
var manualDatatable = [];
var manualGenes = {};
var htpDatatable = [];
var htpGenes = {};
var computationalDatatable = [];
var computationalGenes = {};
for (var i=0; i < data.length; i++) {
var type = data[i].annotation_type;
if (type === 'manually curated') {
manualDatatable.push(go_data_to_table(data[i], i));
manualGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'high-throughput') {
htpDatatable.push(go_data_to_table(data[i], i));
htpGenes[data[i]["locus"]["id"]] = true;
} else if (type === 'computational') {
computationalDatatable.push(go_data_to_table(data[i], i));
computationalGenes[data[i]["locus"]["id"]] = true;
}
}
set_up_header('manual_go_table', manualDatatable.length, 'entry', 'entries', Object.keys(manualGenes).length, 'gene', 'genes');
set_up_header('htp_go_table', htpDatatable.length, 'entry', 'entries', Object.keys(htpGenes).length, 'gene', 'genes');
set_up_header('computational_go_table', computationalDatatable.length, 'entry', 'entries', Object.keys(computationalGenes).length, 'gene', 'genes');
var options = {};
options["bPaginate"] = true;
options["aaSorting"] = [[3, "asc"]];
options["bDestroy"] = true;
// options["oLanguage"] = {"sEmptyTable": "No genes annotated directly to " + go_term['display_name']};
options["aoColumns"] = [
//Use of mData
{"bSearchable":false, "bVisible":false,"aTargets":[0],"mData":0}, //evidence_id
{"bSearchable":false, "bVisible":false,"aTargets":[1],"mData":1}, //analyze_id
{"aTargets":[2],"mData":2}, //gene
{"bSearchable":false, "bVisible":false,"aTargets":[3],"mData":3}, //gene systematic name
{"aTargets":[4],"mData":4}, //gene ontology term -----> qualifier
{"bSearchable":false, "bVisible":false,"aTargets":[5],"mData":5}, //gene ontology term id
{"aTargets":[6],"mData":6}, //qualifier -----> gene ontology term
{"bSearchable":false, "bVisible":false,"aTargets":[7],"mData":7}, //aspect
{"aTargets":[8],"mData":8}, //evidence -----> annotation_extension
{"aTargets":[9],"mData":9}, //method -----> evidence
{"bSearchable":false,"bVisible":false,"aTargets":[10],"mData":10}, //source -----> method
{"aTargets":[11],"mData":11}, //assigned on -----> source
{"aTargets":[12],"mData":12}, //annotation_extension -----> assigned on
{"aTargets":[13],"mData":13} // reference
];
create_or_hide_table(manualDatatable, options, "manual_go_table", go_term["display_name"], go_term["link"], go_term["id"], "manually curated", data);
create_or_hide_table(htpDatatable, options, "htp_go_table", go_term["display_name"], go_term["link"], go_term["id"], "high-throughput", data);
create_or_hide_table(computationalDatatable, options, "computational_go_table", go_term["display_name"], go_term["link"], go_term["id"], "computational", data);
}
function create_or_hide_table(tableData, options, tableIdentifier, goName, goLink, goId, annotationType, originalData) {
if (tableData.length) {
var localOptions = $.extend({ aaData: tableData, oLanguage: { sEmptyTable: 'No genes annotated directly to ' + goName } }, options);
var table = create_table(tableIdentifier, localOptions);
create_analyze_button(tableIdentifier + "_analyze", table, "<a href='" + goLink + "' class='gene_name'>" + goName + "</a> genes", true);
create_download_button(tableIdentifier + "_download", table, goName + "_annotations");
if(go_term['descendant_locus_count'] > go_term['locus_count']) {
create_show_child_button(tableIdentifier + "_show_children", table, originalData, "/backend/go/" + goId + "/locus_details_all", go_data_to_table, function(table_data) {
var genes = {};
for (var i=0; i < table_data.length; i++) {
genes[table_data[i][1]] = true;
}
set_up_header(tableIdentifier, table_data.length, 'entry', 'entries', Object.keys(genes).length, 'gene', 'genes');
}, annotationType);
}
return table;
} else {
$("#" + tableIdentifier + "_header").remove();
var $parent = $("#" + tableIdentifier).parent();
var emptyMessage = "There are no " + annotationType + " annotations for " + goName + ".";
$parent.html(emptyMessage);
}
};
var graph_style = cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 14,
'text-outline-width': 3,
'text-valign': 'center',
'width': 30,
'height': 30,
'border-color': '#fff',
'background-color': "#43a0df",
'text-outline-color': '#fff',
'color': '#888'
})
.selector('edge')
.css({
'content': 'data(name)',
'font-family': 'helvetica',
'font-size': 12,
'color': 'grey',
'width': 2,
'source-arrow-shape': 'triangle'
})
.selector("node[sub_type='FOCUS']")
.css({
'width': 30,
'height': 30,
'background-color': "#fade71",
'text-outline-color': '#fff',
'color': '#888'
})
.selector("node[id='NodeMoreChildren']")
.css({
'width': 30,
'height': 30,
'shape': 'rectangle'
});
// .selector("node[sub_type='HAS_CHILDREN']")
// .css(
// {'background-color': "#165782"
// })
// .selector("node[sub_type='HAS_DESCENDANTS']")
// .css(
// {'background-color': "#43a0df"
// })
// .selector("node[sub_type='NO_DESCENDANTS']")
// .css(
// {'background-color': "#c9e4f6"
// });
var layout = {
"name": "breadthfirst",
"fit": true,
"directed": true
};
| yeastgenome/SGDFrontend | src/sgd/frontend/yeastgenome/static/js/go.js | JavaScript | mit | 7,443 |
// app.js
/*jslint node: true */
'use strict';
var compression = require('compression');
var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var hbs = require('hbs'); // Handlebars templating engine
var configDB = require('./config/database.js'); // Load our db configuration
mongoose.connect(configDB.url); // Connect to our db.
require('./config/passport')(passport); // Configure passport authentication
var app = express();
// Set up express app
app.use(compression({
threshold: 512
}));
app.set('json spaces', 0);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.errorHandler());
app.use(express.methodOverride());
app.use(express.cookieParser('flyingfish'));
app.use(express.session());
app.set('view engine', 'html');
app.engine('html', hbs.__express);
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
require('./routes')(app, passport); // Load our routes and pass in our app and passport
app.listen(process.env.PORT || 3000); | formed/paths.old | app.js | JavaScript | mit | 1,352 |
!function($) {
$(document).on("keydown", 'input[data-type="numeric"]', function (e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
return (
key == 8 ||
key == 9 ||
key == 46 ||
(key >= 37 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
}(window.jQuery || window.ender); | carlalexander/jquery.numeric.input | jquery.numeric.input.js | JavaScript | mit | 420 |
import Chip from '../../components/Chip'
import { vueTest } from '../utils'
describe('Chip', () => {
let vm
before((done) => {
vm = vueTest(Chip)
vm.$nextTick(done)
})
it('renders with text', () => {
const el = vm.$('#chip')
el.should.contain.text('Basic chip')
el.should.not.have.class('mdl-chip--contact')
el.should.not.have.class('mdl-chip--deletable')
})
it('renders with close button', () => {
const el = vm.$('#delete')
el.should.contain.text('Deletable chip')
el.should.not.have.class('mdl-chip--contact')
el.should.have.class('mdl-chip--deletable')
const action = vm.$('#delete .mdl-chip__action')
action.should.exist
action.should.have.text('cancel')
})
it('has custom icon', (done) => {
const action = vm.$('#delete .mdl-chip__action')
action.should.have.text('cancel')
vm.deleteIcon = 'star'
vm.nextTick()
.then(() => {
action.should.have.text('star')
})
.then(done, done)
})
it('emits close event', (done) => {
vm.deleted.should.be.false
const action = vm.$('#delete .mdl-chip__action')
action.click()
vm.nextTick()
.then(() => {
vm.deleted.should.be.true
vm.deleted = false
return vm.nextTick()
})
.then(done, done)
})
it('renders text inside circle', (done) => {
vm.$('#contact').should.have.class('mdl-chip--contact')
const el = vm.$('#contact .mdl-chip__contact')
el.should.contain.text(vm.contact)
el.should.not.have.class('mdl-chip--deletable')
vm.contact = 'A'
vm.nextTick()
.then(() => {
el.should.have.text('A')
})
.then(done, done)
})
it('renders image inside circle', () => {
vm.$('#image').should.have.class('mdl-chip--contact')
const el = vm.$('#image .mdl-chip__contact')
el.should.have.attr('src', 'https://getmdl.io/templates/dashboard/images/user.jpg')
el.should.not.have.class('mdl-chip--deletable')
})
})
| posva/vue-mdl | test/unit/specs/Chip.spec.js | JavaScript | mit | 1,991 |
import { hashHistory } from 'react-router'
import { auth } from 'lib/firebase'
export const redirect = path => hashHistory.push(path)
export const signInWithGoogle = () => {
const provider = new auth.GoogleAuthProvider()
provider.addScope('https://www.googleapis.com/auth/userinfo.profile')
return auth().signInWithPopup(provider)
}
export const signInWithFacebook = () => {
const provider = new auth.FacebookAuthProvider()
return auth().signInWithPopup(provider)
}
export const signOut = () => {
return auth().signOut()
}
export const getCurrentUser = () => {
return Promise.resolve(auth().currentUser)
}
| panelando/panelando | app/lib/auth.js | JavaScript | mit | 629 |
var request = require('supertest');
var should = require('should');
var express = require('express');
var expressRouter = require('../index.js');
var mockPath = 'mock.js';
describe('register routes', function(){
var app;
before(function(){
app = express();
expressRouter.sync(app, mockPath);
});
it('should have register: GET /api/collection', function(done){
request(app)
.get('/api/collection')
.expect(200)
.expect('OK', done);
});
it('should have register: GET /api/entity/:id', function(done){
request(app)
.get('/api/entity/1')
.expect(200)
.expect('OK', done);
});
it('should have register: POST /api/test', function(done){
request(app)
.post('/api/test')
.expect(201)
.expect('Created', done);
});
});
| mastilver/express-annotation | test/sync.js | JavaScript | mit | 905 |
/**
* @author: @AngularClass
*/
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const DefinePlugin = require('webpack/lib/DefinePlugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const IgnorePlugin = require('webpack/lib/IgnorePlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ProvidePlugin = require('webpack/lib/ProvidePlugin');
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin');
const OptimizeJsPlugin = require('optimize-js-plugin');
/**
* Webpack Constants
*/
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
const HOST = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 8080;
const METADATA = webpackMerge(commonConfig({
env: ENV
}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: false
});
module.exports = function (env) {
return webpackMerge(commonConfig({
env: ENV
}), {
/**
* Developer tool to enhance debugging
*
* See: http://webpack.github.io/docs/configuration.html#devtool
* See: https://github.com/webpack/docs/wiki/build-performance#sourcemaps
*/
devtool: 'source-map',
/**
* Options affecting the output of the compilation.
*
* See: http://webpack.github.io/docs/configuration.html#output
*/
output: {
/**
* The output directory as absolute path (required).
*
* See: http://webpack.github.io/docs/configuration.html#output-path
*/
path: helpers.root('dist'),
/**
* Specifies the name of each output file on disk.
* IMPORTANT: You must not specify an absolute path here!
*
* See: http://webpack.github.io/docs/configuration.html#output-filename
*/
filename: '[name].[chunkhash].bundle.js',
/**
* The filename of the SourceMaps for the JavaScript files.
* They are inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-sourcemapfilename
*/
sourceMapFilename: '[name].[chunkhash].bundle.map',
/**
* The filename of non-entry chunks as relative path
* inside the output.path directory.
*
* See: http://webpack.github.io/docs/configuration.html#output-chunkfilename
*/
chunkFilename: '[id].[chunkhash].chunk.js'
},
module: {
rules: [
/*
* Extract CSS files from .src/styles directory to external CSS file
*/
{
test: /\.css$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
}),
include: [helpers.root('src', 'styles')]
},
/*
* Extract and compile SCSS files from .src/styles directory to external CSS file
*/
{
test: /\.scss$/,
loader: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader!sass-loader'
}),
include: [helpers.root('src', 'styles')]
},
]
},
/**
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
/**
* Webpack plugin to optimize a JavaScript file for faster initial load
* by wrapping eagerly-invoked functions.
*
* See: https://github.com/vigneshshanmugam/optimize-js-plugin
*/
new OptimizeJsPlugin({
sourceMap: false
}),
/**
* Plugin: ExtractTextPlugin
* Description: Extracts imported CSS files into external stylesheet
*
* See: https://github.com/webpack/extract-text-webpack-plugin
*/
new ExtractTextPlugin('[name].[contenthash].css'),
/**
* Plugin: DefinePlugin
* Description: Define free variables.
* Useful for having development builds with debug logging or adding global constants.
*
* Environment helpers
*
* See: https://webpack.github.io/docs/list-of-plugins.html#defineplugin
*/
// NOTE: when adding more properties make sure you include them in custom-typings.d.ts
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
}
}),
/**
* Plugin: UglifyJsPlugin
* Description: Minimize all JavaScript output of chunks.
* Loaders are switched into minimizing mode.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
*/
// NOTE: To debug prod builds uncomment //debug lines and comment //prod lines
new UglifyJsPlugin({
// beautify: true, //debug
// mangle: false, //debug
// dead_code: false, //debug
// unused: false, //debug
// deadCode: false, //debug
// compress: {
// screw_ie8: true,
// keep_fnames: true,
// drop_debugger: false,
// dead_code: false,
// unused: false
// }, // debug
// comments: true, //debug
beautify: false, //prod
output: {
comments: false
}, //prod
mangle: {
screw_ie8: true
}, //prod
compress: {
screw_ie8: true,
warnings: false,
conditionals: true,
unused: true,
comparisons: true,
sequences: true,
dead_code: true,
evaluate: true,
if_return: true,
join_vars: true,
negate_iife: false // we need this for lazy v8
},
}),
/**
* Plugin: NormalModuleReplacementPlugin
* Description: Replace resources that matches resourceRegExp with newResource
*
* See: http://webpack.github.io/docs/list-of-plugins.html#normalmodulereplacementplugin
*/
new NormalModuleReplacementPlugin(
/angular2-hmr/,
helpers.root('config/empty.js')
),
new NormalModuleReplacementPlugin(
/zone\.js(\\|\/)dist(\\|\/)long-stack-trace-zone/,
helpers.root('config/empty.js')
),
// AoT
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)upgrade/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)compiler/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /@angular(\\|\/)platform-browser-dynamic/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)ng_probe/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /dom(\\|\/)debug(\\|\/)by/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_node/,
// helpers.root('config/empty.js')
// ),
// new NormalModuleReplacementPlugin(
// /src(\\|\/)debug(\\|\/)debug_renderer/,
// helpers.root('config/empty.js')
// ),
/**
* Plugin: CompressionPlugin
* Description: Prepares compressed versions of assets to serve
* them with Content-Encoding
*
* See: https://github.com/webpack/compression-webpack-plugin
*/
// install compression-webpack-plugin
// new CompressionPlugin({
// regExp: /\.css$|\.html$|\.js$|\.map$/,
// threshold: 2 * 1024
// })
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({
minimize: true,
debug: false,
options: {
/**
* Html loader advanced options
*
* See: https://github.com/webpack/html-loader#advanced-options
*/
// TODO: Need to workaround Angular 2's html syntax => #id [bind] (event) *ngFor
htmlLoader: {
minimize: false,
removeAttributeQuotes: false,
caseSensitive: true,
customAttrSurround: [
[/#/, /(?:)/],
[/\*/, /(?:)/],
[/\[?\(?/, /(?:)/]
],
customAttrAssign: [/\)?\]?=/]
},
}
}),
/**
* Plugin: BundleAnalyzerPlugin
* Description: Webpack plugin and CLI utility that represents
* bundle content as convenient interactive zoomable treemap
*
* `npm run build:prod -- --env.analyze` to use
*
* See: https://github.com/th0r/webpack-bundle-analyzer
*/
],
/*
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: false,
module: false,
clearImmediate: false,
setImmediate: false
}
});
}
| AnastasiaPavlova/Angular2Traning | config/webpack.prod.js | JavaScript | mit | 9,907 |
jest.mock('send')
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql'
import { $$pgClient } from '../../../postgres/inventory/pgClientFromContext'
import createPostGraphQLHttpRequestHandler, { graphiqlDirectory } from '../createPostGraphQLHttpRequestHandler'
const path = require('path')
const http = require('http')
const request = require('supertest')
const connect = require('connect')
const express = require('express')
const sendFile = require('send')
const event = require('events')
sendFile.mockImplementation(() => {
const stream = new event.EventEmitter()
stream.pipe = jest.fn(res => process.nextTick(() => res.end()))
process.nextTick(() => stream.emit('end'))
return stream
})
const gqlSchema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'Query',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
greetings: {
type: GraphQLString,
args: {
name: { type: GraphQLString },
},
resolve: (source, { name }) => `Hello, ${name}!`,
},
query: {
type: GraphQLString,
resolve: (source, args, context) =>
context[$$pgClient].query('EXECUTE'),
},
},
}),
mutation: new GraphQLObjectType({
name: 'Mutation',
fields: {
hello: {
type: GraphQLString,
resolve: () => 'world',
},
},
}),
})
const pgClient = {
query: jest.fn(() => Promise.resolve()),
release: jest.fn(),
}
const pgPool = {
connect: jest.fn(() => pgClient),
}
const defaultOptions = {
getGqlSchema: () => gqlSchema,
pgPool,
disableQueryLog: true,
}
const serverCreators = new Map([
['http', handler => {
return http.createServer(handler)
}],
['connect', handler => {
const app = connect()
app.use(handler)
return http.createServer(app)
}],
['express', handler => {
const app = express()
app.use(handler)
return http.createServer(app)
}],
])
// Parse out the Node.js version number. The version will be in a semantic
// versioning format with maybe a `v` in front. We remove that `v`, split by
// `.`, get the first item in the split array, and parse that as an integer to
// get the Node.js major version number.
const nodeMajorVersion = parseInt(process.version.replace(/^v/, '').split('.')[0], 10)
// Only test Koa in version of Node.js greater than 4 because the Koa source
// code has some ES2015 syntax in it which breaks in Node.js 4 and lower. Koa is
// not meant to be used in Node.js 4 anyway so this is fine.
if (nodeMajorVersion > 4) {
const Koa = require('koa') // tslint:disable-line variable-name
serverCreators.set('koa', handler => {
const app = new Koa()
app.use(handler)
return http.createServer(app.callback())
})
}
for (const [name, createServerFromHandler] of Array.from(serverCreators)) {
const createServer = options =>
createServerFromHandler(createPostGraphQLHttpRequestHandler(Object.assign({}, defaultOptions, options)))
describe(name, () => {
test('will 404 for route other than that specified', async () => {
const server1 = createServer()
const server2 = createServer({ graphqlRoute: '/x' })
await (
request(server1)
.post('/x')
.expect(404)
)
await (
request(server2)
.post('/graphql')
.expect(404)
)
})
test('will respond to queries on a different route', async () => {
const server = createServer({ graphqlRoute: '/x' })
await (
request(server)
.post('/x')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will always respond with CORS to an OPTIONS request when enabled', async () => {
const server = createServer({ enableCors: true })
await (
request(server)
.options('/graphql')
.expect(200)
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Request-Method', 'HEAD, GET, POST')
.expect('Access-Control-Allow-Headers', /Accept, Authorization/)
.expect('')
)
})
test('will always respond to any request with CORS headers when enabled', async () => {
const server = createServer({ enableCors: true })
await (
request(server)
.post('/graphql')
.expect('Access-Control-Allow-Origin', '*')
.expect('Access-Control-Request-Method', 'HEAD, GET, POST')
.expect('Access-Control-Allow-Headers', /Accept, Authorization/)
)
})
test('will not allow requests other than POST', async () => {
const server = createServer()
await (
request(server)
.get('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
await (
request(server)
.delete('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
await (
request(server)
.put('/graphql')
.expect(405)
.expect('Allow', 'POST, OPTIONS')
)
})
test('will run a query on a POST request with JSON data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/json')
.send(JSON.stringify({ query: '{hello}' }))
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will run a query on a POST request with form data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(`query=${encodeURIComponent('{hello}')}`)
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will run a query on a POST request with GraphQL data', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/graphql')
.send('{hello}')
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will error if query parse fails', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{' })
.expect(400)
.expect('Content-Type', /json/)
.expect({ errors: [{ message: 'Syntax Error GraphQL Http Request (1:2) Expected Name, found <EOF>\n\n1: {\n ^\n', locations: [{ line: 1, column: 2 }] }] })
)
})
test('will error if validation fails', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{notFound}' })
.expect(400)
.expect('Content-Type', /json/)
.expect({ errors: [{ message: 'Cannot query field "notFound" on type "Query".', locations: [{ line: 1, column: 2 }] }] })
)
})
test('will allow mutations with POST', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'mutation {hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
})
test('will connect and release a Postgres client from the pool on every request', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([['begin'], ['commit']])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will setup a transaction for requests that use the Postgres client', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{query}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { query: null } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([['begin'], ['EXECUTE'], ['commit']])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will setup a transaction and pass down options for requests that use the Postgres client', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const jwtSecret = 'secret'
const pgDefaultRole = 'pg_default_role'
const server = createServer({ jwtSecret, pgDefaultRole })
await (
request(server)
.post('/graphql')
.send({ query: '{query}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { query: null } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([
['begin'],
[{ text: 'select set_config($1, $2, true)', values: ['role', 'pg_default_role'] }],
['EXECUTE'],
['commit'],
])
expect(pgClient.release.mock.calls).toEqual([[]])
})
test('will respect an operation name', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'query A { a: hello } query B { b: hello }', operationName: 'A' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { a: 'world' } })
)
await (
request(server)
.post('/graphql')
.send({ query: 'query A { a: hello } query B { b: hello }', operationName: 'B' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { b: 'world' } })
)
})
test('will use variables', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: 'query A($name: String!) { greetings(name: $name) }', variables: JSON.stringify({ name: 'Joe' }), operationName: 'A' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { greetings: 'Hello, Joe!' } })
)
await (
request(server)
.post('/graphql')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(`operationName=A&query=${encodeURIComponent('query A($name: String!) { greetings(name: $name) }')}&variables=${encodeURIComponent(JSON.stringify({ name: 'Joe' }))}`)
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { greetings: 'Hello, Joe!' } })
)
})
test('will ignore empty string variables', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', variables: '' })
.expect(200)
.expect({ data: { hello: 'world' } })
)
})
test('will error with variables of the incorrect type', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', variables: 2 })
.expect(400)
.expect({ errors: [{ message: 'Variables must be an object, not \'number\'.' }] })
)
})
test('will error with an operation name of the incorrect type', async () => {
const server = createServer()
await (
request(server)
.post('/graphql')
.send({ query: '{hello}', operationName: 2 })
.expect(400)
.expect({ errors: [{ message: 'Operation name must be a string, not \'number\'.' }] })
)
})
test('will serve a favicon when graphiql is enabled', async () => {
const server1 = createServer({ graphiql: true })
const server2 = createServer({ graphiql: true, route: '/graphql' })
await (
request(server1)
.get('/favicon.ico')
.expect(200)
.expect('Cache-Control', 'public, max-age=86400')
.expect('Content-Type', 'image/x-icon')
)
await (
request(server2)
.get('/favicon.ico')
.expect(200)
.expect('Cache-Control', 'public, max-age=86400')
.expect('Content-Type', 'image/x-icon')
)
})
test('will not serve a favicon when graphiql is disabled', async () => {
const server1 = createServer({ graphiql: false })
const server2 = createServer({ graphiql: false, route: '/graphql' })
await (
request(server1)
.get('/favicon.ico')
.expect(404)
)
await (
request(server2)
.get('/favicon.ico')
.expect(404)
)
})
test('will serve any assets for graphiql', async () => {
sendFile.mockClear()
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/graphiql/anything.css')
.expect(200)
)
await (
request(server)
.get('/_postgraphql/graphiql/something.js')
.expect(200)
)
await (
request(server)
.get('/_postgraphql/graphiql/very/deeply/nested')
.expect(200)
)
expect(sendFile.mock.calls.map(([res, filepath, options]) => [path.relative(graphiqlDirectory, filepath), options]))
.toEqual([
['anything.css', { index: false }],
['something.js', { index: false }],
['very/deeply/nested', { index: false }],
])
})
test('will not serve some graphiql assets', async () => {
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/graphiql/index.html')
.expect(404)
)
await (
request(server)
.get('/_postgraphql/graphiql/asset-manifest.json')
.expect(404)
)
})
test('will not serve any assets for graphiql when disabled', async () => {
sendFile.mockClear()
const server = createServer({ graphiql: false })
await (
request(server)
.get('/_postgraphql/graphiql/anything.css')
.expect(404)
)
await (
request(server)
.get('/_postgraphql/graphiql/something.js')
.expect(404)
)
expect(sendFile.mock.calls.length).toEqual(0)
})
test('will not allow if no text/event-stream headers are set', async () => {
const server = createServer({ graphiql: true })
await (
request(server)
.get('/_postgraphql/stream')
.expect(405)
)
})
test('will render GraphiQL if enabled', async () => {
const server1 = createServer()
const server2 = createServer({ graphiql: true })
await (
request(server1)
.get('/graphiql')
.expect(404)
)
await (
request(server2)
.get('/graphiql')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
)
})
test('will render GraphiQL on another route if desired', async () => {
const server1 = createServer({ graphiqlRoute: '/x' })
const server2 = createServer({ graphiql: true, graphiqlRoute: '/x' })
const server3 = createServer({ graphiql: false, graphiqlRoute: '/x' })
await (
request(server1)
.get('/x')
.expect(404)
)
await (
request(server2)
.get('/x')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
)
await (
request(server3)
.get('/x')
.expect(404)
)
await (
request(server3)
.get('/graphiql')
.expect(404)
)
})
test('cannot use a rejected GraphQL schema', async () => {
const rejectedGraphQLSchema = Promise.reject(new Error('Uh oh!'))
// We don’t want Jest to complain about uncaught promise rejections.
rejectedGraphQLSchema.catch(() => { /* noop */ })
const server = createServer({ getGqlSchema: () => rejectedGraphQLSchema })
// We want to hide `console.error` warnings because we are intentionally
// generating some here.
const origConsoleError = console.error
console.error = () => { /* noop */ }
try {
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(500)
)
}
finally {
console.error = origConsoleError
}
})
test('will correctly hand over pgSettings to the withPostGraphQLContext call', async () => {
pgPool.connect.mockClear()
pgClient.query.mockClear()
pgClient.release.mockClear()
const server = createServer({
pgSettings: {
'foo.string': 'test1',
'foo.number': 42,
'foo.boolean': true,
},
})
await (
request(server)
.post('/graphql')
.send({ query: '{hello}' })
.expect(200)
.expect('Content-Type', /json/)
.expect({ data: { hello: 'world' } })
)
expect(pgPool.connect.mock.calls).toEqual([[]])
expect(pgClient.query.mock.calls).toEqual([
['begin'],
[
{
text: 'select set_config($1, $2, true), set_config($3, $4, true), set_config($5, $6, true)',
values: [
'foo.string', 'test1',
'foo.number', '42',
'foo.boolean', 'true',
],
},
],
['commit'],
])
expect(pgClient.release.mock.calls).toEqual([[]])
})
})
}
| nbushak/postgraphql | src/postgraphql/http/__tests__/createPostGraphQLHttpRequestHandler-test.js | JavaScript | mit | 18,119 |
/* eslint no-console: warn */
const _ = require('lodash');
const { processScore } = require('../helpers/game.js');
const getRandomQuiz = require('../../app/helpers/quizRandomizer.js');
module.exports = function socketHandler(io) {
const players = [];
const game = io.of('/game');
game.on('connect', function (socket) {
socket.join('gameRoom');
console.log('connected !!');
console.log('socket ID', socket.id);
console.log('players', players);
socket.on('score update', broadcastScore.bind(null, socket));
socket.on('spectator join', sendPlayers.bind(null, socket, players));
socket.on('player join', handleGame.bind(null, socket));
socket.on('player input', broadcastPlayerCode.bind(null, socket));
});
game.on('disconnect', (socket) => {
console.log('disconnected', socket.id);
});
const handleGame = (socket, player ) => {
console.log('handling game', player);
addPlayer(players, player);
sendPlayers(socket, players);
// if all players ready
if (players.length >= 2) {
// send randomCodeQuizURL
game.emit('quiz url', getRandomQuiz());
}
};
const broadcastScore = (socket, { id, score, passCount, failCount }) => {
console.log('broadcasting score');
socket.to('gameRoom').emit('score update', { id, score: processScore(score), passCount, failCount });
};
const broadcastPlayerCode = (socket, { id, randomCode, code }) => {
socket.to('gameRoom').emit('player input', { id, randomCode, code });
};
const sendPlayers = (socket, players) => {
console.log('sending players');
socket.to('gameRoom').emit('player join', { players });
};
};
function addPlayer(players, newPlayer) {
// !_.some(players, player => _.includes(player, newPlayer.id)) && players.push(newPlayer);
players[newPlayer.id - 1] = newPlayer;
}
| OperationSpark/code-clash | src/socket/index.js | JavaScript | mit | 1,848 |
'use strict';
import Component from './component';
import VolumeAttachment from './volume-attachment';
import Port from './port';
import {isString} from './util';
const Server = function (properties) {
if (!(this instanceof Server)) {
return new Server(properties);
}
Component.call(this, {
ports: [],
...properties
});
};
Server.prototype = Object.create(Component.prototype);
Server.prototype.constructor = Server;
Server.prototype.getDependencies = function () {
return [
...this.dependencies,
...this.properties.ports
]
};
Server.prototype.attachVolume = function (volume, mountPoint) {
const attachment = new VolumeAttachment({
id: `${isString(volume) ? volume : volume.properties.id}-attachment`,
server: this,
volume,
mountPoint
});
this.dependencies.push(attachment);
return this;
};
Server.prototype.attachPort = function (port) {
this.properties.ports.push(port);
return this;
};
Server.prototype.getSchema = function () {
return {
zone: {
type: String
},
name: {
type: String
},
image: {
type: String,
required: true
},
flavor: {
type: String,
required: true
},
keyPair: {
type: String
},
ports: {
type: Array,
items: [String, Port]
}
};
};
Server.prototype.getResources = function () {
const {
id, zone, name, flavor,
keyPair, image, ports
} = this.properties;
const networks = ports.map(port => ({
port: Component.resolve(port)
}));
const properties = {
flavor,
image
};
Object.assign(
properties,
name ? {name} : {},
zone ? {zone} : {},
keyPair ? {key_name: keyPair} : {},
networks.length ? {networks} : {}
);
return {
[id]: {
type: 'OS::Nova::Server',
properties
}
};
};
export default Server;
| kazet15/heat-templates | src/server.js | JavaScript | mit | 1,872 |
define([
'./src/vertebrae'
], function(Vertebrae) {
return Vertebrae;
}); | Evisions/vertebrae | index.js | JavaScript | mit | 78 |
import Ember from 'ember';
import StatefulMixin from './mixins/stateful';
export default Ember.Object.extend(StatefulMixin);
| IvyApp/ivy-stateful | addon/state-machine.js | JavaScript | mit | 126 |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
Easing,
View,
} from 'react-native';
const INDETERMINATE_WIDTH_FACTOR = 0.3;
const BAR_WIDTH_ZERO_POSITION = INDETERMINATE_WIDTH_FACTOR / (1 + INDETERMINATE_WIDTH_FACTOR);
export default class ProgressBar extends Component {
static propTypes = {
animated: PropTypes.bool,
borderColor: PropTypes.string,
borderRadius: PropTypes.number,
borderWidth: PropTypes.number,
children: PropTypes.node,
color: PropTypes.string,
height: PropTypes.number,
indeterminate: PropTypes.bool,
progress: PropTypes.number,
style: View.propTypes.style,
unfilledColor: PropTypes.string,
width: PropTypes.number,
};
static defaultProps = {
animated: true,
borderRadius: 4,
borderWidth: 1,
color: 'rgba(0, 122, 255, 1)',
height: 6,
indeterminate: false,
progress: 0,
width: 150,
};
constructor(props) {
super(props);
const progress = Math.min(Math.max(props.progress, 0), 1);
this.state = {
progress: new Animated.Value(props.indeterminate ? INDETERMINATE_WIDTH_FACTOR : progress),
animationValue: new Animated.Value(BAR_WIDTH_ZERO_POSITION),
};
}
componentDidMount() {
if (this.props.indeterminate) {
this.animate();
}
}
componentWillReceiveProps(props) {
if (props.indeterminate !== this.props.indeterminate) {
if (props.indeterminate) {
this.animate();
} else {
Animated.spring(this.state.animationValue, {
toValue: BAR_WIDTH_ZERO_POSITION,
}).start();
}
}
if (
props.indeterminate !== this.props.indeterminate ||
props.progress !== this.props.progress
) {
const progress = (props.indeterminate
? INDETERMINATE_WIDTH_FACTOR
: Math.min(Math.max(props.progress, 0), 1)
);
if (props.animated) {
Animated.spring(this.state.progress, {
toValue: progress,
bounciness: 0,
}).start();
} else {
this.state.progress.setValue(progress);
}
}
}
animate() {
this.state.animationValue.setValue(0);
Animated.timing(this.state.animationValue, {
toValue: 1,
duration: 1000,
easing: Easing.linear,
isInteraction: false,
}).start((endState) => {
if (endState.finished) {
this.animate();
}
});
}
render() {
const {
borderColor,
borderRadius,
borderWidth,
children,
color,
height,
style,
unfilledColor,
width,
...restProps
} = this.props;
const innerWidth = width - (borderWidth * 2);
const containerStyle = {
width,
borderWidth,
borderColor: borderColor || color,
borderRadius,
overflow: 'hidden',
backgroundColor: unfilledColor,
};
const progressStyle = {
backgroundColor: color,
height,
width: innerWidth,
transform: [{
translateX: this.state.animationValue.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth * -INDETERMINATE_WIDTH_FACTOR, innerWidth],
}),
}, {
translateX: this.state.progress.interpolate({
inputRange: [0, 1],
outputRange: [innerWidth / -2, 0],
}),
}, {
scaleX: this.state.progress,
}],
};
return (
<View style={[containerStyle, style]} {...restProps}>
<Animated.View style={progressStyle} />
{children}
</View>
);
}
}
| fengshanjian/react-native-komect-uikit | src/Progress/Bar.js | JavaScript | mit | 3,584 |
import './accounts-config.js';
import './i18n.js';
import './routes.js';
import '../../ui/iso3d/phaser-plugin-isometric.min.js';
| Albilab/jeu-environnemental | imports/startup/client/index.js | JavaScript | mit | 130 |
const basicJson = require('./basic.json')
export const jsonExport = {
basicJson
}
| ericwooley/jsonable | tests/files/json-include.json.js | JavaScript | mit | 85 |
/*
* wjquery.calendar 0.1.1
* by composite ([email protected])
* http://www.wonchu.net
* This project licensed under a MIT License.
0.1.0 : 최초작성
0.1.1 : 소스정리
*/
(function ($) {
const WCALENDAR_SV = {
ns: "wcalendar",
dateFormat: "YYYYMMDD",
lang: {
ko: {
week: ["일", "월", "화", "수", "목", "금", "토"]
}
}
};
$.fn.wcalendar = function (method) {
let result, _arguments = arguments;
this.each(function (i, element) {
const $element = $(element);
let $container,
_option = {};
if ($element.prop("tagName").toLowerCase() == "input") {
if ($element.attr("data-wrap-id")) {
$container = $("#" + $element.attr("data-wrap-id"));
} else {
const _id = "wcalendar_" + new Date().getTime();
$element.after("<div id=\"" + _id + "\" />");
_option.element = $element;
$element.attr("data-wrap-id", _id);
$container = $("#" + _id);
}
} else {
$container = $element;
}
const plugin = $container.data(WCALENDAR_SV.ns);
if (plugin && typeof method === 'string') {
if (plugin[method]) {
result = plugin[method].apply(this, Array.prototype.slice.call(_arguments, 1));
} else {
alert('Method ' + method + ' does not exist on jQuery.wcalendar');
}
} else if (!plugin && (typeof method === 'object' || !method)) {
let wcalendar = new WCALENDAR();
$container.data(WCALENDAR_SV.ns, wcalendar);
wcalendar.init($container, $.extend(_option, $.fn.wcalendar.defaultSettings, method || {}));
}
});
return result ? result : $(this);
};
$.fn.wcalendar.defaultSettings = {
width: "200px",
locale: "ko",
dateFormat: "YYYY.MM.DD",
showPrevNextDays: true,
dateIconClass: "wcalendar-dateicon",
mdHoliday: {
"0101": {
ko: "신정"
},
"0505": {
ko: "어린이날"
}
},
holiday: {
"20210519": {
ko: "부처님오신날"
}
}
};
function WCALENDAR() {
let $container, options;
function init(_container, _options) {
$container = _container;
options = _options;
if (options.selectDate) {
options.selectDate = moment(options.selectDate, options.dateFormat);
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
} else {
options.selectDate = moment();
}
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.init($container, options);
}
function draw() {
_WCALENDAR.draw($container, options);
}
function prev() {
options.targetDate = options.targetDate.add(-1, "months");
_WCALENDAR.draw($container, options);
}
function next() {
options.targetDate = options.targetDate.add(1, "months");
_WCALENDAR.draw($container, options);
}
function set(dt) {
options.targetDate = moment(dt, options.dateFormat);
_WCALENDAR.draw($container, options);
}
function select() {
options.targetDate = moment($(".wcalendar-month .title-year", $container).val() + $.pad($(".wcalendar-month .title-month", $container).val(), 2) + "01", "YYYYMMDD");
_WCALENDAR.draw($container, options);
}
function click() {
const _index = $(".wcalendar-undock").index($container);
$(".wcalendar-undock").each(function () {
if ($(".wcalendar-undock").index(this) != _index && $(this).is(":visible")) {
$(this).hide();
}
});
if ($container.is(":visible")) {
$container.hide();
} else {
if (options.element && options.element.val() != "") {
options.selectDate = moment(options.element.val(), options.dateFormat);
options.hasVal = "Y";
} else {
options.selectDate = moment();
options.hasVal = "N";
}
options.targetDate = options.selectDate.clone();
_WCALENDAR.draw($container, options);
$container.show();
}
}
function destory() {
if (options.element) {
options.element.removeClass("wcalendar-input");
if (options.element.next("." + options.dateIconClass)) {
options.element.next("." + options.dateIconClass).remove();
}
}
$container.remove();
}
return {
init: init,
draw: draw,
prev: prev,
next: next,
set: set,
select: select,
click: click,
destory: destory
};
}
var _WCALENDAR = {
init: function ($container, options) {
if (options.element) {
options.element.addClass("wcalendar-input");
$container.addClass("wcalendar-undock").css({
"top": options.element.position().top + options.element.outerHeight(),
"left": options.element.position().left,
"width": options.width
});
const $icon = $("<span class=\"" + options.dateIconClass + "\" />");
options.element.after($icon);
$icon.click(function () {
$container.wcalendar("click");
});
options.element.click(function () {
$container.wcalendar("click");
});
$(document).on("click.wcalendar-undock", function (event) {
if ($(event.target).closest(".wcalendar-wrap, .wcalendar-input, ." + options.dateIconClass).length === 0) {
$container.hide();
}
});
}
$container.html(
"<div class=\"wcalendar-wrap\">" +
" <div class=\"wcalendar-month\">" +
" <ul>" +
" <li class=\"prev\"><a href=\"javascript:;\"><span>❮</span></a></li>" +
" <li class=\"next\"><a href=\"javascript:;\"><span>❯</span></a></li>" +
" <li><select class=\"title-year\"></select> <select class=\"title-month\"></select></li>" +
" </ul>" +
" </div>" +
" <ul class=\"wcalendar-weekdays\"></ul>" +
" <ul class=\"wcalendar-days\"></ul>" +
"</div>"
);
this.draw($container, options);
$(".wcalendar-month li>a", $container).click(function () {
$container.wcalendar($(this).parent().attr("class"));
});
$container.find(".wcalendar-days").on("click", "a", function () {
var $t = $(this);
$t.parent().siblings().find("a.active").removeClass("active");
$t.addClass("active");
if (options.callback) {
options.callback($(this).attr("data-val"));
} else if (options.element) {
options.element.val($(this).attr("data-val"));
$container.hide();
}
});
},
draw: function ($container, options) {
const curentDate = moment(),
selectDate = options.selectDate,
targetDate = options.targetDate,
firstDate = targetDate.clone().startOf("month"),
lastDate = targetDate.clone().endOf("month");
let _prevDate, _targetDate, _nextDate;
this.makeSelectOption($(".wcalendar-month .title-year", $container), targetDate.year() - 10, targetDate.year() + 10, targetDate.year());
this.makeSelectOption($(".wcalendar-month .title-month", $container), 1, 12, options.targetDate.month() + 1);
$(".wcalendar-month .title-month, .wcalendar-month .title-year", $container).off("change").on("change", function () {
$container.wcalendar("select");
});
let _weekdays = [];
for (let n = 0; n < 7; n++) {
_weekdays.push("<li>" + WCALENDAR_SV.lang[options.locale].week[n] + "</li>");
}
$container.find(".wcalendar-weekdays").empty().append(_weekdays.join(""));
let _days = [];
for (let i = firstDate.day(); i > 0; i--) {
if (options.showPrevNextDays) {
_prevDate = firstDate.clone().add(-i, "days");
_days.push(this.makeItem(options, "prev", _prevDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
for (let j = 0; j < lastDate.date(); j++) {
_targetDate = firstDate.clone().add(j, "days");
_days.push(this.makeItem(options, "target", _targetDate, curentDate, selectDate));
}
for (let k = 1; k <= (6 - lastDate.day()); k++) {
if (options.showPrevNextDays) {
_nextDate = lastDate.clone().add(k, "days");
_days.push(this.makeItem(options, "next", _nextDate, curentDate, selectDate));
} else {
_days.push("<li> </li>");
}
}
$container.find(".wcalendar-days").empty().append(_days.join(""));
},
makeItem: function (options, mode, dt, dt2, dt3) {
let classNames = [],
titles = [],
_classNames = "",
_titles = "";
const dtf = dt.format(WCALENDAR_SV.dateFormat),
dtfmd = dt.format("MMDD"),
dtf2 = dt2.format(WCALENDAR_SV.dateFormat),
dtf3 = dt3.format(WCALENDAR_SV.dateFormat);
classNames.push(mode);
if (dtf2 == dtf) {
classNames.push("today");
}
if (dtf3 == dtf ) {
if(options.hasVal && options.hasVal=="N"){
//nothing
}else{
classNames.push("active");
}
}
if (options.mdHoliday && options.mdHoliday[dtfmd]) {
classNames.push("md-holiday");
titles.push(options.mdHoliday[dtfmd][options.locale]);
}
if (options.holiday && options.holiday[dtf]) {
classNames.push("holiday");
titles.push(options.holiday[dtf][options.locale]);
}
if (classNames.length > 0) {
_classNames = " class=\"" + (classNames.join(" ")) + "\"";
}
if (titles.length > 0) {
_titles = " title=\"" + (titles.join(" ")) + "\"";
}
return "<li>" +
" <a href=\"javascript:;\" data-val=\"" + dt.format(options.dateFormat) + "\"" + _titles + _classNames + ">" + dt.date() + "</a>" +
"</li>";
},
makeSelectOption: function ($t, start, end, v) {
let _options = [];
for (let i = start; i <= end; i++) {
_options.push("<option value=\"" + i + "\"" + (i == v ? " selected=\"selected\"" : "") + ">" + i + "</option>");
}
$t.empty().append(_options.join(""));
}
}
})(jQuery); | bibaboo/bibaboo.github.com | js/lib/wjquery/wjquery.calendar.js | JavaScript | mit | 12,657 |
describe("OCombo:", function () {
var wtest, $p;
beforeEach(function () {
wtest = frames[0];
$p = wtest.$p;
});
it("Конствуктор должен возвращать объект типа OCombo", function () {
expect(typeof $p).toBe("object");
});
}); | oknosoft/metadata.js | spec/tests/_wdg_spec.js | JavaScript | mit | 275 |
import { exec } from "child_process"
import test from "tape"
import cliBin from "./utils/cliBin"
test("--watch error if no input files", (t) => {
exec(
`${ cliBin }/testBin --watch`,
(err, stdout, stderr) => {
t.ok(
err,
"should return an error when <input> or <output> are missing when " +
"`--watch` option passed"
)
t.ok(
stderr.includes("--watch requires"),
"should show an explanation when <input> or <output> are missing when" +
" `--watch` option passed"
)
t.end()
}
)
})
| MoOx/cli-for-files | src/__tests__/watcher.error-no-input.js | JavaScript | mit | 579 |
var searchData=
[
['t',['T',['../all__17_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): all_17.js'],['../all__8_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): all_8.js'],['../enumvalues__7_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): enumvalues_7.js'],['../functions__3_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): functions_3.js'],['../functions__7_8js.html#adf1f3edb9115acb0a1e04209b7a9937b',1,'T(): functions_7.js']]],
['t_5ff',['t_f',['../classvo.html#a59a051419df095f766905047916cf7a0',1,'vo']]],
['test_5f2main_5f8cpp',['test_2main_8cpp',['../test__2main__8cpp_8js.html#a616ce37741695e70aeb42c09bf11e83d',1,'test_2main_8cpp.js']]],
['test_5f8cpp',['test_8cpp',['../test__8cpp_8js.html#ac745c2a6c95dd92c7473e1d8486549bf',1,'test_8cpp.js']]],
['tokenize_5f8py',['tokenize_8py',['../tokenize__8py_8js.html#a29054f8eaff39510a045bf811b069903',1,'tokenize_8py.js']]],
['toprint',['ToPrint',['../classes__6_8js.html#ad81a47989c7025eaa75cb3cd6c05ca66',1,'classes_6.js']]]
];
| bhargavipatel/808X_VO | docs/html/search/variables_13.js | JavaScript | mit | 1,034 |
(function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['de_LU@euro'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
"postal_fmt": "%f%N%a%N%d%N%b%N%s %h %e %r%N%z %T%N%c%N",
"country_name": "Luxemburg",
"country_post": null,
"country_ab2": "LU",
"country_ab3": "LUX",
"country_num": 442,
"country_car": "L",
"country_isbn": null,
"lang_name": "Deutsch",
"lang_ab": "de",
"lang_term": "deu",
"lang_lib": "ger"
},
"LC_MEASUREMENT": {
"measurement": 1
},
"LC_MESSAGES": {
"yesexpr": "^[+1jJyY]",
"noexpr": "^[-0nN]",
"yesstr": "ja",
"nostr": "nein"
},
"LC_MONETARY": {
"currency_symbol": "\u20ac",
"mon_decimal_point": ",",
"mon_thousands_sep": ".",
"mon_grouping": [
3,
3
],
"positive_sign": "",
"negative_sign": "-",
"frac_digits": 2,
"p_cs_precedes": 1,
"p_sep_by_space": 1,
"n_cs_precedes": 1,
"n_sep_by_space": 1,
"p_sign_posn": 4,
"n_sign_posn": 4,
"int_curr_symbol": "EUR ",
"int_frac_digits": 2,
"int_p_cs_precedes": null,
"int_p_sep_by_space": null,
"int_n_cs_precedes": null,
"int_n_sep_by_space": null,
"int_p_sign_posn": null,
"int_n_sign_posn": null
},
"LC_NAME": {
"name_fmt": "%d%t%g%t%m%t%f",
"name_gen": null,
"name_mr": null,
"name_mrs": null,
"name_miss": null,
"name_ms": null
},
"LC_NUMERIC": {
"decimal_point": ",",
"thousands_sep": ".",
"grouping": [
3,
3
]
},
"LC_PAPER": {
"height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l",
"tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "352"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"So",
"Mo",
"Di",
"Mi",
"Do",
"Fr",
"Sa"
],
"day": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"week": [
7,
19971130,
4
],
"abmon": [
"Jan",
"Feb",
"M\u00e4r",
"Apr",
"Mai",
"Jun",
"Jul",
"Aug",
"Sep",
"Okt",
"Nov",
"Dez"
],
"mon": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"d_t_fmt": "%a %d %b %Y %T %Z",
"d_fmt": "%Y-%m-%d",
"t_fmt": "%T",
"am_pm": [
"",
""
],
"t_fmt_ampm": "",
"era": null,
"era_year": null,
"era_d_t_fmt": null,
"era_d_fmt": null,
"era_t_fmt": null,
"alt_digits": null,
"first_weekday": 2,
"first_workday": null,
"cal_direction": null,
"timezone": null
}
};
}));
| jsor/locale-data | data/[email protected] | JavaScript | mit | 4,447 |
// TODO: Add tests
import passport from 'passport';
import { OAuth2Strategy as GoogleStrategy } from 'passport-google-oauth';
import authConfig from '../credentials.json';
import init from '../init';
import { upsert } from '../../lib/util';
function passportInit() {
// serialize user into the session
init();
passport.use(new GoogleStrategy(
authConfig.google,
(accessToken, refreshToken, profile, done) => {
const params = {
email: profile.emails[0].value,
external_auth_type: 'google',
};
const data = {
first_name: profile.name.givenName,
last_name: profile.name.familyName,
email: profile.emails.length && profile.emails[0].value,
photo_url: profile.photos.length && profile.photos[0].value,
external_auth_type: 'google',
external_auth_id: profile.id,
};
upsert('/users', params, data)
.then(resp => done(null, resp))
.catch(err => done(err));
},
));
}
passportInit();
export default passport;
| harsh376/Hector | src/server/auth/strategies/google.js | JavaScript | mit | 1,036 |
var React = require('react');
var _ = require('underscore');
var List = React.createClass({
render: function() {
var listItems = [];
_.each(this.props.value, function(data, index) {
listItems.push(<li>{JSON.stringify(data)}</li>);
});
return (
<div>
<strong>{this.props.title}:</strong>
<ol>{listItems}</ol>
</div>
);
}
});
module.exports = List; | jmather/scope.js | client/components/Displays/List.react.js | JavaScript | mit | 466 |
var Helper = require("@kaoscript/runtime").Helper;
module.exports = function() {
var path = require("path");
require("../require/require.string.ks")(Helper.cast(path.join(__dirname, "foobar.txt"), "String", false, null, "String"));
}; | kaoscript/kaoscript | test/fixtures/compile/import/import.parameter.expression.default.js | JavaScript | mit | 236 |
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
});
$scope.orderProp = 'age';
}]);
phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http',
function($scope, $routeParams, $http) {
$http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
$scope.phone = data;
$scope.mainImageUrl = data.images[0];
});
$scope.setImage = function(imageUrl) {
$scope.mainImageUrl = imageUrl;
}
}]);
| dlamoureux/angularaxa | app/js/controllers.js | JavaScript | mit | 696 |
var elixir = require('laravel-elixir');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
elixir(function(mix) {
mix.scriptsIn('resources/assets/js/');
}); | Beyond-Game/Raffaello | gulpfile.js | JavaScript | mit | 572 |
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/views/Home.vue';
import Sms from '@/views/SMS.vue';
import Services from '@/views/Services.vue';
import Settings from '@/views/Settings.vue';
import Wlan from '@/views/settings/wlan.vue';
import DialUp from '@/views/settings/dialup.vue';
import AppSettings from '@/views/AppSettings.vue';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
redirect: { name: 'home' },
},
{
path: '/home',
name: 'home',
component: Home,
},
{
path: '/sms',
name: 'sms',
component: Sms,
},
{
path: '/statistics',
name: 'statistics',
},
{
path: '/services',
name: 'services',
component: Services,
},
{
path: '/settings',
name: 'settings',
component: Settings,
redirect: { name: 'settings/wlan' },
children: [
{
path: 'wlan',
name: 'settings/wlan',
component: Wlan,
label: 'WLAN',
},
{
path: 'dialup',
name: 'settings/dialup',
component: DialUp,
label: 'Dial-up',
},
],
},
{
path: '/app-settings',
name: 'appSettings',
component: AppSettings,
},
],
});
| nextgensparx/quantum-router | src/vue-router/index.js | JavaScript | mit | 1,330 |
const Promise = require('bluebird');
const fs = require('fs-extra');
const debug = require('ghost-ignition').debug('api:themes');
const common = require('../../lib/common');
const themeService = require('../../services/themes');
const settingsCache = require('../../services/settings/cache');
const models = require('../../models');
module.exports = {
docName: 'themes',
browse: {
permissions: true,
query() {
return themeService.toJSON();
}
},
activate: {
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
let checkedTheme;
const newSettings = [{
key: 'active_theme',
value: themeName
}];
const loadedTheme = themeService.list.get(themeName);
if (!loadedTheme) {
return Promise.reject(new common.errors.ValidationError({
message: common.i18n.t('notices.data.validation.index.themeCannotBeActivated', {themeName: themeName}),
errorDetails: newSettings
}));
}
return themeService.validate.checkSafe(loadedTheme)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
// @NOTE: we use the model, not the API here, as we don't want to trigger permissions
return models.Settings.edit(newSettings, frame.options);
})
.then(() => {
debug('Activating theme (method B on API "activate")', themeName);
themeService.activate(loadedTheme, checkedTheme);
return themeService.toJSON(themeName, checkedTheme);
});
}
},
upload: {
headers: {},
permissions: {
method: 'add'
},
query(frame) {
// @NOTE: consistent filename uploads
frame.options.originalname = frame.file.originalname.toLowerCase();
let zip = {
path: frame.file.path,
name: frame.file.originalname,
shortName: themeService.storage.getSanitizedFileName(frame.file.originalname.split('.zip')[0])
};
let checkedTheme;
// check if zip name is casper.zip
if (zip.name === 'casper.zip') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.overrideCasper')
});
}
return themeService.validate.checkSafe(zip, true)
.then((_checkedTheme) => {
checkedTheme = _checkedTheme;
return themeService.storage.exists(zip.shortName);
})
.then((themeExists) => {
// CASE: delete existing theme
if (themeExists) {
return themeService.storage.delete(zip.shortName);
}
})
.then(() => {
// CASE: store extracted theme
return themeService.storage.save({
name: zip.shortName,
path: checkedTheme.path
});
})
.then(() => {
// CASE: loads the theme from the fs & sets the theme on the themeList
return themeService.loadOne(zip.shortName);
})
.then((loadedTheme) => {
// CASE: if this is the active theme, we are overriding
if (zip.shortName === settingsCache.get('active_theme')) {
debug('Activating theme (method C, on API "override")', zip.shortName);
themeService.activate(loadedTheme, checkedTheme);
// CASE: clear cache
this.headers.cacheInvalidate = true;
}
common.events.emit('theme.uploaded');
// @TODO: unify the name across gscan and Ghost!
return themeService.toJSON(zip.shortName, checkedTheme);
})
.finally(() => {
// @TODO: we should probably do this as part of saving the theme
// CASE: remove extracted dir from gscan
// happens in background
if (checkedTheme) {
fs.remove(checkedTheme.path)
.catch((err) => {
common.logging.error(new common.errors.GhostError({err: err}));
});
}
});
}
},
download: {
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: {
method: 'read'
},
query(frame) {
let themeName = frame.options.name;
const theme = themeService.list.get(themeName);
if (!theme) {
return Promise.reject(new common.errors.BadRequestError({
message: common.i18n.t('errors.api.themes.invalidThemeName')
}));
}
return themeService.storage.serve({
name: themeName
});
}
},
destroy: {
statusCode: 204,
headers: {
cacheInvalidate: true
},
options: [
'name'
],
validation: {
options: {
name: {
required: true
}
}
},
permissions: true,
query(frame) {
let themeName = frame.options.name;
if (themeName === 'casper') {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyCasper')
});
}
if (themeName === settingsCache.get('active_theme')) {
throw new common.errors.ValidationError({
message: common.i18n.t('errors.api.themes.destroyActive')
});
}
const theme = themeService.list.get(themeName);
if (!theme) {
throw new common.errors.NotFoundError({
message: common.i18n.t('errors.api.themes.themeDoesNotExist')
});
}
return themeService.storage.delete(themeName)
.then(() => {
themeService.list.del(themeName);
});
}
}
};
| Gargol/Ghost | core/server/api/v2/themes.js | JavaScript | mit | 7,109 |
import React, {PropTypes, Component} from 'react';
import { NavGroup } from 'react-photonkit'
/*class NavGroup extends Component {
static propTypes = {
children: PropTypes.any
}
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<nav className="nav-group">
{this.props.children}
</nav>
);
}
}*/
export default NavGroup
| z81/PolarOS_Next | src/components/Elements/NavGroup/NavGroup.js | JavaScript | mit | 397 |
var Vector;
(function (Vector) {
function clean(n) {
var vector = [];
for (var i = 0; i < n; i++) {
vector[i] = 0;
}
return vector;
}
Vector.clean = clean;
function create() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i - 0] = arguments[_i];
}
var vector = [];
for (var i = 0; i < values.length; i++) {
vector[i] = values[i];
}
return vector;
}
Vector.create = create;
function dot(vec1, vec2) {
var dot = 0;
for (var i = 0; i < vec1.length; i++) {
dot += vec1[i] * vec2[i];
}
return dot;
}
Vector.dot = dot;
function magnitude(vec) {
return Math.sqrt(Vector.dot(vec, vec));
}
Vector.magnitude = magnitude;
function angle(vec1, vec2) {
return Math.acos(Vector.dot(vec1, vec2) / (Vector.magnitude(vec1) * Vector.magnitude(vec2)));
}
Vector.angle = angle;
var Vec2;
(function (Vec2) {
function clean() {
return [0, 0];
}
Vec2.clean = clean;
function create(x, y) {
return [x, y];
}
Vec2.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1];
}
Vec2.dot = dot;
})(Vec2 = Vector.Vec2 || (Vector.Vec2 = {}));
var Vec3;
(function (Vec3) {
function clean() {
return [0, 0, 0];
}
Vec3.clean = clean;
function create(x, y, z) {
return [x, y, z];
}
Vec3.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2];
}
Vec3.dot = dot;
})(Vec3 = Vector.Vec3 || (Vector.Vec3 = {}));
var Vec4;
(function (Vec4) {
function clean() {
return [0, 0, 0, 0];
}
Vec4.clean = clean;
function create(x, y, z, w) {
return [x, y, z, w];
}
Vec4.create = create;
function dot(vec1, vec2) {
return vec1[0] * vec2[0] + vec1[1] * vec2[1] + vec1[2] * vec2[2] + vec1[3] * vec2[3];
}
Vec4.dot = dot;
})(Vec4 = Vector.Vec4 || (Vector.Vec4 = {}));
})(Vector || (Vector = {}));
var Matrix;
(function (Matrix) {
function clean(size) {
return Vector.clean(size * size);
}
Matrix.clean = clean;
function identity(size) {
var mat = [];
for (var i = 0; i < size * size; i++) {
mat[i] = (Math.floor(i / size) - i % size) == 0 ? 1 : 0;
}
return mat;
}
Matrix.identity = identity;
function copy(mat) {
return mat.slice();
}
Matrix.copy = copy;
function getRow(mat, row) {
var size = Matrix.size(mat);
var vec = [];
for (var i = 0; i < size; i++) {
vec[i] = mat[row + i * size];
}
return vec;
}
Matrix.getRow = getRow;
function getColom(mat, colom) {
var size = Matrix.size(mat);
var vec = [];
for (var i = 0; i < size; i++) {
vec[i] = mat[colom * size + i];
}
return vec;
}
Matrix.getColom = getColom;
function getValue(mat, row, colom) {
var size = Matrix.size(mat);
return mat[row + colom * size];
}
Matrix.getValue = getValue;
function setRow(mat, row, value) {
var size = Matrix.size(mat);
for (var i = 0; i < size; i++) {
mat[row + i * size] = value[i];
}
return mat;
}
Matrix.setRow = setRow;
function setColom(mat, colom, value) {
var size = Matrix.size(mat);
for (var i = 0; i < size; i++) {
mat[colom * size + i] = value[i];
}
return mat;
}
Matrix.setColom = setColom;
function setvalue(mat, row, colom, value) {
var size = Matrix.size(mat);
mat[row + colom * size] = value;
return mat;
}
Matrix.setvalue = setvalue;
function size(mat) {
return Math.sqrt(mat.length);
}
Matrix.size = size;
function getTranspose(mat) {
var size = Matrix.size(mat);
var matOut = Matrix.clean(size);
for (var i = 0; i < size; i++) {
Matrix.setColom(matOut, i, Matrix.getRow(mat, i));
}
return matOut;
}
Matrix.getTranspose = getTranspose;
var Mat4;
(function (Mat4) {
function identity() {
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
Mat4.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[4] * mat2[1] + mat1[8] * mat2[2] + mat1[12] * mat2[3],
mat1[1] * mat2[0] + mat1[5] * mat2[1] + mat1[9] * mat2[2] + mat1[13] * mat2[3],
mat1[2] * mat2[0] + mat1[6] * mat2[1] + mat1[10] * mat2[2] + mat1[14] * mat2[3],
mat1[3] * mat2[0] + mat1[7] * mat2[1] + mat1[11] * mat2[2] + mat1[15] * mat2[3],
mat1[0] * mat2[4] + mat1[4] * mat2[5] + mat1[8] * mat2[6] + mat1[12] * mat2[7],
mat1[1] * mat2[4] + mat1[5] * mat2[5] + mat1[9] * mat2[6] + mat1[13] * mat2[7],
mat1[2] * mat2[4] + mat1[6] * mat2[5] + mat1[10] * mat2[6] + mat1[14] * mat2[7],
mat1[3] * mat2[4] + mat1[7] * mat2[5] + mat1[11] * mat2[6] + mat1[15] * mat2[7],
mat1[0] * mat2[8] + mat1[4] * mat2[9] + mat1[8] * mat2[10] + mat1[12] * mat2[11],
mat1[1] * mat2[8] + mat1[5] * mat2[9] + mat1[9] * mat2[10] + mat1[13] * mat2[11],
mat1[2] * mat2[8] + mat1[6] * mat2[9] + mat1[10] * mat2[10] + mat1[14] * mat2[11],
mat1[3] * mat2[8] + mat1[7] * mat2[9] + mat1[11] * mat2[10] + mat1[15] * mat2[11],
mat1[0] * mat2[12] + mat1[4] * mat2[13] + mat1[8] * mat2[14] + mat1[12] * mat2[15],
mat1[1] * mat2[12] + mat1[5] * mat2[13] + mat1[9] * mat2[14] + mat1[13] * mat2[15],
mat1[2] * mat2[12] + mat1[6] * mat2[13] + mat1[10] * mat2[14] + mat1[14] * mat2[15],
mat1[3] * mat2[12] + mat1[7] * mat2[13] + mat1[11] * mat2[14] + mat1[15] * mat2[15]
];
}
Mat4.mul = mul;
function translate(p1, p2, p3) {
if (typeof p3 == "number") {
var x = p2;
var y = p3;
var mat = p1;
var newColom = Vector.Vec4.create(mat[0] * x + mat[4] * y + mat[12], mat[1] * x + mat[5] * y + mat[13], mat[2] * x + mat[6] * y + mat[14], mat[3] * x + mat[7] * y + mat[15]);
return setColom(mat, 3, newColom);
}
else {
var x = p1;
var y = p2;
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1];
}
}
Mat4.translate = translate;
function scale(p1, p2, p3) {
if (typeof p3 == "number") {
var width = p2;
var height = p3;
var mat = p1;
var newColom1 = Vector.Vec4.create(mat[0] * width, mat[1] * width, mat[2] * width, mat[3] * width);
var newColom2 = Vector.Vec4.create(mat[4] * height, mat[5] * height, mat[6] * height, mat[7] * height);
setColom(mat, 0, newColom1);
setColom(mat, 1, newColom2);
return mat;
}
else {
var width = p1;
var height = p2;
return [width, 0, 0, 0, 0, height, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
}
Mat4.scale = scale;
function rotate(p1, p2) {
if (typeof p2 == "number") {
var rad = p2;
var mat = p1;
var newColom1 = Vector.Vec4.create(mat[0] * Math.cos(rad) + mat[4] * Math.sin(rad), mat[1] * Math.cos(rad) + mat[5] * Math.sin(rad), mat[2] * Math.cos(rad) + mat[6] * Math.sin(rad), mat[3] * Math.cos(rad) + mat[7] * Math.sin(rad));
var newColom2 = Vector.Vec4.create(mat[0] * -Math.sin(rad) + mat[4] * Math.cos(rad), mat[1] * -Math.sin(rad) + mat[5] * Math.cos(rad), mat[2] * -Math.sin(rad) + mat[6] * Math.cos(rad), mat[3] * -Math.sin(rad) + mat[7] * Math.cos(rad));
setColom(mat, 0, newColom1);
setColom(mat, 1, newColom2);
return mat;
}
else {
var rad = p1;
return [Math.cos(rad), Math.sin(rad), 0, 0, -Math.sin(rad), Math.cos(rad), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
}
}
Mat4.rotate = rotate;
function ortho(left, right, bottom, top) {
return [2 / (right - left), 0, 0, 0, 0, 2 / (top - bottom), 0, 0, 0, 0, -2 / (-1 - 1), 0, -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(-1 + 1) / (-1 - 1), 1];
}
Mat4.ortho = ortho;
})(Mat4 = Matrix.Mat4 || (Matrix.Mat4 = {}));
var Mat3;
(function (Mat3) {
function identity() {
return [1, 0, 0, 0, 1, 0, 0, 0, 1];
}
Mat3.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[3] * mat2[1] + mat1[6] * mat2[2],
mat1[1] * mat2[0] + mat1[4] * mat2[1] + mat1[7] * mat2[2],
mat1[2] * mat2[0] + mat1[5] * mat2[1] + mat1[8] * mat2[2],
mat1[0] * mat2[3] + mat1[3] * mat2[4] + mat1[6] * mat2[5],
mat1[1] * mat2[3] + mat1[4] * mat2[4] + mat1[7] * mat2[5],
mat1[2] * mat2[3] + mat1[5] * mat2[4] + mat1[8] * mat2[5],
mat1[0] * mat2[6] + mat1[3] * mat2[7] + mat1[6] * mat2[8],
mat1[1] * mat2[6] + mat1[4] * mat2[7] + mat1[7] * mat2[8],
mat1[2] * mat2[6] + mat1[5] * mat2[7] + mat1[8] * mat2[8],
];
}
Mat3.mul = mul;
})(Mat3 = Matrix.Mat3 || (Matrix.Mat3 = {}));
var Mat2;
(function (Mat2) {
function identity() {
return [1, 0, 0, 1];
}
Mat2.identity = identity;
function mul(mat1, mat2) {
return [
mat1[0] * mat2[0] + mat1[2] * mat2[1],
mat1[1] * mat2[0] + mat1[3] * mat2[1],
mat1[0] * mat2[2] + mat1[2] * mat2[3],
mat1[1] * mat2[2] + mat1[3] * mat2[3],
];
}
Mat2.mul = mul;
})(Mat2 = Matrix.Mat2 || (Matrix.Mat2 = {}));
})(Matrix || (Matrix = {}));
var MMath;
(function (MMath) {
var SEED = 0;
var TO_RAD = (Math.PI * 2) / 360;
var TO_DEG = 360 / (Math.PI * 2);
function setRandomSeed(seed) {
SEED = seed;
}
MMath.setRandomSeed = setRandomSeed;
function random(min, max) {
if (min === void 0) { min = 0; }
if (max === void 0) { max = 1; }
SEED = (SEED * 9301 + 49297) % 233280;
var rnd = SEED / 233280;
return min + rnd * (max - min);
}
MMath.random = random;
function toRad(deg) {
return deg * TO_RAD;
}
MMath.toRad = toRad;
function toDeg(rad) {
return rad * TO_DEG;
}
MMath.toDeg = toDeg;
function mod(num, max) {
return ((num % max) + max) % max;
}
MMath.mod = mod;
function logN(base, num) {
return Math.log(num) / Math.log(base);
}
MMath.logN = logN;
function isPowerOf2(n) {
if (n == 0)
return false;
else
return (n & (n - 1)) == 0;
}
MMath.isPowerOf2 = isPowerOf2;
})(MMath || (MMath = {}));
//# sourceMappingURL=math.js.map | Rikmuld/Atlas | public/scripts/libs/plena/math.js | JavaScript | mit | 11,693 |
'use strict';
/*!
* V4Fire Client Core
* https://github.com/V4Fire/Client
*
* Released under the MIT license
* https://github.com/V4Fire/Client/blob/master/LICENSE
*/
const
$C = require('collection.js');
const
{getThemes} = include('build/ds'),
{getThemedPathChunks, checkDeprecated} = include('build/stylus/ds/helpers');
/**
* Returns a function to register Stylus plugins by the specified options
*
* @param {DesignSystem} ds - design system object prepared to use with Stylus
* @param {!Object} cssVariables - dictionary of CSS variables
* @param {boolean=} [useCSSVarsInRuntime] - true, if the design system object values provided
* to style files as css-variables
*
* @param {string=} [theme] - current theme value
* @param {(Array<string>|boolean)=} [includeThemes] - list of themes to include or
* `true` (will include all available themes)
*
* @param {Object=} [stylus] - link to a Stylus package instance
* @returns {!Function}
*/
module.exports = function getPlugins({
ds,
cssVariables,
useCSSVarsInRuntime,
theme,
includeThemes,
stylus = require('stylus')
}) {
const
isBuildHasTheme = Object.isString(theme),
themedFields = $C(ds).get('meta.themedFields') || undefined;
let
buildThemes = includeThemes;
if (!buildThemes) {
buildThemes = isBuildHasTheme ? [theme] : [];
}
const
themesList = getThemes(ds.raw, buildThemes),
isThemesIncluded = themesList != null && themesList.length > 0,
isOneTheme = Object.isArray(themesList) && themesList.length === 1 && themesList[0] === theme;
if (!isThemesIncluded) {
if (Object.isString(theme)) {
console.log(`[stylus] Warning: the design system package has no theme "${theme}"`);
}
if (includeThemes != null) {
console.log(
`[stylus] Warning: the design system package has no themes for the provided "includeThemes" value: "${includeThemes}"`
);
}
}
const
isFieldThemed = (name) => Object.isArray(themedFields) ? themedFields.includes(name) : true;
return function addPlugins(api) {
/**
* Injects additional options to component mixin options ($p)
*
* @param {string} string - component name
* @returns {!Object}
*
* @example
* ```stylus
* injector('bButton')
*
* // If `useCSSVarsInRuntime` is enabled
* //
* // {
* // values: {
* // mods: {
* // size: {
* // s: {
* // offset: {
* // top: 'var(--bButton-mods-size-s-offset-top)'
* // }
* // }
* // }
* // }
* // }
*
* // Otherwise
* //
* // {
* // values: {
* // mods: {
* // size: {
* // s: {
* // offset: {
* // top: 5px
* // }
* // }
* // }
* // }
* // }
* ```
*/
api.define('injector', ({string}) => {
const
values = $C(useCSSVarsInRuntime || isThemesIncluded ? cssVariables : ds).get(`components.${string}`);
if (values) {
const
__diffVars__ = $C(cssVariables).get(`diff.components.${string}`);
return stylus.utils.coerce({
values,
__diffVars__
}, true);
}
return {};
});
/**
* Returns design system CSS variables with their values
*
* @param {string} [theme]
* @returns {!Object}
*
* @example
* ```stylus
* getDSVariables()
*
* // {
* // '--colors-primary': #0F9
* // }
* ```
*/
api.define('getDSVariables', ({string: theme} = {}) => {
const
obj = {},
iterator = Object.isString(theme) ? cssVariables.map[theme] : cssVariables.map;
Object.forEach(iterator, (val) => {
const [key, value] = val;
obj[key] = value;
});
return stylus.utils.coerce(obj, true);
});
/**
* Returns a value from the design system by the specified group and path.
* If passed only the first argument, the function returns parameters for the whole group,
* but not just the one value. If no arguments are passed, it returns the whole design system object.
*
* @param {string} [group] - first level field name (colors, rounding, etc.)
* @param {!Object} [path] - dot-delimited path to the value
* @returns {!Object}
*
* @example
* ```stylus
* getDSValue(colors "green.0") // rgba(0, 255, 0, 1)
* ```
*/
api.define('getDSValue', ({string: group} = {}, {string: path} = {}) => {
if (group === undefined) {
return ds;
}
checkDeprecated(ds, group);
const
getCSSVar = () => $C(cssVariables).get([].concat([group], path || []).join('.'));
if (isOneTheme || !isBuildHasTheme) {
return useCSSVarsInRuntime ?
stylus.utils.coerce(getCSSVar()) :
$C(ds).get([].concat(getThemedPathChunks(group, theme, isFieldThemed(group)), path || []).join('.'));
}
return stylus.utils.coerce(getCSSVar());
});
/**
* Returns an object with text styles for the specified style name
*
* @param {string} name
* @returns {!Object}
*
* @example
* ```stylus
* getDSTextStyles(Small)
*
* // Notice, all values are Stylus types
* //
* // {
* // fontFamily: 'Roboto',
* // fontWeight: 400,
* // fontSize: '14px',
* // lineHeight: '16px'
* // }
* ```
*/
api.define('getDSTextStyles', ({string: name}) => {
const
head = 'text',
isThemed = isFieldThemed(head),
path = [...getThemedPathChunks(head, theme, isThemed), name];
checkDeprecated(ds, path);
if (!isOneTheme && isThemesIncluded && isThemed) {
const
initial = $C(ds).get(path);
if (!Object.isDictionary(initial)) {
throw new Error(`getDSTextStyles: the design system has no "${theme}" styles for the specified name: ${name}`);
}
const
res = {};
Object.forEach(initial, (value, key) => {
res[key] = $C(cssVariables).get([head, name, key]);
});
return stylus.utils.coerce(res, true);
}
const
from = useCSSVarsInRuntime ? cssVariables : ds;
return stylus.utils.coerce($C(from).get(path), true);
});
/**
* Returns color(s) from the design system by the specified name and identifier (optional)
*
* @param {!Object} name
* @param {!Object} [id]
* @returns {(!Object|!Array)}
*
* @example
* ```stylus
* getDSColor("blue", 1) // rgba(0, 0, 255, 1)
* ```
*/
api.define('getDSColor', (name, id) => {
name = name.string || name.name;
if (!name) {
return;
}
const
path = isOneTheme ? getThemedPathChunks('colors', theme, isFieldThemed('colors')) : ['colors'];
if (id) {
id = id.string || id.val;
if (Object.isNumber(id)) {
id -= 1;
}
}
path.push(name);
if (id !== undefined) {
path.push(String(id));
}
checkDeprecated(ds, path);
return isThemesIncluded || useCSSVarsInRuntime ?
stylus.utils.coerce($C(cssVariables).get(path)) :
$C(ds).get(path);
});
/**
* Returns the current theme value
* @returns {!string}
*/
api.define('defaultTheme', () => theme);
/**
* Returns a list of available themes
* @returns {!Array<string>}
*/
api.define('availableThemes', () => themesList);
};
};
| V4Fire/Client | build/stylus/ds/plugins.js | JavaScript | mit | 7,150 |
var model = require('model');
var adapter = require('./..').adapter;
var Issue = function () {
this.adapter = adapter;
this.property('assignees','string');
this.property('htmlUrl','string');
this.property('number','number');
this.property('state','string');
this.property('title','string');
this.property('body','string');
this.property('user','object');
this.property('labels','object');
this.property('assignee','object');
this.property('milestone','object');
this.property('comments','number');
this.property('pullRequest','object');
this.property('closedAt','date');
this.property('createdAt','date');
this.property('updatedAt','date');
this.property('trckrState','string');
this.property('trckrLastReview','date');
this.property('trckrPingback','string'); // ping me back in a specific future
};
model.register('Issue', Issue); | diasdavid/issue-tracker | db/models/meta.js | JavaScript | mit | 873 |
"use strict";
const RandomStrategy = require("../../../src/strategies/random");
const { extendExpect } = require("../utils");
extendExpect(expect);
describe("Test RandomStrategy", () => {
it("test with empty opts", () => {
const strategy = new RandomStrategy();
const list = [
{ a: "hello" },
{ b: "world" },
];
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
expect(strategy.select(list)).toBeAnyOf(list);
});
});
| ice-services/moleculer | test/unit/strategies/random.spec.js | JavaScript | mit | 489 |
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication',
function($scope, Authentication) {
// This provides Authentication context.
$scope.authentication = Authentication;
$scope.alerts = [
{
icon: 'glyphicon-user',
colour: 'btn-success',
total: '20,408',
description: 'TOTAL CUSTOMERS'
},
{
icon: 'glyphicon-calendar',
colour: 'btn-primary',
total: '8,382',
description: 'UPCOMING EVENTS'
},
{
icon: 'glyphicon-edit',
colour: 'btn-success',
total: '527',
description: 'NEW CUSTOMERS IN 24H'
},
{
icon: 'glyphicon-record',
colour: 'btn-info',
total: '85,000',
description: 'EMAILS SENT'
},
{
icon: 'glyphicon-eye-open',
colour: 'btn-warning',
total: '268',
description: 'FOLLOW UPS REQUIRED'
},
{
icon: 'glyphicon-flag',
colour: 'btn-danger',
total: '348',
description: 'REFERRALS TO MODERATE'
}
];
}
]); | jamesynz/mapp | public/modules/core/controllers/home.client.controller.js | JavaScript | mit | 952 |
var Vector = function(values) {
// An N-Dimensional vector.
//
// Args:
// values: A list of values for each dimension of the vector.
var self = this;
self.values = values;
self.hash = function() {
// Generate a hash of the vector.
//
// Returns:
// A hash of the vector.
var r = '';
var i;
for (i = 0; i < self.values.length; i++) {
r += String(self.values[i]) + ','
}
return '[' + r + ']';
};
self.copy = function() {
// Get a duplicate vector.
return (new Vector(self.values.slice()));
};
self.divide = function(c) {
// Divide the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value divided by c.
return self.multiply(1 / c);
};
self.multiply = function(c) {
// Multiply the vector by a constant.
//
// Args:
// c: A constant.
//
// Returns:
// A new vector with each value multiplied by c.
var copy = self.copy();
var i;
for (i = 0; i < self.values.length; i++) {
copy.values[i] *= c;
}
return copy;
};
self.add = function(other) {
// Add another vector to self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot add two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] + other.values[i]);
}
return (new Vector(values));
};
self.subtract = function(other) {
// Subtract another vector from self.
//
// Args:
// other: Another vector.
//
// Returns:
// The resultant vector from other to self.
var values = [];
var i;
if (self.dimension() != other.dimension()) {
var msg = "Cannot subtract two vectors of different dimensionality.";
log(loglevel.error, msg);
throw (new Error(msg));
}
for (i = 0; i < self.values.length; i++) {
values.push(self.values[i] - other.values[i]);
}
return (new Vector(values));
};
self.dimension = function() {
// Get the dimension of the vector.
return self.values.length;
};
self.magnitude = function() {
// Get the magnitude of this vector.
var s = 0;
var i;
var dimension = self.dimension();
for (i = 0; i < self.values.length; i++) {
s += Math.pow(self.values[i], dimension)
}
return Math.pow(s, 1 / dimension);
};
self.unit = function() {
// Get a unit vector in the direction of this vector.
return self.divide(self.magnitude());
};
};
| astex/nbody.js | vector.js | JavaScript | mit | 2,770 |
/**
* Plugin Name: Autocomplete for Textarea
* Author: Amir Harel
* Copyright: amir harel ([email protected])
* Twitter: @amir_harel
* Version 1.4
* Published at : http://www.amirharel.com/2011/03/07/implementing-autocomplete-jquery-plugin-for-textarea/
*/
(function($){
/**
* @param obj
* @attr wordCount {Number} the number of words the user want to for matching it with the dictionary
* @attr mode {String} set "outter" for using an autocomplete that is being displayed in the outter layout of the textarea, as opposed to inner display
* @attr on {Object} containing the followings:
* @attr query {Function} will be called to query if there is any match for the user input
*/
$.fn.autocomplete = function(obj){
if( typeof $.browser.msie != 'undefined' ) obj.mode = 'outter';
this.each(function(index,element){
if( element.nodeName == 'TEXTAREA' ){
makeAutoComplete(element,obj);
}
});
}
var browser = {isChrome: $.browser.webkit };
function getTextAreaSelectionEnd(ta) {
var textArea = ta;//document.getElementById('textarea1');
if (document.selection) { //IE
var bm = document.selection.createRange().getBookmark();
var sel = textArea.createTextRange();
sel.moveToBookmark(bm);
var sleft = textArea.createTextRange();
sleft.collapse(true);
sleft.setEndPoint("EndToStart", sel);
return sleft.text.length + sel.text.length;
}
return textArea.selectionEnd; //ff & chrome
}
function getDefaultCharArray(){
return {
'`':0,
'~':0,
'1':0,
'!':0,
'2':0,
'@':0,
'3':0,
'#':0,
'4':0,
'$':0,
'5':0,
'%':0,
'6':0,
'^':0,
'7':0,
'&':0,
'8':0,
'*':0,
'9':0,
'(':0,
'0':0,
')':0,
'-':0,
'_':0,
'=':0,
'+':0,
'q':0,
'Q':0,
'w':0,
'W':0,
'e':0,
'E':0,
'r':0,
'R':0,
't':0,
'T':0,
'y':0,
'Y':0,
'u':0,
'U':0,
'i':0,
'I':0,
'o':0,
'O':0,
'p':0,
'P':0,
'[':0,
'{':0,
']':0,
'}':0,
'a':0,
'A':0,
's':0,
'S':0,
'd':0,
'D':0,
'f':0,
'F':0,
'g':0,
'G':0,
'h':0,
'H':0,
'j':0,
'J':0,
'k':0,
'K':0,
'l':0,
'L':0,
';':0,
':':0,
'\'':0,
'"':0,
'\\':0,
'|':0,
'z':0,
'Z':0,
'x':0,
'X':0,
'c':0,
'C':0,
'v':0,
'V':0,
'b':0,
'B':0,
'n':0,
'N':0,
'm':0,
'M':0,
',':0,
'<':0,
'.':0,
'>':0,
'/':0,
'?':0,
' ':0
};
}
function setCharSize(data){
for( var ch in data.chars ){
if( ch == ' ' ) $(data.clone).html("<span id='test-width_"+data.id+"' style='line-block'> </span>");
else $(data.clone).html("<span id='test-width_"+data.id+"' style='line-block'>"+ch+"</span>");
var testWidth = $("#test-width_"+data.id).width();
data.chars[ch] = testWidth;
}
}
var _data = {};
var _count = 0;
function makeAutoComplete(ta,obj){
_count++;
_data[_count] = {
id:"auto_"+_count,
ta:ta,
wordCount:obj.wordCount,
wrap: obj.wrap,
on:obj.on,
clone:null,
lineHeight:0,
list:null,
charInLines:{},
mode:obj.mode,
chars:getDefaultCharArray()};
var clone = createClone(_count);
_data[_count].clone = clone;
setCharSize(_data[_count]);
//_data[_count].lineHeight = $(ta).css("font-size");
_data[_count].list = createList(_data[_count]);
registerEvents(_data[_count]);
}
function createList(data){
var ul = document.createElement("ul");
$(ul).addClass("auto-list");
document.body.appendChild(ul);
return ul;
}
function createClone(id){
var data = _data[id];
var div = document.createElement("div");
var offset = $(data.ta).offset();
offset.top = offset.top - parseInt($(data.ta).css("margin-top"));
offset.left = offset.left - parseInt($(data.ta).css("margin-left"));
//console.log("createClone: offset.top=",offset.top," offset.left=",offset.left);
$(div).css({
position:"absolute",
top: offset.top,
left: offset.left,
"overflow-x" : "hidden",
"overflow-y" : "hidden",
"z-index" : -10
});
data.chromeWidthFix = (data.ta.clientWidth - $(data.ta).width());
data.lineHeight = $(data.ta).css("line-height");
if( isNaN(parseInt(data.lineHeight)) ) data.lineHeight = parseInt($(data.ta).css("font-size"))+2;
document.body.appendChild(div);
return div;
}
function getWords(data){
var selectionEnd = getTextAreaSelectionEnd(data.ta);//.selectionEnd;
var text = data.ta.value;
text = text.substr(0,selectionEnd);
if( text.charAt(text.length-1) == ' ' || text.charAt(text.length-1) == '\n' ) return "";
var ret = [];
var wordsFound = 0;
var pos = text.length-1;
while( wordsFound < data.wordCount && pos >= 0 && text.charAt(pos) != '\n'){
ret.unshift(text.charAt(pos));
pos--;
if( text.charAt(pos) == ' ' || pos < 0 ){
wordsFound++;
}
}
return ret.join("");
}
function showList(data,list,text){
if( !data.listVisible ){
data.listVisible = true;
var pos = getCursorPosition(data);
$(data.list).css({
left: pos.left+"px",
top: pos.top+"px",
display: "block"
});
}
var html = "";
var regEx = new RegExp("("+text+")");
var taWidth = $(data.ta).width()-5;
var width = data.mode == "outter" ? "style='width:"+taWidth+"px;'" : "";
for( var i=0; i< list.length; i++ ){
//var a = list[i].replace(regEx,"<mark>$1</mark>");
html += "<li data-value='"+list[i]+"' "+width+">"+list[i].replace(regEx,"<mark>$1</mark>")+"</li>";
}
$(data.list).html(html);
}
function breakLines(text,data){
var lines = [];
var width = $(data.clone).width();
var line1 = "";
var line1Width = 0;
var line2Width = 0;
var line2 = "";
var chSize = data.chars;
var len = text.length;
for( var i=0; i<len; i++){
var ch = text.charAt(i);
line2 += ch.replace(" "," ");
var size = (typeof chSize[ch] == 'undefined' ) ? 0 : chSize[ch];
line2Width += size;
if( ch == ' '|| ch == '-' ){
if( line1Width + line2Width < width-1 ){
line1 = line1 + line2;
line1Width = line1Width + line2Width;
line2 = "";
line2Width = 0;
}
else{
lines.push(line1);
line1= line2;
line1Width = line2Width;
line2= "";
line2Width = 0;
}
}
if( ch == '\n'){
if( line1Width + line2Width < width-1 ){
lines.push(line1 + line2);
}
else{
lines.push(line1);
lines.push(line2);
}
line1 = "";
line2 = "";
line1Width = 0;
line2Width = 0;
}
//else{
//line2 += ch;
//}
}
if( line1Width + line2Width < width-1 ){
lines.push(line1 + line2);
}
else{
lines.push(line1);
lines.push(line2);
}
return lines;
}
function getCursorPosition(data){
if( data.mode == "outter" ){
return getOuterPosition(data);
}
//console.log("getCursorPosition: ta width=",$(data.ta).css("width")," ta clientWidth=",data.ta.clientWidth, "scrollWidth=",data.ta.scrollWidth," offsetWidth=",data.ta.offsetWidth," jquery.width=",$(data.ta).width());
if( browser.isChrome ){
$(data.clone).width(data.ta.clientWidth-data.chromeWidthFix);
}
else{
$(data.clone).width(data.ta.clientWidth);
}
var ta = data.ta;
var selectionEnd = getTextAreaSelectionEnd(data.ta);
var text = ta.value;//.replace(/ /g," ");
var subText = text.substr(0,selectionEnd);
var restText = text.substr(selectionEnd,text.length);
var lines = breakLines(subText,data);//subText.split("\n");
var miror = $(data.clone);
miror.html("");
for( var i=0; i< lines.length-1; i++){
miror.append("<div style='height:"+(parseInt(data.lineHeight))+"px"+";'>"+lines[i]+"</div>");
}
miror.append("<span id='"+data.id+"' style='display:inline-block;'>"+lines[lines.length-1]+"</span>");
miror.append("<span id='rest' style='max-width:'"+data.ta.clientWidth+"px'>"+restText.replace(/\n/g,"<br/>")+" </span>");
miror.get(0).scrollTop = ta.scrollTop;
var span = miror.children("#"+data.id);
var offset = span.offset();
return {top:offset.top+span.height(),left:offset.left+span.width()};
}
function getOuterPosition(data){
var offset = $(data.ta).offset();
return {top:offset.top+$(data.ta).height()+8,left:offset.left};
}
function hideList(data){
if( data.listVisible ){
$(data.list).css("display","none");
data.listVisible = false;
}
}
function setSelected(dir,data){
var selected = $(data.list).find("[data-selected=true]");
if( selected.length != 1 ){
if( dir > 0 ) $(data.list).find("li:first-child").attr("data-selected","true");
else $(data.list).find("li:last-child").attr("data-selected","true");
return;
}
selected.attr("data-selected","false");
if( dir > 0 ){
selected.next().attr("data-selected","true");
}
else{
selected.prev().attr("data-selected","true");
}
}
function getCurrentSelected(data){
var selected = $(data.list).find("[data-selected=true]");
if( selected.length == 1) return selected.get(0);
return null;
}
function onUserSelected(li,data){
var seletedText = $(li).attr("data-value");
var selectionEnd = getTextAreaSelectionEnd(data.ta);//.selectionEnd;
var text = data.ta.value;
text = text.substr(0,selectionEnd);
//if( text.charAt(text.length-1) == ' ' || text.charAt(text.length-1) == '\n' ) return "";
//var ret = [];
var wordsFound = 0;
var pos = text.length-1;
while( wordsFound < data.wordCount && pos >= 0 && text.charAt(pos) != '\n'){
//ret.unshift(text.charAt(pos));
pos--;
if( text.charAt(pos) == ' ' || pos < 0 ){
wordsFound++;
}
}
var a = data.ta.value.substr(0,pos+1);
var c = data.ta.value.substr(selectionEnd,data.ta.value.length);
var scrollTop = data.ta.scrollTop;
if(data.wrap.length > 0){
seletedText = "["+data.wrap+"]"+seletedText+"[/"+data.wrap+"] ";
}
data.ta.value = a+seletedText+c;
data.ta.scrollTop = scrollTop;
data.ta.selectionEnd = pos+1+seletedText.length;
hideList(data);
$(data.ta).focus();
}
function registerEvents(data){
$(data.list).delegate("li","click",function(e){
var li = this;
onUserSelected(li,data);
e.stopPropagation();
e.preventDefault();
return false;
});
$(data.ta).blur(function(e){
setTimeout(function(){
hideList(data);
},400);
});
$(data.ta).click(function(e){
hideList(data);
});
$(data.ta).keydown(function(e){
//console.log("keydown keycode="+e.keyCode);
if( data.listVisible ){
switch(e.keyCode){
case 13:
case 40:
case 38:
e.stopImmediatePropagation();
e.preventDefault();
return false;
case 27: //esc
hideList(data);
}
}
});
$(data.ta).keyup(function(e){
if( data.listVisible ){
//console.log("keCode=",e.keyCode);
if( e.keyCode == 40 ){//down key
setSelected(+1,data);
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
if( e.keyCode == 38 ){//up key
setSelected(-1,data);
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
if( e.keyCode == 13 ){//enter key
var li = getCurrentSelected(data);
if( li ){
e.stopImmediatePropagation();
e.preventDefault();
hideList(data);
onUserSelected(li,data);
return false;
}
hideList(data);
}
if( e.keyCode == 27 ){
e.stopImmediatePropagation();
e.preventDefault();
return false;
}
}
switch( e.keyCode ){
case 27:
return true;
}
var text = getWords(data);
//console.log("getWords return ",text);
if( text != "" ){
data.on.query(text,function(list){
//console.log("got list = ",list);
if( list.length ){
showList(data,list,text);
}
else{
hideList(data);
}
});
}
else{
hideList(data);
}
});
$(data.ta).scroll(function(e){
var ta = e.target;
var miror = $(data.clone);
miror.get(0).scrollTop = ta.scrollTop;
});
}
})(jQuery);
| tygarimew/Mana-Haven | global/js/auto_suggest.js | JavaScript | mit | 12,043 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = fn;
var _includes = require('utilise/includes');
var _includes2 = _interopRequireDefault(_includes);
var _client = require('utilise/client');
var _client2 = _interopRequireDefault(_client);
var _all = require('utilise/all');
var _all2 = _interopRequireDefault(_all);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// register custom element prototype (render is automatic)
function fn(ripple) {
return function (res) {
if (!customs || !customEl(res) || registered(res)) return (0, _all2.default)(res.name + ':not([inert])\n ,[is="' + res.name + '"]:not([inert])').map(ripple.draw);
var proto = Object.create(HTMLElement.prototype),
opts = { prototype: proto };
proto.attachedCallback = ripple.draw;
document.registerElement(res.name, opts);
};
}
var registered = function registered(res) {
return document.createElement(res.name).attachedCallback;
};
var customs = _client2.default && !!document.registerElement,
customEl = function customEl(d) {
return (0, _includes2.default)('-')(d.name);
}; | lems111/bittrex-node-client | node_modules/rijs/node_modules/rijs.components/dist/types/fn.js | JavaScript | mit | 1,205 |
'use strict';
/* jshint -W098 */
angular.module('mean.rules').controller('RulesController', ['$scope', '$stateParams', '$location', '$http','Global', 'Rules', 'MeanUser','Circles','Groups',
function($scope, $stateParams, $location, $http, Global, Rules, MeanUser,Circles,Groups) {
$scope.global = Global;
$scope.rules = {};
$scope.rule = {};
$scope.groups={};
$scope.sortType = 'name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchFish = ''; // set the default search/filter term
$scope.hasAuthorization = function(rule) {
if (!rule || !rule.user) return false;
return MeanUser.isAdmin || rule.user._id === MeanUser.user._id;
};
$scope.popup1 = {
opened: false
};
$scope.testdataerror=false;
$scope.popup2 = {
opened: false
};
$scope.testdataresult='';
$scope.openpicker1 = function() {
$scope.popup1.opened = true;
};
$scope.openpicker2 = function() {
$scope.popup2.opened = true;
};
$scope.availableCircles = [];
Circles.mine(function(acl) {
$scope.availableCircles = acl.allowed;
$scope.allDescendants = acl.descendants;
});
$scope.showDescendants = function(permission) {
var temp = $('.ui-select-container .btn-primary').text().split(' ');
temp.shift(); //remove close icon
var selected = temp.join(' ');
$scope.descendants = $scope.allDescendants[selected];
};
$scope.selectPermission = function() {
$scope.descendants = [];
};
$scope.create = function(isValid) {
if (isValid) {
// $scope.article.permissions.push('test test');
var rule = new Rules($scope.rule);
rule.$save(function(response) {
$location.path('rules/' + response._id);
});
$scope.rules = {};
} else {
$scope.submitted = true;
}
};
$scope.remove = function(rule) {
if (rule) {
rule.$remove(function(response) {
for (var i in $scope.rules) {
if ($scope.rules[i] === rule) {
$scope.rules.splice(i, 1);
}
}
$location.path('rules');
});
} else {
$scope.rules.$remove(function(response) {
$location.path('rules');
});
}
};
$scope.update = function(isValid) {
if (isValid) {
var rule = $scope.rule;
if (!rule.updated) {
rule.updated = [];
}
rule.updated.push(new Date().getTime());
rule.$update(function() {
$location.path('rules/' + rule._id);
});
} else {
$scope.submitted = true;
}
};
$scope.findGroups = function() {
Groups.query(function(groups) {
$scope.groups = groups;
});
};
$scope.find = function() {
Rules.query(function(rules) {
$scope.rules = rules;
});
};
$scope.findOne = function() {
Rules.get({
ruleId: $stateParams.ruleId
}, function(rule) {
$scope.rule = rule;
});
};
$scope.documentupdate = function(testdata) {
$scope.testdataerror=false;
try{
testdata = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
}
}
$scope.cmdtestdata = function (testdata,execIf,execThen,execElse) {
var td={};
$scope.testdataerror=false;
try{
td = JSON.parse(testdata);
} catch (ex) {
$scope.testdataerror=true;
return;
}
$scope.testdataresult = '';
$http({
method: 'PUT',
url: '/api/rulesprocessor/testdata' ,
headers: {
'Content-Type': 'application/json'
},
data: {
"document": td,
"execIf":execIf,
"execThen":execThen,
"execElse":execElse
}
}).then(function successCallback(response) {
if (response.data === undefined) {
$scope.testdataresult = '';
} else {
$scope.testdataresult = '' +
'IF() evaluated to: ' + response.data.resExecIf.var0 +
'\nThen() evaluated to: ' + JSON.stringify(response.data.resExecThen) +
'\nElse() evaluated to: ' + JSON.stringify(response.data.resExecElse);
}
}, function errorCallback(response) {
$scope.testdataresult = 'Error: (HTTP ' + response.status + ') ' + response.data.error;
});
}
}
]); | jenavarro/AllRules | packages/custom/rules/public/controllers/rules.js | JavaScript | mit | 4,812 |
var utilities = (function(window, $){
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function topHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
/**
* Draws a rounded rectangle using the current state of the canvas.
* If you omit the last three params, it will draw a rectangle
* outline with a 5 pixel border radius
* @param {CanvasRenderingContext2D} ctx
* @param {Number} x The top left x coordinate
* @param {Number} y The top left y coordinate
* @param {Number} width The width of the rectangle
* @param {Number} height The height of the rectangle
* @param {Number} radius The corner radius. Defaults to 5;
* @param {Boolean} fill Whether to fill the rectangle. Defaults to false.
* @param {Boolean} stroke Whether to stroke the rectangle. Defaults to true.
*/
function bottomHalfRoundRect(ctx, x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined" ) {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height);
ctx.lineTo(x, y + height);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
if (stroke) {
ctx.stroke();
}
if (fill) {
ctx.fill();
}
}
return {
drawRoundRect: roundRect,
drawTopHalfRoundRect: topHalfRoundRect,
drawBottomHalfRoundRect: bottomHalfRoundRect
}
})(window, $); | paradite/GestFly | js/app/utilities.js | JavaScript | mit | 4,614 |
var c = require("./config").twitter;
var Twit = require('twit');
//console.log(c);
console.log(c.apiKey);
console.log(c.apiSecret);
console.log(c.accessToken);
console.log(c.accessTokenSecret);
var T = new Twit({
consumer_key: c.apiKey,
consumer_secret: c.apiSecret,
access_token: c.accessToken,
access_token_secret: c.accessTokenSecret
});
/*
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
console.log(err);
})
*/
//console.log(T);
//
// tweet 'hello world!'
//
T.get('search/tweets', { q: 'banana since:2011-11-11', count: 100 }, function(err, data, res) {
console.log(data);
//console.log(err);
//console.log(res);
});
| russjohnson09/rdjgvus | twit.js | JavaScript | mit | 691 |
// These are the pages you can go to.
// They are all wrapped in the App component, which should contain the navbar etc
// See http://blog.mxstbr.com/2016/01/react-apps-with-pages for more information
// about the code splitting business
import { getAsyncInjectors } from './utils/asyncInjectors';
const errorLoading = (err) => {
console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};
const loadModule = (cb) => (componentModule) => {
cb(null, componentModule.default);
};
export default function createRoutes(store) {
// create reusable async injectors using getAsyncInjectors factory
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return [
{
path: '/',
name: 'home',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/HomePage/reducer'),
import('containers/HomePage/sagas'),
import('containers/HomePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('home', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/features',
name: 'features',
getComponent(nextState, cb) {
import('containers/FeaturePage')
.then(loadModule(cb))
.catch(errorLoading);
},
}, {
path: '/login',
name: 'login',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/LoginPage/reducer'),
import('containers/LoginPage/sagas'),
import('containers/LoginPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('loginPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/signup',
name: 'signup',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/SignupPage/reducer'),
import('containers/SignupPage/sagas'),
import('containers/SignupPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('signupPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/restorepassword',
name: 'restorepassword',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/PasswordRestorePage/reducer'),
import('containers/PasswordRestorePage/sagas'),
import('containers/PasswordRestorePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('passwordRestorePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/trackingpage',
name: 'trackingpage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/TrackingPage/reducer'),
import('containers/TrackingPage/sagas'),
import('containers/TrackingPage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('trackingPage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '/userprofile',
name: 'userprofilepage',
getComponent(nextState, cb) {
const importModules = Promise.all([
import('containers/UserProfilePage/reducer'),
import('containers/UserProfilePage/sagas'),
import('containers/UserProfilePage'),
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('userProfilePage', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
},
}, {
path: '*',
name: 'notfound',
getComponent(nextState, cb) {
import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
},
},
];
}
| mikejong0815/Temp | app/routes.js | JavaScript | mit | 4,755 |
/**
* Fac.js
* (c) 2017 Owen Luke
* https://github.com/tasjs/fac
* Released under the MIT License.
*/
var copy = require('./copy');
var chain = require('./chain');
var super_ = require('./super');
var core = {
new: function(options){
typeof options === 'string' && (options = {name: options});
var obj = chain.create(this, options);
obj.protoName = this.name;
obj.model = this;
obj.super = super_;
chain.init(obj.parent, options, obj);
return obj;
},
extends: function(proto, p1){
var obj = chain.create(this, {});
var options = proto;
if (typeof p1 !== 'undefined') {
var args = Array.prototype.slice.call(arguments);
for (var i = 0, len = args.length - 1; i < len; i ++) {
options = args[i];
copy.do(obj, options);
}
options = args[i];
}
copy.do(obj, options);
obj.protoName = options.name;
obj.super = super_;
typeof options.default === 'function' && options.default.call(obj, options);
return obj;
},
ext: function(options){
copy.do(this, options);
return this;
},
spawn: function(options) {
typeof options === 'string' && (options = {name: options});
var obj = Object.create(this);
copy.do(obj, options);
chain.init(this, options, obj);
return obj;
},
isChildOf: function(obj){
return chain.isChildOf(obj, this);
},
isParentOf: function(obj){
return chain.isParentOf(obj, this);
},
isAncestorOf: function(obj){
return chain.isAncestorOf(obj, this);
},
isDescendantOf: function(obj){
return chain.isDescendantOf(obj, this);
},
isModelOf: function(obj){
return this === obj.model;
},
isCopyOf: function(obj){
return this.model === obj;
}
};
module.exports = core;
| tasjs/fac | lib/core/core.js | JavaScript | mit | 1,691 |
const express = require('express');
const path = require('path');
const fs = require('fs');
const bodyParser = require('body-parser')
// const formidable = require('formidable');
// const createTorrent = require('create-torrent');
// const WebTorrent = require('webtorrent');
const socketController = require('./socketController');
// max # of sockets to keep open
const socketLimit = 1;
// takes in Node Server instance and returns Express Router
module.exports = function nileServer(server) {
// Pass server instance to use socket controller
const socket = new socketController(server, socketLimit);
// create nile.js mini-app through express Router
const nileServer = express.Router();
// endpoint for receiving magnet URI from Broadcaster
nileServer.post('/magnet', (req, res, next) => {
socket.emitNewMagnet(req.body.magnetURI);
res.sendStatus(200);
});
return nileServer;
} | jpmitchellpierson/nile.js | nileServer.js | JavaScript | mit | 907 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.