code
stringlengths
2
1.05M
const { app } = require('electron') const globalEmitter = require('../lib/globalEmitter') module.exports = () => { const gotTheLock = app.requestSingleInstanceLock() if (!gotTheLock) { app.quit() } else { globalEmitter.emit('showWindow') } }
(function() { 'use strict'; angular.module('fallout4CoolTools.components.ui.icons', [ 'ngMdIcons' ]); })();
// buffer 对象的实例化,遍历,切片操作,toJSON 操作 var buf = new Buffer(256); buf[0] = 23; for(var i=0; i<256; i++) buf[i] = i; console.log(buf); var end = buf.slice(200, 256); console.log(end); console.log(buf.toJSON());
import React from 'react'; import { render } from 'react-dom'; import { createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import { createBrowserHistory as createHistory } from 'history'; import { createRouter } from 'redux-url'; import reducer from './reducer'; import App from './App'; const routes = { '/': 'HOME', '/todos/:id': ({ id }, { status }) => ({ type: 'CHANGE_TODO', payload: { id, status } }), '*': 'NOT_FOUND' }; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const router = createRouter(routes, createHistory()); const store = createStore( reducer, composeEnhancers( applyMiddleware(router), ) ); router.sync(); render( <Provider store={store}> <App /> </Provider>, document.getElementById('app') );
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.7.3.1-2 description: Number.prototype, initial value is the Number prototype object includes: [runTestCase.js] ---*/ function testcase() { // assume that Number.prototype has not been modified. return Object.getPrototypeOf(new Number(42))===Number.prototype; } runTestCase(testcase);
import moment from 'moment-timezone' import sinon from 'sinon' import { getActiveOrder, getOrderFormPrice, getOrderList, getOrderedMeals, getUnconfirmedOrder } from '../' describe('Order selectors', () => { let clock beforeEach(() => { clock = sinon.useFakeTimers(moment('2016-01-02T00:00:00Z').toDate()) }) afterEach(() => { clock.restore() }) it('getUnconfirmedOrder returns order that is not confirmed, not paid and not cancelled', () => { expect(getUnconfirmedOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [ { id: 5, price: 90 }, { id: 6, price: 110 } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } }, orders: { list: { data: [ { id: 100, confirmed: false, paid: false, cancelled: false } ] } } })).toEqual({ assigned: false, accomodation: null, cancelled: false, confirmed: false, id: 100, meals: [], paid: false, workshop: null, year: null }) }) it('getUnconfirmedOrder ignores orders that are confirmed, not paid and not cancelled', () => { expect(getUnconfirmedOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [ { id: 5, price: 90 }, { id: 6, price: 110 } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } }, orders: { list: { data: [ { id: 100, confirmed: true, paid: false, cancelled: false } ] } } })).toEqual(null) }) it('getUnconfirmedOrder ignores orders that are not confirmed, paid and not cancelled', () => { expect(getUnconfirmedOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [ { id: 5, price: 90 }, { id: 6, price: 110 } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } }, orders: { list: { data: [ { id: 100, confirmed: false, paid: true, cancelled: false } ] } } })).toEqual(null) }) it('getUnconfirmedOrder ignores orders that are not confirmed, not paid and cancelled', () => { expect(getUnconfirmedOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [ { id: 5, price: 90 }, { id: 6, price: 110 } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } }, orders: { list: { data: [ { id: 100, confirmed: false, paid: false, cancelled: true } ] } } })).toEqual(null) }) it('getOrderFormPrice returns zero price with expired workshop', () => { expect(getOrderFormPrice({ forms: { order: { values: { workshop: 17 } } }, food: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [ { id: 17, lectors: [], prices: [ { id: 10, price: 200, price_level: 1 }, { id: 10, price: 400, price_level: 2 } ] } ] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(0) }) it('getOrderFormPrice returns zero price with no workshop', () => { expect(getOrderFormPrice({ forms: { order: { values: {} } }, food: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, participants: { detail: {} }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(0) }) it('getOrderFormPrice returns zero price with unknown workshop', () => { expect(getOrderFormPrice({ forms: { order: { values: { workshop: 19 } } }, food: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, participants: { detail: {} }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(0) }) it('getOrderFormPrice returns zero price with empty meals', () => { expect(getOrderFormPrice({ forms: { order: { values: { meals: [] } } }, food: { list: { data: [] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(0) }) it('getOrderFormPrice returns zero price with unknown meals', () => { expect(getOrderFormPrice({ forms: { order: { values: { meals: [5, 9] } } }, food: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, participants: { detail: {} }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(0) }) it('getOrderFormPrice returns price with meals', () => { expect(getOrderFormPrice({ form: { FORM_ORDER: { values: { meals: [5, 6] } } }, food: { list: { data: [ { id: 5, price: 90 }, { id: 6, price: 110 } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [] } ] } } })).toBe(200) }) it('getOrderFormPrice returns unexpired workshop price', () => { expect(getOrderFormPrice({ form: { FORM_ORDER: { values: { workshop: 17 } } }, food: { list: { data: [] } }, workshops: { difficulties: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [ { id: 17, lectors: [], prices: [ { id: 10, price: 200, price_level: 1 }, { id: 10, price: 400, price_level: 2 } ] } ] } }, years: { capacity: { data: {} }, list: { data: [ { id: 1, current: true, year: '2016', priceLevels: [ { id: 1, name: 'Zlevněná cena', takesEffectOn: '2016-01-01T00:00:00Z' }, { id: 2, name: 'Základní cena', takesEffectOn: '2016-01-02T00:00:00Z' } ] } ] } }, participants: { detail: {} } })).toBe(400) }) it('getOrderedMeals returns empty array without order', () => { expect(getOrderedMeals({ food: { list: { data: [ { id: 1, name: 'lunch', date: '2016-04-03', foods: [ { id: 1 }, { id: 2 } ], soup: [ { id: 100 }, { id: 200 } ] }, { id: 2, name: 'lunch', date: '2016-04-03', foods: [ { id: 3 }, { id: 4 } ], soup: [ { id: 300 }, { id: 400 } ] } ] } }, accomodation: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: [] }, list: { data: [] } }, orders: { list: { data: [] } }, participants: { detail: {} } })).toEqual([]) }) it('getOrderedMeals returns meals with groupped food', () => { expect(getOrderedMeals({ food: { list: { data: [ { id: 1, name: 'lunch', date: '2016-04-03', food: [ { id: 1 }, { id: 2 } ], soups: [ { id: 100 }, { id: 200 } ] }, { id: 2, name: 'lunch', date: '2016-04-03', food: [ { id: 3 }, { id: 4 } ], soups: [ { id: 300 }, { id: 400 } ] } ] } }, accomodation: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: [] }, list: { data: [ { id: 4, year: '2018' } ] } }, orders: { list: { data: [ { id: 10, year: 4, reservation: { id: 17, mealReservation: [ { id: 90, meal: 1, food: 1, soup: 200 }, { id: 90, meal: 2, food: 4, soup: 400 } ] } } ] } }, participants: { detail: {} } })).toEqual([ { id: 1, name: 'lunch', date: '2016-04-03', orderedFood: { id: 1 }, orderedSoup: { id: 200 }, food: [ { id: 1 }, { id: 2 } ], soups: [ { id: 100 }, { id: 200 } ] }, { id: 2, name: 'lunch', date: '2016-04-03', orderedFood: { id: 4 }, orderedSoup: { id: 400 }, food: [ { id: 3 }, { id: 4 } ], soups: [ { id: 300 }, { id: 400 } ] } ]) }) it('getOrderedMeals returns strips away unknown foods', () => { expect(getOrderedMeals({ food: { list: { data: [ { id: 1, name: 'lunch', date: '2016-04-03', food: [ { id: 1 }, { id: 2 } ], soups: [ { id: 100 }, { id: 200 } ] } ] } }, accomodation: { list: { data: [] } }, workshops: { difficulties: { data: [] }, list: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } } }, years: { capacity: { data: [] }, list: { data: [ { id: 4, year: '2018' } ] } }, orders: { list: { data: [ { id: 10, year: 4, reservation: { id: 17, mealReservation: [ { id: 90, meal: 1, food: 1, soup: 200 }, { id: 90, meal: 2, food: 4, soup: 400 } ] } } ] } }, participants: { detail: {} } })).toEqual([ { id: 1, name: 'lunch', date: '2016-04-03', orderedFood: { id: 1 }, orderedSoup: { id: 200 }, food: [ { id: 1 }, { id: 2 } ], soups: [ { id: 100 }, { id: 200 } ] } ]) }) it('getOrderList returns empty array when no orders are present', () => { expect(getOrderList({ accomodation: { list: { data: [] } }, orders: { list: { data: [] } }, participants: { detail: {} }, food: { list: { data: [] } }, workshops: { lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [] } }, years: { list: { data: [] }, capacity: { data: {} } } })).toEqual([]) }) it('getOrderList returns array of orders sorted by date created', () => { expect(getOrderList({ accomodation: { list: { data: [] } }, orders: { list: { data: [ { id: 15, createdAt: '2017-12-12' }, { id: 16, createdAt: '2017-12-12' }, { id: 19, createdAt: '2017-01-12' }, { id: 20, createdAt: '2017-12-13' } ] } }, participants: { detail: {} }, food: { list: { data: [] } }, workshops: { lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [] } }, years: { list: { data: [] }, capacity: { data: {} } } })).toEqual([ { accomodation: null, assigned: false, id: 20, createdAt: '2017-12-13', meals: [], workshop: null, year: null }, { accomodation: null, assigned: false, id: 15, createdAt: '2017-12-12', meals: [], workshop: null, year: null }, { accomodation: null, assigned: false, id: 16, createdAt: '2017-12-12', meals: [], workshop: null, year: null }, { accomodation: null, assigned: false, id: 19, createdAt: '2017-01-12', meals: [], workshop: null, year: null } ]) }) it('getActiveOrder returns null when there is no year', () => { expect(getActiveOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [] } }, orders: { list: { data: [] } }, participants: { detail: {} }, workshops: { lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [] } }, years: { list: { data: [] }, capacity: {} } })).toBe(null) }) it('getActiveOrder returns null when there are only cancelled orders', () => { expect(getActiveOrder({ accomodation: { list: { data: [] } }, food: { list: { data: [] } }, orders: { list: { data: [ { id: 5, year: 8, cancelled: true } ] } }, participants: { detail: {} }, workshops: { lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [] } }, years: { list: { data: [ { id: 8, year: '2018', current: true } ] }, capacity: {} } })).toBe(null) }) it('getActiveOrder latest order with aggregated data', () => { expect(getActiveOrder({ accomodation: { list: { data: [ { id: 130, name: 'Hotel' } ] } }, food: { list: { data: [ { id: 130, date: '2018-10-10', year: 8 }, { id: 131, date: '2018-10-11', year: 8 } ] } }, orders: { list: { data: [ { id: 5, year: 8, reservation: { accomodation: 130, mealReservation: [ { id: 231, meal: 130 }, { id: 232, meal: 131 } ], workshopPrice: { id: 60, price_level: 8, workshop: 13 } } } ] } }, participants: { detail: {} }, workshops: { difficulties: { data: [] }, lectors: { list: { data: [] }, roles: { data: [] } }, list: { data: [ { id: 13, name: 'Longforms', lectors: [] } ] } }, years: { list: { data: [ { id: 8, year: '2017' } ] }, capacity: {} } })).toEqual({ assigned: false, id: 5, accomodation: { capacityStatus: {}, id: 130, name: 'Hotel' }, year: { id: 8, year: '2017' }, workshop: { capacityStatus: {}, difficulty: null, id: 13, lectors: [], name: 'Longforms', prices: [] }, meals: [ { id: 130, date: '2018-10-10', year: 8 }, { id: 131, date: '2018-10-11', year: 8 } ], reservation: { accomodation: 130, mealReservation: [ { meal: 130, id: 231 }, { meal: 131, id: 232 } ], workshopPrice: { id: 60, price_level: 8, workshop: 13 } } }) }) })
/* jshint expr: true */ /* global describe */ // shim mz/fs.readFile() var pathModule = require('path'), mz = require('mz/fs'), readFile = mz.readFile; if (!readFile.shimmed) { mz.readFile = function(filename, encoding) { return readFile(pathModule.join(__dirname, 'native', filename), encoding); }; mz.readFile.shimmed = true; } // run co tests describe('Without use()', function() { require('./native/test/arguments.js') require('./native/test/arrays.js') require('./native/test/context.js') require('./native/test/generator-functions.js') require('./native/test/generators.js') require('./native/test/invalid.js') require('./native/test/objects.js') require('./native/test/promises.js') require('./native/test/recursion.js') require('./native/test/thunks.js') require('./native/test/wrap.js') });
var express = require('express'); var router = express.Router(); var request = require ('request'); var jsonString = null; var urlIDR = "https://www.quandl.com/api/v3/datasets/YAHOO/MC_IDR.json?api_key=HGoTu3E3A_Lsv6biw1kc"; request({ url: urlIDR, json: true }, function (error, response, body){ if (!error && response.statusCode == 200){ var parseo = body.dataset.data; //console.log(parseo) var jsonString=[]; for(var i = 0 ; i < parseo.length; i++){ var jsonDato={}; jsonDato.fecha = String(parseo[i][0]); jsonDato.abierto = parseFloat(parseo[i][1]); jsonDato.alto = parseFloat(parseo[i][2]); jsonDato.bajo = parseFloat(parseo[i][3]); jsonDato.cierre = parseFloat(parseo[i][4]); jsonDato.volumen = parseFloat(parseo[i][5]); jsonDato.ajuste_cierre = parseFloat(parseo[i][6]); jsonString.push(jsonDato); } var jsonArrayValor = JSON.parse(JSON.stringify(jsonString)); // var aDocs = jsonArrayValor; //console.log(jsonArrayValor); var parseo_code = body.dataset.dataset_code; var parseo_nombre = body.dataset.name; //console.log(parseo_code) //console.log(parseo_nombre) } var dato2 = []; for (var n = 0; n < jsonArrayValor.length; n++){ dato2.push([ jsonArrayValor[n]['fecha'], jsonArrayValor[n]['abierto'], jsonArrayValor[n]['alto'], jsonArrayValor[n]['bajo'], jsonArrayValor[n]['cierre'], jsonArrayValor[n]['volumen'], jsonArrayValor[n]['ajuste_cierre'] ]); } var valores00 = ([dato2 [n=0]]); var valores01 = ([dato2 [n=1]]); var valores02 = ([dato2 [n=2]]); var valores03 = ([dato2 [n=3]]); var valores04 = ([dato2 [n=4]]); var valores05 = ([dato2 [n=5]]); var valores06 = ([dato2 [n=6]]); var valores07 = ([dato2 [n=7]]); var valores08 = ([dato2 [n=8]]); var valores09 = ([dato2 [n=9]]); var valores10 = ([dato2 [n=10]]); var valores11 = ([dato2 [n=11]]); var valores12 = ([dato2 [n=12]]); var valores13 = ([dato2 [n=13]]); var valores14 = ([dato2 [n=14]]); var valores15 = ([dato2 [n=15]]); var valores16 = ([dato2 [n=16]]); var valores17 = ([dato2 [n=17]]); var valores18 = ([dato2 [n=18]]); var valores19 = ([dato2 [n=19]]); //console.log(valores00) var stockchart = []; for (var m = 0; m < jsonArrayValor.length; m++){ stockchart.push([ jsonArrayValor[m]['fecha'], jsonArrayValor[m]['abierto'], jsonArrayValor[m]['alto'], jsonArrayValor[m]['bajo'], jsonArrayValor[m]['cierre'], jsonArrayValor[m]['volumen'], jsonArrayValor[m]['ajuste_cierre'] ]); } var grafico00 = ([stockchart [m=0]]); var grafico01 = ([stockchart [m=1]]); var grafico02 = ([stockchart [m=2]]); var grafico03 = ([stockchart [m=3]]); var grafico04 = ([stockchart [m=4]]); var grafico05 = ([stockchart [m=5]]); var grafico06 = ([stockchart [m=6]]); var grafico07 = ([stockchart [m=7]]); var grafico08 = ([stockchart [m=8]]); var grafico09 = ([stockchart [m=9]]); var grafico10 = ([stockchart [m=10]]); var grafico11 = ([stockchart [m=11]]); var grafico12 = ([stockchart [m=12]]); var grafico13 = ([stockchart [m=13]]); var grafico14 = ([stockchart [m=14]]); var grafico15 = ([stockchart [m=15]]); var grafico16 = ([stockchart [m=16]]); var grafico17 = ([stockchart [m=17]]); var grafico18 = ([stockchart [m=18]]); var grafico19 = ([stockchart [m=19]]); var grafico20 = ([stockchart [m=20]]); var grafico21 = ([stockchart [m=21]]); var grafico22 = ([stockchart [m=22]]); var grafico23 = ([stockchart [m=23]]); var grafico24 = ([stockchart [m=24]]); var grafico25 = ([stockchart [m=25]]); var grafico26 = ([stockchart [m=26]]); var grafico27 = ([stockchart [m=27]]); var grafico28 = ([stockchart [m=28]]); var grafico29 = ([stockchart [m=29]]); var grafico30 = ([stockchart [m=30]]); var grafico31 = ([stockchart [m=31]]); var grafico32 = ([stockchart [m=32]]); var grafico33 = ([stockchart [m=33]]); var grafico34 = ([stockchart [m=34]]); var grafico35 = ([stockchart [m=35]]); var grafico36 = ([stockchart [m=36]]); var grafico37 = ([stockchart [m=37]]); var grafico38 = ([stockchart [m=38]]); var grafico39 = ([stockchart [m=39]]); var grafico40 = ([stockchart [m=40]]); var grafico41 = ([stockchart [m=41]]); var grafico42 = ([stockchart [m=42]]); var grafico43 = ([stockchart [m=43]]); var grafico44 = ([stockchart [m=44]]); var grafico45 = ([stockchart [m=45]]); var grafico46 = ([stockchart [m=46]]); var grafico47 = ([stockchart [m=47]]); var grafico48 = ([stockchart [m=48]]); var grafico49 = ([stockchart [m=49]]); var grafico50 = ([stockchart [m=50]]); var grafico51 = ([stockchart [m=51]]); var grafico52 = ([stockchart [m=52]]); var grafico53 = ([stockchart [m=53]]); var grafico54 = ([stockchart [m=54]]); var grafico55 = ([stockchart [m=56]]); var grafico56 = ([stockchart [m=56]]); var grafico57 = ([stockchart [m=57]]); var grafico58 = ([stockchart [m=58]]); var grafico59 = ([stockchart [m=59]]); var grafico60 = ([stockchart [m=60]]); var grafico61 = ([stockchart [m=61]]); var grafico62 = ([stockchart [m=62]]); var grafico63 = ([stockchart [m=63]]); var grafico64 = ([stockchart [m=64]]); var grafico65 = ([stockchart [m=65]]); var grafico66 = ([stockchart [m=66]]); var grafico67 = ([stockchart [m=67]]); var grafico68 = ([stockchart [m=68]]); var grafico69 = ([stockchart [m=69]]); var grafico70 = ([stockchart [m=70]]); var grafico71 = ([stockchart [m=71]]); var grafico72 = ([stockchart [m=72]]); var grafico73 = ([stockchart [m=73]]); var grafico74 = ([stockchart [m=74]]); var grafico75 = ([stockchart [m=76]]); var grafico76 = ([stockchart [m=76]]); var grafico77 = ([stockchart [m=77]]); var grafico78 = ([stockchart [m=78]]); var grafico79 = ([stockchart [m=79]]); var grafico80 = ([stockchart [m=80]]); var grafico81 = ([stockchart [m=81]]); var grafico82 = ([stockchart [m=82]]); var grafico83 = ([stockchart [m=83]]); var grafico84 = ([stockchart [m=84]]); var grafico85 = ([stockchart [m=85]]); var grafico86 = ([stockchart [m=86]]); var grafico87 = ([stockchart [m=87]]); var grafico88 = ([stockchart [m=88]]); var grafico89 = ([stockchart [m=89]]); var grafico90 = ([stockchart [m=90]]); var grafico91 = ([stockchart [m=91]]); var grafico92 = ([stockchart [m=92]]); var grafico93 = ([stockchart [m=93]]); var grafico94 = ([stockchart [m=94]]); var grafico95 = ([stockchart [m=95]]); var grafico96 = ([stockchart [m=96]]); var grafico97 = ([stockchart [m=97]]); var grafico98 = ([stockchart [m=98]]); var grafico99 = ([stockchart [m=99]]); var grafico100 = ([stockchart [m=100]]); var grafico101 = ([stockchart [m=101]]); var grafico102 = ([stockchart [m=102]]); var grafico103 = ([stockchart [m=103]]); var grafico104 = ([stockchart [m=104]]); var grafico105 = ([stockchart [m=105]]); var grafico106 = ([stockchart [m=106]]); var grafico107 = ([stockchart [m=107]]); var grafico108 = ([stockchart [m=108]]); var grafico109 = ([stockchart [m=109]]); var grafico110 = ([stockchart [m=110]]); var grafico111 = ([stockchart [m=111]]); var grafico112 = ([stockchart [m=112]]); var grafico113 = ([stockchart [m=113]]); var grafico114 = ([stockchart [m=114]]); var grafico115 = ([stockchart [m=115]]); var grafico116 = ([stockchart [m=116]]); var grafico117 = ([stockchart [m=117]]); var grafico118 = ([stockchart [m=118]]); var grafico119 = ([stockchart [m=119]]); var grafico120 = ([stockchart [m=120]]); var grafico121 = ([stockchart [m=121]]); var grafico122 = ([stockchart [m=122]]); var grafico123 = ([stockchart [m=123]]); var grafico124 = ([stockchart [m=124]]); var grafico125 = ([stockchart [m=125]]); var grafico126 = ([stockchart [m=126]]); var grafico127 = ([stockchart [m=127]]); var grafico128 = ([stockchart [m=128]]); var grafico129 = ([stockchart [m=129]]); var grafico130 = ([stockchart [m=130]]); var grafico131 = ([stockchart [m=131]]); var grafico132 = ([stockchart [m=132]]); var grafico133 = ([stockchart [m=133]]); var grafico134 = ([stockchart [m=134]]); var grafico135 = ([stockchart [m=135]]); var grafico136 = ([stockchart [m=136]]); var grafico137 = ([stockchart [m=137]]); var grafico138 = ([stockchart [m=138]]); var grafico139 = ([stockchart [m=139]]); var grafico140 = ([stockchart [m=140]]); var grafico141 = ([stockchart [m=141]]); var grafico142 = ([stockchart [m=142]]); var grafico143 = ([stockchart [m=143]]); var grafico144 = ([stockchart [m=144]]); var grafico145 = ([stockchart [m=145]]); var grafico146 = ([stockchart [m=146]]); var grafico147 = ([stockchart [m=147]]); var grafico148 = ([stockchart [m=148]]); var grafico149 = ([stockchart [m=149]]); var grafico150 = ([stockchart [m=150]]); var grafico151 = ([stockchart [m=151]]); var grafico152 = ([stockchart [m=152]]); var grafico153 = ([stockchart [m=153]]); var grafico154 = ([stockchart [m=154]]); var grafico155 = ([stockchart [m=155]]); var grafico156 = ([stockchart [m=156]]); var grafico157 = ([stockchart [m=157]]); var grafico158 = ([stockchart [m=158]]); var grafico159 = ([stockchart [m=159]]); var grafico160 = ([stockchart [m=160]]); var grafico161 = ([stockchart [m=161]]); var grafico162 = ([stockchart [m=162]]); var grafico163 = ([stockchart [m=163]]); var grafico164 = ([stockchart [m=164]]); var grafico165 = ([stockchart [m=165]]); var grafico166 = ([stockchart [m=166]]); var grafico167 = ([stockchart [m=167]]); var grafico168 = ([stockchart [m=168]]); var grafico169 = ([stockchart [m=169]]); var grafico170 = ([stockchart [m=170]]); var grafico171 = ([stockchart [m=171]]); var grafico172 = ([stockchart [m=172]]); var grafico173 = ([stockchart [m=173]]); var grafico174 = ([stockchart [m=174]]); var grafico175 = ([stockchart [m=175]]); var grafico176 = ([stockchart [m=176]]); var grafico177 = ([stockchart [m=177]]); var grafico178 = ([stockchart [m=178]]); var grafico179 = ([stockchart [m=179]]); var grafico180 = ([stockchart [m=180]]); var grafico181 = ([stockchart [m=181]]); var grafico182 = ([stockchart [m=182]]); var grafico183 = ([stockchart [m=183]]); var grafico184 = ([stockchart [m=184]]); var grafico185 = ([stockchart [m=185]]); var grafico186 = ([stockchart [m=186]]); var grafico187 = ([stockchart [m=187]]); var grafico188 = ([stockchart [m=188]]); var grafico189 = ([stockchart [m=189]]); var grafico190 = ([stockchart [m=190]]); var grafico191 = ([stockchart [m=191]]); var grafico192 = ([stockchart [m=192]]); var grafico193 = ([stockchart [m=193]]); var grafico194 = ([stockchart [m=194]]); var grafico195 = ([stockchart [m=195]]); var grafico196 = ([stockchart [m=196]]); var grafico197 = ([stockchart [m=197]]); var grafico198 = ([stockchart [m=198]]); var grafico199 = ([stockchart [m=199]]); var grafico200 = ([stockchart [m=200]]); var grafico201 = ([stockchart [m=201]]); var grafico202 = ([stockchart [m=202]]); var grafico203 = ([stockchart [m=203]]); var grafico204 = ([stockchart [m=204]]); var grafico205 = ([stockchart [m=205]]); var grafico206 = ([stockchart [m=206]]); var grafico207 = ([stockchart [m=207]]); var grafico208 = ([stockchart [m=208]]); var grafico209 = ([stockchart [m=209]]); var grafico210 = ([stockchart [m=210]]); var grafico211 = ([stockchart [m=211]]); var grafico212 = ([stockchart [m=212]]); var grafico213 = ([stockchart [m=213]]); var grafico214 = ([stockchart [m=214]]); var grafico215 = ([stockchart [m=215]]); var grafico216 = ([stockchart [m=216]]); var grafico217 = ([stockchart [m=217]]); var grafico218 = ([stockchart [m=218]]); var grafico219 = ([stockchart [m=219]]); var grafico220 = ([stockchart [m=220]]); var grafico221 = ([stockchart [m=221]]); var grafico222 = ([stockchart [m=222]]); var grafico223 = ([stockchart [m=223]]); var grafico224 = ([stockchart [m=224]]); var grafico225 = ([stockchart [m=225]]); var grafico226 = ([stockchart [m=226]]); var grafico227 = ([stockchart [m=227]]); var grafico228 = ([stockchart [m=228]]); var grafico229 = ([stockchart [m=229]]); var grafico230 = ([stockchart [m=230]]); var grafico231 = ([stockchart [m=231]]); var grafico232 = ([stockchart [m=232]]); var grafico233 = ([stockchart [m=233]]); var grafico234 = ([stockchart [m=234]]); var grafico235 = ([stockchart [m=235]]); var grafico236 = ([stockchart [m=236]]); var grafico237 = ([stockchart [m=237]]); var grafico238 = ([stockchart [m=238]]); var grafico239 = ([stockchart [m=239]]); //console.log(grafico19) router.get('/', function(req, res, next) { res.render('./home/ibex/indra', { parseo_nombre: parseo_nombre, parseo_code:parseo_code, valores00: valores00, valores01: valores01, valores02: valores02, valores03: valores03, valores04: valores04, valores05: valores05, valores06: valores06, valores07: valores07, valores08: valores08, valores09: valores09, valores10: valores10, valores11: valores11, valores12: valores12, valores13: valores13, valores14: valores14, valores15: valores15, valores16: valores16, valores17: valores17, valores18: valores18, valores19: valores19, grafico00: grafico00, grafico01: grafico01, grafico02: grafico02, grafico03: grafico03, grafico04: grafico04, grafico05: grafico05, grafico06: grafico06, grafico07: grafico07, grafico08: grafico08, grafico09: grafico09, grafico10: grafico10, grafico11: grafico11, grafico12: grafico12, grafico13: grafico13, grafico14: grafico14, grafico15: grafico15, grafico16: grafico16, grafico17: grafico17, grafico18: grafico18, grafico19: grafico19, grafico20: grafico20, grafico21: grafico21, grafico22: grafico22, grafico23: grafico23, grafico24: grafico24, grafico25: grafico25, grafico26: grafico26, grafico27: grafico27, grafico28: grafico28, grafico29: grafico29, grafico30: grafico30, grafico31: grafico31, grafico32: grafico32, grafico33: grafico33, grafico34: grafico34, grafico35: grafico35, grafico36: grafico36, grafico37: grafico37, grafico38: grafico38, grafico39: grafico39, grafico40: grafico40, grafico41: grafico41, grafico42: grafico42, grafico43: grafico43, grafico44: grafico44, grafico45: grafico45, grafico46: grafico46, grafico47: grafico47, grafico48: grafico48, grafico49: grafico49, grafico50: grafico50, grafico51: grafico51, grafico52: grafico52, grafico53: grafico53, grafico54: grafico54, grafico55: grafico55, grafico56: grafico56, grafico57: grafico57, grafico58: grafico58, grafico59: grafico59, grafico60: grafico60, grafico61: grafico61, grafico62: grafico62, grafico63: grafico63, grafico64: grafico64, grafico65: grafico65, grafico66: grafico66, grafico67: grafico67, grafico68: grafico68, grafico69: grafico69, grafico70: grafico70, grafico71: grafico71, grafico72: grafico72, grafico73: grafico73, grafico74: grafico74, grafico75: grafico75, grafico76: grafico76, grafico77: grafico77, grafico78: grafico78, grafico79: grafico79, grafico80: grafico80, grafico81: grafico81, grafico82: grafico82, grafico83: grafico83, grafico84: grafico84, grafico85: grafico85, grafico86: grafico86, grafico87: grafico87, grafico88: grafico88, grafico89: grafico89, grafico90: grafico90, grafico91: grafico91, grafico92: grafico92, grafico93: grafico93, grafico94: grafico94, grafico95: grafico95, grafico96: grafico96, grafico97: grafico97, grafico98: grafico98, grafico99: grafico99, grafico100: grafico100, grafico101: grafico101, grafico102: grafico102, grafico103: grafico103, grafico104: grafico104, grafico105: grafico105, grafico106: grafico106, grafico107: grafico107, grafico108: grafico108, grafico109: grafico109, grafico110: grafico110, grafico111: grafico111, grafico112: grafico112, grafico113: grafico113, grafico114: grafico114, grafico115: grafico115, grafico116: grafico116, grafico117: grafico117, grafico118: grafico118, grafico119: grafico119, grafico120: grafico120, grafico121: grafico121, grafico122: grafico122, grafico123: grafico123, grafico124: grafico124, grafico125: grafico125, grafico126: grafico126, grafico127: grafico127, grafico128: grafico128, grafico129: grafico129, grafico130: grafico130, grafico131: grafico131, grafico132: grafico132, grafico133: grafico133, grafico134: grafico134, grafico135: grafico135, grafico136: grafico136, grafico137: grafico137, grafico138: grafico138, grafico139: grafico139, grafico140: grafico140, grafico141: grafico141, grafico142: grafico142, grafico143: grafico143, grafico144: grafico144, grafico145: grafico145, grafico146: grafico146, grafico147: grafico147, grafico148: grafico148, grafico149: grafico149, grafico150: grafico150, grafico151: grafico151, grafico152: grafico152, grafico153: grafico153, grafico154: grafico154, grafico155: grafico155, grafico156: grafico156, grafico157: grafico157, grafico158: grafico158, grafico159: grafico159, grafico160: grafico160, grafico161: grafico161, grafico162: grafico162, grafico163: grafico163, grafico164: grafico164, grafico165: grafico165, grafico166: grafico166, grafico167: grafico167, grafico168: grafico168, grafico169: grafico169, grafico170: grafico170, grafico171: grafico171, grafico172: grafico172, grafico173: grafico173, grafico174: grafico174, grafico175: grafico175, grafico176: grafico176, grafico177: grafico177, grafico178: grafico178, grafico179: grafico179, grafico180: grafico180, grafico181: grafico181, grafico182: grafico182, grafico183: grafico183, grafico184: grafico184, grafico185: grafico185, grafico186: grafico186, grafico187: grafico187, grafico188: grafico188, grafico189: grafico189, grafico190: grafico190, grafico191: grafico191, grafico192: grafico192, grafico193: grafico193, grafico194: grafico194, grafico195: grafico195, grafico196: grafico196, grafico197: grafico197, grafico198: grafico198, grafico199: grafico199, grafico200: grafico200, grafico201: grafico201, grafico202: grafico202, grafico203: grafico203, grafico204: grafico204, grafico205: grafico205, grafico206: grafico206, grafico207: grafico207, grafico208: grafico208, grafico209: grafico209, grafico210: grafico210, grafico211: grafico211, grafico212: grafico212, grafico213: grafico213, grafico214: grafico214, grafico215: grafico215, grafico216: grafico216, grafico217: grafico217, grafico218: grafico218, grafico219: grafico219, grafico220: grafico220, grafico221: grafico221, grafico222: grafico222, grafico223: grafico223, grafico224: grafico224, grafico225: grafico225, grafico226: grafico226, grafico227: grafico227, grafico228: grafico228, grafico229: grafico229, grafico230: grafico230, grafico231: grafico231, grafico232: grafico232, grafico233: grafico233, grafico234: grafico234, grafico235: grafico235, grafico236: grafico236, grafico237: grafico237, grafico238: grafico238, grafico239: grafico239, }); }); }); module.exports = router; //exports.valores00;
define(["UI","Shell","R"], function (UI,sh,R) { var res={}; res.show=function (ide, onLineClick) { var d=res.embed(ide,onLineClick); d.dialog({width:600}); }; res.embed=function (ide, onLineClick) { const files=ide.project.sourceFiles(); if (!res.d) { res.d=UI("div",{title:R("find")}, ["div", ["span",R("wordToFind")], ["input",{$var:"word",$edit:"word",on:{input: function () { res.d.fileNames(); },enterkey:function () { res.d.start(); }}}]], ["div", {$var:"validationMessage", css:{color:"red"}}], ["button", {$var:"OKButton", on:{click: function () { res.d.start(); }}}, R("find")], ["div",{style:"overflow-y:scroll; height:200px"}, ["table",{$var:"searchRes"}]] ); } var d=res.d; var word=res.d.$vars.word; word.val(""); //var model={word:""}; //d.$edits.load(model); d.fileNames=function () { d.$vars.searchRes.empty(); const doLineClickF=l=>()=>doLineClick(l); for (let fileName in files) { const file=files[fileName]; /*console.log(file.truncExt().toLowerCase(), model.word.toLowerCase(), file.truncExt().toLowerCase().indexOf(model.word.toLowerCase()));*/ if (file.truncExt().toLowerCase().indexOf(word.val().toLowerCase())>=0) { const file=files[fileName]; const lineNo=-1; const line=R("filenameMatched"); d.$vars.searchRes.append( UI("tr", ["td",{on:{click:doLineClickF({file,lineNo,line})}},file.name()], ["td",{on:{click:doLineClickF({file,lineNo,line})}},line] )); } } function doLineClick(l) { if (onLineClick) onLineClick(l); } }; d.start=function () { d.$vars.searchRes.empty(); const doLineClickF=l=>()=>doLineClick(l); for (let fileName in files) { const file=files[fileName]; let lineNo=0; for (let line of file.lines()) { lineNo++; if (line.indexOf(word.val())<0) continue; d.$vars.searchRes.append( UI("tr", ["td",{on:{click:doLineClickF({file,lineNo,line})}},file.name()+"("+lineNo+")"], ["td",{on:{click:doLineClickF({file,lineNo,line})}},line] )); } } function doLineClick(l) { if (onLineClick) onLineClick(l); } }; return d; }; return res; });
'use strict'; module.exports = { app: { title: 'Musings', description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js', keywords: 'MongoDB, Express, AngularJS, Node.js' }, port: process.env.PORT || 3000, templateEngine: 'swig', sessionSecret: 'MEAN', sessionCollection: 'sessions', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.css', ], js: [ 'public/lib/angular/angular.js', 'public/lib/angular-resource/angular-resource.js', 'public/lib/angular-cookies/angular-cookies.js', 'public/lib/angular-animate/angular-animate.js', 'public/lib/angular-touch/angular-touch.js', 'public/lib/angular-sanitize/angular-sanitize.js', 'public/lib/angular-ui-router/release/angular-ui-router.js', 'public/lib/angular-ui-utils/ui-utils.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.js', 'public/lib/angular-route/angular-route.min.js' ] }, css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config.js', 'public/application.js', 'public/modules/*/*.js', 'public/modules/*/*[!tests]*/*.js' ], tests: [ 'public/lib/angular-mocks/angular-mocks.js', 'public/modules/*/tests/*.js' ] } };
/** * Developer: Stepan Burguchev * Date: 6/29/2015 * Copyright: 2009-2015 Comindware® * All Rights Reserved * * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Comindware * The copyright notice above does not evidence any * actual or intended publication of such source code. */ /* global define, require, Handlebars, Backbone, Marionette, $, _, Localizer */ define(['coreui'], function (core) { 'use strict'; var objectTypes = { RECORD_TYPE: 'RecordType', ROOM: 'Room', PROJECT: 'Project', ACCOUNT_GROUP: 'AccountGroup', PROCESS_TEMPLATE: 'ProcessTemplate', FORM: 'Form', DATA_SOURCE: 'DataSource' }; var objectIdPrefixes = {}; objectIdPrefixes[objectTypes.RECORD_TYPE] = 'oa.'; objectIdPrefixes[objectTypes.PROCESS_TEMPLATE] = 'pa.'; objectIdPrefixes[objectTypes.ROOM] = 'room.'; objectIdPrefixes[objectTypes.PROJECT] = 'project.'; objectIdPrefixes[objectTypes.ACCOUNT_GROUP] = 'group.'; objectIdPrefixes[objectTypes.FORM] = 'form.'; objectIdPrefixes[objectTypes.DATA_SOURCE] = 'ds.'; return { encodeObjectId: function (objectType, objectId) { var prefix = objectIdPrefixes[objectType]; if (!prefix) { core.utils.helpers.throwFormatError('Invalid objectType.'); } if (!objectId) { core.utils.helpers.throwFormatError('Empty object id: `' + objectId + '`.'); } if (objectId.indexOf(prefix) === 0) { return objectId.substring(prefix.length); } return objectId; }, decodeObjectId: function (objectType, objectId) { var prefix = objectIdPrefixes[objectType]; if (!prefix) { core.utils.helpers.throwFormatError('Invalid objectType.'); } if (!objectId) { core.utils.helpers.throwFormatError('Empty object id: `' + objectId + '`.'); } if (_.isString(objectId) && objectId.indexOf(prefix) === 0) { return objectId; } if (!_.isFinite(parseInt(objectId))) { core.utils.helpers.throwFormatError('Invalid object id: `' + objectId + '`.'); } return prefix + objectId; }, objectTypes: objectTypes }; });
const gulp = require("gulp"); gulp.task("copy-validation", function() { // const browserSync = require("browser-sync"); const config = require("../util/loadConfig").copy_validation; // browserSync.notify( config.notification ); return gulp.src(config.src) .pipe(gulp.dest(config.dest)); });
var eyes = require('eyes'), haibu = require('../lib/haibu'); // Create a new client for communicating with the haibu server var client = new haibu.drone.Client({ host: process.env.HOST || '127.0.0.1', port: 9002 }); // A basic package.json for a node.js application on Haibu var app = { "user": "marak", "name": "test", "domain": "devjitsu.com", "repository": { "type": "git", "url": "https://github.com/Marak/hellonode.git" }, "scripts": { "start": "server.js" }, "engine": { "node": "0.8.x" } }; var total = 200; function start() { // Attempt to start up a new application client.start(app, function (err, result) { if (err) { console.log('Error spawning app: ' + app.name); return eyes.inspect(err); } if(total > 0) { total--; start(); } //console.log('Successfully spawned app:'); //eyes.inspect(result); }); } start();
/** * color util * @type {ONECOLOR|exports|*} */ var color = require('onecolor'); exports.rainbow = function (baseColor, length) { baseColor = baseColor || '#EE1'; length = length || 7; var result = []; for (var i = 0; i < length; i++) { var hue = (360 / length * (i % length)) / 360; result.push( color(baseColor) .hue(hue, true) .hex()); } return result; };
import _ from "lodash"; import React, {Component} from "react"; import {inject, observer} from "mobx-react"; import PropTypes from "prop-types"; import SelectInput from "../common/SelectInput"; import TextAreaInput from "../common/TextAreaInput"; import Button from "../common/Button"; @inject("outputStore") @observer class SelectModelIndex extends Component { render() { const {outputStore} = this.props, selectedOutput = outputStore.selectedOutput.frequentist, {models} = selectedOutput, {model_index, notes} = selectedOutput.selected, selectValue = _.isNumber(model_index) ? model_index : -1, textValue = _.isNull(notes) ? "" : notes, choices = models.map((model, idx) => { return {value: idx, text: model.name}; }); choices.unshift({value: -1, text: "None (no model selected)"}); return ( <form className="form-group row well py-2"> <div className="col-md-4"> <SelectInput label="Selected best-fitting model" onChange={value => outputStore.saveSelectedModelIndex(parseInt(value))} value={selectValue} choices={choices} /> </div> <div className="col-md-4"> <TextAreaInput label="Selection notes" value={textValue} onChange={outputStore.saveSelectedIndexNotes} /> </div> <div className="col-md-4"> <label>&nbsp;</label> <Button className="btn btn-primary btn-block mt-1" onClick={outputStore.saveSelectedModel} text="Save model selection" /> </div> </form> ); } } SelectModelIndex.propTypes = { outputStore: PropTypes.object, }; export default SelectModelIndex;
describe('The Indexed Collection', function(){ var collection, emptyCollection; beforeEach(module('collection')); beforeEach(inject(function(IndexedCollection){ collection = new IndexedCollection(['value1','value2','value3']); emptyCollection = new IndexedCollection(); })); it('shoud tell if it is empty', function(){ expect(emptyCollection.isEmpty()).toBe(true); }); it('should have a size', function(){ expect(collection.size()).toBe(3); }); it('should have an array of items', function(){ expect(collection.items).toBeDefined(); }); it('should add a new item', function(){ collection.add('value4'); expect(collection.size()).toBe(4); }); it('should tell if there is a item after another', function(){ var first = collection.getAt(0), last = collection.getLast(); expect(collection.haveNext(first)).toBe(true); expect(collection.haveNext(last)).toBe(false); }); it('should tell if there is a item before another', function(){ var first = collection.getAt(0), last = collection.getLast(); expect(collection.havePrevious(first)).toBe(false); expect(collection.havePrevious(last)).toBe(true); }); it('should get the next element', function(){ var first = collection.getAt(0), second = collection.getAt(1); expect(collection.getNext(first)).toBe(second); }); it('should get the next element', function(){ var first = collection.getAt(0), second = collection.getAt(1); expect(collection.getPrevious(second)).toBe(first); }); });
/*global FB*/ import React, { useContext } from "react"; import { FaFacebookSquare } from "react-icons/fa"; import CocktailDatabase from "../CocktailDatabase"; import { DrinkListContext } from "../DrinkListProvider"; import { useLocation } from "react-router-dom"; const shareOverrideOGMeta = ( overrideLink, overrideTitle, overrideDescription, overrideImage ) => { FB.ui( { method: "share_open_graph", action_type: "og.likes", action_properties: JSON.stringify({ object: { "og:url": overrideLink, "og:title": overrideTitle, "og:description": overrideDescription, "og:image": overrideImage, }, }), }, function (response) { // Action after response } ); }; const createDescription = (drinkList, cocktails) => { if (!drinkList || Object.keys(drinkList).length === 0) { return "Friends coming over for cocktails? Find tasty cocktail recipes and check what ingredients you need."; } return Object.entries(drinkList) .map((keyToValue) => { var cocktail = cocktails.find((x) => x.id === parseInt(keyToValue[0])); return keyToValue[1] + "x " + cocktail.name; }) .join(", "); }; const createTitle = (drinkList) => { return !drinkList || Object.keys(drinkList).length === 0 ? "Cocktails World" : "Drinks and Ingredients Needed"; }; export const FacebookShare = () => { const { drinkList } = useContext(DrinkListContext); const location = useLocation(); const shareUrl = "http://www.cocktailsworld.eu" + location.pathname; return ( <FaFacebookSquare size="2em" color="#3b5998" style={{ cursor: "pointer" }} onClick={() => { shareOverrideOGMeta( shareUrl, createTitle(drinkList), createDescription(drinkList, CocktailDatabase), "http://www.cocktailsworld.eu/Images/cocktail_og_image.jpg" ); }} /> ); };
/*! * @websanova/vue-auth v4.1.11 * https://websanova.com/docs/vue-auth * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.VueAuth = factory()); }(this, (function () { 'use strict'; var frisbee_1_x = { init: function () { if (!this.plugins.http) { return 'drivers/http/frisbee.js: http plugin has not been set.'; } }, interceptor: function (req, res) { var _this = this; this.plugins.http.interceptor.register({ request: function (path, options) { req.call(_this, options); return [path, options]; }, requestError: err => { req.call(_this, err.request); return Promise.reject(err); }, response: response => { res.call(_this, response); return response; }, responseError: err => { res.call(_this, err.response); return Promise.reject(err); } }); }, invalidToken: res => { if (res.status === 401) { return true; } }, httpData: res => { return res.body || {}; }, http: function (data) { return this.plugins.http[data.method.toLowerCase()](data.url, data); }, getHeaders: res => { return res.headers; }, setHeaders: (req, headers) => { req.headers = Object.assign({}, req.headers, headers); } }; return frisbee_1_x; })));
'use strict'; var path = require('path'); function sanitizeOptions(opt) { return { title: opt.title || 'Styleguide Generator', sass: opt.sass || {}, less: opt.less || {}, css: opt.css || {}, kssOpt: opt.kssOpt || {}, overviewPath: opt.overviewPath || path.join(__dirname, '/overview.md'), extraHead: (typeof opt.extraHead === 'object') ? opt.extraHead.join('\n') : opt.extraHead, beforeBody: (typeof opt.beforeBody === 'object') ? opt.beforeBody.join('\n') : opt.beforeBody, afterBody: (typeof opt.afterBody === 'object') ? opt.afterBody.join('\n') : opt.afterBody, sideNav: opt.sideNav || false, disableEncapsulation: opt.disableEncapsulation || false, disableHtml5Mode: opt.disableHtml5Mode || (typeof opt.disableHtml5Mode === 'undefined' && !opt.server) || false, appRoot: opt.appRoot || '', commonClass: opt.commonClass || '', styleVariables: opt.styleVariables || false, customColors: opt.customColors || false, server: opt.server || false, port: opt.port || 3000, basicAuth: opt.basicAuth || null, rootPath: opt.rootPath, readOnly: opt.readOnly || false, parsers: opt.parsers || { sass: 'sass', scss: 'scss', less: 'less', postcss: 'postcss' }, filesConfig: opt.filesConfig, styleguideProcessors: opt.styleguideProcessors || {} }; } module.exports = { sanitizeOptions: sanitizeOptions };
#!/usr/bin/node var pi = Math.PI; var Circle = function (radius) { this.diameter = function() { return 2 * radius; } this.circumference = function() { return pi * 2 * radius; } this.area = function() { return pi * radius * radius; } } console.log('\n02-export-object\n', module); module.exports = Circle;
require("./helpers/setup"); var wd = require("wd"), _ = require('underscore'), Q = require('q'), serverConfigs = require('./helpers/appium-servers'); var Asserter = wd.Asserter; // asserter base class describe("ios simple", function () { this.timeout(300000); var driver; var allPassed = true; before(function () { var serverConfig = process.env.SAUCE ? serverConfigs.sauce : serverConfigs.local; driver = wd.promiseChainRemote(serverConfig); require("./helpers/logging").configure(driver); var desired = _.clone(require("./helpers/caps").ios92); desired.app = require("./helpers/apps").iosToDoApp; if (process.env.SAUCE) { desired.name = 'ios - todo'; desired.tags = ['appium,test']; } return driver.init(desired); }); after(function () { return driver .quit() .finally(function () { if (process.env.SAUCE) { return driver.sauceJobStatus(allPassed); } }); }); afterEach(function () { allPassed = allPassed && this.currentTest.state === 'passed'; }); it("should be possible to create a new todo ", function () { return driver .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIATextField[1]").click() .elementByXPath("//UIAApplication[1]/UIAWindow[4]/UIAKeyboard[1]") .should.eventually.exist .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIATextField[1]").sendKeys("Test 1 \n") .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAStaticText[3]") .should.eventually.exist }); it("should be possible to create another new todo", function () { return driver .elementByXPath("//UIAApplication[1]/UIAWindow[4]/UIAKeyboard[1]") .should.eventually.exist .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIATextField[1]").sendKeys("Test 2 \n") .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAStaticText[4]") .should.eventually.exist }); it("should be possible to mark the first todo complete", function () { return driver .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIASwitch[3]") .should.eventually.exist .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIASwitch[3]").click() .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAButton[1]") .should.eventually.exist }); it("should be possible to delete the first todo", function () { return driver .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAButton[1]").click() }); it("should be possible to delete the second todo and make the delete button dissappear", function () { return driver .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAButton[1]").click() .elementByXPath("//UIAApplication[1]/UIAWindow[1]/UIAScrollView[1]/UIAWebView[1]/UIAButton[1]") .then(function() { console.log("found the button"); throw Error('Delete button is still there, where it should not be!'); },function rejectedPromise(){ //throw Error('Delete button for entry is not there!'); }) }); });
import _extends from "@babel/runtime/helpers/esm/extends"; import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose"; import contains from 'dom-helpers/query/contains'; import React, { cloneElement } from 'react'; import ReactDOM from 'react-dom'; import warning from 'warning'; import Overlay from './Overlay'; var RefHolder = /*#__PURE__*/ function (_React$Component) { _inheritsLoose(RefHolder, _React$Component); function RefHolder() { return _React$Component.apply(this, arguments) || this; } var _proto = RefHolder.prototype; _proto.render = function render() { return this.props.children; }; return RefHolder; }(React.Component); var normalizeDelay = function normalizeDelay(delay) { return delay && typeof delay === 'object' ? delay : { show: delay, hide: delay }; }; var defaultProps = { defaultOverlayShown: false, trigger: ['hover', 'focus'] }; // eslint-disable-next-line react/no-multi-comp var OverlayTrigger = /*#__PURE__*/ function (_React$Component2) { _inheritsLoose(OverlayTrigger, _React$Component2); function OverlayTrigger(props, context) { var _this; _this = _React$Component2.call(this, props, context) || this; _this.getTarget = function () { return ReactDOM.findDOMNode(_this.trigger.current); }; _this.handleShow = function () { clearTimeout(_this._timeout); _this._hoverState = 'show'; var delay = normalizeDelay(_this.props.delay); if (!delay.show) { _this.show(); return; } _this._timeout = setTimeout(function () { if (_this._hoverState === 'show') _this.show(); }, delay.show); }; _this.handleHide = function () { clearTimeout(_this._timeout); _this._hoverState = 'hide'; var delay = normalizeDelay(_this.props.delay); if (!delay.hide) { _this.hide(); return; } _this._timeout = setTimeout(function () { if (_this._hoverState === 'hide') _this.hide(); }, delay.hide); }; _this.handleFocus = function (e) { var _this$getChildProps = _this.getChildProps(), onFocus = _this$getChildProps.onFocus; _this.handleShow(e); if (onFocus) onFocus(e); }; _this.handleBlur = function (e) { var _this$getChildProps2 = _this.getChildProps(), onBlur = _this$getChildProps2.onBlur; _this.handleHide(e); if (onBlur) onBlur(e); }; _this.handleClick = function (e) { var _this$getChildProps3 = _this.getChildProps(), onClick = _this$getChildProps3.onClick; if (_this.state.show) _this.hide();else _this.show(); if (onClick) onClick(e); }; _this.handleMouseOver = function (e) { _this.handleMouseOverOut(_this.handleShow, e, 'fromElement'); }; _this.handleMouseOut = function (e) { return _this.handleMouseOverOut(_this.handleHide, e, 'toElement'); }; _this.trigger = React.createRef(); _this.state = { show: !!props.defaultShow }; // We add aria-describedby in the case where the overlay is a role="tooltip" // for other cases describedby isn't appropriate (e.g. a popover with inputs) so we don't add it. _this.ariaModifier = { enabled: true, order: 900, fn: function fn(data) { var popper = data.instance.popper; var target = _this.getTarget(); if (!_this.state.show || !target) return data; var role = popper.getAttribute('role') || ''; if (popper.id && role.toLowerCase() === 'tooltip') { target.setAttribute('aria-describedby', popper.id); } return data; } }; return _this; } var _proto2 = OverlayTrigger.prototype; _proto2.componentWillUnmount = function componentWillUnmount() { clearTimeout(this._timeout); }; _proto2.getChildProps = function getChildProps() { return React.Children.only(this.props.children).props; }; // Simple implementation of mouseEnter and mouseLeave. // React's built version is broken: https://github.com/facebook/react/issues/4251 // for cases when the trigger is disabled and mouseOut/Over can cause flicker // moving from one child element to another. _proto2.handleMouseOverOut = function handleMouseOverOut(handler, e, relatedNative) { var target = e.currentTarget; var related = e.relatedTarget || e.nativeEvent[relatedNative]; if ((!related || related !== target) && !contains(target, related)) { handler(e); } }; _proto2.hide = function hide() { this.setState({ show: false }); }; _proto2.show = function show() { this.setState({ show: true }); }; _proto2.render = function render() { var _this$props = this.props, trigger = _this$props.trigger, overlay = _this$props.overlay, children = _this$props.children, _this$props$popperCon = _this$props.popperConfig, popperConfig = _this$props$popperCon === void 0 ? {} : _this$props$popperCon, props = _objectWithoutPropertiesLoose(_this$props, ["trigger", "overlay", "children", "popperConfig"]); delete props.delay; delete props.defaultShow; var child = React.Children.only(children); var triggerProps = {}; var triggers = trigger == null ? [] : [].concat(trigger); if (triggers.indexOf('click') !== -1) { triggerProps.onClick = this.handleClick; } if (triggers.indexOf('focus') !== -1) { triggerProps.onFocus = this.handleShow; triggerProps.onBlur = this.handleHide; } if (triggers.indexOf('hover') !== -1) { process.env.NODE_ENV !== "production" ? warning(triggers.length >= 1, '[react-bootstrap] Specifying only the `"hover"` trigger limits the ' + 'visibility of the overlay to just mouse users. Consider also ' + 'including the `"focus"` trigger so that touch and keyboard only ' + 'users can see the overlay as well.') : void 0; triggerProps.onMouseOver = this.handleMouseOver; triggerProps.onMouseOut = this.handleMouseOut; } return React.createElement(React.Fragment, null, React.createElement(RefHolder, { ref: this.trigger }, cloneElement(child, triggerProps)), React.createElement(Overlay, _extends({}, props, { popperConfig: _extends({}, popperConfig, { modifiers: _extends({}, popperConfig.modifiers, { ariaModifier: this.ariaModifier }) }), show: this.state.show, onHide: this.handleHide, target: this.getTarget }), overlay)); }; return OverlayTrigger; }(React.Component); OverlayTrigger.defaultProps = defaultProps; export default OverlayTrigger;
var gulp = require('gulp'); var uglify = require('gulp-uglify'); var del = require('del'); var jshint = require('gulp-jshint'); var rename = require('gulp-rename'); var karma = require('karma').server; var path = require('path'); var paths = { scripts: ['src/**/*.js'], dist: 'dist' }; gulp.task('clean', function(done) { del([paths.dist], done); }); gulp.task('build', function() { return gulp.src(paths.scripts) .pipe(jshint()) .pipe(gulp.dest(paths.dist)) .pipe(uglify()) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest(paths.dist)); }); gulp.task('test:1.3', function(done) { var karmaConfig = { configFile: path.join(__dirname, 'karma.angular-1.3.conf.js') }; karma.start(karmaConfig, done); }); gulp.task('test:1.4', function(done) { var karmaConfig = { configFile: path.join(__dirname, 'karma.angular-1.4.conf.js') }; karma.start(karmaConfig, done); }); gulp.task('test', ['test:1.4', 'test:1.3']); gulp.task('default', ['clean', 'build']);
"use strict"; /** * Timer Class * * - manages a setTimout timer */ class Timer { /** * constructor * * @param {Number} timeout * @param {Function} callback */ constructor(timeout, callback) { this.timeout = timeout; this.callback = callback; this.start(); } start() { let self = this; if (this.timeout > 0) { this.timer = setTimeout(function () { self.callback(); }, this.timeout); } } clear() { if (this.timeout > 0) { clearTimeout(this.timer); } } reset() { this.clear(); this.start(); } } module.exports = Timer;
//= base/amd.js //= base/factory.js ;
Package.describe({ name: 'jshint', version: '1.0.4_1', summary: 'Lint all your JavaScript files with JSHint.', documentation: 'README.md' }); Package.registerBuildPlugin({ name: "lintJshint", sources: [ 'plugin/lint-jshint.js' ], npmDependencies: { "jshint": "2.7.0" } }); Package.onUse(function(api) { api.use('isobuild:linter-plugin@1.0.0'); }); Package.onTest(function(api) { api.use('tinytest'); api.use('jshint'); });
module.exports = { description: "", ns: "react-material-ui", type: "ReactNode", dependencies: { npm: { "material-ui/svg-icons/action/settings-cell": require('material-ui/svg-icons/action/settings-cell') } }, name: "ActionSettingsCell", ports: { input: {}, output: { component: { title: "ActionSettingsCell", type: "Component" } } } }
// jquery shit $(function() { var jptr = 0; $("div[data-toggle=fieldset]").each(function() { var $this = $(this); //Add new entry $this.find("button[data-toggle=fieldset-add-row]").click(function() { //var fieldthis = $(this); var target = $($(this).data("target")); //console.log(target); var oldrow = target.find("[data-toggle=fieldset-entry]:last"); var row = oldrow.clone(true, true); //console.log(row.find(":input")[0]); var elem_id = row.find(":input")[0].id; var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1; row.attr('data-id', elem_num); row.find(":input").each(function() { //console.log(this); var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-'); $(this).attr('name', id).attr('id', id).val('').removeAttr("checked"); }); oldrow.after(row); }); //$('document').on('keyup', function( e ) { //console.log("up"); console.log(jptr); jptr++; // $(window).keypress(function(e) { // //console.log(e.keyCode); // if (e.keyCode == 46) { // //console.log('Space pressed'); // time = precise_round(vid.time(),2); // if (time-1 > 0){ // prev_time = precise_round(time-1,2); // } else { // prev_time = 0; // } // segments.push(new Segment(time)); // segmentIndex+=1; // segments.sort(function(a, b){ // return a.end_time > b.end_time; // }); // //console.log("next index",segmentIndex); // //markings.sort(); // //console.log("Added"); // var target = $($this.find("button[data-toggle=fieldset-add-row]").data("target")); // //console.log("target",target); // var oldrow = target.find("[data-toggle=fieldset-entry]:last"); // //console.log("id",oldrow.find(":input")[0].id); // var row = oldrow.clone(true, true); // //console.log(row.find(":input")[0]); // var elem_id = row.find(":input")[0].id; // var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1; // row.attr('data-id', elem_num); // row.find(":input").each(function() { // //console.log(this.id); // var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-'); // //console.log(id); // // YOU MIGHT NEED THIS LINE! // //$(this).attr('name', id).attr('id', id).val('').removeAttr("checked"); // if ($(this).attr('name').includes('start_time')){ // $(this).attr('name', id).attr('id', id).val(prev_time).removeAttr("checked"); // //console.log($(this).attr('name')); // } else if ($(this).attr('name').includes('end_time')){ // $(this).attr('name', id).attr('id', id).val(time).removeAttr("checked"); // //console.log($(this).attr('name')); // } else { // $(this).attr('name', id).attr('id', id).val('').removeAttr("checked"); // //console.log($(this).attr('name')); // } // }); // oldrow.after(row); // if (first){ // oldrow.remove(); // first = false; // } // } // }); //End add new entry //Remove row $this.find("button[data-toggle=fieldset-remove-row]").click(function() { if($this.find("[data-toggle=fieldset-entry]").length > 1) { var thisRow = $(this).closest("[data-toggle=fieldset-entry]"); //console.log("removing"); var removeTime = thisRow.find(':input').find('end_time').prevObject[1].value; //var index = segments.indexOf(Number(removeTime)); var index = segments.map(function(e) { return e.index; }).indexOf(int(thisRow.attr('data-id'))); //console.log("index remove",index); //var index=int(thisRow.attr('data-id')); //console.log(index); if(index!=-1){ segments.splice(index, 1); } thisRow.remove(); } }); //End remove row }); }); var time=0; var prev_time=0; var first = true; function precise_round(value, decPlaces){ var val = value * Math.pow(10, decPlaces); var fraction = (Math.round((val-parseInt(val))*10)/10); //this line is for consistency with .NET Decimal.Round behavior // -342.055 => -342.06 if(fraction == -0.5) fraction = -0.6; val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces); return val; } // p5.js shit var vid; var markings = []; var segments = []; var drag = false; var progress = false; var dragWhich; var changefield; var segmentIndex=1; var video; function preload() { console.log("Loading video into element"); vid = createVideo(video); } console.log("Downloading video...hellip;Please wait...") var xhr = new XMLHttpRequest(); xhr.open('GET', vidname, true); xhr.responseType = 'blob'; xhr.onload = function(e) { if (this.status == 200) { console.log("got it"); var myBlob = this.response; video = (window.webkitURL ? webkitURL : URL).createObjectURL(myBlob); // myBlob is now the blob that the object URL pointed to. //vid = document.getElementById("video"); vid.src = video; // not needed if autoplay is set for the video element // video.play() } } xhr.send(); function setup() { vid.show(); vid.showControls(); vid.volume(0); vid.size(600,400); vid.position(40, 220); //console.log(vid.position().y); //console.log(vid.size()); createCanvas(600,20); // start with a dummy segment to cap the beginning times segments.push(new Segment(inverseTransform(102),inverseTransform(102),0)); } function draw() { // draw the background background(255); // draw the timeline drawTimeline(108,549); // draw the segments after the dummy segment for (var i=1; i<segments.length;i++){ segments[i].drawSegment(); } // drag the marker that is selected if (drag){ // if marker is beginning marker if (dragWhich==0){ // move the marker //var index = segments.map(function(e) { return e.index; }).indexOf(drag-1); //console.log("index",index,"drag",drag); var newTime = Math.round(segments[drag].dragStart(segments[drag-1].end.xPos+6)*100)/100; // update times in data fields changefield.val(newTime); } else { // if it's an end marker //console.log("index",index, "drag",drag); // if it's not the last end marker if (drag<segments.length-1){ // move the marker //var index = segments.map(function(e) { return e.index; }).indexOf(drag+1); var newTime = Math.round(segments[drag].dragEnd(segments[drag+1].start.xPos-6)*100)/100; } else { // move the marker var newTime = Math.round(segments[drag].dragEnd(timeTransform(duration))*100)/100; } // update the data field changefield.val(newTime); } } if (progress){ console.log("progress",progress); var newTime = segments[progress].progress(); changefield.val(newTime); } //console.log({{num}},vid.duration(),'{{this_video}}'); } function drawTimeline(x0,x1){ stroke(157,157,157); strokeWeight(2); line(x0,9,x1,9); strokeWeight(6); line(timeTransform(0),7,timeTransform(0),13); line(timeTransform(duration),7,timeTransform(duration),13); } function timeTransform(time){ var fraction = time/duration; var posTime = 108 + fraction*(549-108); return posTime; } function inverseTransform(xPos){ var fraction = duration/(549-108); var time = fraction*(xPos-108); return time; } function Marking(time){ this.time=time; this.xPos=timeTransform(time); this.dragMarking=function(bound0,bound1){ if (mouseX>=bound0&&mouseX<=bound1){ this.xPos=mouseX; } else if (mouseX<bound0){ this.xPos=bound0; } else { this.xPos=bound1; } this.time=inverseTransform(this.xPos); return this.time; }; this.progMarking=function(new_time){ this.xPos=timeTransform(new_time); return new_time; }; this.drawMarking=function(){ strokeWeight(6); line(this.xPos,7,this.xPos,13); }; } function Segment(t1, t2, segmentIndex){ this.start = new Marking(t1); this.end = new Marking(t2); this.index = segmentIndex; this.end_time = this.end.time; //console.log("added index",segmentIndex); this.drawSegment=function(){ stroke(0,255,0); this.start.drawMarking(); stroke(255,0,0); this.end.drawMarking(); stroke('#1474cd'); strokeWeight(4); line(this.start.xPos,9,this.end.xPos,9); }; this.dragStart=function(bound0){ return this.start.dragMarking(bound0,this.end.xPos-6); }; this.dragEnd=function(bound1){ end_time = this.end.dragMarking(this.start.xPos+6,bound1); this.end_time = end_time; return end_time; }; this.progress=function(){ this.end_time = this.end.progMarking(precise_round(vid.time(),2)); //console.log("progress",this.end_time); return this.end_time; }; } function mousePressed(){ // Check if the mouse is on a marker for (var i=1; i<segments.length;i++){ // if it's on a beginning marker if (mouseX<=(segments[i].start.xPos+4)&&mouseX>=(segments[i].start.xPos-4)&&mouseY<=14&&mouseY>=6){ // save that it's a beginning marker and which marker it is drag = i; dragWhich = 0; //console.log("drag",drag); // store the field to update in a variable changefield=$("div[data-toggle=fieldset]").find("[data-toggle=fieldset-entry]").filter("[data-id="+segments[drag].index+"]").find(":input[name='segments-"+segments[drag].index+"-start_time']"); } // if it's an end marker if (mouseX<=(segments[i].end.xPos+4)&&mouseX>=(segments[i].end.xPos-4)&&mouseY<=14&&mouseY>=6){ // save that it's an end marker drag = i; // save which marker dragWhich = 1; //console.log("drag",drag); // store the field to update in a variable changefield=$("div[data-toggle=fieldset]").find("[data-toggle=fieldset-entry]").filter("[data-id="+segments[drag].index+"]").find(":input[name='segments-"+segments[drag].index+"-end_time']"); } } } function mouseReleased(){ // stop dragging drag = false; } function keyReleased() { // set the beginning time for the new segment progress = false; } function insert(st_time) { var loc = 0; for (var j=0; j < segments.length; j++){ if (segments[j].start.time>=st_time){ loc = j-1; break; } else { loc = j; } } console.log("loc",loc); segments.splice(loc + 1, 0, new Segment(st_time, st_time, segmentIndex)); for (var i=0; i < segments.length; i++){ console.log("start",segments[i].start.time,"index",segments[i].index); } return ; } // create the new field and segment function keyPressed() { //$("div[data-toggle=fieldset]").each(function() { var $this = $(this); //console.log(keyCode); //console.log(e.keyCode); if (keyCode == 220) { console.log('PERIOD ON!'); time = precise_round(vid.time(),2); prev_time = time; // if (time-1 > 0){ // prev_time = precise_round(time-1,2); // } else { // prev_time = 0; // } console.log("segmentIndex",segmentIndex); //segments.push(new Segment(prev_time, time, segmentIndex)); insert(time); progress = segments.map(function(e) { return e.index; }).indexOf(segmentIndex); console.log("numsegs",segments.length); //console.log("progress",progress); segmentIndex+=1; // segments.sort(function(a, b){ // return a.start_time > b.start_time; // }); //console.log("next index",segmentIndex); //markings.sort(); //console.log("Added"); var target = $($this.find("button[data-toggle=fieldset-add-row]").data("target")); //console.log("target",target); var oldrow = target.find("[data-toggle=fieldset-entry]:last"); //console.log("id",oldrow.find(":input")[0].id); var row = oldrow.clone(true, true); //console.log(row.find(":input")[0]); var elem_id = row.find(":input")[0].id; var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1; row.attr('data-id', elem_num); row.find(":input").each(function() { //console.log(this.id); var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-'); //console.log(id); // YOU MIGHT NEED THIS LINE! //$(this).attr('name', id).attr('id', id).val('').removeAttr("checked"); if ($(this).attr('name').includes('start_time')){ $(this).attr('name', id).attr('id', id).val(prev_time).removeAttr("checked"); //console.log($(this).attr('name')); } else if ($(this).attr('name').includes('end_time')){ $(this).attr('name', id).attr('id', id).val(time).removeAttr("checked"); //console.log($(this).attr('name')); } else { $(this).attr('name', id).attr('id', id).val('').removeAttr("checked"); //console.log($(this).attr('name')); } }); oldrow.after(row); if (first){ oldrow.remove(); first = false; } changefield=$("div[data-toggle=fieldset]").find("[data-toggle=fieldset-entry]").filter("[data-id="+segments[progress].index+"]").find(":input[name='segments-"+segments[progress].index+"-end_time']"); } //End add new entry //}); } // function mousePressed(){ // for (var i=2; i<markings.length;i++){ // //console.log(markings[i]); // if (mouseX<=(markings[i].xPos+3)&&mouseX>=(markings[i].xPos-3)&&mouseY<=13&&mouseY>=7){ // drag = i; // $("div[data-toggle=fieldset]").find("[data-toggle=fieldset-entry]").each(function() { // if ($(this).attr('data-id')==drag-2){ // $(this).find(":input").each(function() { // if ($(this).attr('name').includes('end_time')){ // changefield=$(this); // } // }); // } // }); // } // } // } // function mouseReleased(){ // drag = false; // }
export default from './Settings.js';
var EventEmitter = require('events').EventEmitter; var assign = require('object-assign'); var CONSTANTS = require('./constants'); var keybord = assign({}, EventEmitter.prototype, { start : function(){ this.onKeydownHandler = this.onKeydownHandler.bind(this); document.addEventListener('keydown', this.onKeydownHandler); }, onKeydownHandler : function(ev){ this.emit(CONSTANTS.KEYBOARD_DOWN, ev.keyCode); } }); keybord.start(); module.exports = keybord;
/*jslint node: true */ module.exports = { app: { // Server IP ip: process.env.ip || undefined, // Server port port: process.env.PORT || 3000 }, // MongoDB connection options mongo: { uri: 'mongodb://sooserver:arbulon@ds060749.mlab.com:60749/soodb' }, jwt: { secret: 'secret', alghorithm: 'HS512', type: 'Bearer', header: 'authorization' }, passport: { options: { session: false } } };
describe('Testing main.js', function() { // necessary it('newStudent should be object', function() { expect(typeof newStudent).toBe('object'); }); it('newStudent name should be RSR', function() { expect(newStudent.name).toBe('RSR'); }); it('newStudent name should change', function() { newStudent.setName('jabong'); expect(newStudent.name).toBe('jabong'); }); });
let selectMany = checkMe = prev = false; const boxes = document.querySelectorAll('input[type="checkbox"]'); document.querySelector('.inbox').addEventListener('change', e => { if (selectMany && prev && e.target.checked && prev !== e.target) { boxes.forEach(box => { if (box === prev || box === e.target) { checkMe = ! checkMe; } if (! box.checked && checkMe) { box.checked = true; } }); } // else do nothing prev = e.target; }); // I didn't know about Event.shiftKey on keyboard and mouse events before the // video. So I used the same keydown and keyup tricks from Day 1 to pull off // the same general logic. window.addEventListener('keydown', e => { if (e.keyCode === 16) { selectMany = true; } }); window.addEventListener('keyup', e => { if (e.keyCode === 16) { selectMany = false; } });
mod = {}; // load paths mod.torito = { paths : require("./paths.js") }; var toInclude = JSON.parse( require("fs").readFileSync(mod.torito.paths.server.includes + "/index.json","utf8") ); for(i in toInclude) { console.log("[["+i+"]]"); mod[i] = require(toInclude[i]); } if("services" in mod) { // DANGER DANGER DANGER console.log("----------------------------------------------------------------------------------------------------") console.log("SERVICES STARTED"); console.log("----------------------------------------------------------------------------------------------------") mod.services.start(); } var routesDirectory = { get : mod.torito.paths.server.routes.get, post : mod.torito.paths.server.routes.post, websocket: mod.torito.paths.server.routes.websocket, static : mod.torito.paths.server.routes.static }; app = mod.express_ws_routes(); mod.app = app; app.set("port",process.env.PORT || 3002); function guid() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } app.use(function(req,res,next){ console.log("------------------------------------------------------------------------------------------------"); console.log('Request URL:', req.originalUrl,'Request Type:', req.method,'Request Params:', req.params,'Request Query:', req.query); console.log("------------------------------------------------------------------------------------------------"); next(); }) if("session" in mod) { mod.session.reset(); app.use(function (req, res, next) { //mod.session.print(); var found = false; //console.log(req.headers); if("cookie" in req.headers) { console.log("req.headers.cookie:",req.headers.cookie); req.cookies = mod.cookie.parse(req.headers.cookie); console.log("req.cookies:",req.cookies); if("session" in req.cookies) { var data = mod.session.get( req.cookies.session ); if(data != null) { var ip; if (req.headers['x-forwarded-for']) { ip = req.headers['x-forwarded-for'].split(",")[0]; } else if (req.connection && req.connection.remoteAddress) { ip = req.connection.remoteAddress; } else { ip = req.ip; } req.session = data; if( req.session.ip == ip ) { // not found req.session.id = req.cookies.session; console.log("SESSION:",req.session.id); //data.date = new Date(); found = true; } } } } if(!found) { // find a available id var id = guid(); while(true) { var data = mod.session.get( id ); if(data != null) { id = guid(); } else { break; } } // create a new session var ip; if (req.headers['x-forwarded-for']) { ip = req.headers['x-forwarded-for'].split(",")[0]; } else if (req.connection && req.connection.remoteAddress) { ip = req.connection.remoteAddress; } else { ip = req.ip; } var session = { id : id, ip : ip, logged : false, date : new Date() }; console.log("NEW SESSION:",id); var d1 = new Date (), d2 = new Date ( d1 ); d2.setMinutes ( d1.getMinutes() + 60*24*365 ); var d0 = new Date(0); mod.session.set(id,session); var cookie_str = mod.cookie.serialize("session",id,{ httpOnly : true, path : "/", expires : d2, sameSite : true, SameSite : "strict" }); console.log("cookie:",cookie_str); res.setHeader('Set-Cookie', cookie_str); req.session = session; } next(); }); } var builtin = { "get" : {}, "post" : {}, "websocket" : {}, "static" : {} }; function readdirrecSync(dir,top) { top = top || ""; var files = mod.fs.readdirSync(dir); var ret = []; for(var x in files) { if( mod.fs.lstatSync(dir + "/" + files[x]).isDirectory() ) { var r = readdirrecSync(dir + "/" + files[x], top + files[x] + "/"); ret = ret.concat(r); console.log("DIR:"+dir+" TOP:" + top, JSON.stringify(ret)); } else { ret.push(top + files[x]); console.log("DIR:"+dir+" TOP:" + top, JSON.stringify(ret)); } } return ret; } for(var dir in routesDirectory) { console.log("DIR:",routesDirectory[dir]); arrv = readdirrecSync(routesDirectory[dir]); for(var file in arrv) { if(dir == "get" || dir == "post" || dir == "websocket") { console.log("@:",arrv[file]); if( arrv[file].lastIndexOf(".jsf") == arrv[file].length-4 ) { var name = arrv[file].substring(0,arrv[file].length-4); var names = name.split("/"); for(var x = 0; x < names.length;x++) { if(names[x].indexOf("__param__")==0) { names[x] = unescape( names[x].substring("__param__".length) ); } } name = names.join("/"); try { eval("builtin."+dir+"[ \"/\" + name ] = " + mod.fs.readFileSync(routesDirectory[dir] + "/"+arrv[file],"utf8")); } catch(e) { console.log( mod.fs.readFileSync(routesDirectory[dir] + "/"+arrv[file],"utf8") ); console.log("[["+e+"]]"); } } } else if(dir == "static") { if( arrv[file].lastIndexOf(".json") == arrv[file].length-5 ) { console.log(arrv[file]); var name = arrv[file].substring(0,arrv[file].length-5); var data = mod.fs.readFileSync(routesDirectory[dir] + "/"+arrv[file],"utf8"); var json = JSON.parse(data); builtin.static[json.path] = json; //json.path,json.target } } } if(dir == "get" || dir == "post" || dir == "websocket") { for(var r in builtin[dir]) { console.log(dir + ":" + r); app[dir](r,builtin[dir][r]); } } else if(dir == "static") { for(var r in builtin[dir]) { var i = builtin[dir][r]; console.log(dir + ":" + i.path); app.use(i.path,mod.express.static(i.target)); } } } app.listen(app.set("port"), function() { console.log("server at "+app.set("port")+"!"); });
module.exports = (function(global) { return { /** * Creates a global object in a single line * @example * Namespace.create('foo.bar'); // -> foo.bar * @param {String} namespace */ create: (namespace) => { let parent = global const parts = namespace.split('.') const len = parts.length let i = 0 let part for (; i < len; i++) { part = parts[i] parent = (parent[part] = parent[part] || {}) } return parent }, /** * Check for global and local objects. * @param {String|Object} namespaceOrParent * @param {String} [namespace] * @return {Boolean} Returns true or if namespace already exist */ is: (namespaceOrParent, namespace) => { let parent = global let result = false let i = 0 let len let parts let part if (typeof namespaceOrParent === 'object') { parent = namespaceOrParent } else { namespace = namespaceOrParent } parts = namespace.split('.') len = parts.length for (; i < len; i++) { part = parts[i] if (!parent[part]) { result = false return false } parent = parent[part] result = true } return result } } }(window || this))
import Ember from 'ember'; import Form from 'aeonvera/mixins/components/edit-form'; import ENV from 'aeonvera/config/environment'; export default Ember.Component.extend(Form, { modelName: 'housing-provision', saveSuccessPath: 'events.show.housing.provisions', cancelPath: 'events.show.housing.provisions', parentAssociation: 'host', // set by form, not persisted // - 0: A Registrant // - 1: Entered Name whoIsProvidingType: 0, isRegistrantProviding: Ember.computed.equal('whoIsProvidingType', 0) });
'use strict' /* (c) Copyright 2015, bzb-stcnx * all rights reserved * SEE LICENSE IN ../LICENSE */ /* eslint-env jasmine */ /** * @description recursively create a hierarchically defined spy object * @example * var mock = createSpy({ * fs: [ 'readFile', 'readFileSync' ], * stream: { 'Readable': [ 'read', 'pipe' ] } * }) * var mockedFunction = createSpy('mockedFunction') * @param {string} name * @param {Array|object} props optional * @return {function|object} * * a spy function named as defined if props is not defined, * * otherwise an object built from the props object as follows: * * non-object-value entries map to their key, * the resulting value being a spy function named after the key * * object-value entries are recursively mapped to their key */ var createSpy = module.exports = function createSpy (name) { if (typeof name === 'string') return createSpyFunction(name) if (Array.isArray(name)) return name.reduce(reducer(createSpyFunction), {}) if (typeof name !== 'object') throw new Error('incorrect spy definition') return Object.keys(name).reduce(reducer(spyObjectCreator(name)), {}) } function createSpyFunction (name) { return jasmine.createSpy(name) } function spyObjectCreator (obj) { return function createSpyObject (key) { return createSpy(obj[key]) } } function reducer (fn) { return function (map, key) { map[key] = fn(key) return map } }
module.exports = { pragmaExport: 'gio.exports', transformExports: false }
"use strict"; var router_1 = require('@angular/router'); var app_component_1 = require('./app.component'); var routes = app_component_1.appRoutes.slice(); exports.APP_ROUTER_PROVIDERS = [ router_1.provideRouter(routes) ]; //# sourceMappingURL=../../dist/app/app.routes.js.map
function log(x) { document.querySelector('#result').textContent = x; } const sum = (x, y) => x + y; const $leftInput = document.querySelector('#leftT'); const $rightInput = document.querySelector('#rightT'); const $leftButton = document.querySelector('#leftB'); const $rightButton = document.querySelector('#rightB'); const leftValues$ = most.fromEvent('keyup', $leftInput) .map(e => e.target.value); const rightValues$ = most.fromEvent('keyup', $rightInput) .map(e => e.target.value); const leftClick$ = most.fromEvent('click', $leftButton); const rightClick$ = most.fromEvent('click', $rightButton); const a$ = leftValues$.sampleWith(leftClick$); const b$ = rightValues$.sampleWith(rightClick$); a$.zip(sum, b$).observe(log);
'use strict'; var merge = require('extend-shallow'); module.exports = function (engine, assemble) { if(require('handlebars-layouts')(engine) !== engine.helpers.extend) { engine.registerHelper(require('handlebars-layouts')(engine)); } return function (name) { var options = arguments[2] || arguments[1]; var context = {}; if(arguments[2]) { context = arguments[1]; } if (typeof name !== 'string') { return ''; } var ctx = {}; var localContext = assemble.views.partials[name].context(); if(localContext) { ctx = merge(ctx, localContext, getContextData(context)); } ctx.relativeToRoot = options.data.root.relativeToRoot; return engine.helpers.extend(name, ctx, options); }; }; function getContextData(context) { if(context) { if(context.data) { return context.data.root; } else { return context; } } else { return {}; } }
var test = require('tape') var toGithub = require('../') function t (giturl, url) { test(giturl + ' -> ' +url, function (t) { var _url = toGithub(giturl) t.equal(_url, url) t.end() }) } t( 'git://github.com/isaacs/readable-stream.git', 'https://codeload.github.com/isaacs/readable-stream/tar.gz/master' ) t( 'https://github.com/isaacs/readable-stream/archive/master.tar.gz', 'https://codeload.github.com/isaacs/readable-stream/tar.gz/master' ) t( 'git://github.com/substack/sockjs-client.git#browserify-npm', 'https://codeload.github.com/substack/sockjs-client/tar.gz/browserify-npm' ) t( 'shtylman/engine.io-client#v0.5.0-dz0', 'https://codeload.github.com/shtylman/engine.io-client/tar.gz/v0.5.0-dz0' ) t( 'git://github.com/shtylman/engine.io-client#v0.5.0-dz0', 'https://codeload.github.com/shtylman/engine.io-client/tar.gz/v0.5.0-dz0' ) t( 'substack/sockjs-client.git#browserify-npm', 'https://codeload.github.com/substack/sockjs-client/tar.gz/browserify-npm' ) t( 'git+ssh://git@github.com:isaacs/readable-stream.git#master', 'https://codeload.github.com/isaacs/readable-stream/tar.gz/master' ) t( 'git+ssh://github.com:isaacs/readable-stream.git', 'https://codeload.github.com/isaacs/readable-stream/tar.gz/master' ) t( 'bigeasy/locket', 'https://codeload.github.com/bigeasy/locket/tar.gz/master' ) t( 'dominictarr/npmd#v1', 'https://codeload.github.com/dominictarr/npmd/tar.gz/v1' ) t( 'https://registry.npmjs.org/curry/-/curry-1.2.0.tgz', 'https://registry.npmjs.org/curry/-/curry-1.2.0.tgz' ) t( 'git+ssh://github.com/ariya/esprima.git#harmony', 'https://codeload.github.com/ariya/esprima/tar.gz/harmony' ) t( 'git+https://github.com/ariya/esprima.git#harmony', 'https://codeload.github.com/ariya/esprima/tar.gz/harmony' )
var category_data_SU = { "99999": { "skill_id": "99999", "tree_id": "99999", "name2_refine": "Blank", "name2_refine_en": "Blank", "pc_level": "0", "pc_mastery_level": "0", "complete_quest": null, "complete_quest_name": null, "default_keycap": "LB", "sort_no": "0", "skill_icon": { "1": "default_icon_00_24.png" }, "tooltip_stance_type": { "0": null, "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26100": { "skill_id": "26100", "tree_id": "1", "name2_refine": "Sob Sob<br>흐규흐규", "name2_refine_en": "Sob Sob", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "244", "complete_quest_name": "4장. 사부님의 부름", "default_keycap": "TAB", "sort_no": "106", "skill_icon": { "1": "skill_icon_summon_0_1.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/inventory_summoncat_1.png\' class=\'icon_in_description\' /> While the familiar is dead " }, "26101": { "skill_id": "26101", "tree_id": "26101", "name2_refine": "Rose<br>장미", "name2_refine_en": "Rose", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "245", "complete_quest_name": "5장. 홍문파 입문", "default_keycap": "LB", "sort_no": "109", "skill_icon": { "1": "skill_icon_summon_0_2.png", "11": "skill_icon_summon_0_2.png", "12": "skill_icon_summon_0_2.png", "14": "skill_icon_summon_0_2.png", "15": "skill_icon_summon_0_2.png", "24": "skill_icon_summon_0_2.png", "25": "skill_icon_summon_0_2.png", "32": "skill_icon_summon_0_2.png", "34": "skill_icon_summon_0_2.png", "35": "skill_icon_summon_0_2.png", "43": "skill_icon_summon_0_2.png", "45": "skill_icon_summon_0_2.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26105": { "skill_id": "26105", "tree_id": "26105", "name2_refine": "Tendril<br>덩굴손", "name2_refine_en": "Tendril", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "246", "complete_quest_name": "6장. 수련의 시작", "default_keycap": "1", "sort_no": "99", "skill_icon": { "1": "skill_icon_summon_0_8.png", "11": "skill_icon_summon_0_8.png", "12": "skill_icon_summon_0_8.png", "13": "skill_icon_summon_0_8.png", "15": "skill_icon_summon_0_8.png", "23": "skill_icon_summon_0_8.png", "25": "skill_icon_summon_0_8.png", "33": "skill_icon_summon_0_39.png", "35": "skill_icon_summon_0_39.png", "43": "skill_icon_summon_0_39.png", "45": "skill_icon_summon_0_39.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26106": { "skill_id": "26106", "tree_id": "26106", "name2_refine": "Siphon<br>흡수", "name2_refine_en": "Siphon", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "246", "complete_quest_name": "6장. 수련의 시작", "default_keycap": "2", "sort_no": "98", "skill_icon": { "1": "skill_icon_summon_0_9.png", "11": "skill_icon_summon_0_9.png", "13": "skill_icon_summon_0_9.png", "14": "skill_icon_summon_0_9.png", "15": "skill_icon_summon_0_9.png", "23": "skill_icon_summon_0_40.png", "24": "skill_icon_summon_0_40.png", "25": "skill_icon_summon_0_40.png", "34": "skill_icon_summon_0_40.png", "35": "skill_icon_summon_0_40.png", "44": "skill_icon_summon_0_40.png", "45": "skill_icon_summon_0_40.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26107": { "skill_id": "26107", "tree_id": "26107", "name2_refine": "Hornet<br>말벌", "name2_refine_en": "Hornet", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "245", "complete_quest_name": "5장. 홍문파 입문", "default_keycap": "RB", "sort_no": "108", "skill_icon": { "1": "skill_icon_summon_0_10.png", "11": "skill_icon_summon_0_10.png", "12": "skill_icon_summon_0_10.png", "13": "skill_icon_summon_0_10.png", "15": "skill_icon_summon_0_10.png", "22": "skill_icon_summon_0_10.png", "23": "skill_icon_summon_0_10.png", "25": "skill_icon_summon_0_10.png", "32": "skill_icon_summon_0_10.png", "33": "skill_icon_summon_0_10.png", "35": "skill_icon_summon_0_10.png", "42": "skill_icon_summon_0_10.png", "43": "skill_icon_summon_0_10.png", "45": "skill_icon_summon_0_10.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26200": { "skill_id": "26200", "tree_id": "26200", "name2_refine": "Tackle<br>달려들기", "name2_refine_en": "Tackle", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "246", "complete_quest_name": "6장. 수련의 시작", "default_keycap": "TAB", "sort_no": "106", "skill_icon": { "1": "skill_icon_summon_0_6.png", "11": "skill_icon_summon_0_6.png", "12": "skill_icon_summon_0_6.png", "13": "skill_icon_summon_0_6.png", "15": "skill_icon_summon_0_6.png", "23": "skill_icon_summon_0_42.png", "25": "skill_icon_summon_0_42.png", "33": "skill_icon_summon_0_42.png", "35": "skill_icon_summon_0_42.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26201": { "skill_id": "26201", "tree_id": "26201", "name2_refine": "Nyan~<br>냥~", "name2_refine_en": "Nyan~", "pc_level": "1", "pc_mastery_level": null, "complete_quest": "244", "complete_quest_name": "4장. 사부님의 부름", "default_keycap": "NONE", "sort_no": null, "skill_icon": { "1": "skill_icon_summon_0_28.png", "11": "skill_icon_summon_0_28.png", "14": "skill_icon_summon_0_28.png", "15": "skill_icon_summon_0_28.png", "24": "skill_icon_summon_0_28.png", "25": "skill_icon_summon_0_28.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26108": { "skill_id": "26108", "tree_id": "26108", "name2_refine": "Morning Glory Siphon<br>나팔꽃 흡수", "name2_refine_en": "Morning Glory Siphon", "pc_level": "4", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_11.png", "11": "skill_icon_summon_0_11.png", "12": "skill_icon_summon_0_11.png", "14": "skill_icon_summon_0_11.png", "15": "skill_icon_summon_0_11.png", "24": "skill_icon_summon_0_11.png", "25": "skill_icon_summon_0_11.png", "32": "skill_icon_summon_0_11.png", "34": "skill_icon_summon_0_11.png", "35": "skill_icon_summon_0_11.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26202": { "skill_id": "26202", "tree_id": "26202", "name2_refine": "Low Slash<br>하단베기", "name2_refine_en": "Low Slash", "pc_level": "4", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "V", "sort_no": "92", "skill_icon": { "1": "skill_icon_summon_0_34.png", "11": "skill_icon_summon_0_34.png", "12": "skill_icon_summon_0_34.png", "14": "skill_icon_summon_0_34.png", "15": "skill_icon_summon_0_34.png", "22": "skill_icon_summon_0_26.png", "23": "skill_icon_summon_0_26.png", "25": "skill_icon_summon_0_26.png", "33": "skill_icon_summon_0_26.png", "35": "skill_icon_summon_0_26.png", "43": "buff_debuff_icon_03_21.png", "45": "buff_debuff_icon_03_21.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26211": { "skill_id": "26211", "tree_id": "26214", "name2_refine": "Impact<br>충격", "name2_refine_en": "Impact", "pc_level": "4", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "C", "sort_no": "93", "skill_icon": { "1": "skill_icon_summon_0_25.png", "13": "skill_icon_summon_0_25.png", "14": "skill_icon_summon_0_25.png", "23": "skill_icon_summon_0_25.png", "24": "skill_icon_summon_0_25.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26109": { "skill_id": "26109", "tree_id": "26109", "name2_refine": "Foxtail<br>강아지풀", "name2_refine_en": "Foxtail", "pc_level": "6", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "E", "sort_no": "88", "skill_icon": { "1": "skill_icon_summon_0_14.png", "11": "skill_icon_summon_0_14.png", "12": "skill_icon_summon_0_14.png", "13": "skill_icon_summon_0_14.png", "15": "skill_icon_summon_0_14.png", "22": "skill_icon_summon_0_14.png", "23": "skill_icon_summon_0_14.png", "25": "skill_icon_summon_0_14.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26111": { "skill_id": "26111", "tree_id": "26111", "name2_refine": "Pollen<br>꽃가루", "name2_refine_en": "Pollen", "pc_level": "6", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "3", "sort_no": "97", "skill_icon": { "1": "skill_icon_summon_0_16.png", "11": "skill_icon_summon_0_16.png", "12": "skill_icon_summon_0_16.png", "14": "skill_icon_summon_0_16.png", "15": "skill_icon_summon_0_16.png", "22": "skill_icon_summon_0_16.png", "24": "skill_icon_summon_0_16.png", "25": "skill_icon_summon_0_16.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26130": { "skill_id": "26130", "tree_id": "1", "name2_refine": "Burn Pollen<br>꽃가루 태우기", "name2_refine_en": "Burn Pollen", "pc_level": "6", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "3", "sort_no": "97", "skill_icon": { "1": "skill_icon_assassin_0_64.png", "11": "skill_icon_assassin_0_64.png", "12": "skill_icon_assassin_0_64.png", "14": "skill_icon_assassin_0_64.png", "15": "skill_icon_assassin_0_64.png", "22": "skill_icon_assassin_0_64.png", "24": "skill_icon_assassin_0_64.png", "25": "skill_icon_assassin_0_64.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/skill_icon_summon_0_16.png\' class=\'icon_in_description\' /> After using Pollen " }, "26104": { "skill_id": "26104", "tree_id": "26104", "name2_refine": "Cheer<br>응원", "name2_refine_en": "Cheer", "pc_level": "8", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "Z", "sort_no": "95", "skill_icon": { "1": "skill_icon_summon_0_7.png", "11": "skill_icon_summon_0_7.png", "12": "skill_icon_summon_0_7.png", "14": "skill_icon_summon_0_7.png", "15": "skill_icon_summon_0_7.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26112": { "skill_id": "26112", "tree_id": "26112", "name2_refine": "Dandelion<br>민들레씨", "name2_refine_en": "Dandelion", "pc_level": "10", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "4", "sort_no": "96", "skill_icon": { "1": "skill_icon_summon_0_17.png", "11": "skill_icon_summon_0_17.png", "12": "skill_icon_summon_0_17.png", "14": "skill_icon_summon_0_17.png", "15": "skill_icon_summon_0_17.png", "25": "skill_icon_summon_0_17.png", "32": "skill_icon_summon_0_17.png", "33": "skill_icon_summon_0_17.png", "35": "skill_icon_summon_0_17.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26110": { "skill_id": "26110", "tree_id": "26110", "name2_refine": "Chestnut Burr<br>밤송이", "name2_refine_en": "Chestnut Burr", "pc_level": "12", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "4", "sort_no": "96", "skill_icon": { "1": "skill_icon_summon_0_15.png", "11": "skill_icon_summon_0_15.png", "12": "skill_icon_summon_0_15.png", "13": "skill_icon_summon_0_15.png", "22": "skill_icon_summon_0_15.png", "23": "skill_icon_summon_0_15.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/skill_icon_assassin_0_2.png\' class=\'icon_in_description\' /> Stealth stance " }, "26113": { "skill_id": "26113", "tree_id": "1", "name2_refine": "Backward Roll<br>뒤구르기", "name2_refine_en": "Backward Roll", "pc_level": "12", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_23.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_1.png\' class=\'icon_in_description\' /> While downed, groggy, unconscious " }, "26125": { "skill_id": "26125", "tree_id": "26125", "name2_refine": "Evade<br>회피", "name2_refine_en": "Evade", "pc_level": "12", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "S,DOWN", "sort_no": "87", "skill_icon": { "1": "skill_icon_forcemaster_0_56.png", "11": "skill_icon_forcemaster_0_56.png", "12": "skill_icon_forcemaster_0_56.png", "22": "skill_icon_forcemaster_0_56.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26206": { "skill_id": "26206", "tree_id": "26206", "name2_refine": "Press<br>누르기", "name2_refine_en": "Press", "pc_level": "12", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "TAB", "sort_no": "106", "skill_icon": { "1": "skill_icon_summon_0_18.png", "11": "skill_icon_summon_0_18.png", "12": "skill_icon_summon_0_18.png", "14": "skill_icon_summon_0_18.png", "22": "skill_icon_summon_0_18.png", "24": "skill_icon_summon_0_18.png", "34": "skill_icon_summon_0_45.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_1.png\' class=\'icon_in_description\' /> Target downed, groggy, stunned, unconscious <br/><img src=\'../img/skill/buff_debuff_icon_03_26.png\' class=\'icon_in_description\' /> Target using block, counter ability " }, "26310": { "skill_id": "26310", "tree_id": "26110", "name2_refine": "Throwing Chestnut Burr<br>투척밤송이", "name2_refine_en": "Throwing Chestnut Burr", "pc_level": "12", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_15.png", "11": "skill_icon_summon_0_15.png", "12": "skill_icon_summon_0_15.png", "13": "skill_icon_summon_0_15.png", "22": "skill_icon_summon_0_15.png", "23": "skill_icon_summon_0_15.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/skill_icon_summon_0_17.png\' class=\'icon_in_description\' /> Target countered with Dandelion <br/><img src=\'../img/skill/skill_icon_summon_0_10.png\' class=\'icon_in_description\' /> Target hit with pointless, Class1, Class2 Hornet <br/><img src=\'../img/skill/skill_icon_summon_0_8.png\' class=\'icon_in_description\' /> Target rooted <br/><img src=\'../img/skill/skill_icon_summon_0_40.png\' class=\'icon_in_description\' /> Target with Ivy Poison <br/><img src=\'../img/skill/skill_icon_summon_0_18.png\' class=\'icon_in_description\' /> Target hit with Class2 Press, UuDaDa " }, "26114": { "skill_id": "26114", "tree_id": "1", "name2_refine": "Switch<br>교체", "name2_refine_en": "Switch", "pc_level": "14", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "1", "sort_no": "99", "skill_icon": { "1": "skill_icon_summon_0_24.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_1.png\' class=\'icon_in_description\' /> While downed " }, "26137": { "skill_id": "26137", "tree_id": "26137", "name2_refine": "Evade Back<br>후방 회피", "name2_refine_en": "Evade Back", "pc_level": "14", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "2", "sort_no": "98", "skill_icon": { "1": "skill_icon_kungfufighter_1_2.png", "11": "skill_icon_kungfufighter_1_2.png", "13": "skill_icon_kungfufighter_1_2.png", "14": "skill_icon_kungfufighter_1_2.png", "15": "skill_icon_kungfufighter_1_2.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_1.png\' class=\'icon_in_description\' /> While downed, unconscious " }, "26210": { "skill_id": "26210", "tree_id": "1", "name2_refine": "Hammer Spin<br>망치 돌리기", "name2_refine_en": "Hammer Spin", "pc_level": "14", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "C", "sort_no": "93", "skill_icon": { "1": "skill_icon_summon_0_22.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/inventory_summoncat_1.png\' class=\'icon_in_description\' /> While the familiar is downed " }, "26214": { "skill_id": "26214", "tree_id": "26214", "name2_refine": "Detonate<br>터뜨리기", "name2_refine_en": "Detonate", "pc_level": "14", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "NONE", "sort_no": null, "skill_icon": { "1": "skill_icon_summon_0_44.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_22.png\' class=\'icon_in_description\' /> Target with 5 stacks of Poison " }, "26000": { "skill_id": "26000", "tree_id": "26214", "name2_refine": "Cat's Violence<br>고양이의 폭력성", "name2_refine_en": "Cat's Violence", "pc_level": "15", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "NONE", "sort_no": null, "skill_icon": { "1": "skill_icon_summon_0_38.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26001": { "skill_id": "26001", "tree_id": "26214", "name2_refine": "Talented Cat<br>재주넘는 고양이", "name2_refine_en": "Talented Cat", "pc_level": "15", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "NONE", "sort_no": null, "skill_icon": { "1": "skill_icon_summon_0_37.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26412": { "skill_id": "26412", "tree_id": "26214", "name2_refine": "Swish<br>샤샥", "name2_refine_en": "Swish", "pc_level": "15", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "NONE", "sort_no": null, "skill_icon": { "1": "skill_icon_summon_0_46.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/skill_icon_summon_0_8.png\' class=\'icon_in_description\' /> Target rooted <br/><img src=\'../img/skill/buff_debuff_icon_00_20.png\' class=\'icon_in_description\' /> Target frozen " }, "26209": { "skill_id": "26209", "tree_id": "26209", "name2_refine": "Curl<br>웅크리기", "name2_refine_en": "Curl", "pc_level": "16", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "Q", "sort_no": "89", "skill_icon": { "1": "skill_icon_summon_0_21.png", "11": "skill_icon_summon_0_21.png", "12": "skill_icon_summon_0_21.png", "14": "skill_icon_summon_0_21.png", "15": "skill_icon_summon_0_21.png", "23": "skill_icon_summon_0_21.png", "25": "skill_icon_summon_0_21.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26103": { "skill_id": "26103", "tree_id": "1", "name2_refine": "Entwine<br>휘감기", "name2_refine_en": "Entwine", "pc_level": "18", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "RB", "sort_no": "108", "skill_icon": { "1": "skill_icon_summon_0_4.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_03_26.png\' class=\'icon_in_description\' /> Target using block, counter ability " }, "26119": { "skill_id": "26119", "tree_id": "1", "name2_refine": "Escape<br>탈출", "name2_refine_en": "Escape", "pc_level": "20", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "1", "sort_no": "99", "skill_icon": { "1": "skill_icon_summon_0_36.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_42.png\' class=\'icon_in_description\' /> While suppressed, seized, force gripped " }, "26219": { "skill_id": "26219", "tree_id": "1", "name2_refine": "Boing Boing<br>뿌잉뿌잉", "name2_refine_en": "Boing Boing", "pc_level": "20", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "LB", "sort_no": "109", "skill_icon": { "1": "skill_icon_summon_0_5.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_11.png\' class=\'icon_in_description\' /> While meditating, ally is meditating " }, "26304": { "skill_id": "26304", "tree_id": "26304", "name2_refine": "Friendship<br>우정", "name2_refine_en": "Friendship", "pc_level": "22", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "X", "sort_no": "94", "skill_icon": { "1": "skill_icon_summon_0_41.png", "11": "skill_icon_summon_0_41.png", "12": "skill_icon_summon_0_41.png", "13": "skill_icon_summon_0_41.png", "14": "skill_icon_summon_0_41.png", "22": "skill_icon_summon_0_41.png", "24": "skill_icon_summon_0_41.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null }, "26419": { "skill_id": "26419", "tree_id": "26304", "name2_refine": "ThThump<br>우당탕", "name2_refine_en": "ThThump", "pc_level": "22", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_43.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/skill_icon_summon_0_41.png\' class=\'icon_in_description\' /> While Friendship is active " }, "26215": { "skill_id": "26215", "tree_id": "1", "name2_refine": "Uppercut<br>올려치기", "name2_refine_en": "Uppercut", "pc_level": "24", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "V", "sort_no": "92", "skill_icon": { "1": "skill_icon_summon_0_29.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_1.png\' class=\'icon_in_description\' /> Target groggy, stunned " }, "26216": { "skill_id": "26216", "tree_id": "26216", "name2_refine": "Flap Flap<br>파닥파닥", "name2_refine_en": "Flap Flap", "pc_level": "24", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "V", "sort_no": "92", "skill_icon": { "1": "skill_icon_summon_0_30.png", "11": "skill_icon_summon_0_30.png", "12": "skill_icon_summon_0_30.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_8.png\' class=\'icon_in_description\' /> Target airborne " }, "26208": { "skill_id": "26208", "tree_id": "1", "name2_refine": "Headbutt<br>박치기", "name2_refine_en": "Headbutt", "pc_level": "26", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "X", "sort_no": "93", "skill_icon": { "1": "skill_icon_summon_0_20.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/inventory_summoncat_1.png\' class=\'icon_in_description\' /> Familiar using Press " }, "26217": { "skill_id": "26217", "tree_id": "1", "name2_refine": "Guard<br>경호", "name2_refine_en": "Guard", "pc_level": "30", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_31.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_11.png\' class=\'icon_in_description\' /> While meditating " }, "26220": { "skill_id": "26220", "tree_id": "1", "name2_refine": "CPR<br>심폐소생술", "name2_refine_en": "CPR", "pc_level": "36", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "LB", "sort_no": "109", "skill_icon": { "1": "skill_icon_summon_0_12.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_11.png\' class=\'icon_in_description\' /> While dead, ally is dead " }, "26203": { "skill_id": "26203", "tree_id": "1", "name2_refine": "Cat's Gratitude<br>고양이의 보은", "name2_refine_en": "Cat's Gratitude", "pc_level": "45", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "F", "sort_no": "107", "skill_icon": { "1": "skill_icon_summon_0_13.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": "<img src=\'../img/skill/buff_debuff_icon_00_11.png\' class=\'icon_in_description\' /> While dead " }, "26559": { "skill_id": "26559", "tree_id": "1", "name2_refine": "Awakened Rose<br>각성 장미", "name2_refine_en": "Awakened Rose", "pc_level": "45", "pc_mastery_level": null, "complete_quest": null, "complete_quest_name": null, "default_keycap": "LB", "sort_no": "109", "skill_icon": { "1": "skill_icon_summon_0_47.png" }, "tooltip_stance_type": { "0": "소환", "1": null, "2": null }, "tooltip_stance_refine": null, "tooltip_condition_refine": null } };
js_download = """ var csv = source.get('data'); var filetext = 'itemnum,storename,date,usage,netsales\\n'; for (i=0; i < csv['date'].length; i++) { var currRow = [csv['itemnum'][i].toString(), csv['storename'][i].toString(), csv['date'][i].toString(), csv['usage'][i].toString(), csv['netsales'][i].toString().concat('\\n')]; var joined = currRow.join(); filetext = filetext.concat(joined); } var filename = 'results.csv'; var blob = new Blob([filetext], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); if (link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute var url = URL.createObjectURL(blob); link.setAttribute("href", url); link.setAttribute("download", filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } }""
const { REQUIRED_CONDITION_PARAMETER_MISSING, REQUIRED_RULE_DEPENDENCY_MISSING, REQUIRED_RULE_PARAMETER_MISSING } = require('./types'); const initializeTypesDefinition = require('./initializeTypesDefinition'); class RuleErrorHandler { constructor({ getRuleAttribute }) { this.addItem = this.addItem.bind(this); this.hasErrors = this.hasErrors.bind(this); this.getMessages = this.getMessages.bind(this); this.getMissingParameters = this.getMissingParameters.bind(this); this.getAllMissingParameters = this.getAllMissingParameters.bind(this); this.joinHandler = this.joinHandler.bind(this); this.getRuleAttribute = getRuleAttribute; this.types = {}; this.initializeTypesDefinition(); } getAllMissingParameters(){ return [ ...(this.types[REQUIRED_CONDITION_PARAMETER_MISSING].items||[]).map( ({id}) => id ), ...(this.types[REQUIRED_RULE_DEPENDENCY_MISSING].items||[]).map( ({id}) => id ), ...(this.types[REQUIRED_RULE_PARAMETER_MISSING].items||[]).map( ({id}) => id ) ]; } getMissingParameters( string ){ const dataType = this.getRuleAttribute("dataType"); const allMissingParameters = this.getAllMissingParameters(); return allMissingParameters.filter( missingParamId => ( string.includes( dataType === "template string" ? `{${missingParamId}}` : missingParamId ) )); } addItem(errorType, item){ if( this.types[ errorType ] ){ this.types[ errorType ].addItem( item ); } else { console.error('Invalid Type Provided to RuleErrorHandler.addItem Type: ' + errorType) } } getMessages(){ return Object.values( this.types ).reduce( ( messages, errorDefinition) => { if( errorDefinition.hasErrors() ){ messages = [ ...messages, errorDefinition.getMessage() ] } return messages; }, []) } hasErrors(){ return Object.values( this.types ).some( errorDefinition => errorDefinition.hasErrors() ) } joinHandler({ types }){ Object.values( types ).map( typeDef => { if( this.types[typeDef.id].items || typeDef.items ){ this.types[typeDef.id].items = [ ...this.types[typeDef.id].items||[], ...typeDef.items||[]] } }) } } RuleErrorHandler.prototype.initializeTypesDefinition = initializeTypesDefinition; module.exports = RuleErrorHandler;
const envEnum = require('./envEnum'); const api = require('./api'); module.exports = { EnvEnum: envEnum, api };
module.exports = function ( karma ) { karma.set({ /** * From where to look for files, starting with the location of this file. */ basePath: '../', /** * This is the list of file patterns to load into the browser during testing. */ files: [ <% scripts.forEach( function ( file ) { %>'<%= file %>', <% }); %> 'src/**/*.js', 'src/**/*.coffee', ], exclude: [ 'src/assets/**/*.js' ], frameworks: [ 'jasmine' ], plugins: [ 'karma-jasmine', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-coffee-preprocessor' ], preprocessors: { // '**/*.coffee': 'coffee', }, /** * How to report, by default. */ reporters: 'dots', /** * On which port should the browser connect, on which port is the test runner * operating, and what is the URL path for the browser to use. */ port: 9018, runnerPort: 9100, urlRoot: '/', /** * Disable file watching by default. */ autoWatch: true, /** * The list of browsers to launch to test on. This includes only "Firefox" by * default, but other browser names include: * Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS * * Note that you can also use the executable name of the browser, like "chromium" * or "firefox", but that these vary based on your operating system. * * You may also leave this blank and manually navigate your browser to * http://localhost:9018/ when you're running tests. The window/tab can be left * open and the tests will automatically occur there during the build. This has * the aesthetic advantage of not launching a browser every time you save. */ browsers: [ 'Firefox' ] }); };
var supertest = require('supertest'); var should = require('should'); describe('API tests: login', function() { var port = '7891'; // defined in global.js var request = supertest('http://localhost:' + port); describe('Login', function() { this.slow(500); it('should return an error on empty username', function(done) { request .post('/login') .set('x-requested-with', 'XmlHttpRequest') .send({username: '', password: ''}) .expect(400) .end(function(err, res) { if (err) throw err; res.body.errors[0].msg.should.equal('Missing username.'); done(); }); }); it('should return an error on wrong username', function(done) { request .post('/login') .set('x-requested-with', 'XmlHttpRequest') .send({username: 'admina', password: 'pwdadmin'}) .expect(401) .end(function(err, res) { if (err) throw err; res.body.errors[0].msg.should.equal('Incorrect username.'); done(); }); }); it('should return an error on empty password', function(done) { request .post('/login') .set('x-requested-with', 'XmlHttpRequest') .send({username: 'admin', password: ''}) .expect(400) .end(function(err, res) { if (err) throw err; res.body.errors[0].msg.should.equal('Missing password.'); done(); }); }); it('should return an error on wrong password', function(done) { request .post('/login') .set('x-requested-with', 'XmlHttpRequest') .send({username: 'admin', password: 'pwdadmina'}) .expect(401) .end(function(err, res) { if (err) throw err; res.body.errors[0].msg.should.equal('Incorrect password.'); done(); }); }); it('should return the logged user on successful login', function(done) { request .post('/login') .set('x-requested-with', 'XmlHttpRequest') .send({username: 'admin', password: 'pwdadmin'}) .expect(200) .end(function(err, res) { if (err) throw err; res.body.user.should.equal('admin'); done(); }); }); it('should return OK if the logout is successul performed', function(done) { request .post('/logout') .set('x-requested-with', 'XmlHttpRequest') .expect(200, done); }); }); })
/*global expect*/ describe('expect.it', function() { it('returns an expectation function that when applyed runs the assertion on the given subject', function() { var expectation = expect.it('to be greater than', 14); expectation(20); expect( function() { expectation(10); }, 'to throw', 'expected 10 to be greater than 14' ); }); it('is inspected as it is written', function() { var expectation = expect .it('to be a number') .and('to be less than', 14) .and('to be negative') .or('to be a string') .and('to have length', 6); expect( expect.inspect(expectation).toString(), 'to equal', "expect.it('to be a number')\n" + " .and('to be less than', 14)\n" + " .and('to be negative')\n" + " .or('to be a string')\n" + " .and('to have length', 6)" ); }); it('does not catch errors that are not thrown by unexpected', function() { var clonedExpect = expect .clone() .addAssertion('explode', function(expect, subject) { throw new Error('Explosion'); }); expect(clonedExpect.it('explode'), 'to throw', 'Explosion'); }); describe('with chained and', function() { it('all assertions has to be satisfied', function() { var expectation = expect .it('to be a number') .and('to be less than', 14) .and('to be negative'); expect( function() { expectation(20); }, 'to throw', '✓ expected 20 to be a number and\n' + '⨯ expected 20 to be less than 14 and\n' + '⨯ expected 20 to be negative' ); }); it('returns a new function', function() { var expectation = expect.it('to be a number'); var compositeExpectation = expectation.and('to be less than', 14); expect(compositeExpectation, 'not to be', expectation); expectation(20); expect( function() { compositeExpectation(20); }, 'to throw', '✓ expected 20 to be a number and\n' + '⨯ expected 20 to be less than 14' ); }); it('outputs one failing assertion correctly', function() { var expectation = expect .it('to be a number') .and('to be less than', 14) .and('to be negative'); expect( function() { expectation(8); }, 'to throw', '✓ expected 8 to be a number and\n' + '✓ expected 8 to be less than 14 and\n' + '⨯ expected 8 to be negative' ); }); }); describe('with chained or', function() { it('succeeds if any expectations succeeds', function() { var expectation = expect .it('to be a number') .or('to be a string') .or('to be an array'); expect(function() { expectation('success'); }, 'not to throw'); }); it('fails if all the expectations fails', function() { var expectation = expect .it('to be a number') .and('to be greater than', 6) .or('to be a string') .and('to have length', 6) .or('to be an array'); expect( function() { expectation('foobarbaz'); }, 'to throw', "⨯ expected 'foobarbaz' to be a number and\n" + "⨯ expected 'foobarbaz' to be greater than 6\n" + 'or\n' + "✓ expected 'foobarbaz' to be a string and\n" + "⨯ expected 'foobarbaz' to have length 6\n" + ' expected 9 to be 6\n' + 'or\n' + "⨯ expected 'foobarbaz' to be an array" ); }); it('if there are no and-clauses it writes the failure output more compactly', function() { var expectation = expect .it('to be a number') .or('to be a string') .or('to be an array'); expect( function() { expectation(true); }, 'to throw', '⨯ expected true to be a number or\n' + '⨯ expected true to be a string or\n' + '⨯ expected true to be an array' ); }); it('returns a new function', function() { var expectation = expect.it('to be a number'); var compositeExpectation = expectation.or('to be a string'); expect(compositeExpectation, 'not to be', expectation); expectation(20); expect( function() { compositeExpectation(20); compositeExpectation(true); }, 'to throw', '⨯ expected true to be a number or\n' + '⨯ expected true to be a string' ); }); }); describe('with async assertions', function() { var clonedExpect = expect .clone() .addAssertion('to be a number after a short delay', function( expect, subject ) { expect.errorMode = 'nested'; return expect.promise(function(run) { setTimeout( run(function() { expect(subject, 'to be a number'); }), 1 ); }); }) .addAssertion('to be finite after a short delay', function( expect, subject ) { expect.errorMode = 'nested'; return expect.promise(function(run) { setTimeout( run(function() { expect(subject, 'to be finite'); }), 1 ); }); }) .addAssertion('to be a string after a short delay', function( expect, subject ) { expect.errorMode = 'nested'; return expect.promise(function(run) { setTimeout( run(function() { expect(subject, 'to be a string'); }), 1 ); }); }); it('should succeed', function() { return clonedExpect.it('to be a number after a short delay')(123); }); it('should fail with a diff', function() { return expect( clonedExpect.it('to be a number after a short delay')(false), 'to be rejected with', 'expected false to be a number after a short delay\n' + ' expected false to be a number' ); }); describe('with a chained "and" construct', function() { it('should succeed', function() { return clonedExpect .it('to be a number after a short delay') .and('to be finite after a short delay')(123); }); it('should fail with a diff', function() { return expect( clonedExpect .it('to be a number after a short delay') .and('to be finite after a short delay')(false), 'to be rejected with', '⨯ expected false to be a number after a short delay and\n' + ' expected false to be a number\n' + '⨯ expected false to be finite after a short delay' ); }); }); describe('with a chained "or" construct', function() { it('should succeed', function() { return clonedExpect .it('to be a number after a short delay') .and('to be finite after a short delay') .or('to be a string after a short delay')('abc'); }); it('should fail with a diff', function() { return expect( clonedExpect .it('to be a number after a short delay') .and('to be finite after a short delay') .or('to be a string after a short delay')(false), 'to be rejected with', '⨯ expected false to be a number after a short delay and\n' + ' expected false to be a number\n' + '⨯ expected false to be finite after a short delay\n' + 'or\n' + '⨯ expected false to be a string after a short delay\n' + ' expected false to be a string' ); }); }); }); it('should not swallow a "missing assertion" error when using an expect.it(...).or(...) construct', function() { expect( function() { expect( 'foo', 'to satisfy', expect.it('this is misspelled', 1).or('to be a string') ); }, 'to throw', "expected 'foo' to satisfy\n" + "expect.it('this is misspelled', 1)\n" + " .or('to be a string')\n" + '\n' + "Unknown assertion 'this is misspelled', did you mean: 'to be fulfilled'" ); }); it('should fail with a "missing assertion" error even when it is not the first failing one in an "and" group', function() { expect( function() { expect( 'foo', 'to satisfy', expect .it('to begin with', 'bar') .and('misspelled') .or('to be a string') ); }, 'to throw', "expected 'foo' to satisfy\n" + "expect.it('to begin with', 'bar')\n" + " .and('misspelled')\n" + " .or('to be a string')\n" + '\n' + "Unknown assertion 'misspelled', did you mean: 'called'" ); }); it('should not fail when the first clause in an or group specifies an assertion that is not defined for the given arguments', function() { expect( [false, 'foo', 'bar'], 'to have items satisfying', expect.it('to be false').or('to be a string') ); }); describe('with forwarding of flags', function() { var clonedExpect = expect .clone() .addAssertion('<object> [not] to have a foo property of bar', function( expect, subject ) { return expect(subject, 'to satisfy', { foo: expect.it('[not] to equal', 'bar') }); }); it('should succeed', function() { clonedExpect({ quux: 123 }, 'not to have a foo property of bar'); }); it('should fail with a diff', function() { return expect( function() { clonedExpect({ foo: 'bar' }, 'not to have a foo property of bar'); }, 'to throw', "expected { foo: 'bar' } not to have a foo property of bar\n" + '\n' + '{\n' + " foo: 'bar' // should not equal 'bar'\n" + '}' ); }); }); describe('when passed a function', function() { it('should succeed', function() { expect.it(function(value) { expect(value, 'to equal', 'foo'); })('foo'); }); it('should fail with a diff', function() { expect( function() { expect.it(function(value) { expect(value, 'to equal', 'bar'); })('foo'); }, 'to throw', "expected 'foo' to equal 'bar'\n" + '\n' + '-foo\n' + '+bar' ); }); it('should fail when passed more than two arguments', function() { expect( function() { expect.it(function(value) { expect(value, 'to equal', 'bar'); }, 'yadda')('foo'); }, 'to throw', 'expect.it(<function>) does not accept additional arguments' ); }); }); });
'use strict'; var options = require('../config/config'); var AfricasTalking = require('africastalking')(options.AT); var db = require('./../models'); exports.voice = function(req, res) { var isActive = req.body.isActive; if (isActive === '1') { console.log(req.body); var response = '<Response>'; response += '<GetDigits timeout="30" finishOnKey="#" callbackUrl="http://62.12.117.25:8010/voiceMenus">'; response += '<Say>Thank you for calling Biz Africa. Press 0 followed by the hash sign to talk to sales, 1 followed by the hash sign to talk to support or 2 followed by the hash sign to hear this message again.</Say>'; response += '</GetDigits>'; response += '<Say>Thank you for calling. Good bye!</Say>'; response += '</Response>'; res.setHeader('Content-Type', 'text/plain'); res.send( response ); } else { db.Voice.create({ 'durationInSeconds': req.body.durationInSeconds, 'direction': req.body.direction, 'amount': req.body.amount, 'callerNumber': req.body.callerNumber, 'destinationNumber': req.body.destinationNumber, 'sessionId': req.body.sessionId, 'callStartTime': req.body.callStartTime, 'isActive': req.body.isActive, 'currencyCode': req.body.currencyCode, 'status': req.body.status }).then(function(voice) { console.log('client added', voice); }); } };
var searchData= [ ['index_2ephp',['index.php',['../Assets_2CSS_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Views_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Model_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Controllers_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../conf_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Assets_2JS_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Assets_2index_8php.html',1,'']]], ['index_2ephp',['index.php',['../Assets_2IMG_2index_8php.html',1,'']]] ];
var app = angular.module('SampleApp', [ 'swiftsuggest' ]); app.controller('SimpleController', function($scope, $http, $timeout) { $scope.moderators = []; $scope.selectedModerator = null; $scope.selectModerator = function(user, suggest) { $scope.selectedModerator = user; suggest.clearInput(); }; $scope.updateSuggestions = function(term) { $scope.users = []; $timeout(function() { users = [ {name: 'Laju', description: 'Some description'}, {name: 'Misan', description: 'Some description'}, {name: 'Miskoli', description: 'Some description'}, {name: 'LajuStick', description: 'Some description'}, {name: 'Timeyin', description: 'Some description'} ]; }, 1000).then(function() { $scope.moderators = users; }); } }); app.config(function() { });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var common_1 = require("@angular/common"); var forms_1 = require("@angular/forms"); exports.TRISTATECHECKBOX_VALUE_ACCESSOR = { provide: forms_1.NG_VALUE_ACCESSOR, useExisting: core_1.forwardRef(function () { return TriStateCheckbox; }), multi: true }; var TriStateCheckbox = (function () { function TriStateCheckbox(cd) { this.cd = cd; this.onChange = new core_1.EventEmitter(); this.onModelChange = function () { }; this.onModelTouched = function () { }; } TriStateCheckbox.prototype.onClick = function (event, input) { if (!this.disabled) { this.toggle(event); this.focus = true; input.focus(); } }; TriStateCheckbox.prototype.onKeydown = function (event) { if (event.keyCode == 32) { event.preventDefault(); } }; TriStateCheckbox.prototype.onKeyup = function (event) { if (event.keyCode == 32) { this.toggle(event); event.preventDefault(); } }; TriStateCheckbox.prototype.toggle = function (event) { if (this.value == null || this.value == undefined) this.value = true; else if (this.value == true) this.value = false; else if (this.value == false) this.value = null; this.onModelChange(this.value); this.onChange.emit({ originalEvent: event, value: this.value }); }; TriStateCheckbox.prototype.onFocus = function () { this.focus = true; }; TriStateCheckbox.prototype.onBlur = function () { this.focus = false; this.onModelTouched(); }; TriStateCheckbox.prototype.registerOnChange = function (fn) { this.onModelChange = fn; }; TriStateCheckbox.prototype.registerOnTouched = function (fn) { this.onModelTouched = fn; }; TriStateCheckbox.prototype.writeValue = function (value) { this.value = value; this.cd.markForCheck(); }; TriStateCheckbox.prototype.setDisabledState = function (disabled) { this.disabled = disabled; }; return TriStateCheckbox; }()); TriStateCheckbox.decorators = [ { type: core_1.Component, args: [{ selector: 'p-triStateCheckbox', template: "\n <div [ngStyle]=\"style\" [ngClass]=\"'ui-chkbox ui-tristatechkbox ui-widget'\" [class]=\"styleClass\">\n <div class=\"ui-helper-hidden-accessible\">\n <input #input type=\"text\" [attr.id]=\"inputId\" [name]=\"name\" [attr.tabindex]=\"tabindex\" readonly [disabled]=\"disabled\" (keyup)=\"onKeyup($event)\" (keydown)=\"onKeydown($event)\" (focus)=\"onFocus()\" (blur)=\"onBlur()\">\n </div>\n <div class=\"ui-chkbox-box ui-widget ui-corner-all ui-state-default\" (click)=\"onClick($event,input)\"\n [ngClass]=\"{'ui-state-active':value!=null,'ui-state-disabled':disabled,'ui-state-focus':focus}\">\n <span class=\"ui-chkbox-icon fa ui-clickable\" [ngClass]=\"{'fa-check':value==true,'fa-close':value==false}\"></span>\n </div>\n </div>\n ", providers: [exports.TRISTATECHECKBOX_VALUE_ACCESSOR] },] }, ]; /** @nocollapse */ TriStateCheckbox.ctorParameters = function () { return [ { type: core_1.ChangeDetectorRef, }, ]; }; TriStateCheckbox.propDecorators = { 'disabled': [{ type: core_1.Input },], 'name': [{ type: core_1.Input },], 'tabindex': [{ type: core_1.Input },], 'inputId': [{ type: core_1.Input },], 'style': [{ type: core_1.Input },], 'styleClass': [{ type: core_1.Input },], 'onChange': [{ type: core_1.Output },], }; exports.TriStateCheckbox = TriStateCheckbox; var TriStateCheckboxModule = (function () { function TriStateCheckboxModule() { } return TriStateCheckboxModule; }()); TriStateCheckboxModule.decorators = [ { type: core_1.NgModule, args: [{ imports: [common_1.CommonModule], exports: [TriStateCheckbox], declarations: [TriStateCheckbox] },] }, ]; /** @nocollapse */ TriStateCheckboxModule.ctorParameters = function () { return []; }; exports.TriStateCheckboxModule = TriStateCheckboxModule; //# sourceMappingURL=tristatecheckbox.js.map
/*global $ Matrix Point */ /** * Represents an instance of UnshredTag API client. * @constructor * @param {string} baseUrl - Base URL to use for HTTP requests, e.g. "/api". */ var UnshredAPIClient = function (baseUrl) { this.baseUrl = baseUrl; // Attributes handle shred cache; // shredCache is a mapping of shredId -> shredObj; this.shredCache = {}; // shredCallbacksPending maps shredId -> [success(), error()] callbacks // whileshred request is in-flight. this.shredCallbacksPending = {}; // Maximum number of shred cache entries. this.shredCacheSize = 100; }; /** * Constructs and sends an HTTP request to an API endpoint. * * @param {string} type - HTTP request type. * @param {path} path - Path under baseUrl for request (no leading "/"). * @param success - A success callback, called with returned data as arg. * @param error - Failure callback. Called on error. * @data {Object} [data] - Optional data object to serialize as json and send * with request. */ UnshredAPIClient.prototype.Request = function(type, path, success, error, data) { var opts = { type: type, url: this.baseUrl + "/" + path, dataType: 'json', contentType: 'application/json', success: success, error: error }; if (data) { opts.data = JSON.stringify(data); } $.ajax(opts); }; /** * Fetches a single Shred instance. * * @param {string} shredId - Shred ID to fetch. * @param success - Success callback. Called with shred instance as an argument. * @param error - Failure callback. */ UnshredAPIClient.prototype.GetShred = function (shredId, success, error) { console.log("Getting shred " + shredId); if (this.shredCache[shredId] !== undefined) { success(this.shredCache[shredId]); return; } if (this.shredCallbacksPending[shredId] !== undefined) { this.shredCallbacksPending[shredId].push([success, error]); return; } if (Object.keys(this.shredCache).length >= this.shredCacheSize) { this.shredCache = {}; } this.shredCallbacksPending[shredId] = [[success, error]]; var client = this; this.Request("GET", "shred/" + shredId, function (response_data) { client.shredCache[shredId] = response_data.data.shred; var callbacks; while ((callbacks = client.shredCallbacksPending[shredId].pop()) !== undefined) { callbacks[0](response_data.data.shred); } delete client.shredCallbacksPending[shredId]; }, function(error) { var callbacks; while ((callbacks = client.shredCallbacksPending[shredId].pop()) !== undefined) { callbacks[1](error); } delete client.shredCallbacksPending[shredId]; }); }; /** * Fetches a single Cluster instance. * * @param {string} clusterId - Shred ID to fetch. * @param success - Success callback. Called with Cluster instance as an * argument. * @param error - Failure callback. */ UnshredAPIClient.prototype.GetCluster = function (clusterId, success, error) { console.log("Getting cluster " + clusterId); var path = "cluster"; if (clusterId !== null) { path += "/" + clusterId; } this.Request("GET", path, function (response_data) { success(response_data.data.cluster); }, error); }; /** * Fetches a pair of clusters from the backend. The pair is expected to be * somewhat related, possibly suitable for stitching. * * @param success - Success callback. On success called with two cluster * objects. * @param error - Failure callback. */ UnshredAPIClient.prototype.GetClusterPairForStitching = function(success, error) { console.log("Getting cluster pair."); var pair = []; this.Request("GET", "cluster-pair", function(response_data) { var data = response_data.data; success(data.shreds_pair[0], data.shreds_pair[1]); }, error); }; /** * Merges two clusters, given their relative positions. * * @param cluster1 - An object with 'members' and '_id' fields. Every member has * 'shred', 'position', 'angle' fields. * @param position1 - Relative position of cluster1. List of [x, y]. * @param angle1 - Relative angle of cluster1 in degrees. * @param cluster2 - Second cluster object. Same type as cluster1. * @param position2 - Relative position of cluster2. List of [x, y]. * @param angle2 - Relative angle of cluster2 in degrees. * @param success - Success callback. On success called with a single argument - * string new cluster id. * @param error - Failure callback. */ UnshredAPIClient.prototype.MergeClusters = function (cluster1, position1, angle1, cluster2, position2, angle2, success, error) { // Angle in degrees. // // Translate to cluster1's [0, 0] as origin. position2[0] -= position1[0]; position1[0] -= position1[0]; position2[1] -= position1[1]; position1[1] -= position1[1]; var degreesToRadians = function(angle) { return angle * Math.PI / 180; }; var radiansToDegrees = function(angle) { return angle / (Math.PI / 180); }; var copyMember = function(member) { return { shred: member.shred, position: member.position, angle: member.angle }; }; // Angle is in degrees. Need radians for rotation matrix. angle1 = degreesToRadians(angle1); angle2 = degreesToRadians(angle2); var members = []; // Transform cluster1's members. for (var i = 0; i < cluster1.members.length; i++) { members.push(copyMember(cluster1.members[i])); } // m1 rotates clusters' origins around (0,0); var m1 = Matrix().rotate(-angle1); // m2 rotates shred origins around cluster2 origin. var m2 = Matrix().rotate(angle2); var cluster2Position = Point(position2[0], position2[1]); for (var j = 0; j < cluster2.members.length; j++) { var member = copyMember(cluster2.members[j]); var p = Point(member.position[0], member.position[1]); // Rotate member base point around it's cluster's origin. p = m2.transformPoint(p); // Transform to coordinates relative to base cluster's origin. p = p.add(cluster2Position); // Rotate member origin around base cluster's origin. p = m1.transformPoint(p); member.position = [p.x, p.y]; // Angle to degrees. member.angle = member.angle + radiansToDegrees(angle2-angle1); members.push(member); } var data = { cluster: { parents: [cluster1._id, cluster2._id], members: members } }; console.log(data); this.Request("POST", "cluster", function (response_data) { success(response_data.id); }, error, data); return data; };
/* Renderer test */ var fs = require('fs'); var app = require("./app.js"); var svg2png = require('svg2png'); var Renderer = require(app.basepath + "/libs/renderer.js"); Renderer.init(app); var path = app.basepath + "/tests/exports/"; fs.access(path, fs.R_OK | fs.W_OK, function(err) { if (err) { fs.mkdirSync(path); } var png = function(name) { svg2png(path + name + '.svg', path + name + '.png', 0.3, function (err) { if (err) console.log("svg2png", err); }); }; //Value + no loading Renderer.settings.display_level = "true"; var i, name; for (i = 0; i <= 100; i++) { name = Renderer.createName(i, false, false); Renderer.render(i, false, false, path + name + ".svg"); png(name); } //Value + loading for (i = 0; i <= 100; i++) { name = Renderer.createName(i, true, false); Renderer.render(i, true, false, path + name + ".svg"); png(name); } //no value + loading Renderer.settings.display_level = "false"; name = Renderer.createName(0, true, false); Renderer.render(0, true, false, path + name + ".svg"); png(name); //no value + no loading var values = [0,10,40,70]; for (i = 0; i < values.length; i++) { name = Renderer.createName(values[i], false, false); Renderer.render(values[i], false, false, path + name + ".svg"); png(name); } });
'use strict'; var soapEnvelope = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">' + '{header}' + '{body}' + '</s:Envelope>'; var authenticationHeader = '<s:Header>' + '<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>' + '<a:MessageID>urn:uuid:{messageId}</a:MessageID>' + '<a:ReplyTo>' + '<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>' + '</a:ReplyTo>' + '<a:To s:mustUnderstand="1">{authUrl}</a:To>' + '<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">' + '<u:Timestamp u:Id="_0">' + '<u:Created>{created}</u:Created>' + '<u:Expires>{expires}</u:Expires>' + '</u:Timestamp>' + '<o:UsernameToken u:Id="uuid-{usernameToken}-1">' + '<o:Username>{username}</o:Username>' + '<o:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">{password}</o:Password>' + '</o:UsernameToken>' + '</o:Security>' + '</s:Header>'; var authenticationBody = '<s:Body>' + '<t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">' + '<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">' + '<a:EndpointReference>' + '<a:Address>urn:{organizationUrl}</a:Address>' + '</a:EndpointReference>' + '</wsp:AppliesTo>' + '<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>' + '</t:RequestSecurityToken>' + '</s:Body>'; var soapAuthenticationEnvelopeTemplate = soapEnvelope .replace('{header}', authenticationHeader) .replace('{body}', authenticationBody); var headerTemplate = '<s:Header>' + '<a:Action s:mustUnderstand="1">http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/{message}</a:Action>' + '<a:MessageID>{messageId}</a:MessageID>' + '<a:ReplyTo><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>' + '<a:To s:mustUnderstand="1">{organizationUrl}</a:To>' + '<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">' + '<u:Timestamp u:Id="_0"><u:Created>{created}</u:Created>' + '<u:Expires>{expires}</u:Expires></u:Timestamp>' + '<EncryptedData Id="Assertion0" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">' + '<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc"></EncryptionMethod>' + '<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><EncryptedKey><EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"></EncryptionMethod>' + '<ds:KeyInfo Id="keyinfo"><wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">' + '<wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier">{keyIdentifier}</wsse:KeyIdentifier>' + '</wsse:SecurityTokenReference></ds:KeyInfo><CipherData>' + '<CipherValue>{tokenOne}</CipherValue>' + '</CipherData></EncryptedKey></ds:KeyInfo><CipherData>' + '<CipherValue>{tokenTwo}</CipherValue>' + '</CipherData></EncryptedData></o:Security></s:Header>'; var whoAmIRequestTemplate = '<s:Body><Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' + '<request i:type="c:WhoAmIRequest" xmlns:b="http://schemas.microsoft.com/xrm/2011/Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://schemas.microsoft.com/crm/2011/Contracts">' + '<b:Parameters xmlns:d="http://schemas.datacontract.org/2004/07/System.Collections.Generic"/><b:RequestId i:nil="true"/>' + '<b:RequestName>WhoAmI</b:RequestName>' + '</request></Execute></s:Body>'; var createRequestTemplate = '<s:Body>' + '<Create xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">' + '<entity xmlns:a="http://schemas.microsoft.com/xrm/2011/Contracts">' + '<a:Attributes xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic">' + '{attributes}' + '</a:Attributes>' + '<a:EntityState i:nil="true" />' + '<a:FormattedValues xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />' + '<a:Id>00000000-0000-0000-0000-000000000000</a:Id>' + '<a:LogicalName>{logicalname}</a:LogicalName>' + '<a:RelatedEntities xmlns:b="http://schemas.datacontract.org/2004/07/System.Collections.Generic" />' + '</entity>' + '</Create>' + '</s:Body>'; module.exports.soapEnvelopeTemplate = soapEnvelope; module.exports.soapRequestHeader = headerTemplate; module.exports.authenticationEnvelope = soapAuthenticationEnvelopeTemplate; module.exports.whoAmIRequestBodyTemplate = whoAmIRequestTemplate; module.exports.createRequestBodyTemplate = createRequestTemplate;
/** * Helpers and tools to ease your JavaScript day. * * @author Mikael Roos (me@mikaelroos.se) */ window.Foiki = (function(window, document, undefined ) { var Foiki = {}; /** * Display the type of the object * @param the object to check */ Foiki.reflection = function (obj) { // if (typeof obj === 'undefined') console.log("is type: Undefined"); // if (typeof obj === 'boolean') console.log("is type: Boolean"); // if (typeof obj === 'number') console.log("is type: Number"); // if (typeof obj === 'string') console.log("is type: String"); // if (typeof obj === 'function') console.log("is type: Function"); // if (typeof obj === 'object') console.log("is type: Object"); console.log("is type: " + typeof obj); if (isNaN(obj)) { console.log("is NaN, Not a Number"); } if (isFinite(obj)) { console.log("is a real number, not Infinite nor NaN"); } if (obj instanceof Array) console.log("is instance of: Array"); if (obj instanceof Boolean) console.log("is instance of: Boolean"); if (obj instanceof Date) console.log("is instance of: Date"); if (obj instanceof Function) console.log("is instance of: Function"); if (obj instanceof Number) console.log("is instance of: Number"); if (obj instanceof RegExp) console.log("is instance of: RegExp"); if (obj instanceof String) console.log("is instance of: String"); if (obj instanceof Error) console.log("is instance of: Error"); if (obj instanceof Object) console.log("is instance of: Object"); if (obj !== null && typeof obj !== 'undefined') { console.log("toString(): " + obj.toString()); console.log("valueOf(): " + obj.valueOf()); } }; /** * Display properties of an object * * @param the object to show */ Foiki.properties = function (obj) { if (typeof obj !== 'object') { console.log('Not an object.'); } else { console.log('Object has the following properties:') for (var prop in obj) { console.log(prop + ' : ' + obj[prop]); } } }; /** * Dump own properties of an object * * @param the object to show */ Foiki.dump = function (obj) { if (typeof obj !== 'object') { console.log('Not an object.'); } else { for (var prop in obj) { if (obj.hasOwnProperty(prop)) { console.log(prop); } } } }; /** * Dump properties and values of an object * * @param the object to show * * @returns string */ Foiki.dumpAsString = function (obj) { var s = '\n'; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { s += prop + ' : ' + obj[prop] + '\n'; } } return s; }; /** * Delete cached LESS files from local storage. * * @param regular expressen to search for, for example /style.less/ */ Foiki.deleteLESSFromLocalStorage = function (which) { for (var item in window.localStorage) { if (item.match(which)) { console.log('Deleted ' + item + ':' + (delete window.localStorage[item])); } } }; /** * Generate a random number. * * @param min the smallest possible number * @param max the largest possible number * * @returns a random number where min >= number <= max */ Foiki.random = function (min, max) { return Math.floor(Math.random()*(max+1-min)+min); }; /** * Get the position of an element. * http://stackoverflow.com/questions/442404/dynamically-retrieve-html-element-x-y-position-with-javascript * * @param el the element. */ Foiki.getOffset = function ( el ) { var _x = 0; var _y = 0; while (el && ! isNaN(el.offsetLeft) && ! isNaN(el.offsetTop)) { _x += el.offsetLeft - el.scrollLeft; _y += el.offsetTop - el.scrollTop; el = el.offsetParent; } return { top: _y, left: _x }; } // Expose public methods return Foiki; })(window, window.document);
import buildCakedayRoute from "discourse/plugins/discourse-cakeday/discourse/routes/build-cakeday-route"; export default buildCakedayRoute("birthday", "tomorrow");
/** * Copyright (c) 2017 Steve Simenic <orffen@orffenspace.com> * * This file is part of the SWN Toolbox. * * 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. */ var leaderships = [ "Social elite: the group is led by members of the planet's ruling class", "Outcasts: the group's leadership is filled out by members of a taboo, outcast, or otherwise socially marginal group", "Bourgeoisie: the group is driven by a leadership drawn from the middle class and those aspiring to join the elite", "Proletariat: the working class, both agricultural and industrial, provides the leadership for this group", "Urban: city-dwellers compose the leadership of the group", "Rural: farmers, herdsmen, small-town artisans, and other residents of the rural zones of a planet make up the leadership of the group", "Pious: clergy and devout laymen of a religion form the leadership", "Intellectuals: the movement is led by intellectuals" ]; var economicPolicies = [ "Laissez-faire: minimal or no government intervention in the market", "State industry: the government should own or support specific industries important to the group", "Protectionist: the government should tax imports that threaten to displace the products of local manufactures", "Autarky: the government should ensure that the world can provide all of its own goods and services and forbid the import of foreign goods", "Socialist: the market should be harnessed to ensure a state-determined minimal standard of living for all", "Communist: the state should control the economy, disbursing its products according to need and determined efficiency" ]; var importantIssues = [ "Poverty among the group's membership", "Social hostility to the group's membership", "Immigration and immigrants", "The membership's important industries", "Religion in public life", "Gender roles and sexual mores", "Culture of the group membership", "Military preparedness", "Governmental reform", "Secession", "Foreign relations", "Wealth redistribution" ]; var descriptors = [ "People's", "Freedom", "National", "Unified", "Democratic", "Royal", "Social", "Progressive", "Popular", "Republican", "Federal", "Liberty", "(A local animal)", "Homeland", "Conservative", "Liberal", "Victory", "Black", "White", "Red", "Green", "Blue", "Yellow", "Scarlet", "Emerald", "Cyan", "Amber", "Purple", "Crimson", "Grey", "Orange", "Bronze", "Silver", "Gold", "Steel", "Iron", "Northern", "Southern", "Western", "Eastern", "Ascendant", "Upward" ]; var names = [ "Front", "Party", "Faction", "Group", "Element", "Consensus", "Council", "Banner", "Union", "Combine", "Society", "Sodality", "Brotherhood", "Commune", "Pact", "Foundation", "Fellowship", "Guild", "Federation", "Alliance" ]; function generatePoliticalParty() { var name = descriptors[Math.floor(Math.random() * descriptors.length)] + " " + names[Math.floor(Math.random() * names.length)]; var leadership = leaderships[Math.floor(Math.random() * leaderships.length)]; var economicPolicy = economicPolicies[Math.floor(Math.random() * economicPolicies.length)]; var importantIssue = importantIssues[Math.floor(Math.random() * importantIssues.length)]; return [name, leadership, economicPolicy, importantIssue]; }
/** * Created by WareBare on 11/2/2016. */ class cBase extends libWZ.Core.cBase{ constructor(){ super(); // DBR for mod folder (DS - DataSet) //noinspection JSUnresolvedVariable //this._modDBR_DS = wzGD_dataSet; //this._configGD = _wzData.Settings.configGD; //this._tplApp = _wzTPL.AppGD; //this.pathMod = this.getPathMod(); //this._dataGD = _wzData.GrimDawn; //this._propertiesGD = this._dataGD.Properties; //this.traitsGD = libWZ.GrimDawn.oTraits; this.fn = libWZ.GrimDawn.tFn; /* * LvL | DPS * 1 | 50 * 10 | 80 | 140 * 25 | 110 | 191 * 40 | 140 | 244 * 55 | 165 | 287 * 70 | 180 | 320 * 85 | 200 | 345 * * 58 = 0.35 * 75 = 0.45 * 103 = 0.62 * 108 = 0.65 * 132 = 0.80 * 141 = 0.85 * 157 = 0.95 * let testLvL = 70, minMul = 0.10, maxMul = 0.22, atkMul = 1.0, minDmg = parseInt(this.mathStatValue('offensivePhysicalMin',testLvL,1,minMul)), maxDmg = parseInt(this.mathStatValue('offensivePhysicalMax',testLvL,1,maxMul)), avgDmg = (minDmg + maxDmg) / 2, atkSpeed = ( (1 + this.mathStatValue('characterBaseAttackSpeed',testLvL,1) * atkMul * -0.1) * 1.25).toFixed(2); console.log(`${minDmg} - ${maxDmg} (${avgDmg}); Speed ${atkSpeed}; DPS ${ (avgDmg * atkSpeed).toFixed(2)}`); */ //this.mathStatValue('offensivePierceRatioMin',100,1,0.12); //console.log(this.getTagAttackSpeed(-0.17)); //this.mathStatValue('characterManaRegen',4,1); /* let eq = 0; for(let i=1; i<=85; i++){ //eq = (((((i*i*i)^1.16)*32)+((i*i)*300))*0.1)+36; //eq = (((((i*i*i)^1.16)*32)+((i*i)*300))*0.1)+36; eq = ((((((i*i*i)**1.16)*32)+((i*i)*300))*0.1)+36) - eq; console.log(`${i}: ${eq}`); } */ } /* getTagValue($tag){ return this._modDBR_DS.getTags()[$tag]; } getPathMod(){ return this._configGD.getData().Paths.Home+'/'+this._configGD.getData().Paths.Mods[this._configGD.getData().activeMod]; } mathStatIndex($level){ let ret = $level / 10; if(ret.toString().indexOf('.') != -1){ //console.log('needs math'); let tempDown = Math.floor(ret), tempUp = Math.ceil(ret), tempFraction = ret - tempDown; ret = [tempDown,tempUp,tempFraction]; } //ret = Math.floor(ret); return ret; } mathStatValue($fieldName,$level,$dec,$mul){ let prop = this._propertiesGD.getData().properties, settings = this._propertiesGD.getData().settings, ret = false; $fieldName = $fieldName || 'characterLife'; $level = $level || 10; //$dec = $dec || 0; $mul = $mul || 1; let iLevel = $level, reqLevel = ($level >= 85) ? 85 : $level, mulIndex = this.mathStatIndex($level); //useDec = Math.pow(10,$dec); //useDec = ($dec == 0) ? 1 : 10 * $dec; let fieldValue = prop[$fieldName].value, fieldMul = (Array.isArray(mulIndex)) ? ((settings.scale[prop[$fieldName].scale][mulIndex[1]] - settings.scale[prop[$fieldName].scale][mulIndex[0]]) * mulIndex[2]) + settings.scale[prop[$fieldName].scale][mulIndex[0]]: settings.scale[prop[$fieldName].scale][mulIndex]; ret = Math.ceil(fieldValue * fieldMul * $mul).toFixed($dec); //ret = fieldValue * fieldMul; //console.log(fieldValue); //console.log(fieldMul); //console.log(useDec); //console.log(ret); return ret; } */ } module.exports = cBase;
/*! * hnzswh-dolalive * Copyright(c) 2015 hnzswh-dolalive <3203317@qq.com> * MIT Licensed */ 'use strict'; var util = require('speedt-utils'), EventProxy = require('eventproxy'), path = require('path'), fs = require('fs'), velocity = require('velocityjs'), cwd = process.cwd(); var conf = require('../../settings'), macros = require('../../lib/macro'); var biz = { menu: require('../../../biz/menu') }; /** * * @params * @return */ exports.indexUI = function(req, res, next){ biz.menu.getByPId('1', function (err, docs){ if(err) return next(err); var topMenu = docs; var first = docs[0]; // TODO biz.menu.getChildrenByPId(first.id, function (err, docs){ if(err) return next(err); var childMenu = docs; // TODO res.render('manage/Index', { conf: conf, title: '后台管理 | '+ conf.corp.name, description: '', keywords: ',dolalive,html5', data: { topMenu: topMenu, childMenu: childMenu } }); }); }); }; /** * * @params * @return */ exports.indexUI_side = function(req, res, next){ var result = { success: false }; var pid = req.params.pid; biz.menu.getChildrenByPId(pid, function (err, docs){ if(err) return next(err); // TODO exports.getTemplate(function (err, template){ if(err){ result.msg = err; return res.send(result); } var html = velocity.render(template, { conf: conf, data: { childMenu: docs } }, macros); result.success = true; result.data = html; res.send(result); }); }); }; (function (exports){ var temp = null; /** * 获取模板 * * @params * @return */ exports.getTemplate = function(cb){ // if(temp) return cb(null, temp); fs.readFile(path.join(cwd, 'views', 'manage', '_pagelet', 'Side.Nav.html'), 'utf8', function (err, template){ if(err) return cb(err); temp = template; cb(null, template); }); }; })(exports); /** * * @params * @return */ exports.welcomeUI = function(req, res, next){ res.render('manage/Welcome', { conf: conf, title: '欢迎页 | 后台管理 | '+ conf.corp.name, description: '', keywords: ',dolalive,html5' }); };
`use strict` const express = require('express') const app = express() // body parser const bodyParser = require('body-parser') app.use(bodyParser.json()); // for parsing application/json app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded // 启动服务器 const port = 80 const server = app.listen(port, () => { console.log(`food-energy is running at port ${port}`) }) // mongoDB相关 const MongoClient = require('mongodb').MongoClient const dbURL = 'mongodb://localhost:27017/food-energy' const collectionName = 'entry' // 静态资源 app.use(express.static('public')) // app.use(express.static('public/pages')) // 路由 // food-energy首页 app.get('/food-energy', (req, res) => { res.sendFile('/food-energy/index.html') }) // 处理提交的申请 app.post('/food-energy/submit', (req, res) => { let entry = req.body.entry // 提交的时间 entry.date = new Date() // 连接数据库 MongoClient.connect(dbURL, (err, db) => { if (err) { console.log(err) return } console.log('connected successfully') let col = db.collection(collectionName) // 增加数据 col.insert(entry, (err, result) => { if (err) { console.log(err) res.send('垃圾服务器又出错了,麻烦你再重试一次') } else { console.log(result) res.redirect('/food-energy/success.html') } db.close() }) }) }) // 查询 app.get('/food-energy/query', (req, res) => { MongoClient.connect(dbURL, (err, db) => { if (err) { console.log(err) return } console.log('成功连接数据库') let col = db.collection(collectionName) col.find().toArray((err, docs) => { if (err) { console.log(err) return } else { console.log(docs) res.json(docs) } db.close() }) }) })
import { joinCommandArgs, requireArgs } from './util' export function formatRmCommand({ file }) { requireArgs(['file'], { file }, 'rm') const args = ['rm', file] return joinCommandArgs(args) }
$(function() { simpleCart({ // array representing the format and columns of the cart, see // the cart columns documentation cartColumns: [ { attr: "name" , label: "Nimi" }, { attr: "price" , label: "Hinta", view: 'currency' }, { view: "decrement" , label: false }, { attr: "quantity" , label: "Määrä" }, { view: "increment" , label: false }, { attr: "total" , label: "Yhteensä", view: 'currency' }, { view: "remove" , text: "Poista" , label: false } ], // "div" or "table" - builds the cart as a table or collection of divs cartStyle: "div", // how simpleCart should checkout, see the checkout reference for more info checkout: { type: "PayPal" , email: "you@yours.com" }, // set the currency, see the currency reference for more info currency: "EUR", // collection of arbitrary data you may want to store with the cart, // such as customer info data: {}, // set the cart langauge (may be used for checkout) language: "english-us", // array of item fields that will not be sent to checkout excludeFromCheckout: [ 'qty', 'thumb' ], // custom function to add shipping cost shippingCustom: null, // flat rate shipping option shippingFlatRate: 0, // added shipping based on this value multiplied by the cart quantity shippingQuantityRate: 0, // added shipping based on this value multiplied by the cart subtotal shippingTotalRate: 0, // tax rate applied to cart subtotal taxRate: 0, // true if tax should be applied to shipping taxShipping: false, // event callbacks beforeAdd : null, afterAdd : null, load : null, beforeSave : null, afterSave : null, update : null, ready : null, checkoutSuccess : null, checkoutFail : null, beforeCheckout : null }); simpleStore.init({ // brand can be text or image URL brand : "SyforeShop", // numder of products per row (accepts 1, 2 or 3) numColumns : 3, // name of JSON file, located in directory root JSONFile : "products.json" }); });
class QueryClause { constructor(name = '', type = ':', args = []) { this.name = name; this.type = type; this.args = args; } hasArgs() { return this.args.length > 0; } addArg(arg) { this.args.push(arg); } getArg(i = 0) { if (this.args.length > i) { return this.args[i]; } return null; } } export default QueryClause;
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides default renderer for control sap.ui.commons.RowRepeater sap.ui.define(['jquery.sap.global', './Button', './Paginator', './Toolbar'], function(jQuery, Button, Paginator, Toolbar) { "use strict"; /** * RowRepeater renderer. * @namespace */ var RowRepeaterRenderer = { }; /** * Renders the HTML for the given control, using the provided {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} oRenderManager the RenderManager that can be used for writing to the Render-Output-Buffer * @param {sap.ui.core.Control} oControl an object representation of the control that should be rendered */ RowRepeaterRenderer.render = function(oRenderManager, oControl){ // opening root DIV oRenderManager.write("<div"); oRenderManager.writeControlData(oControl); // add design CSS class: sapUiRrDesignStandard/sapUiRrDesignTransparent/sapUiRrDesignBareShell oRenderManager.addClass("sapUiRrDesign" + oControl.getDesign() ); oRenderManager.writeClasses(); oRenderManager.write(">"); // render the row repeater header (not in BARESHELL design) if ( oControl.getDesign() !== sap.ui.commons.RowRepeaterDesign.BareShell) { this.renderHeader(oRenderManager, oControl); } // render the row repeater body this.renderBody(oRenderManager, oControl); // render the row repeater footer (not in BARESHELL design) if ( oControl.getDesign() !== sap.ui.commons.RowRepeaterDesign.BareShell) { this.renderFooter(oRenderManager, oControl); } // closing root DIV oRenderManager.write("</div>"); }; RowRepeaterRenderer.renderHeader = function(oRenderManager, oControl) { // render the primary toolbar this.renderPrimaryToolbar(oRenderManager, oControl); // render the secondary toolbar only if more than one sorter is defined if (oControl.getSorters().length > 1 && oControl.isBound()) { this.renderSecondaryToolbar(oRenderManager, oControl); } }; RowRepeaterRenderer.renderPrimaryToolbar = function(oRenderManager, oControl) { // opening primary toolbar DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrPtb"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render a title if the title aggregation is provided if (oControl.getTitle() !== null) { this.renderTitle(oRenderManager, oControl); } // render the buttons of the filter this.renderFilterToolbar(oRenderManager, oControl); // always render the controller that displays either pager or show more this.renderController(oRenderManager, oControl); // closing primary toolbar DIV oRenderManager.write("</div>"); }; RowRepeaterRenderer.renderTitle = function(oRenderManager, oControl) { // local variables var oTitle = oControl.getTitle(); var sTooltip = oTitle.getTooltip_AsString(); //BACKUP FOR LOGO AND TITLE IN A SINGLE SHARED DIV: // // opening title DIV // oRenderManager.write("<div"); // oRenderManager.addClass("sapUiRrTitle"); // oRenderManager.writeClasses(); // if(sTooltip!==undefined) { // oRenderManager.writeAttributeEscaped("title", sTooltip); // } // oRenderManager.write(">"); // // // render the icon if it is defined // if(oTitle.getIcon()!==null) { // oRenderManager.write("<img"); // oRenderManager.writeAttributeEscaped("src", oTitle.getIcon()); // oRenderManager.write("/>"); // } // // // render the text if provided // if(oTitle.getText()!==null) { // oRenderManager.writeEscaped(oTitle.getText()); // } // // // closing title DIV // oRenderManager.write("</div>"); //LOGO AND TITLE IN 2 SEPARATE DIVs: // render the icon if it is defined if (oTitle.getIcon()) { // opening logo DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrLogo"); oRenderManager.writeClasses(); if (sTooltip !== undefined) { oRenderManager.writeAttributeEscaped("title", sTooltip); } oRenderManager.write(">"); if (oTitle.getIcon()) { oRenderManager.write("<img"); oRenderManager.writeAttributeEscaped("src", oTitle.getIcon()); oRenderManager.write("/>"); } // closing DIV oRenderManager.write("</div>"); } // render the text if provided if (oTitle.getText()) { // opening title DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrTitle"); oRenderManager.writeClasses(); oRenderManager.writeAttribute("role", "heading"); oRenderManager.write(">"); oRenderManager.writeEscaped(oTitle.getText()); // closing DIV oRenderManager.write("</div>"); } }; RowRepeaterRenderer.renderFilterToolbar = function(oRenderManager, oControl) { // local variables var aFilters = oControl.getFilters(); if (aFilters.length > 0) { // opening filter toolbar DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrFilters"); oRenderManager.writeClasses(); oRenderManager.write(">"); // don't render any content if there is not minimum 2 filters OR // if the row repeater is not bound if (aFilters.length > 1 && oControl.isBound()) { oRenderManager.renderControl(oControl.getAggregation("filterToolbar")); } // closing filter toolbar DIV oRenderManager.write("</div>"); } }; RowRepeaterRenderer.renderController = function(oRenderManager, oControl) { if (!oControl.bPagingMode) { // opening controller DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrCtrl"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render "show more" button or pager depending on pager mode flag oRenderManager.renderControl(oControl.getAggregation("headerShowMoreButton")); // closing controller DIV oRenderManager.write("</div>"); } }; RowRepeaterRenderer.renderSecondaryToolbar = function(oRenderManager, oControl) { // opening secondary toolbar DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrStb"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render the "Sort By:" text oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrSortBy"); oRenderManager.writeClasses(); oRenderManager.write(">"); oRenderManager.writeEscaped(oControl.oResourceBundle.getText("SORT_BY") + ":"); oRenderManager.write("</div>"); // begin of sorter toolbar wrapping DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrSorters"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render the toolbar oRenderManager.renderControl(oControl.getAggregation("sorterToolbar")); // end of sorter toolbar wrapping DIV oRenderManager.write("</div>"); // closing secondary toolbar DIV oRenderManager.write("</div>"); }; RowRepeaterRenderer.renderBody = function(oRenderManager, oControl) { // variables var sId = oControl.getId(); var iShowMoreSteps = oControl.getShowMoreSteps(); var iCurrentPage = oControl.getCurrentPage(); var iNumberOfRows = oControl.getNumberOfRows(); var iStartIndex = (iCurrentPage - 1) * iNumberOfRows; var aRows = oControl.getRows(); var iRowCount = oControl._getRowCount(); var iMaxRows = iRowCount - iStartIndex; var iCurrentVisibleRows = oControl._getRowCount() > iNumberOfRows ? iNumberOfRows : iMaxRows; var iLastPage = Math.ceil(iRowCount / iNumberOfRows); var iCurrentRow; // make sure only to render the max visible rows (not to render pseudo rows) iCurrentVisibleRows = Math.min(iCurrentVisibleRows, iMaxRows); // in the show more mode we always start with the first row if (iShowMoreSteps > 0) { iStartIndex = 0; } // opening body DIV oRenderManager.write("<div"); oRenderManager.writeAttribute("id", sId + "-body"); oRenderManager.addClass("sapUiRrBody"); oRenderManager.writeClasses(); oRenderManager.write(">"); // opening UL for current page oRenderManager.write("<ul"); oRenderManager.writeAttribute("id", sId + "-page_" + iCurrentPage); oRenderManager.addClass("sapUiRrPage"); oRenderManager.writeClasses(); oRenderManager.write(">"); // we display a text, if the length of aggregation rows is 0 or we are past the last page if (aRows.length === 0 || iLastPage < iCurrentPage) { // render a "No Data" LI with custom control or default text oRenderManager.write("<li"); oRenderManager.addClass("sapUiRrNoData"); oRenderManager.writeClasses(); oRenderManager.write(">"); var oNoData = oControl.getNoData(); if (oNoData) { oRenderManager.renderControl(oNoData); } else { oRenderManager.writeEscaped(oControl.oResourceBundle.getText("NO_DATA")); } oRenderManager.write("</li>"); } else { // create additional LI style if row height is fixed var sRowHeightStyle; if ( oControl.getFixedRowHeight() !== "" ) { sRowHeightStyle = "height:" + oControl.getFixedRowHeight() + ";overflow:hidden;"; } // loop over all rows visible on current page if (oControl.getBinding("rows")) { iStartIndex = oControl._bSecondPage ? iNumberOfRows : 0; } for ( iCurrentRow = iStartIndex; iCurrentRow < iStartIndex + iCurrentVisibleRows; iCurrentRow++ ) { // open the LI wrapping each row oRenderManager.write("<li"); oRenderManager.writeAttribute("id", sId + "-row_" + iCurrentRow); if (sRowHeightStyle) { oRenderManager.writeAttribute("style", sRowHeightStyle); } oRenderManager.addClass("sapUiRrRow"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render the nested control oRenderManager.renderControl(aRows[iCurrentRow]); // close the wrapping LI oRenderManager.write("</li>"); } } // closing page UL oRenderManager.write("</ul>"); // closing body DIV oRenderManager.write("</div>"); }; RowRepeaterRenderer.renderFooter = function(oRenderManager, oControl) { // opening footer DIV oRenderManager.write("<div"); oRenderManager.addClass("sapUiRrFtr"); oRenderManager.writeClasses(); oRenderManager.write(">"); // render "show more" button or pager depending on pager mode flag if (oControl.bPagingMode) { oRenderManager.renderControl(oControl.getAggregation("footerPager")); } else { oRenderManager.renderControl(oControl.getAggregation("footerShowMoreButton")); } // closing footer DIV oRenderManager.write("</div>"); }; return RowRepeaterRenderer; }, /* bExport= */ true);
'use strict'; /* Services */ var dashboardServices = angular.module('dashboardServices', ['ngResource']); dashboardServices.factory('Dashboard', ['$resource', function($resource){ return $resource('https://ci.jenkins-ci.org/view/All/api/json?pretty=true&depth=1', {}, { query: {method:'GET', params:{}, isArray:false} }); } ]);
Template.userProfile.helpers({ name: function(){ return Meteor.user().profile.name; }, email: function(){ var user = Meteor.user(); if (user.emails && user.emails[0]) return Meteor.user().emails[0].address; }, phone: function(){ return Meteor.user().profile.phone; }, });
/*! jQuery Timepicker Addon - v1.4.3 - 2013-11-30 * http://trentrichardson.com/examples/timepicker * Copyright (c) 2013 Trent Richardson; Licensed MIT * The MIT License (MIT) * 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. * */ (function ($) { /* * Lets not redefine timepicker, Prevent "Uncaught RangeError: Maximum call stack size exceeded" */ $.ui.timepicker = $.ui.timepicker || {}; if ($.ui.timepicker.version) { return; } /* * Extend jQueryUI, get it started with our version number */ $.extend($.ui, { timepicker: { version: "1.4.3" } }); /* * Timepicker manager. * Use the singleton instance of this class, $.timepicker, to interact with the time picker. * Settings for (groups of) time pickers are maintained in an instance object, * allowing multiple different settings on the same page. */ var Timepicker = function () { this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings currentText: 'Now', closeText: 'Done', amNames: ['AM', 'A'], pmNames: ['PM', 'P'], timeFormat: 'HH:mm', timeSuffix: '', timeOnlyTitle: 'Choose Time', timeText: 'Time', hourText: 'Hour', minuteText: 'Minute', secondText: 'Second', millisecText: 'Millisecond', microsecText: 'Microsecond', timezoneText: 'Time Zone', isRTL: false }; this._defaults = { // Global defaults for all the datetime picker instances showButtonPanel: true, timeOnly: false, showHour: null, showMinute: null, showSecond: null, showMillisec: null, showMicrosec: null, showTimezone: null, showTime: true, stepHour: 1, stepMinute: 1, stepSecond: 1, stepMillisec: 1, stepMicrosec: 1, hour: 0, minute: 0, second: 0, millisec: 0, microsec: 0, timezone: null, hourMin: 0, minuteMin: 0, secondMin: 0, millisecMin: 0, microsecMin: 0, hourMax: 23, minuteMax: 59, secondMax: 59, millisecMax: 999, microsecMax: 999, minDateTime: null, maxDateTime: null, onSelect: null, hourGrid: 0, minuteGrid: 0, secondGrid: 0, millisecGrid: 0, microsecGrid: 0, alwaysSetTime: true, separator: ' ', altFieldTimeOnly: true, altTimeFormat: null, altSeparator: null, altTimeSuffix: null, pickerTimeFormat: null, pickerTimeSuffix: null, showTimepicker: true, timezoneList: null, addSliderAccess: false, sliderAccessArgs: null, controlType: 'slider', defaultValue: null, parse: 'strict' }; $.extend(this._defaults, this.regional['']); }; $.extend(Timepicker.prototype, { $input: null, $altInput: null, $timeObj: null, inst: null, hour_slider: null, minute_slider: null, second_slider: null, millisec_slider: null, microsec_slider: null, timezone_select: null, hour: 0, minute: 0, second: 0, millisec: 0, microsec: 0, timezone: null, hourMinOriginal: null, minuteMinOriginal: null, secondMinOriginal: null, millisecMinOriginal: null, microsecMinOriginal: null, hourMaxOriginal: null, minuteMaxOriginal: null, secondMaxOriginal: null, millisecMaxOriginal: null, microsecMaxOriginal: null, ampm: '', formattedDate: '', formattedTime: '', formattedDateTime: '', timezoneList: null, units: ['hour', 'minute', 'second', 'millisec', 'microsec'], support: {}, control: null, /* * Override the default settings for all instances of the time picker. * @param {Object} settings object - the new settings to use as defaults (anonymous object) * @return {Object} the manager object */ setDefaults: function (settings) { extendRemove(this._defaults, settings || {}); return this; }, /* * Create a new Timepicker instance */ _newInst: function ($input, opts) { var tp_inst = new Timepicker(), inlineSettings = {}, fns = {}, overrides, i; for (var attrName in this._defaults) { if (this._defaults.hasOwnProperty(attrName)) { var attrValue = $input.attr('time:' + attrName); if (attrValue) { try { inlineSettings[attrName] = eval(attrValue); } catch (err) { inlineSettings[attrName] = attrValue; } } } } overrides = { beforeShow: function (input, dp_inst) { if ($.isFunction(tp_inst._defaults.evnts.beforeShow)) { return tp_inst._defaults.evnts.beforeShow.call($input[0], input, dp_inst, tp_inst); } }, onChangeMonthYear: function (year, month, dp_inst) { // Update the time as well : this prevents the time from disappearing from the $input field. tp_inst._updateDateTime(dp_inst); if ($.isFunction(tp_inst._defaults.evnts.onChangeMonthYear)) { tp_inst._defaults.evnts.onChangeMonthYear.call($input[0], year, month, dp_inst, tp_inst); } }, onClose: function (dateText, dp_inst) { if (tp_inst.timeDefined === true && $input.val() !== '') { tp_inst._updateDateTime(dp_inst); } if ($.isFunction(tp_inst._defaults.evnts.onClose)) { tp_inst._defaults.evnts.onClose.call($input[0], dateText, dp_inst, tp_inst); } } }; for (i in overrides) { if (overrides.hasOwnProperty(i)) { fns[i] = opts[i] || null; } } tp_inst._defaults = $.extend({}, this._defaults, inlineSettings, opts, overrides, { evnts: fns, timepicker: tp_inst // add timepicker as a property of datepicker: $.datepicker._get(dp_inst, 'timepicker'); }); tp_inst.amNames = $.map(tp_inst._defaults.amNames, function (val) { return val.toUpperCase(); }); tp_inst.pmNames = $.map(tp_inst._defaults.pmNames, function (val) { return val.toUpperCase(); }); // detect which units are supported tp_inst.support = detectSupport( tp_inst._defaults.timeFormat + (tp_inst._defaults.pickerTimeFormat ? tp_inst._defaults.pickerTimeFormat : '') + (tp_inst._defaults.altTimeFormat ? tp_inst._defaults.altTimeFormat : '')); // controlType is string - key to our this._controls if (typeof(tp_inst._defaults.controlType) === 'string') { if (tp_inst._defaults.controlType === 'slider' && typeof($.ui.slider) === 'undefined') { tp_inst._defaults.controlType = 'select'; } tp_inst.control = tp_inst._controls[tp_inst._defaults.controlType]; } // controlType is an object and must implement create, options, value methods else { tp_inst.control = tp_inst._defaults.controlType; } // prep the timezone options var timezoneList = [-720, -660, -600, -570, -540, -480, -420, -360, -300, -270, -240, -210, -180, -120, -60, 0, 60, 120, 180, 210, 240, 270, 300, 330, 345, 360, 390, 420, 480, 525, 540, 570, 600, 630, 660, 690, 720, 765, 780, 840]; if (tp_inst._defaults.timezoneList !== null) { timezoneList = tp_inst._defaults.timezoneList; } var tzl = timezoneList.length, tzi = 0, tzv = null; if (tzl > 0 && typeof timezoneList[0] !== 'object') { for (; tzi < tzl; tzi++) { tzv = timezoneList[tzi]; timezoneList[tzi] = { value: tzv, label: $.timepicker.timezoneOffsetString(tzv, tp_inst.support.iso8601) }; } } tp_inst._defaults.timezoneList = timezoneList; // set the default units tp_inst.timezone = tp_inst._defaults.timezone !== null ? $.timepicker.timezoneOffsetNumber(tp_inst._defaults.timezone) : ((new Date()).getTimezoneOffset() * -1); tp_inst.hour = tp_inst._defaults.hour < tp_inst._defaults.hourMin ? tp_inst._defaults.hourMin : tp_inst._defaults.hour > tp_inst._defaults.hourMax ? tp_inst._defaults.hourMax : tp_inst._defaults.hour; tp_inst.minute = tp_inst._defaults.minute < tp_inst._defaults.minuteMin ? tp_inst._defaults.minuteMin : tp_inst._defaults.minute > tp_inst._defaults.minuteMax ? tp_inst._defaults.minuteMax : tp_inst._defaults.minute; tp_inst.second = tp_inst._defaults.second < tp_inst._defaults.secondMin ? tp_inst._defaults.secondMin : tp_inst._defaults.second > tp_inst._defaults.secondMax ? tp_inst._defaults.secondMax : tp_inst._defaults.second; tp_inst.millisec = tp_inst._defaults.millisec < tp_inst._defaults.millisecMin ? tp_inst._defaults.millisecMin : tp_inst._defaults.millisec > tp_inst._defaults.millisecMax ? tp_inst._defaults.millisecMax : tp_inst._defaults.millisec; tp_inst.microsec = tp_inst._defaults.microsec < tp_inst._defaults.microsecMin ? tp_inst._defaults.microsecMin : tp_inst._defaults.microsec > tp_inst._defaults.microsecMax ? tp_inst._defaults.microsecMax : tp_inst._defaults.microsec; tp_inst.ampm = ''; tp_inst.$input = $input; if (tp_inst._defaults.altField) { tp_inst.$altInput = $(tp_inst._defaults.altField).css({ cursor: 'pointer' }).focus(function () { $input.trigger("focus"); }); } if (tp_inst._defaults.minDate === 0 || tp_inst._defaults.minDateTime === 0) { tp_inst._defaults.minDate = new Date(); } if (tp_inst._defaults.maxDate === 0 || tp_inst._defaults.maxDateTime === 0) { tp_inst._defaults.maxDate = new Date(); } // datepicker needs minDate/maxDate, timepicker needs minDateTime/maxDateTime.. if (tp_inst._defaults.minDate !== undefined && tp_inst._defaults.minDate instanceof Date) { tp_inst._defaults.minDateTime = new Date(tp_inst._defaults.minDate.getTime()); } if (tp_inst._defaults.minDateTime !== undefined && tp_inst._defaults.minDateTime instanceof Date) { tp_inst._defaults.minDate = new Date(tp_inst._defaults.minDateTime.getTime()); } if (tp_inst._defaults.maxDate !== undefined && tp_inst._defaults.maxDate instanceof Date) { tp_inst._defaults.maxDateTime = new Date(tp_inst._defaults.maxDate.getTime()); } if (tp_inst._defaults.maxDateTime !== undefined && tp_inst._defaults.maxDateTime instanceof Date) { tp_inst._defaults.maxDate = new Date(tp_inst._defaults.maxDateTime.getTime()); } tp_inst.$input.bind('focus', function () { tp_inst._onFocus(); }); return tp_inst; }, /* * add our sliders to the calendar */ _addTimePicker: function (dp_inst) { var currDT = (this.$altInput && this._defaults.altFieldTimeOnly) ? this.$input.val() + ' ' + this.$altInput.val() : this.$input.val(); this.timeDefined = this._parseTime(currDT); this._limitMinMaxDateTime(dp_inst, false); this._injectTimePicker(); }, /* * parse the time string from input value or _setTime */ _parseTime: function (timeString, withDate) { if (!this.inst) { this.inst = $.datepicker._getInst(this.$input[0]); } if (withDate || !this._defaults.timeOnly) { var dp_dateFormat = $.datepicker._get(this.inst, 'dateFormat'); try { var parseRes = parseDateTimeInternal(dp_dateFormat, this._defaults.timeFormat, timeString, $.datepicker._getFormatConfig(this.inst), this._defaults); if (!parseRes.timeObj) { return false; } $.extend(this, parseRes.timeObj); } catch (err) { $.timepicker.log("Error parsing the date/time string: " + err + "\ndate/time string = " + timeString + "\ntimeFormat = " + this._defaults.timeFormat + "\ndateFormat = " + dp_dateFormat); return false; } return true; } else { var timeObj = $.datepicker.parseTime(this._defaults.timeFormat, timeString, this._defaults); if (!timeObj) { return false; } $.extend(this, timeObj); return true; } }, /* * generate and inject html for timepicker into ui datepicker */ _injectTimePicker: function () { var $dp = this.inst.dpDiv, o = this.inst.settings, tp_inst = this, litem = '', uitem = '', show = null, max = {}, gridSize = {}, size = null, i = 0, l = 0; // Prevent displaying twice if ($dp.find("div.ui-timepicker-div").length === 0 && o.showTimepicker) { var noDisplay = ' style="display:none;"', html = '<div class="ui-timepicker-div' + (o.isRTL ? ' ui-timepicker-rtl' : '') + '"><div>' + '<div class="ui_tpicker_time_label"' + ((o.showTime) ? '' : noDisplay) + '>' + o.timeText + '</div>' + '<div class="ui_tpicker_time"' + ((o.showTime) ? '' : noDisplay) + '></div>'; // Create the markup for (i = 0, l = this.units.length; i < l; i++) { litem = this.units[i]; uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1); show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem]; // Added by Peter Medeiros: // - Figure out what the hour/minute/second max should be based on the step values. // - Example: if stepMinute is 15, then minMax is 45. max[litem] = parseInt((o[litem + 'Max'] - ((o[litem + 'Max'] - o[litem + 'Min']) % o['step' + uitem])), 10); gridSize[litem] = 0; html += '<div class="ui_tpicker_' + litem + '_label"' + (show ? '' : noDisplay) + '>' + o[litem + 'Text'] + '</div>' + '<div class="ui_tpicker_' + litem + '"><div class="ui_tpicker_' + litem + '_slider"' + (show ? '' : noDisplay) + '></div>'; if (show && o[litem + 'Grid'] > 0) { html += '<div style="padding-left: 1px"><table class="ui-tpicker-grid-label"><tr>'; if (litem === 'hour') { for (var h = o[litem + 'Min']; h <= max[litem]; h += parseInt(o[litem + 'Grid'], 10)) { gridSize[litem]++; var tmph = $.datepicker.formatTime(this.support.ampm ? 'hht' : 'HH', {hour: h}, o); html += '<td data-for="' + litem + '">' + tmph + '</td>'; } } else { for (var m = o[litem + 'Min']; m <= max[litem]; m += parseInt(o[litem + 'Grid'], 10)) { gridSize[litem]++; html += '<td data-for="' + litem + '">' + ((m < 10) ? '0' : '') + m + '</td>'; } } html += '</tr></table></div>'; } html += '</dd>'; } // Timezone var showTz = o.showTimezone !== null ? o.showTimezone : this.support.timezone; html += '<dt class="ui_tpicker_timezone_label"' + (showTz ? '' : noDisplay) + '>' + o.timezoneText + '</dt>'; html += '<div class="ui_tpicker_timezone" ' + (showTz ? '' : noDisplay) + '></div>'; // Create the elements from string html += '</div></div>'; var $tp = $(html); // if we only want time picker... if (o.timeOnly === true) { $tp.prepend('<div class="ui-widget-header ui-helper-clearfix ui-corner-all">' + '<div class="ui-datepicker-title">' + o.timeOnlyTitle + '</div>' + '</div>'); $dp.find('.ui-datepicker-header, .ui-datepicker-calendar').hide(); } // add sliders, adjust grids, add events for (i = 0, l = tp_inst.units.length; i < l; i++) { litem = tp_inst.units[i]; uitem = litem.substr(0, 1).toUpperCase() + litem.substr(1); show = o['show' + uitem] !== null ? o['show' + uitem] : this.support[litem]; // add the slider tp_inst[litem + '_slider'] = tp_inst.control.create(tp_inst, $tp.find('.ui_tpicker_' + litem + '_slider'), litem, tp_inst[litem], o[litem + 'Min'], max[litem], o['step' + uitem]); // adjust the grid and add click event if (show && o[litem + 'Grid'] > 0) { size = 100 * gridSize[litem] * o[litem + 'Grid'] / (max[litem] - o[litem + 'Min']); $tp.find('.ui_tpicker_' + litem + ' table').css({ width: size + "%", marginLeft: o.isRTL ? '0' : ((size / (-2 * gridSize[litem])) + "%"), marginRight: o.isRTL ? ((size / (-2 * gridSize[litem])) + "%") : '0', borderCollapse: 'collapse' }).find("td").click(function (e) { var $t = $(this), h = $t.html(), n = parseInt(h.replace(/[^0-9]/g), 10), ap = h.replace(/[^apm]/ig), f = $t.data('for'); // loses scope, so we use data-for if (f === 'hour') { if (ap.indexOf('p') !== -1 && n < 12) { n += 12; } else { if (ap.indexOf('a') !== -1 && n === 12) { n = 0; } } } tp_inst.control.value(tp_inst, tp_inst[f + '_slider'], litem, n); tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }).css({ cursor: 'pointer', width: (100 / gridSize[litem]) + '%', textAlign: 'center', overflow: 'hidden' }); } // end if grid > 0 } // end for loop // Add timezone options this.timezone_select = $tp.find('.ui_tpicker_timezone').append('<select></select>').find("select"); $.fn.append.apply(this.timezone_select, $.map(o.timezoneList, function (val, idx) { return $("<option />").val(typeof val === "object" ? val.value : val).text(typeof val === "object" ? val.label : val); })); if (typeof(this.timezone) !== "undefined" && this.timezone !== null && this.timezone !== "") { var local_timezone = (new Date(this.inst.selectedYear, this.inst.selectedMonth, this.inst.selectedDay, 12)).getTimezoneOffset() * -1; if (local_timezone === this.timezone) { selectLocalTimezone(tp_inst); } else { this.timezone_select.val(this.timezone); } } else { if (typeof(this.hour) !== "undefined" && this.hour !== null && this.hour !== "") { this.timezone_select.val(o.timezone); } else { selectLocalTimezone(tp_inst); } } this.timezone_select.change(function () { tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }); // End timezone options // inject timepicker into datepicker var $buttonPanel = $dp.find('.ui-datepicker-buttonpane'); if ($buttonPanel.length) { $buttonPanel.before($tp); } else { $dp.append($tp); } this.$timeObj = $tp.find('.ui_tpicker_time'); if (this.inst !== null) { var timeDefined = this.timeDefined; this._onTimeChange(); this.timeDefined = timeDefined; } // slideAccess integration: http://trentrichardson.com/2011/11/11/jquery-ui-sliders-and-touch-accessibility/ if (this._defaults.addSliderAccess) { var sliderAccessArgs = this._defaults.sliderAccessArgs, rtl = this._defaults.isRTL; sliderAccessArgs.isRTL = rtl; setTimeout(function () { // fix for inline mode if ($tp.find('.ui-slider-access').length === 0) { $tp.find('.ui-slider:visible').sliderAccess(sliderAccessArgs); // fix any grids since sliders are shorter var sliderAccessWidth = $tp.find('.ui-slider-access:eq(0)').outerWidth(true); if (sliderAccessWidth) { $tp.find('table:visible').each(function () { var $g = $(this), oldWidth = $g.outerWidth(), oldMarginLeft = $g.css(rtl ? 'marginRight' : 'marginLeft').toString().replace('%', ''), newWidth = oldWidth - sliderAccessWidth, newMarginLeft = ((oldMarginLeft * newWidth) / oldWidth) + '%', css = { width: newWidth, marginRight: 0, marginLeft: 0 }; css[rtl ? 'marginRight' : 'marginLeft'] = newMarginLeft; $g.css(css); }); } } }, 10); } // end slideAccess integration tp_inst._limitMinMaxDateTime(this.inst, true); } }, /* * This function tries to limit the ability to go outside the * min/max date range */ _limitMinMaxDateTime: function (dp_inst, adjustSliders) { var o = this._defaults, dp_date = new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay); if (!this._defaults.showTimepicker) { return; } // No time so nothing to check here if ($.datepicker._get(dp_inst, 'minDateTime') !== null && $.datepicker._get(dp_inst, 'minDateTime') !== undefined && dp_date) { var minDateTime = $.datepicker._get(dp_inst, 'minDateTime'), minDateTimeDate = new Date(minDateTime.getFullYear(), minDateTime.getMonth(), minDateTime.getDate(), 0, 0, 0, 0); if (this.hourMinOriginal === null || this.minuteMinOriginal === null || this.secondMinOriginal === null || this.millisecMinOriginal === null || this.microsecMinOriginal === null) { this.hourMinOriginal = o.hourMin; this.minuteMinOriginal = o.minuteMin; this.secondMinOriginal = o.secondMin; this.millisecMinOriginal = o.millisecMin; this.microsecMinOriginal = o.microsecMin; } if (dp_inst.settings.timeOnly || minDateTimeDate.getTime() === dp_date.getTime()) { this._defaults.hourMin = minDateTime.getHours(); if (this.hour <= this._defaults.hourMin) { this.hour = this._defaults.hourMin; this._defaults.minuteMin = minDateTime.getMinutes(); if (this.minute <= this._defaults.minuteMin) { this.minute = this._defaults.minuteMin; this._defaults.secondMin = minDateTime.getSeconds(); if (this.second <= this._defaults.secondMin) { this.second = this._defaults.secondMin; this._defaults.millisecMin = minDateTime.getMilliseconds(); if (this.millisec <= this._defaults.millisecMin) { this.millisec = this._defaults.millisecMin; this._defaults.microsecMin = minDateTime.getMicroseconds(); } else { if (this.microsec < this._defaults.microsecMin) { this.microsec = this._defaults.microsecMin; } this._defaults.microsecMin = this.microsecMinOriginal; } } else { this._defaults.millisecMin = this.millisecMinOriginal; this._defaults.microsecMin = this.microsecMinOriginal; } } else { this._defaults.secondMin = this.secondMinOriginal; this._defaults.millisecMin = this.millisecMinOriginal; this._defaults.microsecMin = this.microsecMinOriginal; } } else { this._defaults.minuteMin = this.minuteMinOriginal; this._defaults.secondMin = this.secondMinOriginal; this._defaults.millisecMin = this.millisecMinOriginal; this._defaults.microsecMin = this.microsecMinOriginal; } } else { this._defaults.hourMin = this.hourMinOriginal; this._defaults.minuteMin = this.minuteMinOriginal; this._defaults.secondMin = this.secondMinOriginal; this._defaults.millisecMin = this.millisecMinOriginal; this._defaults.microsecMin = this.microsecMinOriginal; } } if ($.datepicker._get(dp_inst, 'maxDateTime') !== null && $.datepicker._get(dp_inst, 'maxDateTime') !== undefined && dp_date) { var maxDateTime = $.datepicker._get(dp_inst, 'maxDateTime'), maxDateTimeDate = new Date(maxDateTime.getFullYear(), maxDateTime.getMonth(), maxDateTime.getDate(), 0, 0, 0, 0); if (this.hourMaxOriginal === null || this.minuteMaxOriginal === null || this.secondMaxOriginal === null || this.millisecMaxOriginal === null) { this.hourMaxOriginal = o.hourMax; this.minuteMaxOriginal = o.minuteMax; this.secondMaxOriginal = o.secondMax; this.millisecMaxOriginal = o.millisecMax; this.microsecMaxOriginal = o.microsecMax; } if (dp_inst.settings.timeOnly || maxDateTimeDate.getTime() === dp_date.getTime()) { this._defaults.hourMax = maxDateTime.getHours(); if (this.hour >= this._defaults.hourMax) { this.hour = this._defaults.hourMax; this._defaults.minuteMax = maxDateTime.getMinutes(); if (this.minute >= this._defaults.minuteMax) { this.minute = this._defaults.minuteMax; this._defaults.secondMax = maxDateTime.getSeconds(); if (this.second >= this._defaults.secondMax) { this.second = this._defaults.secondMax; this._defaults.millisecMax = maxDateTime.getMilliseconds(); if (this.millisec >= this._defaults.millisecMax) { this.millisec = this._defaults.millisecMax; this._defaults.microsecMax = maxDateTime.getMicroseconds(); } else { if (this.microsec > this._defaults.microsecMax) { this.microsec = this._defaults.microsecMax; } this._defaults.microsecMax = this.microsecMaxOriginal; } } else { this._defaults.millisecMax = this.millisecMaxOriginal; this._defaults.microsecMax = this.microsecMaxOriginal; } } else { this._defaults.secondMax = this.secondMaxOriginal; this._defaults.millisecMax = this.millisecMaxOriginal; this._defaults.microsecMax = this.microsecMaxOriginal; } } else { this._defaults.minuteMax = this.minuteMaxOriginal; this._defaults.secondMax = this.secondMaxOriginal; this._defaults.millisecMax = this.millisecMaxOriginal; this._defaults.microsecMax = this.microsecMaxOriginal; } } else { this._defaults.hourMax = this.hourMaxOriginal; this._defaults.minuteMax = this.minuteMaxOriginal; this._defaults.secondMax = this.secondMaxOriginal; this._defaults.millisecMax = this.millisecMaxOriginal; this._defaults.microsecMax = this.microsecMaxOriginal; } } if (adjustSliders !== undefined && adjustSliders === true) { var hourMax = parseInt((this._defaults.hourMax - ((this._defaults.hourMax - this._defaults.hourMin) % this._defaults.stepHour)), 10), minMax = parseInt((this._defaults.minuteMax - ((this._defaults.minuteMax - this._defaults.minuteMin) % this._defaults.stepMinute)), 10), secMax = parseInt((this._defaults.secondMax - ((this._defaults.secondMax - this._defaults.secondMin) % this._defaults.stepSecond)), 10), millisecMax = parseInt((this._defaults.millisecMax - ((this._defaults.millisecMax - this._defaults.millisecMin) % this._defaults.stepMillisec)), 10), microsecMax = parseInt((this._defaults.microsecMax - ((this._defaults.microsecMax - this._defaults.microsecMin) % this._defaults.stepMicrosec)), 10); if (this.hour_slider) { this.control.options(this, this.hour_slider, 'hour', { min: this._defaults.hourMin, max: hourMax }); this.control.value(this, this.hour_slider, 'hour', this.hour - (this.hour % this._defaults.stepHour)); } if (this.minute_slider) { this.control.options(this, this.minute_slider, 'minute', { min: this._defaults.minuteMin, max: minMax }); this.control.value(this, this.minute_slider, 'minute', this.minute - (this.minute % this._defaults.stepMinute)); } if (this.second_slider) { this.control.options(this, this.second_slider, 'second', { min: this._defaults.secondMin, max: secMax }); this.control.value(this, this.second_slider, 'second', this.second - (this.second % this._defaults.stepSecond)); } if (this.millisec_slider) { this.control.options(this, this.millisec_slider, 'millisec', { min: this._defaults.millisecMin, max: millisecMax }); this.control.value(this, this.millisec_slider, 'millisec', this.millisec - (this.millisec % this._defaults.stepMillisec)); } if (this.microsec_slider) { this.control.options(this, this.microsec_slider, 'microsec', { min: this._defaults.microsecMin, max: microsecMax }); this.control.value(this, this.microsec_slider, 'microsec', this.microsec - (this.microsec % this._defaults.stepMicrosec)); } } }, /* * when a slider moves, set the internal time... * on time change is also called when the time is updated in the text field */ _onTimeChange: function () { if (!this._defaults.showTimepicker) { return; } var hour = (this.hour_slider) ? this.control.value(this, this.hour_slider, 'hour') : false, minute = (this.minute_slider) ? this.control.value(this, this.minute_slider, 'minute') : false, second = (this.second_slider) ? this.control.value(this, this.second_slider, 'second') : false, millisec = (this.millisec_slider) ? this.control.value(this, this.millisec_slider, 'millisec') : false, microsec = (this.microsec_slider) ? this.control.value(this, this.microsec_slider, 'microsec') : false, timezone = (this.timezone_select) ? this.timezone_select.val() : false, o = this._defaults, pickerTimeFormat = o.pickerTimeFormat || o.timeFormat, pickerTimeSuffix = o.pickerTimeSuffix || o.timeSuffix; if (typeof(hour) === 'object') { hour = false; } if (typeof(minute) === 'object') { minute = false; } if (typeof(second) === 'object') { second = false; } if (typeof(millisec) === 'object') { millisec = false; } if (typeof(microsec) === 'object') { microsec = false; } if (typeof(timezone) === 'object') { timezone = false; } if (hour !== false) { hour = parseInt(hour, 10); } if (minute !== false) { minute = parseInt(minute, 10); } if (second !== false) { second = parseInt(second, 10); } if (millisec !== false) { millisec = parseInt(millisec, 10); } if (microsec !== false) { microsec = parseInt(microsec, 10); } if (timezone !== false) { timezone = timezone.toString(); } var ampm = o[hour < 12 ? 'amNames' : 'pmNames'][0]; // If the update was done in the input field, the input field should not be updated. // If the update was done using the sliders, update the input field. var hasChanged = ( hour !== parseInt(this.hour,10) || // sliders should all be numeric minute !== parseInt(this.minute,10) || second !== parseInt(this.second,10) || millisec !== parseInt(this.millisec,10) || microsec !== parseInt(this.microsec,10) || (this.ampm.length > 0 && (hour < 12) !== ($.inArray(this.ampm.toUpperCase(), this.amNames) !== -1)) || (this.timezone !== null && timezone !== this.timezone.toString()) // could be numeric or "EST" format, so use toString() ); if (hasChanged) { if (hour !== false) { this.hour = hour; } if (minute !== false) { this.minute = minute; } if (second !== false) { this.second = second; } if (millisec !== false) { this.millisec = millisec; } if (microsec !== false) { this.microsec = microsec; } if (timezone !== false) { this.timezone = timezone; } if (!this.inst) { this.inst = $.datepicker._getInst(this.$input[0]); } this._limitMinMaxDateTime(this.inst, true); } if (this.support.ampm) { this.ampm = ampm; } // Updates the time within the timepicker this.formattedTime = $.datepicker.formatTime(o.timeFormat, this, o); if (this.$timeObj) { if (pickerTimeFormat === o.timeFormat) { this.$timeObj.text(this.formattedTime + pickerTimeSuffix); } else { this.$timeObj.text($.datepicker.formatTime(pickerTimeFormat, this, o) + pickerTimeSuffix); } } this.timeDefined = true; if (hasChanged) { this._updateDateTime(); this.$input.focus(); } }, /* * call custom onSelect. * bind to sliders slidestop, and grid click. */ _onSelectHandler: function () { var onSelect = this._defaults.onSelect || this.inst.settings.onSelect; var inputEl = this.$input ? this.$input[0] : null; if (onSelect && inputEl) { onSelect.apply(inputEl, [this.formattedDateTime, this]); } }, /* * update our input with the new date time.. */ _updateDateTime: function (dp_inst) { dp_inst = this.inst || dp_inst; var dtTmp = (dp_inst.currentYear > 0? new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay) : new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)), dt = $.datepicker._daylightSavingAdjust(dtTmp), //dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.selectedYear, dp_inst.selectedMonth, dp_inst.selectedDay)), //dt = $.datepicker._daylightSavingAdjust(new Date(dp_inst.currentYear, dp_inst.currentMonth, dp_inst.currentDay)), dateFmt = $.datepicker._get(dp_inst, 'dateFormat'), formatCfg = $.datepicker._getFormatConfig(dp_inst), timeAvailable = dt !== null && this.timeDefined; this.formattedDate = $.datepicker.formatDate(dateFmt, (dt === null ? new Date() : dt), formatCfg); var formattedDateTime = this.formattedDate; // if a slider was changed but datepicker doesn't have a value yet, set it if (dp_inst.lastVal === "") { dp_inst.currentYear = dp_inst.selectedYear; dp_inst.currentMonth = dp_inst.selectedMonth; dp_inst.currentDay = dp_inst.selectedDay; } /* * remove following lines to force every changes in date picker to change the input value * Bug descriptions: when an input field has a default value, and click on the field to pop up the date picker. * If the user manually empty the value in the input field, the date picker will never change selected value. */ //if (dp_inst.lastVal !== undefined && (dp_inst.lastVal.length > 0 && this.$input.val().length === 0)) { // return; //} if (this._defaults.timeOnly === true) { formattedDateTime = this.formattedTime; } else if (this._defaults.timeOnly !== true && (this._defaults.alwaysSetTime || timeAvailable)) { formattedDateTime += this._defaults.separator + this.formattedTime + this._defaults.timeSuffix; } this.formattedDateTime = formattedDateTime; if (!this._defaults.showTimepicker) { this.$input.val(this.formattedDate); } else if (this.$altInput && this._defaults.timeOnly === false && this._defaults.altFieldTimeOnly === true) { this.$altInput.val(this.formattedTime); this.$input.val(this.formattedDate); } else if (this.$altInput) { this.$input.val(formattedDateTime); var altFormattedDateTime = '', altSeparator = this._defaults.altSeparator ? this._defaults.altSeparator : this._defaults.separator, altTimeSuffix = this._defaults.altTimeSuffix ? this._defaults.altTimeSuffix : this._defaults.timeSuffix; if (!this._defaults.timeOnly) { if (this._defaults.altFormat) { altFormattedDateTime = $.datepicker.formatDate(this._defaults.altFormat, (dt === null ? new Date() : dt), formatCfg); } else { altFormattedDateTime = this.formattedDate; } if (altFormattedDateTime) { altFormattedDateTime += altSeparator; } } if (this._defaults.altTimeFormat) { altFormattedDateTime += $.datepicker.formatTime(this._defaults.altTimeFormat, this, this._defaults) + altTimeSuffix; } else { altFormattedDateTime += this.formattedTime + altTimeSuffix; } this.$altInput.val(altFormattedDateTime); } else { this.$input.val(formattedDateTime); } this.$input.trigger("change"); }, _onFocus: function () { if (!this.$input.val() && this._defaults.defaultValue) { this.$input.val(this._defaults.defaultValue); var inst = $.datepicker._getInst(this.$input.get(0)), tp_inst = $.datepicker._get(inst, 'timepicker'); if (tp_inst) { if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) { try { $.datepicker._updateDatepicker(inst); } catch (err) { $.timepicker.log(err); } } } } }, /* * Small abstraction to control types * We can add more, just be sure to follow the pattern: create, options, value */ _controls: { // slider methods slider: { create: function (tp_inst, obj, unit, val, min, max, step) { var rtl = tp_inst._defaults.isRTL; // if rtl go -60->0 instead of 0->60 return obj.prop('slide', null).slider({ orientation: "horizontal", value: rtl ? val * -1 : val, min: rtl ? max * -1 : min, max: rtl ? min * -1 : max, step: step, slide: function (event, ui) { tp_inst.control.value(tp_inst, $(this), unit, rtl ? ui.value * -1 : ui.value); tp_inst._onTimeChange(); }, stop: function (event, ui) { tp_inst._onSelectHandler(); } }); }, options: function (tp_inst, obj, unit, opts, val) { if (tp_inst._defaults.isRTL) { if (typeof(opts) === 'string') { if (opts === 'min' || opts === 'max') { if (val !== undefined) { return obj.slider(opts, val * -1); } return Math.abs(obj.slider(opts)); } return obj.slider(opts); } var min = opts.min, max = opts.max; opts.min = opts.max = null; if (min !== undefined) { opts.max = min * -1; } if (max !== undefined) { opts.min = max * -1; } return obj.slider(opts); } if (typeof(opts) === 'string' && val !== undefined) { return obj.slider(opts, val); } return obj.slider(opts); }, value: function (tp_inst, obj, unit, val) { if (tp_inst._defaults.isRTL) { if (val !== undefined) { return obj.slider('value', val * -1); } return Math.abs(obj.slider('value')); } if (val !== undefined) { return obj.slider('value', val); } return obj.slider('value'); } }, // select methods select: { create: function (tp_inst, obj, unit, val, min, max, step) { var sel = '<select class="ui-timepicker-select" data-unit="' + unit + '" data-min="' + min + '" data-max="' + max + '" data-step="' + step + '">', format = tp_inst._defaults.pickerTimeFormat || tp_inst._defaults.timeFormat; for (var i = min; i <= max; i += step) { sel += '<option value="' + i + '"' + (i === val ? ' selected' : '') + '>'; if (unit === 'hour') { sel += $.datepicker.formatTime($.trim(format.replace(/[^ht ]/ig, '')), {hour: i}, tp_inst._defaults); } else if (unit === 'millisec' || unit === 'microsec' || i >= 10) { sel += i; } else {sel += '0' + i.toString(); } sel += '</option>'; } sel += '</select>'; obj.children('select').remove(); $(sel).appendTo(obj).change(function (e) { tp_inst._onTimeChange(); tp_inst._onSelectHandler(); }); return obj; }, options: function (tp_inst, obj, unit, opts, val) { var o = {}, $t = obj.children('select'); if (typeof(opts) === 'string') { if (val === undefined) { return $t.data(opts); } o[opts] = val; } else { o = opts; } return tp_inst.control.create(tp_inst, obj, $t.data('unit'), $t.val(), o.min || $t.data('min'), o.max || $t.data('max'), o.step || $t.data('step')); }, value: function (tp_inst, obj, unit, val) { var $t = obj.children('select'); if (val !== undefined) { return $t.val(val); } return $t.val(); } } } // end _controls }); $.fn.extend({ /* * shorthand just to use timepicker. */ timepicker: function (o) { o = o || {}; var tmp_args = Array.prototype.slice.call(arguments); if (typeof o === 'object') { tmp_args[0] = $.extend(o, { timeOnly: true }); } return $(this).each(function () { $.fn.datetimepicker.apply($(this), tmp_args); }); }, /* * extend timepicker to datepicker */ datetimepicker: function (o) { o = o || {}; var tmp_args = arguments; if (typeof(o) === 'string') { if (o === 'getDate') { return $.fn.datepicker.apply($(this[0]), tmp_args); } else { return this.each(function () { var $t = $(this); $t.datepicker.apply($t, tmp_args); }); } } else { return this.each(function () { var $t = $(this); $t.datepicker($.timepicker._newInst($t, o)._defaults); }); } } }); /* * Public Utility to parse date and time */ $.datepicker.parseDateTime = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) { var parseRes = parseDateTimeInternal(dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings); if (parseRes.timeObj) { var t = parseRes.timeObj; parseRes.date.setHours(t.hour, t.minute, t.second, t.millisec); parseRes.date.setMicroseconds(t.microsec); } return parseRes.date; }; /* * Public utility to parse time */ $.datepicker.parseTime = function (timeFormat, timeString, options) { var o = extendRemove(extendRemove({}, $.timepicker._defaults), options || {}), iso8601 = (timeFormat.replace(/\'.*?\'/g, '').indexOf('Z') !== -1); // Strict parse requires the timeString to match the timeFormat exactly var strictParse = function (f, s, o) { // pattern for standard and localized AM/PM markers var getPatternAmpm = function (amNames, pmNames) { var markers = []; if (amNames) { $.merge(markers, amNames); } if (pmNames) { $.merge(markers, pmNames); } markers = $.map(markers, function (val) { return val.replace(/[.*+?|()\[\]{}\\]/g, '\\$&'); }); return '(' + markers.join('|') + ')?'; }; // figure out position of time elements.. cause js cant do named captures var getFormatPositions = function (timeFormat) { var finds = timeFormat.toLowerCase().match(/(h{1,2}|m{1,2}|s{1,2}|l{1}|c{1}|t{1,2}|z|'.*?')/g), orders = { h: -1, m: -1, s: -1, l: -1, c: -1, t: -1, z: -1 }; if (finds) { for (var i = 0; i < finds.length; i++) { if (orders[finds[i].toString().charAt(0)] === -1) { orders[finds[i].toString().charAt(0)] = i + 1; } } } return orders; }; var regstr = '^' + f.toString() .replace(/([hH]{1,2}|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) { var ml = match.length; switch (match.charAt(0).toLowerCase()) { case 'h': return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})'; case 'm': return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})'; case 's': return ml === 1 ? '(\\d?\\d)' : '(\\d{' + ml + '})'; case 'l': return '(\\d?\\d?\\d)'; case 'c': return '(\\d?\\d?\\d)'; case 'z': return '(z|[-+]\\d\\d:?\\d\\d|\\S+)?'; case 't': return getPatternAmpm(o.amNames, o.pmNames); default: // literal escaped in quotes return '(' + match.replace(/\'/g, "").replace(/(\.|\$|\^|\\|\/|\(|\)|\[|\]|\?|\+|\*)/g, function (m) { return "\\" + m; }) + ')?'; } }) .replace(/\s/g, '\\s?') + o.timeSuffix + '$', order = getFormatPositions(f), ampm = '', treg; treg = s.match(new RegExp(regstr, 'i')); var resTime = { hour: 0, minute: 0, second: 0, millisec: 0, microsec: 0 }; if (treg) { if (order.t !== -1) { if (treg[order.t] === undefined || treg[order.t].length === 0) { ampm = ''; resTime.ampm = ''; } else { ampm = $.inArray(treg[order.t].toUpperCase(), o.amNames) !== -1 ? 'AM' : 'PM'; resTime.ampm = o[ampm === 'AM' ? 'amNames' : 'pmNames'][0]; } } if (order.h !== -1) { if (ampm === 'AM' && treg[order.h] === '12') { resTime.hour = 0; // 12am = 0 hour } else { if (ampm === 'PM' && treg[order.h] !== '12') { resTime.hour = parseInt(treg[order.h], 10) + 12; // 12pm = 12 hour, any other pm = hour + 12 } else { resTime.hour = Number(treg[order.h]); } } } if (order.m !== -1) { resTime.minute = Number(treg[order.m]); } if (order.s !== -1) { resTime.second = Number(treg[order.s]); } if (order.l !== -1) { resTime.millisec = Number(treg[order.l]); } if (order.c !== -1) { resTime.microsec = Number(treg[order.c]); } if (order.z !== -1 && treg[order.z] !== undefined) { resTime.timezone = $.timepicker.timezoneOffsetNumber(treg[order.z]); } return resTime; } return false; };// end strictParse // First try JS Date, if that fails, use strictParse var looseParse = function (f, s, o) { try { var d = new Date('2012-01-01 ' + s); if (isNaN(d.getTime())) { d = new Date('2012-01-01T' + s); if (isNaN(d.getTime())) { d = new Date('01/01/2012 ' + s); if (isNaN(d.getTime())) { throw "Unable to parse time with native Date: " + s; } } } return { hour: d.getHours(), minute: d.getMinutes(), second: d.getSeconds(), millisec: d.getMilliseconds(), microsec: d.getMicroseconds(), timezone: d.getTimezoneOffset() * -1 }; } catch (err) { try { return strictParse(f, s, o); } catch (err2) { $.timepicker.log("Unable to parse \ntimeString: " + s + "\ntimeFormat: " + f); } } return false; }; // end looseParse if (typeof o.parse === "function") { return o.parse(timeFormat, timeString, o); } if (o.parse === 'loose') { return looseParse(timeFormat, timeString, o); } return strictParse(timeFormat, timeString, o); }; /** * Public utility to format the time * @param {string} format format of the time * @param {Object} time Object not a Date for timezones * @param {Object} [options] essentially the regional[].. amNames, pmNames, ampm * @returns {string} the formatted time */ $.datepicker.formatTime = function (format, time, options) { options = options || {}; options = $.extend({}, $.timepicker._defaults, options); time = $.extend({ hour: 0, minute: 0, second: 0, millisec: 0, microsec: 0, timezone: null }, time); var tmptime = format, ampmName = options.amNames[0], hour = parseInt(time.hour, 10); if (hour > 11) { ampmName = options.pmNames[0]; } tmptime = tmptime.replace(/(?:HH?|hh?|mm?|ss?|[tT]{1,2}|[zZ]|[lc]|'.*?')/g, function (match) { switch (match) { case 'HH': return ('0' + hour).slice(-2); case 'H': return hour; case 'hh': return ('0' + convert24to12(hour)).slice(-2); case 'h': return convert24to12(hour); case 'mm': return ('0' + time.minute).slice(-2); case 'm': return time.minute; case 'ss': return ('0' + time.second).slice(-2); case 's': return time.second; case 'l': return ('00' + time.millisec).slice(-3); case 'c': return ('00' + time.microsec).slice(-3); case 'z': return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, false); case 'Z': return $.timepicker.timezoneOffsetString(time.timezone === null ? options.timezone : time.timezone, true); case 'T': return ampmName.charAt(0).toUpperCase(); case 'TT': return ampmName.toUpperCase(); case 't': return ampmName.charAt(0).toLowerCase(); case 'tt': return ampmName.toLowerCase(); default: return match.replace(/'/g, ""); } }); return tmptime; }; /* * the bad hack :/ override datepicker so it doesn't close on select // inspired: http://stackoverflow.com/questions/1252512/jquery-datepicker-prevent-closing-picker-when-clicking-a-date/1762378#1762378 */ $.datepicker._base_selectDate = $.datepicker._selectDate; $.datepicker._selectDate = function (id, dateStr) { var inst = this._getInst($(id)[0]), tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { tp_inst._limitMinMaxDateTime(inst, true); inst.inline = inst.stay_open = true; //This way the onSelect handler called from calendarpicker get the full dateTime this._base_selectDate(id, dateStr); inst.inline = inst.stay_open = false; this._notifyChange(inst); this._updateDatepicker(inst); } else { this._base_selectDate(id, dateStr); } }; /* * second bad hack :/ override datepicker so it triggers an event when changing the input field * and does not redraw the datepicker on every selectDate event */ $.datepicker._base_updateDatepicker = $.datepicker._updateDatepicker; $.datepicker._updateDatepicker = function (inst) { // don't popup the datepicker if there is another instance already opened var input = inst.input[0]; if ($.datepicker._curInst && $.datepicker._curInst !== inst && $.datepicker._datepickerShowing && $.datepicker._lastInput !== input) { return; } if (typeof(inst.stay_open) !== 'boolean' || inst.stay_open === false) { this._base_updateDatepicker(inst); // Reload the time control when changing something in the input text field. var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { tp_inst._addTimePicker(inst); } } }; /* * third bad hack :/ override datepicker so it allows spaces and colon in the input field */ $.datepicker._base_doKeyPress = $.datepicker._doKeyPress; $.datepicker._doKeyPress = function (event) { var inst = $.datepicker._getInst(event.target), tp_inst = $.datepicker._get(inst, 'timepicker'); if (tp_inst) { if ($.datepicker._get(inst, 'constrainInput')) { var ampm = tp_inst.support.ampm, tz = tp_inst._defaults.showTimezone !== null ? tp_inst._defaults.showTimezone : tp_inst.support.timezone, dateChars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat')), datetimeChars = tp_inst._defaults.timeFormat.toString() .replace(/[hms]/g, '') .replace(/TT/g, ampm ? 'APM' : '') .replace(/Tt/g, ampm ? 'AaPpMm' : '') .replace(/tT/g, ampm ? 'AaPpMm' : '') .replace(/T/g, ampm ? 'AP' : '') .replace(/tt/g, ampm ? 'apm' : '') .replace(/t/g, ampm ? 'ap' : '') + " " + tp_inst._defaults.separator + tp_inst._defaults.timeSuffix + (tz ? tp_inst._defaults.timezoneList.join('') : '') + (tp_inst._defaults.amNames.join('')) + (tp_inst._defaults.pmNames.join('')) + dateChars, chr = String.fromCharCode(event.charCode === undefined ? event.keyCode : event.charCode); return event.ctrlKey || (chr < ' ' || !dateChars || datetimeChars.indexOf(chr) > -1); } } return $.datepicker._base_doKeyPress(event); }; /* * Fourth bad hack :/ override _updateAlternate function used in inline mode to init altField * Update any alternate field to synchronise with the main field. */ $.datepicker._base_updateAlternate = $.datepicker._updateAlternate; $.datepicker._updateAlternate = function (inst) { var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { var altField = tp_inst._defaults.altField; if (altField) { // update alternate field too var altFormat = tp_inst._defaults.altFormat || tp_inst._defaults.dateFormat, date = this._getDate(inst), formatCfg = $.datepicker._getFormatConfig(inst), altFormattedDateTime = '', altSeparator = tp_inst._defaults.altSeparator ? tp_inst._defaults.altSeparator : tp_inst._defaults.separator, altTimeSuffix = tp_inst._defaults.altTimeSuffix ? tp_inst._defaults.altTimeSuffix : tp_inst._defaults.timeSuffix, altTimeFormat = tp_inst._defaults.altTimeFormat !== null ? tp_inst._defaults.altTimeFormat : tp_inst._defaults.timeFormat; altFormattedDateTime += $.datepicker.formatTime(altTimeFormat, tp_inst, tp_inst._defaults) + altTimeSuffix; if (!tp_inst._defaults.timeOnly && !tp_inst._defaults.altFieldTimeOnly && date !== null) { if (tp_inst._defaults.altFormat) { altFormattedDateTime = $.datepicker.formatDate(tp_inst._defaults.altFormat, date, formatCfg) + altSeparator + altFormattedDateTime; } else { altFormattedDateTime = tp_inst.formattedDate + altSeparator + altFormattedDateTime; } } $(altField).val(altFormattedDateTime); } } else { $.datepicker._base_updateAlternate(inst); } }; /* * Override key up event to sync manual input changes. */ $.datepicker._base_doKeyUp = $.datepicker._doKeyUp; $.datepicker._doKeyUp = function (event) { var inst = $.datepicker._getInst(event.target), tp_inst = $.datepicker._get(inst, 'timepicker'); if (tp_inst) { if (tp_inst._defaults.timeOnly && (inst.input.val() !== inst.lastVal)) { try { $.datepicker._updateDatepicker(inst); } catch (err) { $.timepicker.log(err); } } } return $.datepicker._base_doKeyUp(event); }; /* * override "Today" button to also grab the time. */ $.datepicker._base_gotoToday = $.datepicker._gotoToday; $.datepicker._gotoToday = function (id) { var inst = this._getInst($(id)[0]), $dp = inst.dpDiv; this._base_gotoToday(id); var tp_inst = this._get(inst, 'timepicker'); selectLocalTimezone(tp_inst); var now = new Date(); this._setTime(inst, now); $('.ui-datepicker-today', $dp).click(); }; /* * Disable & enable the Time in the datetimepicker */ $.datepicker._disableTimepickerDatepicker = function (target) { var inst = this._getInst(target); if (!inst) { return; } var tp_inst = this._get(inst, 'timepicker'); $(target).datepicker('getDate'); // Init selected[Year|Month|Day] if (tp_inst) { inst.settings.showTimepicker = false; tp_inst._defaults.showTimepicker = false; tp_inst._updateDateTime(inst); } }; $.datepicker._enableTimepickerDatepicker = function (target) { var inst = this._getInst(target); if (!inst) { return; } var tp_inst = this._get(inst, 'timepicker'); $(target).datepicker('getDate'); // Init selected[Year|Month|Day] if (tp_inst) { inst.settings.showTimepicker = true; tp_inst._defaults.showTimepicker = true; tp_inst._addTimePicker(inst); // Could be disabled on page load tp_inst._updateDateTime(inst); } }; /* * Create our own set time function */ $.datepicker._setTime = function (inst, date) { var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { var defaults = tp_inst._defaults; // calling _setTime with no date sets time to defaults tp_inst.hour = date ? date.getHours() : defaults.hour; tp_inst.minute = date ? date.getMinutes() : defaults.minute; tp_inst.second = date ? date.getSeconds() : defaults.second; tp_inst.millisec = date ? date.getMilliseconds() : defaults.millisec; tp_inst.microsec = date ? date.getMicroseconds() : defaults.microsec; //check if within min/max times.. tp_inst._limitMinMaxDateTime(inst, true); tp_inst._onTimeChange(); tp_inst._updateDateTime(inst); } }; /* * Create new public method to set only time, callable as $().datepicker('setTime', date) */ $.datepicker._setTimeDatepicker = function (target, date, withDate) { var inst = this._getInst(target); if (!inst) { return; } var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { this._setDateFromField(inst); var tp_date; if (date) { if (typeof date === "string") { tp_inst._parseTime(date, withDate); tp_date = new Date(); tp_date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec); tp_date.setMicroseconds(tp_inst.microsec); } else { tp_date = new Date(date.getTime()); tp_date.setMicroseconds(date.getMicroseconds()); } if (tp_date.toString() === 'Invalid Date') { tp_date = undefined; } this._setTime(inst, tp_date); } } }; /* * override setDate() to allow setting time too within Date object */ $.datepicker._base_setDateDatepicker = $.datepicker._setDateDatepicker; $.datepicker._setDateDatepicker = function (target, date) { var inst = this._getInst(target); if (!inst) { return; } if (typeof(date) === 'string') { date = new Date(date); if (!date.getTime()) { $.timepicker.log("Error creating Date object from string."); } } var tp_inst = this._get(inst, 'timepicker'); var tp_date; if (date instanceof Date) { tp_date = new Date(date.getTime()); tp_date.setMicroseconds(date.getMicroseconds()); } else { tp_date = date; } // This is important if you are using the timezone option, javascript's Date // object will only return the timezone offset for the current locale, so we // adjust it accordingly. If not using timezone option this won't matter.. // If a timezone is different in tp, keep the timezone as is if (tp_inst && tp_date) { // look out for DST if tz wasn't specified if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) { tp_inst.timezone = tp_date.getTimezoneOffset() * -1; } date = $.timepicker.timezoneAdjust(date, tp_inst.timezone); tp_date = $.timepicker.timezoneAdjust(tp_date, tp_inst.timezone); } this._updateDatepicker(inst); this._base_setDateDatepicker.apply(this, arguments); this._setTimeDatepicker(target, tp_date, true); }; /* * override getDate() to allow getting time too within Date object */ $.datepicker._base_getDateDatepicker = $.datepicker._getDateDatepicker; $.datepicker._getDateDatepicker = function (target, noDefault) { var inst = this._getInst(target); if (!inst) { return; } var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { // if it hasn't yet been defined, grab from field if (inst.lastVal === undefined) { this._setDateFromField(inst, noDefault); } var date = this._getDate(inst); if (date && tp_inst._parseTime($(target).val(), tp_inst.timeOnly)) { date.setHours(tp_inst.hour, tp_inst.minute, tp_inst.second, tp_inst.millisec); date.setMicroseconds(tp_inst.microsec); // This is important if you are using the timezone option, javascript's Date // object will only return the timezone offset for the current locale, so we // adjust it accordingly. If not using timezone option this won't matter.. if (tp_inst.timezone != null) { // look out for DST if tz wasn't specified if (!tp_inst.support.timezone && tp_inst._defaults.timezone === null) { tp_inst.timezone = date.getTimezoneOffset() * -1; } date = $.timepicker.timezoneAdjust(date, tp_inst.timezone); } } return date; } return this._base_getDateDatepicker(target, noDefault); }; /* * override parseDate() because UI 1.8.14 throws an error about "Extra characters" * An option in datapicker to ignore extra format characters would be nicer. */ $.datepicker._base_parseDate = $.datepicker.parseDate; $.datepicker.parseDate = function (format, value, settings) { var date; try { date = this._base_parseDate(format, value, settings); } catch (err) { // Hack! The error message ends with a colon, a space, and // the "extra" characters. We rely on that instead of // attempting to perfectly reproduce the parsing algorithm. if (err.indexOf(":") >= 0) { date = this._base_parseDate(format, value.substring(0, value.length - (err.length - err.indexOf(':') - 2)), settings); $.timepicker.log("Error parsing the date string: " + err + "\ndate string = " + value + "\ndate format = " + format); } else { throw err; } } return date; }; /* * override formatDate to set date with time to the input */ $.datepicker._base_formatDate = $.datepicker._formatDate; $.datepicker._formatDate = function (inst, day, month, year) { var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { tp_inst._updateDateTime(inst); return tp_inst.$input.val(); } return this._base_formatDate(inst); }; /* * override options setter to add time to maxDate(Time) and minDate(Time). MaxDate */ $.datepicker._base_optionDatepicker = $.datepicker._optionDatepicker; $.datepicker._optionDatepicker = function (target, name, value) { var inst = this._getInst(target), name_clone; if (!inst) { return null; } var tp_inst = this._get(inst, 'timepicker'); if (tp_inst) { var min = null, max = null, onselect = null, overrides = tp_inst._defaults.evnts, fns = {}, prop; if (typeof name === 'string') { // if min/max was set with the string if (name === 'minDate' || name === 'minDateTime') { min = value; } else if (name === 'maxDate' || name === 'maxDateTime') { max = value; } else if (name === 'onSelect') { onselect = value; } else if (overrides.hasOwnProperty(name)) { if (typeof (value) === 'undefined') { return overrides[name]; } fns[name] = value; name_clone = {}; //empty results in exiting function after overrides updated } } else if (typeof name === 'object') { //if min/max was set with the JSON if (name.minDate) { min = name.minDate; } else if (name.minDateTime) { min = name.minDateTime; } else if (name.maxDate) { max = name.maxDate; } else if (name.maxDateTime) { max = name.maxDateTime; } for (prop in overrides) { if (overrides.hasOwnProperty(prop) && name[prop]) { fns[prop] = name[prop]; } } } for (prop in fns) { if (fns.hasOwnProperty(prop)) { overrides[prop] = fns[prop]; if (!name_clone) { name_clone = $.extend({}, name); } delete name_clone[prop]; } } if (name_clone && isEmptyObject(name_clone)) { return; } if (min) { //if min was set if (min === 0) { min = new Date(); } else { min = new Date(min); } tp_inst._defaults.minDate = min; tp_inst._defaults.minDateTime = min; } else if (max) { //if max was set if (max === 0) { max = new Date(); } else { max = new Date(max); } tp_inst._defaults.maxDate = max; tp_inst._defaults.maxDateTime = max; } else if (onselect) { tp_inst._defaults.onSelect = onselect; } } if (value === undefined) { return this._base_optionDatepicker.call($.datepicker, target, name); } return this._base_optionDatepicker.call($.datepicker, target, name_clone || name, value); }; /* * jQuery isEmptyObject does not check hasOwnProperty - if someone has added to the object prototype, * it will return false for all objects */ var isEmptyObject = function (obj) { var prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { return false; } } return true; }; /* * jQuery extend now ignores nulls! */ var extendRemove = function (target, props) { $.extend(target, props); for (var name in props) { if (props[name] === null || props[name] === undefined) { target[name] = props[name]; } } return target; }; /* * Determine by the time format which units are supported * Returns an object of booleans for each unit */ var detectSupport = function (timeFormat) { var tf = timeFormat.replace(/'.*?'/g, '').toLowerCase(), // removes literals isIn = function (f, t) { // does the format contain the token? return f.indexOf(t) !== -1 ? true : false; }; return { hour: isIn(tf, 'h'), minute: isIn(tf, 'm'), second: isIn(tf, 's'), millisec: isIn(tf, 'l'), microsec: isIn(tf, 'c'), timezone: isIn(tf, 'z'), ampm: isIn(tf, 't') && isIn(timeFormat, 'h'), iso8601: isIn(timeFormat, 'Z') }; }; /* * Converts 24 hour format into 12 hour * Returns 12 hour without leading 0 */ var convert24to12 = function (hour) { hour %= 12; if (hour === 0) { hour = 12; } return String(hour); }; var computeEffectiveSetting = function (settings, property) { return settings && settings[property] ? settings[property] : $.timepicker._defaults[property]; }; /* * Splits datetime string into date and time substrings. * Throws exception when date can't be parsed * Returns {dateString: dateString, timeString: timeString} */ var splitDateTime = function (dateTimeString, timeSettings) { // The idea is to get the number separator occurrences in datetime and the time format requested (since time has // fewer unknowns, mostly numbers and am/pm). We will use the time pattern to split. var separator = computeEffectiveSetting(timeSettings, 'separator'), format = computeEffectiveSetting(timeSettings, 'timeFormat'), timeParts = format.split(separator), // how many occurrences of separator may be in our format? timePartsLen = timeParts.length, allParts = dateTimeString.split(separator), allPartsLen = allParts.length; if (allPartsLen > 1) { return { dateString: allParts.splice(0, allPartsLen - timePartsLen).join(separator), timeString: allParts.splice(0, timePartsLen).join(separator) }; } return { dateString: dateTimeString, timeString: '' }; }; /* * Internal function to parse datetime interval * Returns: {date: Date, timeObj: Object}, where * date - parsed date without time (type Date) * timeObj = {hour: , minute: , second: , millisec: , microsec: } - parsed time. Optional */ var parseDateTimeInternal = function (dateFormat, timeFormat, dateTimeString, dateSettings, timeSettings) { var date, parts, parsedTime; parts = splitDateTime(dateTimeString, timeSettings); date = $.datepicker._base_parseDate(dateFormat, parts.dateString, dateSettings); if (parts.timeString === '') { return { date: date }; } parsedTime = $.datepicker.parseTime(timeFormat, parts.timeString, timeSettings); if (!parsedTime) { throw 'Wrong time format'; } return { date: date, timeObj: parsedTime }; }; /* * Internal function to set timezone_select to the local timezone */ var selectLocalTimezone = function (tp_inst, date) { if (tp_inst && tp_inst.timezone_select) { var now = date || new Date(); tp_inst.timezone_select.val(-now.getTimezoneOffset()); } }; /* * Create a Singleton Instance */ $.timepicker = new Timepicker(); /** * Get the timezone offset as string from a date object (eg '+0530' for UTC+5.5) * @param {number} tzMinutes if not a number, less than -720 (-1200), or greater than 840 (+1400) this value is returned * @param {boolean} iso8601 if true formats in accordance to iso8601 "+12:45" * @return {string} */ $.timepicker.timezoneOffsetString = function (tzMinutes, iso8601) { if (isNaN(tzMinutes) || tzMinutes > 840 || tzMinutes < -720) { return tzMinutes; } var off = tzMinutes, minutes = off % 60, hours = (off - minutes) / 60, iso = iso8601 ? ':' : '', tz = (off >= 0 ? '+' : '-') + ('0' + Math.abs(hours)).slice(-2) + iso + ('0' + Math.abs(minutes)).slice(-2); if (tz === '+00:00') { return 'Z'; } return tz; }; /** * Get the number in minutes that represents a timezone string * @param {string} tzString formatted like "+0500", "-1245", "Z" * @return {number} the offset minutes or the original string if it doesn't match expectations */ $.timepicker.timezoneOffsetNumber = function (tzString) { var normalized = tzString.toString().replace(':', ''); // excuse any iso8601, end up with "+1245" if (normalized.toUpperCase() === 'Z') { // if iso8601 with Z, its 0 minute offset return 0; } if (!/^(\-|\+)\d{4}$/.test(normalized)) { // possibly a user defined tz, so just give it back return tzString; } return ((normalized.substr(0, 1) === '-' ? -1 : 1) * // plus or minus ((parseInt(normalized.substr(1, 2), 10) * 60) + // hours (converted to minutes) parseInt(normalized.substr(3, 2), 10))); // minutes }; /** * No way to set timezone in js Date, so we must adjust the minutes to compensate. (think setDate, getDate) * @param {Date} date * @param {string} toTimezone formatted like "+0500", "-1245" * @return {Date} */ $.timepicker.timezoneAdjust = function (date, toTimezone) { var toTz = $.timepicker.timezoneOffsetNumber(toTimezone); if (!isNaN(toTz)) { date.setMinutes(date.getMinutes() + -date.getTimezoneOffset() - toTz); } return date; }; /** * Calls `timepicker()` on the `startTime` and `endTime` elements, and configures them to * enforce date range limits. * n.b. The input value must be correctly formatted (reformatting is not supported) * @param {Element} startTime * @param {Element} endTime * @param {Object} options Options for the timepicker() call * @return {jQuery} */ $.timepicker.timeRange = function (startTime, endTime, options) { return $.timepicker.handleRange('timepicker', startTime, endTime, options); }; /** * Calls `datetimepicker` on the `startTime` and `endTime` elements, and configures them to * enforce date range limits. * @param {Element} startTime * @param {Element} endTime * @param {Object} options Options for the `timepicker()` call. Also supports `reformat`, * a boolean value that can be used to reformat the input values to the `dateFormat`. * @param {string} method Can be used to specify the type of picker to be added * @return {jQuery} */ $.timepicker.datetimeRange = function (startTime, endTime, options) { $.timepicker.handleRange('datetimepicker', startTime, endTime, options); }; /** * Calls `datepicker` on the `startTime` and `endTime` elements, and configures them to * enforce date range limits. * @param {Element} startTime * @param {Element} endTime * @param {Object} options Options for the `timepicker()` call. Also supports `reformat`, * a boolean value that can be used to reformat the input values to the `dateFormat`. * @return {jQuery} */ $.timepicker.dateRange = function (startTime, endTime, options) { $.timepicker.handleRange('datepicker', startTime, endTime, options); }; /** * Calls `method` on the `startTime` and `endTime` elements, and configures them to * enforce date range limits. * @param {string} method Can be used to specify the type of picker to be added * @param {Element} startTime * @param {Element} endTime * @param {Object} options Options for the `timepicker()` call. Also supports `reformat`, * a boolean value that can be used to reformat the input values to the `dateFormat`. * @return {jQuery} */ $.timepicker.handleRange = function (method, startTime, endTime, options) { options = $.extend({}, { minInterval: 0, // min allowed interval in milliseconds maxInterval: 0, // max allowed interval in milliseconds start: {}, // options for start picker end: {} // options for end picker }, options); function checkDates(changed, other) { var startdt = startTime[method]('getDate'), enddt = endTime[method]('getDate'), changeddt = changed[method]('getDate'); if (startdt !== null) { var minDate = new Date(startdt.getTime()), maxDate = new Date(startdt.getTime()); minDate.setMilliseconds(minDate.getMilliseconds() + options.minInterval); maxDate.setMilliseconds(maxDate.getMilliseconds() + options.maxInterval); if (options.minInterval > 0 && minDate > enddt) { // minInterval check endTime[method]('setDate', minDate); } else if (options.maxInterval > 0 && maxDate < enddt) { // max interval check endTime[method]('setDate', maxDate); } else if (startdt > enddt) { other[method]('setDate', changeddt); } } } function selected(changed, other, option) { if (!changed.val()) { return; } var date = changed[method].call(changed, 'getDate'); if (date !== null && options.minInterval > 0) { if (option === 'minDate') { date.setMilliseconds(date.getMilliseconds() + options.minInterval); } if (option === 'maxDate') { date.setMilliseconds(date.getMilliseconds() - options.minInterval); } } if (date.getTime) { other[method].call(other, 'option', option, date); } } $.fn[method].call(startTime, $.extend({ onClose: function (dateText, inst) { checkDates($(this), endTime); }, onSelect: function (selectedDateTime) { selected($(this), endTime, 'minDate'); } }, options, options.start)); $.fn[method].call(endTime, $.extend({ onClose: function (dateText, inst) { checkDates($(this), startTime); }, onSelect: function (selectedDateTime) { selected($(this), startTime, 'maxDate'); } }, options, options.end)); checkDates(startTime, endTime); selected(startTime, endTime, 'minDate'); selected(endTime, startTime, 'maxDate'); return $([startTime.get(0), endTime.get(0)]); }; /** * Log error or data to the console during error or debugging * @param {Object} err pass any type object to log to the console during error or debugging * @return {void} */ $.timepicker.log = function (err) { if (window.console) { window.console.log(err); } }; /* * Add util object to allow access to private methods for testability. */ $.timepicker._util = { _extendRemove: extendRemove, _isEmptyObject: isEmptyObject, _convert24to12: convert24to12, _detectSupport: detectSupport, _selectLocalTimezone: selectLocalTimezone, _computeEffectiveSetting: computeEffectiveSetting, _splitDateTime: splitDateTime, _parseDateTimeInternal: parseDateTimeInternal }; /* * Microsecond support */ if (!Date.prototype.getMicroseconds) { Date.prototype.microseconds = 0; Date.prototype.getMicroseconds = function () { return this.microseconds; }; Date.prototype.setMicroseconds = function (m) { this.setMilliseconds(this.getMilliseconds() + Math.floor(m / 1000)); this.microseconds = m % 1000; return this; }; } /* * Keep up with the version */ $.timepicker.version = "1.4.3"; })(jQuery);
{"filter":false,"title":"clockpicker.js","tooltip":"/vendor/clockpicker/clockpicker.js","undoManager":{"mark":-1,"position":-1,"stack":[]},"ace":{"folds":[],"scrolltop":2165,"scrollleft":0,"selection":{"start":{"row":153,"column":3},"end":{"row":153,"column":4},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":{"row":143,"state":"start","mode":"ace/mode/javascript"}},"timestamp":1428774469755,"hash":"ff9d655ce8636b19d1d8c9c57c6c98303157fe0d"}
(function() { function navBarDirective() { return { restrict: 'EA', templateUrl: '../partials/nav-bar.html', replace: true } } var app = angular.module('MyApp') app.directive('navBar', navBarDirective); }());
import $ from 'jquery'; import { ActionType } from './actions'; export default function(state, action) { if (typeof state === 'undefined') { return $(window).height() - 25; } else { switch (action.type) { case ActionType.RESIZE: return $(window).height() - $('#header').height(); } } return state; }
function getCurrentScript(base) { // 参考 https://github.com/samyk/jiagra/blob/master/jiagra.js var stack try { a.b.c() //强制报错,以便捕获e.stack } catch (e) { //safari的错误对象只有line,sourceId,sourceURL stack = e.stack if (!stack && window.opera) { //opera 9没有e.stack,但有e.Backtrace,但不能直接取得,需要对e对象转字符串进行抽取 stack = (String(e).match(/of linked script \S+/g) || []).join(" ") } } if (stack) { /**e.stack最后一行在所有支持的浏览器大致如下: *chrome23: * at http://113.93.50.63/data.js:4:1 *firefox17: *@http://113.93.50.63/query.js:4 *opera12:http://www.oldapps.com/opera.php?system=Windows_XP *@http://113.93.50.63/data.js:4 *IE10: * at Global code (http://113.93.50.63/data.js:4:1) * //firefox4+ 可以用document.currentScript */ stack = stack.split(/[@ ]/g).pop() //取得最后一行,最后一个空格或@之后的部分 stack = stack[0] === "(" ? stack.slice(1, -1) : stack.replace(/\s/, "") //去掉换行符 return stack.replace(/(:\d+)?:\d+$/i, "") //去掉行号与或许存在的出错字符起始位置 } var nodes = document.getElementsByTagName("script") //只在head标签中寻找 for (var i = nodes.length, node; node = nodes[--i]; ) { if (node.readyState === "interactive") { return node.className = node.src } } } alert(getCurrentScript());
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.addColumn('Registrations', 'notes', { type: Sequelize.STRING }); }, down: function (queryInterface) { return queryInterface.removeColumn('Registrations', 'notes'); } };
$(document).ready(function() { var player = document.getElementById('video_player'); var client = new BinaryClient('ws://'+window.location.hostname+':9001'); var stream; var media = new window.MediaSource(); var url = URL.createObjectURL(media); var videoSource; player.src = url; media.addEventListener('sourceopen', function (e) { try { videoSource = media.addSourceBuffer('video/mp4'); } catch (e) { return; } },false); client.on('open', function(){ console.log('Stream opened at port 9001'); stream = client.createStream({ id: player.getAttribute('play-id') }); stream.on('data', function(data) { console.log(data); videoSource.appendBuffer(new Uint8Array(data)); }); }); console.log('player src being set'); });
chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('../index.html', { id: 'microflo-ui', bounds: { width: 400, height: 600 }, resizable: false }); });
/** * Copyright (c) 2014, 2017, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0 */ "use strict"; define(['ojs/ojcore', 'jquery', 'ojs/ojcomponentcore', 'ojs/ojdomscroller', 'ojs/ojanimation', 'promise'], function(oj, $) { /** * Base class for TableDataSourceContentHandler and TreeDataSourceContentHandler * Handler for DataSource generated content * @constructor * @ignore */ oj.DataSourceContentHandler = function(widget, root, data) { this.m_root = root; this.m_widget = widget; this.m_fetching = false; this.setDataSource(data); this.Init(); }; // Subclass from oj.Object oj.Object.createSubclass(oj.DataSourceContentHandler, oj.Object, "oj.DataSourceContentHandler"); /** * Initializes the instance. * @export */ oj.DataSourceContentHandler.prototype.Init = function() { oj.DataSourceContentHandler.superclass.Init.call(this); }; /** * Handles when the container has resize * @param {number} width the new width * @param {number} height the new height * @protected */ oj.DataSourceContentHandler.prototype.HandleResize = function(width, height) { // by default do nothing, to be override by subclass }; /** * Handles when the listview is shown due to for example CSS changes (inside a dialog) */ oj.DataSourceContentHandler.prototype.notifyShown = function() { // by default do nothing, to be override by subclass }; /** * Destroy the content handler * @protected */ oj.DataSourceContentHandler.prototype.Destroy = function() { $(this.m_root).empty(); // @HTMLUpdateOK this.m_widget = null; this.m_root = null; }; /** * Determines whether the content handler is in a ready state * @return {boolean} true if there's no outstanding fetch, false otherwise. * @protected */ oj.DataSourceContentHandler.prototype.IsReady = function() { return !this.m_fetching; }; /** * @private */ oj.DataSourceContentHandler.prototype.setRootAriaProperties = function() { if (this.IsHierarchical()) { this.m_root.setAttribute("role", "tree"); } else { this.m_root.setAttribute("role", "listbox"); } }; /** * Renders the content inside the list * @protected */ oj.DataSourceContentHandler.prototype.RenderContent = function() { this.signalTaskStart(); // signal method task start this.fetchRows(false); this.setRootAriaProperties(); this.signalTaskEnd(); // signal method task end }; /** * Retrieve the key given the item element * @param {Element} element * @return {Object|null} * @protected */ oj.DataSourceContentHandler.prototype.GetKey = function(element) { // should be in the element return element.key; }; oj.DataSourceContentHandler.prototype.FindElementByKey = function(key) { var children, i, elem; children = $(this.m_root).find("."+this.m_widget.getItemElementStyleClass()); for (i=0; i<children.length; i++) { elem = children[i]; if (key == this.GetKey(elem)) { return elem; } } return null; }; oj.DataSourceContentHandler.prototype.getDataSource = function() { return this.m_dataSource; }; /** * @protected */ oj.DataSourceContentHandler.prototype.setDataSource = function(dataSource) { this.m_dataSource = dataSource; }; oj.DataSourceContentHandler.prototype.fetchRows = function(forceFetch) { this.m_widget.showStatusText(); }; /** * Create a list item and add it to the list * @param {Element} parentElement the element to add the list items to * @param {number} index the index of the item * @param {Object|null} data the data for the item * @param {Object} metadata the set of metadata for the item * @param {Function=} callback optional callback function to invoke after item is added * @return {Object} contains the list item and the context object * @protected */ oj.DataSourceContentHandler.prototype.addItem = function(parentElement, index, data, metadata, callback) { var item, referenceNode, childElements, position; item = document.createElement("li"); $(item).uniqueId(); childElements = $(parentElement).children('.'+this.m_widget.getItemElementStyleClass()+', .'+this.m_widget.getEmptyTextStyleClass()); if (index === childElements.length) { referenceNode = null; } else { referenceNode = childElements[index]; } parentElement.insertBefore(item, referenceNode); // @HTMLUpdateOK position = $(parentElement).children().index(item); return this._addOrReplaceItem(item, position, parentElement, index, data, metadata, callback); }; /** * Replace an existing list item in the list * @param {Element} item the list item to change * @param {number} index the index of the item * @param {Object|null} data the data for the item * @param {Object} metadata the set of metadata for the item * @param {Function=} callback optional callback function to invoke after item is added * @protected */ oj.DataSourceContentHandler.prototype.replaceItem = function(item, index, data, metadata, callback) { var parentElement, position; // animate hiding of existing item first this.signalTaskStart(); // signal replace item animation start. Ends in _handleReplaceTransitionEnd() defined in TableDataSourceContentHandler $(item).empty(); // now actually replace the item parentElement = item.parentNode; position = $(parentElement).children().index(item); this._addOrReplaceItem(item, position, parentElement, index, data, metadata, callback); }; /** * Handles both add and replace item * @private */ oj.DataSourceContentHandler.prototype._addOrReplaceItem = function(item, position, parentElement, index, data, metadata, callback) { var contentContainer, context, inlineStyle, styleClass, renderer, content, textWrapper; if (callback == undefined) { callback = this.afterRenderItem.bind(this); } context = this.createContext(index, data, metadata, item); renderer = this.m_widget._getItemRenderer(); if (renderer != null) { // if an element is returned from the renderer and the parent of that element is null, we will append // the returned element to the parentElement. If non-null, we won't do anything, assuming that the // rendered content has already added into the DOM somewhere. content = renderer.call(this, context); if (content != null) { // allow return of document fragment from jquery create/js document.createDocumentFragment if (content['parentNode'] === null || content['parentNode'] instanceof DocumentFragment) { item.appendChild(content); // @HTMLUpdateOK } else if (content['parentNode'] != null) { // parent node exists, do nothing } else if (content.toString) { textWrapper = document.createElement("span"); textWrapper.appendChild(document.createTextNode(content.toString())); // @HTMLUpdateOK item.appendChild(textWrapper); // @HTMLUpdateOK } } } else { textWrapper = document.createElement("span"); textWrapper.appendChild(document.createTextNode(data == null ? "" : data.toString())); // @HTMLUpdateOK item.appendChild(textWrapper); // @HTMLUpdateOK } // get the item from root again as template replaces the item element item = parentElement.children[position]; context['parentElement'] = item; // cache data in item element, this is needed for getDataForVisibleItem. $.data(item, "data", data); // do any post processing callback(item, context); return {item: item, context: context}; }; oj.DataSourceContentHandler.prototype.afterRenderItem = function(item, context) { var elem; // save the key in the element (cannot use data- here since it could be a non-string) item.key = context['key']; item = $(item); item.uniqueId(); // if there's only one element inside the item and it is focusable, set // the role on it instead elem = this.m_widget.getSingleFocusableElement(item); elem.attr("role", this.IsHierarchical() ? "treeitem" : "option"); if (elem != item) { item.attr("role", "presentation"); } elem.addClass(this.m_widget.getFocusedElementStyleClass()); // tag it if item is not focusable if (!this.isFocusable(context)) { item.addClass("oj-skipfocus"); } item.addClass(this.m_widget.getItemElementStyleClass()); }; oj.DataSourceContentHandler.prototype.createContext = function(index, data, metadata, elem) { var context, prop; context = { }; context['parentElement'] = elem; context['index'] = index; context['data'] = data; context['component'] = this.m_widget.getWidgetConstructor(); context['datasource'] = this.getDataSource(); // merge properties from metadata into cell context // the properties in metadata would have precedence for (prop in metadata) { if (metadata.hasOwnProperty(prop)) { context[prop] = metadata[prop]; } } return context; }; oj.DataSourceContentHandler.prototype.isFocusable = function(context) { return this.m_widget._getItemOption("focusable", context, true); }; oj.DataSourceContentHandler.prototype.isSelectable = function(context) { return this.m_widget._getItemOption("selectable", context, true); }; oj.DataSourceContentHandler.prototype.signalTaskStart = function() { if (this.m_widget) // check that widget exists (e.g. not destroyed) { this.m_widget.signalTaskStart(); } }; oj.DataSourceContentHandler.prototype.signalTaskEnd = function() { if (this.m_widget) // check that widget exists (e.g. not destroyed) { this.m_widget.signalTaskEnd(); } }; /** * Handler for TableDataSource generated content * @constructor * @extends oj.DataSourceContentHandler * @ignore */ oj.TableDataSourceContentHandler = function(widget, root, data) { oj.TableDataSourceContentHandler.superclass.constructor.call(this, widget, root, data); }; // Subclass from oj.DataSourceContentHandler oj.Object.createSubclass(oj.TableDataSourceContentHandler, oj.DataSourceContentHandler, "oj.TableDataSourceContentHandler"); /** * Initializes the instance. * @protected */ oj.TableDataSourceContentHandler.prototype.Init = function() { oj.TableDataSourceContentHandler.superclass.Init.call(this); }; oj.TableDataSourceContentHandler.prototype.IsHierarchical = function() { return false; }; /** * Destroy the content handler * @protected */ oj.TableDataSourceContentHandler.prototype.Destroy = function() { oj.TableDataSourceContentHandler.superclass.Destroy.call(this); this._removeDataSourceEventListeners(); if (this.m_domScroller != null) { this.m_domScroller.destroy(); this.m_domScroller = null; this.m_domScrollerMaxCountFunc = null; } this.m_loadingIndicator = null; }; /** * @override */ oj.TableDataSourceContentHandler.prototype.HandleResize = function(width, height) { // we only care about the highwatermark scrolling case, and if height changes if (!this._isLoadMoreOnScroll() || this.m_height == undefined || this.m_height == height) { return; } this.m_height = height; // check viewport this.checkViewport(); }; /** * @override */ oj.TableDataSourceContentHandler.prototype.notifyShown = function() { // we only care about the highwatermark scrolling case if (!this._isLoadMoreOnScroll()) { return; } // for loadMoreOnScroll case, we will have to make sure the viewport is satisfied this.checkViewport(); }; /** * Is loadMoreOnScroll * @return {boolean} true or false * @private */ oj.TableDataSourceContentHandler.prototype._isLoadMoreOnScroll = function() { return this.m_widget.options['scrollPolicy'] == "loadMoreOnScroll" ? true: false; }; /** * Gets the number of items to return in each fetch * @return {number} the fetch size * @private */ oj.TableDataSourceContentHandler.prototype._getFetchSize = function() { return Math.max(0, this.m_widget.options['scrollPolicyOptions']['fetchSize']); }; /** * Gets the scroller element used in DomScroller * @return {Element} the scroller element * @private */ oj.TableDataSourceContentHandler.prototype._getScroller = function() { var scroller = this.m_widget.options['scrollPolicyOptions']['scroller']; if (scroller != null) { // make sure it's an ancestor if ($.contains(scroller, this.m_root)) { // might as well calculate offset here this._fetchTrigger = oj.DomScroller.calculateOffsetTop(scroller, this.m_root); return scroller; } } // if not specified or not an ancestor, use the listview root element return this.m_widget.getRootElement(); }; /** * Gets the distance from maximum scroll position that triggers a fetch * @return {number|undefined} the distance in pixel or undefined if no scroller is specified * @private */ oj.TableDataSourceContentHandler.prototype._getFetchTrigger = function() { return this._fetchTrigger; }; /** * Gets the maximum number of items that can be retrieved from data source * @return {number} the maximum fetch count * @private */ oj.TableDataSourceContentHandler.prototype._getMaxCount = function() { return this.m_widget.options['scrollPolicyOptions']['maxCount']; }; oj.TableDataSourceContentHandler.prototype.setDataSource = function(dataSource) { var self; this._removeDataSourceEventListeners(); if (dataSource != null) { if (this._isLoadMoreOnScroll()) { self = this; this.m_domScrollerMaxCountFunc = function(result) { if (result != null) { self.signalTaskStart(); // signal task start // remove any loading indicator, which is always added to the end after fetch self._removeLoadingIndicator(); if (self.IsReady()) { self.signalTaskStart(); // start a dummy task to be paired with the fetchEnd() call below if no new data were fetched. } self._handleFetchedData(result); // will call fetchEnd(), which signals a task end. Started either in fetchRows() or in a dummy task not involving data fetch. // always append the loading indicator at the end except the case when max limit has been reached if (result['maxCountLimit']) { self._handleScrollerMaxRowCount(); } else { self._appendLoadingIndicator(); } self.signalTaskEnd(); // signal domscroller fetch end. Started in this.m_domScroller._handleScrollerScrollTop monkey patched below self.signalTaskEnd(); // signal task end } else if (result === undefined) { // when there's no more data self._removeLoadingIndicator(); self.signalTaskEnd(); // signal domscroller fetch end. Started in this.m_domScroller._handleScrollerScrollTop monkey patched below } }; this.m_domScroller = new oj.DomScroller(this._getScroller(), dataSource, {'fetchSize' : this._getFetchSize(), 'fetchTrigger' : this._getFetchTrigger(), 'maxCount' : this._getMaxCount(), 'success': this.m_domScrollerMaxCountFunc, 'error': this.signalTaskEnd}); // Monkey patch this.m_domScroller's _handleScrollerScrollTop() to signal a task start before starting data fetch this.m_domScroller._handleScrollerScrollTop = function(scrollTop, maxScrollTop) { if (maxScrollTop - scrollTop <= 1) self.signalTaskStart(); // signal domscroller data fetching. Ends either in success call (m_domScrollerMaxCountFunc) or in error call (self.signalTaskEnd) oj.DomScroller.prototype._handleScrollerScrollTop.call(this, scrollTop, maxScrollTop); } } this.m_handleModelSyncEventListener = this.handleModelSyncEvent.bind(this); this.m_handleModelSortEventListener = this.handleModelSortEvent.bind(this); this.m_handleModelAddEventListener = this.handleModelAddEvent.bind(this); this.m_handleModelRemoveEventListener = this.handleModelRemoveEvent.bind(this); this.m_handleModelChangeEventListener = this.handleModelChangeEvent.bind(this); this.m_handleModelResetEventListener = this.handleModelResetEvent.bind(this); if (oj.PagingTableDataSource && (dataSource instanceof oj.PagingTableDataSource)) { dataSource.on("sync", this.m_handleModelSyncEventListener); } dataSource.on("sort", this.m_handleModelSortEventListener); dataSource.on("add", this.m_handleModelAddEventListener); dataSource.on("remove", this.m_handleModelRemoveEventListener); dataSource.on("change", this.m_handleModelChangeEventListener); dataSource.on("reset", this.m_handleModelResetEventListener); dataSource.on("refresh", this.m_handleModelResetEventListener); } this.m_dataSource = dataSource; }; /** * Add a loading indicator to the list for high watermark scrolling scenario * @private */ oj.TableDataSourceContentHandler.prototype._appendLoadingIndicator = function() { var item, icon; // check if it's already added if (this.m_loadingIndicator != null) { return; } item = $(document.createElement("li")); item.uniqueId() .attr("role", "presentation") .addClass(this.m_widget.getItemStyleClass()); icon = $(document.createElement("div")); icon.addClass("oj-listview-loading-icon"); item.append(icon); // @HtmlUpdateOK $(this.m_root).append(item); // @HtmlUpdateOK this.m_loadingIndicator = item; }; /** * Remove the loading indicator * @private */ oj.TableDataSourceContentHandler.prototype._removeLoadingIndicator = function() { if (this.m_loadingIndicator != null) { this.m_loadingIndicator.remove(); } this.m_loadingIndicator = null; }; /** * Add required attributes to item after it is rendered by the renderer * @param {Element} item the item element to modify * @param {Object} context the item context * @protected */ oj.TableDataSourceContentHandler.prototype.afterRenderItem = function(item, context) { var size; oj.TableDataSourceContentHandler.superclass.afterRenderItem.call(this, item, context); $(item).addClass(this.m_widget.getItemStyleClass()); if (this.m_widget._isSelectionEnabled() && this.isSelectable(context)) { this.m_widget.getFocusItem($(item)).attr("aria-selected", false); } // for highwatermark scrolling, we'll need to add additional wai-aria attribute since not // all items are in the DOM if (this._isLoadMoreOnScroll()) { size = Math.min(this.m_dataSource.totalSize(), this._getMaxCount()); if (size === -1) { // if count is unknown, then use max count, and re-adjust later as necessary size = this._getMaxCount(); } if (size > 0) { $(item).attr("aria-setsize", size) .attr("aria-posinset", context['index']+1); } } this.m_widget.itemRenderComplete(item, context); }; /** * Add required attributes to item after it is rendered by the renderer, and perform * animation for insert * @param {Element} item the item element to modify * @param {Object} context the item context * @private */ oj.TableDataSourceContentHandler.prototype.afterRenderItemForInsertEvent = function(item, context) { var elem, height, itemStyleClass, content, action = "add", effect, promise; this.signalTaskStart(); // signal post rendering processing start. Ends at the end of the method. this.afterRenderItem(item, context); // hide it before starting animation to show added item elem = $(item); height = elem.outerHeight(); itemStyleClass = this.m_widget.getItemStyleClass(); elem.children().wrapAll("<div></div>"); //@HTMLUpdateOK elem.removeClass(itemStyleClass) .addClass("oj-listview-item-add-remove-transition"); content = elem.children().first(); content.addClass(itemStyleClass); this.signalTaskStart(); // signal add animation start. Ends in _handleAddTransitionEnd(). effect = this.m_widget.getAnimationEffect(action); promise = oj.AnimationUtils.startAnimation(item, action, effect); // now show it var self = this; promise.then(function(val) { self._handleAddTransitionEnd(context, item); }); this.signalTaskEnd(); // signal post rendering processing end. Started at the beginning of the method. }; /** * Callback handler max fetch count. * @private */ oj.TableDataSourceContentHandler.prototype._handleScrollerMaxRowCount = function() { // TODO: use resource bundle oj.Logger.error("max count reached"); }; /** * Remove data source event listeners * @private */ oj.TableDataSourceContentHandler.prototype._removeDataSourceEventListeners = function() { if (this.m_dataSource != null) { this.m_dataSource.off("sync", this.m_handleModelSyncEventListener); this.m_dataSource.off("sort", this.m_handleModelSortEventListener); this.m_dataSource.off("add", this.m_handleModelAddEventListener); this.m_dataSource.off("remove", this.m_handleModelRemoveEventListener); this.m_dataSource.off("change", this.m_handleModelChangeEventListener); this.m_dataSource.off("reset", this.m_handleModelResetEventListener); this.m_dataSource.off("refresh", this.m_handleModelResetEventListener); } }; /** * Checks whether loading indicator should be appended to the end of the list * @param {Object} results fetch result set * @return {boolean} whether loading indicator should be appended to the end of list * @private */ oj.TableDataSourceContentHandler.prototype._shouldAppendLoadingIndicator = function(results) { // checks if it's highwatermark scroling and there are results and the total size is either unknown or // more than the size of the result set return this._isLoadMoreOnScroll() && results != null && results['keys'] && results['keys'].length > 0 && (this.m_dataSource.totalSize() == -1 || this.m_dataSource.totalSize() > results['keys'].length); }; /** * @param {boolean} forceFetch * @override */ oj.TableDataSourceContentHandler.prototype.fetchRows = function(forceFetch) { var initFetch = true, options, self, promise; this.signalTaskStart(); // signal method task start // checks if we are already fetching cells if (this.IsReady()) { this.m_fetching = true; oj.TableDataSourceContentHandler.superclass.fetchRows.call(this, forceFetch); // otherwise paging control will initialize fetching of content // note this flag can be remove once we sort out not having paging control initialize fetch if (oj.PagingTableDataSource && (this.m_dataSource instanceof oj.PagingTableDataSource)) { initFetch = false; // signal fetch started. // For pagingTableDataSource, ends in fetchEnd() if successful. // Otherwise, _handleFetchError() runs, and then fetchEnd() runs. So ends in fetchEnd() always. this.signalTaskStart(); } if (initFetch || forceFetch) { // signal fetch started. Ends in fetchEnd() if successful. Otherwise, ends in the reject block of promise below right after _handleFetchError(). // Cannot end in _handleFetchError() to be consistent with pagingTableDataSource behavior (see comment above) if (initFetch) { this.signalTaskStart(); } options = {'fetchType': 'init', 'startIndex': 0}; if (this._isLoadMoreOnScroll()) { options['pageSize'] = this._getFetchSize(); } self = this; promise = this.m_dataSource.fetch(options); promise.then(function(value){ // check if content handler has been destroyed already if (self.m_widget == null) { return; } if (initFetch) { // empty content now that we have data $(self.m_root).empty(); self._handleFetchedData(value); // append loading indicator at the end as needed if (self._shouldAppendLoadingIndicator(value)) { self._appendLoadingIndicator(); // check scroll position again since loading indicator added space to scroll self.m_widget.syncScrollPosition(); } }}, function(reason){ self._handleFetchError(reason); self.signalTaskEnd(); // signal fetch stopped. Started above. }); this.signalTaskEnd(); // signal method task end return; } } this.signalTaskEnd(); // signal method task end }; oj.TableDataSourceContentHandler.prototype._handleFetchError = function(msg) { // TableDataSource aren't giving me any error message oj.Logger.error(msg); if (this._isLoadMoreOnScroll()) { this._removeLoadingIndicator(); } this.m_widget.renderComplete(); }; /** * Callback for handling fetch success * @param {Array} data the array of data * @param {Array} keys the array of keys * @private */ oj.TableDataSourceContentHandler.prototype._handleFetchSuccess = function(data, keys) { var index, i, row; index = this.m_root.childElementCount; for (i=0; i<data.length; i++) { row = data[i]; this.addItem(this.m_root, index, row, this.getMetadata(index, keys[i], row)); index = index + 1; } }; /** * Model add event handler. Called when either a new row of data is added to the data source, or a set of rows are added as a result of * highwater mark scrolling. * @param {Object} event the add model event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelAddEvent = function(event) { var data, keys, indexes, i; if (this.m_root == null) { return; } this.signalTaskStart(); // signal method task start data = event['data']; keys = event['keys']; indexes = event['indexes']; if (data != null && keys != null && keys.length > 0 && data.length > 0 && keys.length == data.length && indexes != null && keys.length == indexes.length) { for (i=0; i<data.length; i++) { this.signalTaskStart(); // signal add item start this.addItem(this.m_root, indexes[i], data[i], this.getMetadata(indexes[i], keys[i], data[i]), this.afterRenderItemForInsertEvent.bind(this)); this.signalTaskEnd(); // signal add item end } if (this.IsReady()) { this.signalTaskStart(); // start a dummy task to be paired with the fetchEnd() call below if no new data were fetched. } // do whatever post fetch processing this.fetchEnd(); // signals a task end. Started either in fetchRows() or in a dummy task not involving data fetch. } this.signalTaskEnd(); // signal method task end }; /** * Handles when add item animation transition ends * @param {Object} context * @param {Element} elem * @private */ oj.TableDataSourceContentHandler.prototype._handleAddTransitionEnd = function(context, elem) { // cleanup $(elem).removeClass("oj-listview-item-add-remove-transition") .addClass(this.m_widget.getItemStyleClass()) .children().children().unwrap(); //@HTMLUpdateOK this.m_widget.itemInsertComplete(elem, context); this.signalTaskEnd(); // signal add animation end. Started in afterRenderItemForInsertEvent(); }; /** * Model remove event handler. Called when a row has been removed from the underlying data. * @param {Object} event the model remove event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelRemoveEvent = function(event) { var keys, i, elem, itemStyleClass; keys = event['keys']; if (this.m_root == null || keys == null || keys.length == 0) { return; } this.signalTaskStart(); // signal method task start for (i=0; i<keys.length; i++) { elem = this.FindElementByKey(keys[i]); if (elem != null) { this.signalTaskStart(); // signal removeItem start this._removeItem(elem); this.signalTaskEnd(); // signal removeItem end } } // since the items are removed, need to clear cache this.m_widget.ClearCache(); this.signalTaskEnd(); // signal method task end }; /** * Remove a single item element * @param {jQuery|Element} elem the element to remove * @private */ oj.TableDataSourceContentHandler.prototype._removeItem = function(elem) { var itemStyleClass, self = this, action = "remove", effect, item, promise; this.signalTaskStart(); // signal method task start itemStyleClass = this.m_widget.getItemStyleClass(); elem = $(elem); elem.children().wrapAll("<div class='"+itemStyleClass+"'></div>"); // @HtmlUpdateOK elem.removeClass(itemStyleClass) .addClass("oj-listview-item-add-remove-transition"); this.signalTaskStart(); // signal remove item animation start. Ends in _handleRemoveTransitionEnd() effect = this.m_widget.getAnimationEffect(action); item = /** @type {Element} */ (elem.get(0)); promise = oj.AnimationUtils.startAnimation(item, action, effect); // now hide it promise.then(function(val) { self._handleRemoveTransitionEnd(elem); }); this.signalTaskEnd(); // signal method task end }; /** * Handles when remove item animation transition ends * @param {Element|jQuery} elem * @private */ oj.TableDataSourceContentHandler.prototype._handleRemoveTransitionEnd = function(elem) { elem = $(elem); var parent = elem.parent(); // invoke hook before actually removing the item this.m_widget.itemRemoveComplete(elem.get(0)); elem.remove(); // if it's the last item, show empty text if (parent.get(0).childElementCount == 0) { this.m_widget.renderComplete(); } this.signalTaskEnd(); // signal remove item animation end. Started in _removeItem() }; /** * Model change event handler. Called when a row has been changed from the underlying data. * @param {Object} event the model change event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelChangeEvent = function(event) { var keys, data, indexes, i, elem; keys = event['keys']; if (this.m_root == null || keys == null || keys.length == 0) { return; } this.signalTaskStart(); // signal method task start data = event['data']; indexes = event['indexes']; for (i=0; i<keys.length; i++) { elem = this.FindElementByKey(keys[i]); if (elem != null) { this.signalTaskStart(); // signal replace item start this.replaceItem(elem, indexes[i], data[i], this.getMetadata(indexes[i], keys[i], data[i]), this.afterRenderItemForChangeEvent.bind(this)); this.signalTaskEnd(); // signal replace item end } } // since the item element will change, need to clear cache this.m_widget.ClearCache(); this.signalTaskEnd(); // signal method task end }; /** * @private */ oj.TableDataSourceContentHandler.prototype.afterRenderItemForChangeEvent = function(item, context) { var self = this, action = "update", effect, promise; this.signalTaskStart(); // signal method task start // adds all neccessary wai aria role and classes this.afterRenderItem(item, context); effect = this.m_widget.getAnimationEffect(action); promise = oj.AnimationUtils.startAnimation(item, action, effect); // now hide it promise.then(function(val) { self._handleReplaceTransitionEnd(item); }); this.signalTaskEnd(); // signal method task end }; /** * @private */ oj.TableDataSourceContentHandler.prototype._handleReplaceTransitionEnd = function(item) { $(item).removeClass("oj-listview-item-add-remove-transition"); this.m_widget.restoreCurrentItem(); this.signalTaskEnd(); // signal replace item animation end. Started in replaceItem() from handleModelChangeEvent() (see base class DataSourceContentHandler) }; /** * Model reset (and refresh) event handler. Called when all rows has been removed from the underlying data. * @param {Object} event the model reset/refresh event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelResetEvent = function(event) { if (this.m_root == null) { return; } this.signalTaskStart(); // signal method task start // empty everything (later) and clear cache this.m_widget.ClearCache(); // fetch data this.fetchRows(true); this.signalTaskEnd(); // signal method task end }; /** * Handle fetched data, either from a fetch call or from a sync event * @param {Object} dataObj the fetched data object * @private */ oj.TableDataSourceContentHandler.prototype._handleFetchedData = function(dataObj) { var data, keys; // this could happen if destroy comes before fetch completes (note a refresh also causes destroy) if (this.m_root == null) { return; } data = dataObj['data']; keys = dataObj['keys']; if (Array.isArray(data) && Array.isArray(keys) && data.length == keys.length) { this._handleFetchSuccess(data, keys); // do whatever post fetch processing this.fetchEnd(); } }; /** * Model sync event handler * @param {Object} event the model sync event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelSyncEvent = function(event) { // there is a bug that datasource.off does not remove listener if (this.m_root == null) { return; } this.signalTaskStart(); // signal method task start // when paging control is used clear the list, note in paging control loadMore mode // the startIndex would not be null and we don't want to clear the list in that case if (event['startIndex'] === 0) { $(this.m_root).empty(); } this.m_widget.ClearCache(); // handle result data this._handleFetchedData(event); this.signalTaskEnd(); // signal method task end }; /** * Model sort event handler * @param {Event} event the model sort event * @private */ oj.TableDataSourceContentHandler.prototype.handleModelSortEvent = function(event) { if (this.m_root == null) { return; } this.signalTaskStart(); // signal method task start // empty everything (later) and clear cache this.m_widget.ClearCache(); // if multi-selection, clear selection as well if (this.m_widget._isMultipleSelection()) { this.m_widget._clearSelection(true); } // fetch sorted data this.fetchRows(true); this.signalTaskEnd(); // signal method task end }; /** * Do any logic needed after results from fetch are processed * @private */ oj.TableDataSourceContentHandler.prototype.fetchEnd = function() { // fetch is done this.m_fetching = false; this.m_widget.renderComplete(); // check viewport this.checkViewport(); this.signalTaskEnd(); // signal fetch end. Started in either fetchRows() or started as a dummy task whenever this method is called without fetching rows first (e.g. see m_domScrollerMaxCountFunc). }; /** * Checks the viewport to see if additional fetch is needed * @private */ oj.TableDataSourceContentHandler.prototype.checkViewport = function() { var self = this, fetchPromise; this.signalTaskStart(); // signal method task start // if loadMoreOnScroll then check if we have underflow and do a fetch if we do if (this.m_domScroller != null && this.m_dataSource.totalSize() > 0 && this.IsReady()) { fetchPromise = this.m_domScroller.checkViewport(); if (fetchPromise != null) { this.signalTaskStart(); // signal fetchPromise started. Ends in promise resolution below fetchPromise.then(function(result) { self.m_domScrollerMaxCountFunc(result); self.signalTaskEnd(); // signal checkViewport task end. Started above before fetchPromise resolves here; }, null); } } this.signalTaskEnd(); // signal method task end }; /** * Creates the context object containing metadata * @param {number} index the index * @param {Object} key the key * @param {Object} data the data * @return {Object} the context object * @private */ oj.TableDataSourceContentHandler.prototype.getMetadata = function(index, key, data) { var context = data['context']; if (context == null) { context = {}; } if (context['index'] == null) { context['index'] = index; } if (context['key'] == null) { context['key'] = key; } return context; }; /** * Handler for TreeDataSource generated content * @constructor * @extends oj.DataSourceContentHandler * @ignore */ oj.TreeDataSourceContentHandler = function(widget, root, data) { oj.TreeDataSourceContentHandler.superclass.constructor.call(this, widget, root, data); }; // Subclass from oj.DataSourceContentHandler oj.Object.createSubclass(oj.TreeDataSourceContentHandler, oj.DataSourceContentHandler, "oj.TreeDataSourceContentHandler"); /** * Initializes the instance. * @protected */ oj.TreeDataSourceContentHandler.prototype.Init = function() { oj.TreeDataSourceContentHandler.superclass.Init.call(this); }; /** * Determines whether the conent is hierarchical. * @return {boolean} returns true if content is hierarhical, false otherwise. * @protected */ oj.TreeDataSourceContentHandler.prototype.IsHierarchical = function() { return true; }; /** * @protected */ oj.TreeDataSourceContentHandler.prototype.fetchRows = function(forceFetch) { this.signalTaskStart(); // signal method task start oj.TreeDataSourceContentHandler.superclass.fetchRows.call(this, forceFetch); this.fetchChildren(0, null, this.m_root, null); this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype.fetchChildren = function(start, parent, parentElem, successCallback) { var range; this.signalTaskStart(); // signal method task start // no need to check ready since multiple fetch from different parents can occur at the same time this.m_fetching = true; range = {"start": start, "count": this.m_dataSource.getChildCount(parent)}; this.m_dataSource.fetchChildren(parent, range, {"success": function(nodeSet){this._handleFetchSuccess(nodeSet, parent, parentElem, successCallback);}.bind(this), "error": function(status){this._handleFetchError(status);}.bind(this)}); this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype._handleFetchSuccess = function(nodeSet, parent, parentElem, successCallback) { var start, count, endIndex, fragment, i, data, metadata, item, content; this.signalTaskStart(); // signal method task start start = nodeSet.getStart(); count = nodeSet.getCount(); endIndex = start+count; // walk the node set for (i=0; i<count; i++) { data = nodeSet.getData(start+i); metadata = nodeSet.getMetadata(start+i); this.addItem(parentElem, start+i, data, metadata); } // fetch is done this.m_fetching = false; // if a callback is specified (as it is in the expand case), then invoke it if (successCallback != null) { successCallback.call(null, parentElem); } this.m_widget.renderComplete(); this.m_initialized = true; this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype.afterRenderItem = function(item, context) { var groupStyleClass, itemStyleClass, groupItemStyleClass, groupCollapseStyleClass, focusedStyleClass, collapseClass, content, icon, groupItem; this.signalTaskStart(); // signal method task start oj.TreeDataSourceContentHandler.superclass.afterRenderItem.call(this, item, context); groupStyleClass = this.m_widget.getGroupStyleClass(); itemStyleClass = this.m_widget.getItemStyleClass(); groupItemStyleClass = this.m_widget.getGroupItemStyleClass(); groupCollapseStyleClass = this.m_widget.getGroupCollapseStyleClass(); collapseClass = this.m_widget.getCollapseIconStyleClass(); focusedStyleClass = this.m_widget.getFocusedElementStyleClass(); item = $(item); if (context['leaf'] == false) { item.children().wrapAll("<div></div>"); //@HTMLUpdateOK // collapsed by default if(item.hasClass(focusedStyleClass)) { item.removeClass(focusedStyleClass) .children().first() .addClass(focusedStyleClass) .attr("aria-expanded", "false"); } else{ item.children().first() .attr("role","presentation") .find("." + focusedStyleClass) .attr("aria-expanded", "false"); } content = item.children().first(); content.uniqueId() .addClass(groupItemStyleClass); // add the expand icon if (this.m_widget.isExpandable()) { item.addClass("oj-collapsed") icon = document.createElement("a"); $(icon).attr("href", "#") .attr("aria-labelledby", content.get(0).id) .addClass("oj-component-icon oj-clickable-icon-nocontext") .addClass(collapseClass); content.prepend(icon); //@HTMLUpdateOK } // the yet to be expand group element groupItem = document.createElement("ul"); $(groupItem).addClass(groupStyleClass) .addClass(groupCollapseStyleClass) .attr("role", "group"); item.append(groupItem); //@HTMLUpdateOK } else if (context['leaf'] == true) { item.addClass(itemStyleClass); } if (this.m_widget._isSelectionEnabled() && this.isSelectable(context)) { this.m_widget.getFocusItem(item).attr("aria-selected", false); } // callback to widget this.m_widget.itemRenderComplete(item[0], context); this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype._handleFetchError = function(status) { this.signalTaskStart(); // signal method task start // TableDataSource aren't giving me any error message oj.Logger.error(status); this.m_widget.renderComplete(); this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype.Expand = function(item, successCallback) { var parentKey, parentElem; this.signalTaskStart(); // signal method task start parentKey = this.GetKey(item[0]); parentElem = item.children("ul")[0]; this.fetchChildren(0, parentKey, parentElem, successCallback); this.signalTaskEnd(); // signal method task end }; oj.TreeDataSourceContentHandler.prototype.Collapse = function(item) { // remove all children nodes item.empty(); //@HTMLUpdateOK }; /** * Handler for static HTML content * @constructor * @ignore */ oj.StaticContentHandler = function(widget, root) { this.m_widget = widget; this.m_root = root; }; // Subclass from oj.Object oj.Object.createSubclass(oj.StaticContentHandler, oj.Object, "oj.StaticContentHandler"); /** * Initializes the instance. * @protected */ oj.StaticContentHandler.prototype.Init = function() { oj.StaticContentHandler.superclass.Init.call(this); }; /** * Destroy the content handler * @protected */ oj.StaticContentHandler.prototype.Destroy = function() { this.restoreContent(this.m_root, 0); this.unsetRootAriaProperties(); }; /** * Determine whether the content handler is ready * @return {boolean} returns true there's no outstanding request, false otherwise. * @protected */ oj.StaticContentHandler.prototype.IsReady = function() { // static content does not fetch return true; }; oj.StaticContentHandler.prototype.HandleResize = function(width, height) { // do nothing since all items are present }; oj.StaticContentHandler.prototype.notifyShown = function() { // do nothing since all items are present }; oj.StaticContentHandler.prototype.RenderContent = function() { this.modifyContent(this.m_root, 0); this.setRootAriaProperties(); this.m_widget.renderComplete(); }; oj.StaticContentHandler.prototype.Expand = function(item, successCallback) { var selector, groupItem; selector = "."+this.m_widget.getGroupStyleClass(); groupItem = $(item).children(selector)[0]; $(groupItem).css("display", "block"); successCallback.call(null, groupItem); }; oj.StaticContentHandler.prototype.Collapse = function(item) { // nothing to do }; oj.StaticContentHandler.prototype.IsHierarchical = function() { if (this.m_hier == null) { this.m_hier = $(this.m_root).children("li").children("ul").length > 0; } return this.m_hier; }; /** * Restore the static content into its original format by removing all ListView specific style classes and attributes. * @param {Element} elem the element it is currently restoring * @param {number} depth the depth of the element it is currently restoring * @private */ oj.StaticContentHandler.prototype.restoreContent = function(elem, depth) { var groupStyleClass, groupCollapseStyleClass, groupExpandStyleClass, groupItemStyleClass, itemStyleClass, itemElementStyleClass, items, i, item, groupItems, groupItem; groupStyleClass = this.m_widget.getGroupStyleClass(); groupCollapseStyleClass = this.m_widget.getGroupCollapseStyleClass(); groupExpandStyleClass = this.m_widget.getGroupExpandStyleClass(); groupItemStyleClass = this.m_widget.getGroupItemStyleClass(); itemStyleClass = this.m_widget.getItemStyleClass(); itemElementStyleClass = this.m_widget.getItemElementStyleClass(); items = elem.children; for (i=0; i<items.length; i++) { item = items[i]; this.unsetAriaProperties(item); item = $(item); item.removeClass(itemElementStyleClass) .removeClass(itemStyleClass) .removeClass(this.m_widget.getDepthStyleClass(depth)) .removeClass("oj-skipfocus") .removeClass("oj-focus") .removeClass("oj-hover") .removeClass("oj-expanded") .removeClass("oj-collapsed") .removeClass("oj-selected"); groupItems = item.children("ul"); if (groupItems.length > 0) { item.children("."+groupItemStyleClass).children().unwrap(); item.children(".oj-component-icon").remove(); groupItem = $(groupItems[0]); groupItem.removeClass(groupStyleClass) .removeClass(groupExpandStyleClass) .removeClass(groupCollapseStyleClass) .removeAttr("role"); this.restoreContent(groupItem[0], depth+1); } } }; /** * Modify the static content to include ListView specific style classes and attributes. * @param {Element} elem the element it is currently modifying * @param {number} depth the depth of the element it is currently modifying * @private */ oj.StaticContentHandler.prototype.modifyContent = function(elem, depth) { var itemStyleClass, itemElementStyleClass, groupStyleClass, groupItemStyleClass, groupCollapseStyleClass, collapseClass, focusedElementStyleClass, items, expandable, i, item, context, groupItems, content, icon, groupItem; itemStyleClass = this.m_widget.getItemStyleClass(); itemElementStyleClass = this.m_widget.getItemElementStyleClass(); groupStyleClass = this.m_widget.getGroupStyleClass(); groupItemStyleClass = this.m_widget.getGroupItemStyleClass(); groupCollapseStyleClass = this.m_widget.getGroupCollapseStyleClass(); collapseClass = this.m_widget.getCollapseIconStyleClass(); focusedElementStyleClass = this.m_widget.getFocusedElementStyleClass(); items = elem.children; expandable = this.m_widget.isExpandable(); for (i=0; i<items.length; i++) { item = $(items[i]); context = this.createContext(item); this.setAriaProperties(item, context); item.uniqueId() .addClass(itemElementStyleClass); if (depth > 0) { item.addClass(this.m_widget.getDepthStyleClass(depth)); } // tag it if item is not focusable if (!this.isFocusable(context)) { item.addClass("oj-skipfocus"); } groupItems = item.children("ul"); if (groupItems.length > 0) { this.m_hier = true; item.children(":not(ul)") .wrapAll("<div></div>"); //@HTMLUpdateOK content = item.children().first(); content.addClass(groupItemStyleClass); if (this.hasChildren(groupItems[0])) { if(item.hasClass(focusedElementStyleClass)) { item.removeClass(focusedElementStyleClass); content.addClass(focusedElementStyleClass).attr("aria-expanded", "false"); } else { content.attr("role","presentation"); content.find("."+focusedElementStyleClass).attr("aria-expanded", "false"); } // add the expand icon if (expandable) { item.addClass("oj-collapsed"); content.uniqueId(); // add the expand icon icon = document.createElement("a"); $(icon).attr("href", "#") .attr("role", "button") .attr("aria-labelledby", content.get(0).id) .addClass("oj-component-icon oj-clickable-icon-nocontext") .addClass(collapseClass); content.prepend(icon); //@HTMLUpdateOK } } groupItem = $(groupItems[0]); groupItem.addClass(groupStyleClass) .addClass(groupCollapseStyleClass) .attr("role", "group") .css("display", "none"); this.modifyContent(groupItem[0], depth+1); } else { item.addClass(itemStyleClass); } if (this.m_widget._isSelectionEnabled() && this.isSelectable(context)) { this.m_widget.getFocusItem(item).attr("aria-selected", false); } this.m_widget.itemRenderComplete(item[0], context); } }; /** * @private */ oj.StaticContentHandler.prototype.setRootAriaProperties = function() { if (this.IsHierarchical()) { this.m_root.setAttribute("role", "tree"); } else { this.m_root.setAttribute("role", "listbox"); } }; /** * @private */ oj.StaticContentHandler.prototype.unsetRootAriaProperties = function() { this.m_root.removeAttribute("role"); }; /** * @private */ oj.StaticContentHandler.prototype.hasChildren = function(item) { return ($(item).children("li").length > 0); }; /** * Creates the object with context information for the specified item * @param {jQuery} item the item to create context info object for * @return {Object} the context object * @private */ oj.StaticContentHandler.prototype.createContext = function(item) { var context, parents; context = {}; context['key'] = item.attr('id'); context['parentElement'] = item.children().first()[0]; context['index'] = item.index(); context['data'] = item[0]; context['component'] = this.m_widget.getWidgetConstructor(); // additional context info for hierarhical data if (this.IsHierarchical()) { context['leaf'] = item.children("ul").length == 0; parents = item.parents("li."+this.m_widget.getItemElementStyleClass()); context['depth'] = parents.length; if (parents.length == 0) { context['parentKey'] = null; } else { context['parentKey'] = parents.first().attr('id'); } } return context; }; /** * @private */ oj.StaticContentHandler.prototype.setAriaProperties = function(item, context) { // if there's only one element inside the item and it is focusable, set // the role on it instead var elem = this.m_widget.getSingleFocusableElement(item); elem.attr("role", this.IsHierarchical() ? "treeitem" : "option"); if (elem != item) { item.attr("role", "presentation"); } elem.addClass(this.m_widget.getFocusedElementStyleClass()); }; /** * @private */ oj.StaticContentHandler.prototype.unsetAriaProperties = function(item) { var elem = this.m_widget.getSingleFocusableElement($(item)); elem.removeAttr("role"); elem.removeAttr("aria-selected"); elem.removeAttr("aria-expanded"); elem.removeClass(this.m_widget.getFocusedElementStyleClass()); }; oj.StaticContentHandler.prototype.GetKey = function(element) { return $(element).attr("id"); }; oj.StaticContentHandler.prototype.FindElementByKey = function(key) { return document.getElementById(key); }; oj.StaticContentHandler.prototype.isFocusable = function(context) { return this.m_widget._getItemOption("focusable", context, true); }; oj.StaticContentHandler.prototype.isSelectable = function(context) { return this.m_widget._getItemOption("selectable", context, true); }; /** * todo: create common utility class between combobox and listview * @private */ var _ListViewUtils = { clazz: function(SuperClass, methods) { var constructor = function() {}; oj.Object.createSubclass(constructor, SuperClass, ''); constructor.prototype = $.extend(constructor.prototype, methods); return constructor; } }; /** * @export * @class oj._ojListView * @classdesc Listview * @constructor * @ignore */ oj._ojListView = _ListViewUtils.clazz(Object, /** @lends oj._ojListView.prototype */ { // constants for key codes, todo: move to ListViewUtils LEFT_KEY: 37, RIGHT_KEY: 39, DOWN_KEY: 40, UP_KEY: 38, TAB_KEY: 9, ENTER_KEY: 13, ESC_KEY: 27, F2_KEY: 113, SPACE_KEY: 32, // constants for disclosure state /** @protected **/ STATE_EXPANDED: 0, /** @protected **/ STATE_COLLAPSED: 1, /** @protected **/ STATE_NONE: 2, /** @protected **/ FOCUS_MODE_LIST: 0, /** @protected **/ FOCUS_MODE_ITEM: 1, /** * Initialize the listview at creation * Invoked by widget */ init: function(opts) { var self = this, dndContext; this.readinessStack = []; this.signalTaskStart(); // Move component out of ready state; component is initializing. End in afterCreate() this.ojContext = opts.ojContext; this.element = opts.element; this.OuterWrapper = opts.OuterWrapper; this.options = opts; this.element .uniqueId() .addClass(this.GetStyleClass()+" oj-component-initnode"); this.SetRootElementTabIndex(); // listens for dnd events if ListViewDndContext is defined if (typeof oj.ListViewDndContext != "undefined") { dndContext = new oj.ListViewDndContext(this); this.m_dndContext = dndContext; this.ojContext._on(this.element, { "dragstart": function(event) { return dndContext._handleDragStart(event); }, "dragenter": function(event) { return dndContext._handleDragEnter(event); }, "dragover": function(event) { return dndContext._handleDragOver(event); }, "dragleave": function(event) { return dndContext._handleDragLeave(event); }, "dragend": function(event) { return dndContext._handleDragEnd(event); }, "drag": function(event) { return dndContext._handleDrag(event); }, "drop": function(event) { return dndContext._handleDrop(event); } }); } this.ojContext._on(this.element, { "click": function(event) { self.HandleMouseClick(event); }, "touchstart": function(event) { self.HandleMouseDownOrTouchStart(event); }, "touchend": function(event) { self.HandleTouchEndOrCancel(event); }, "touchcancel": function(event) { self.HandleTouchEndOrCancel(event); }, "mousedown": function(event) { if (event.button === 0) { if (!self._recentTouch()) { self.HandleMouseDownOrTouchStart(event); } } else { // on right click we should prevent focus from shifting to first item self.m_preActive = true; } }, "mouseup": function(event) { self._handleMouseUpOrPanMove(event); self.m_preActive = false; }, "mouseout": function(event) { self._handleMouseOut(event); }, "mouseover": function(event) { self._handleMouseOver(event); }, "keydown": function(event) { self.HandleKeyDown(event); }, "ojpanmove": function(event) { self._handleMouseUpOrPanMove(event); } }); this.ojContext._on(this.ojContext.element, { "focus": function(event) { self.HandleFocus(event); }, "blur": function(event) { self.HandleBlur(event); }, }); // in Firefox, need to explicitly make list container not focusable otherwise first tab will focus on the list container if (oj.AgentUtils.getAgentInfo()['browser'] === oj.AgentUtils.BROWSER.FIREFOX) { this._getListContainer().attr("tabIndex", -1); } // for item focus mode (aka roving focus), we'll need to use focusout handler instead // of blur because blur doesn't bubble if (this.GetFocusMode() === this.FOCUS_MODE_ITEM) { this.ojContext._on(this.ojContext.element, { "focusin": function(event) { self.HandleFocus(event); }, "focusout": function(event) { self.HandleFocusOut(event); } }); } else { this.ojContext._on(this.element, { "focus": function(event) { self.HandleFocus(event); }, "blur": function(event) { self.HandleBlur(event); } }); } this.ojContext.document.bind("touchend.ojlistview touchcancel.ojlistview", this.HandleTouchEndOrCancel.bind(this)); this._registerScrollHandler(); this.ojContext._focusable({ 'applyHighlight': self.ShouldApplyHighlight(), 'recentPointer' : self.RecentPointerCallback(), 'setupHandlers': function( focusInHandler, focusOutHandler) { self._focusInHandler = focusInHandler; self._focusOutHandler = focusOutHandler; } }); }, /** * Initialize the listview after creation * Invoked by widget */ afterCreate: function () { var container; this._buildList(); this._addContextMenu(); this._initContentHandler(); // register a resize listener container = this._getListContainer(); this._registerResizeListener(container[0]); this.signalTaskEnd(); // resolve component initializing task. Started in init() }, /** * Redraw the entire list view after having made some external modifications. * Invoked by widget */ refresh: function() { // reset content, wai aria properties, and ready state this._resetInternal(); this.signalTaskStart(); // signal method task start // set the wai aria properties this.SetAriaProperties(); // recreate the context menu this._addContextMenu(); // recreate the content handler this._initContentHandler(); // reattach scroll listener if neccessary this._registerScrollHandler(); this.signalTaskEnd(); // signal method task end }, /** * Returns a Promise that resolves when the component is ready, i.e. after data fetching, rendering, and animations complete. * Invoked by widget * @return {Promise} A Promise that resolves when the component is ready. */ whenReady: function() { return this.readyPromise; }, /** * Destroy the list view * Invoked by widget */ destroy: function() { this.element.removeClass(this.GetStyleClass()+" oj-component-initnode"); this._unregisterResizeListener(this._getListContainer()); this._resetInternal(); // - DomUtils.unwrap() will avoid unwrapping if the node is being destroyed by Knockout oj.DomUtils.unwrap(this.element, this._getListContainer()); this.ojContext.document.off(".ojlistview"); }, /** * Remove any wai-aria properties and listview specific attributes. * Reset anything done by the content handler. * @private */ _resetInternal: function() { var self = this; this.UnsetAriaProperties(); this._cleanupTabbableElementProperties(this.element); if (this.m_contentHandler != null) { this.m_contentHandler.Destroy(); delete this.m_contentHandler; this.m_contentHandler = null; } this.m_active = null; this.m_isExpandAll = null; this.m_disclosing = null; this.readinessStack = []; this.readyPromise = new Promise(function(resolve, reject) { self.readyResolve = resolve; }); this.ClearCache(); }, /** * Called when listview root element is re-attached to DOM tree. * Invoke by widget */ notifyAttached: function() { // restore scroll position as needed since some browsers reset scroll position this.syncScrollPosition(); }, /** * In browsers [Chrome v35, Firefox v24.5, IE9, Safari v6.1.4], blur and mouseleave events are generated for hidden content but not detached content, * so for detached content only, we must use this hook to remove the focus and hover classes. * Invoke by widget. */ notifyDetached: function() { // Remove focus/hover/active style classes when listview element got detached from document. // For details see related button . this._getListContainer().removeClass("oj-focus-ancestor"); if (this.m_active != null) { $(this.m_active['elem']).removeClass("oj-focus oj-focus-highlight"); } if (this.m_hoverItem != null) { this._unhighlightElem(this.m_hoverItem, "oj-hover"); } }, /** * Called when application programmatically change the css style so that the ListView becomes visible */ notifyShown: function() { // restore scroll position as needed since some browsers reset scroll position this.syncScrollPosition(); // call ContentHandler in case action is neccessarily if (this.m_contentHandler != null) { this.m_contentHandler.notifyShown(); } }, /** * Return the subcomponent node represented by the documented locator attribute values. * Invoked by widget * @param {Object} locator An Object containing at minimum a subId property * whose value is a string, documented by the component, that allows * the component to look up the subcomponent associated with that * string. It contains:<p> * component: optional - in the future there may be more than one * component contained within a page element<p> * subId: the string, documented by the component, that the component * expects in getNodeBySubId to locate a particular subcomponent * @returns {Array.<(Element|null)>|Element|null} the subcomponent located by the subId string passed * in locator, if found.<p> */ getNodeBySubId: function(locator) { var subId, key, item, anchor; if (locator == null) { return this.element ? this.element[0] : null; } subId = locator['subId']; if (subId === 'oj-listview-disclosure' || subId === 'oj-listview-icon') { key = locator['key']; item = this.FindElementByKey(key); if (item != null && item.firstElementChild) { // this should be the anchor anchor = item.firstElementChild.firstElementChild; if (anchor != null && ($(anchor).hasClass(this.getExpandIconStyleClass()) || $(anchor).hasClass(this.getCollapseIconStyleClass()))) { return anchor; } } } // Non-null locators have to be handled by the component subclasses return null; }, /** * Returns the subId locator for the given child DOM node. * Invoked by widget * @param {!Element} node - child DOM node * @return {Object|null} The subId for the DOM node, or null when none is found. */ getSubIdByNode: function(node) { var item, key; // check to see if it's expand/collapse icon if (node != null && $(node).hasClass(this.getExpandIconStyleClass()) || $(node).hasClass(this.getCollapseIconStyleClass())) { item = this.FindItem(node); if (item != null && item.length > 0) { key = this.GetKey(item[0]); if (key != null) { return {'subId': 'oj-listview-disclosure', 'key': key}; } } } return null; }, /** * Returns an object with context for the given child DOM node. * This will always contain the subid for the node, defined as the 'subId' property on the context object. * Additional component specific information may also be included. For more details on returned objects, see context objects. * Invoked by widget * * @param {!Element} node the child DOM node * @returns {Object|null} the context for the DOM node, or null when none is found. */ getContextByNode: function(node) { var item, key, parent, index, context; item = this.FindItem(node); if (item != null && item.length > 0) { key = this.GetKey(item[0]); if (key != null) { parent = item.parent(); index = parent.children("li").index(item); context = {'subId': 'oj-listview-item', 'key': key, 'index': index}; // group item should return the li if (parent.get(0) != this.element.get(0)) { context['parent'] = parent.parent().get(0); } // check if it's a group item if (item.children().first().hasClass(this.getGroupItemStyleClass())) { context['group'] = true; } else { context['group'] = false; } return context; } } return null; }, /** * Return the raw data for an item in ListView. * Invoked by widget * * @param {Object} context the context of the item to retrieve raw data. * @param {Number} context.index the index of the item relative to its parent. * @param {jQuery|Element|string|undefined} context.parent the jQuery wrapped parent node, not required if parent is the root. * @returns {Object | null} item data<p> */ getDataForVisibleItem: function(context) { var index, parent, item; index = context['index']; parent = context['parent']; if (parent == null) { // use the root element parent = this.element.get(0); } else { // find the appropriate group element parent = $(parent).children("ul."+this.getGroupStyleClass()).first(); } item = $(parent).children("li").get(index); if (item != null && $(item).hasClass(this.getItemStyleClass())) { return this._getDataForItem(item); } return null; }, /** * Retrieve data stored in dom * @param {Element} item * @return {*} data for item * @private */ _getDataForItem: function(item) { // if static HTML, returns the item's dom element if (this.GetOption("data") == null) { return item; } else { return $.data(item, "data"); } }, /** * Add a default context menu to the list if there is none. If there is * a context menu set on the listview we use that one. Add listeners * for context menu before show and select. * @param {string=} contextMenu the context menu selector * @private */ _addContextMenu: function(contextMenu) { // currently context menu is only needed for item reordering if (this.m_dndContext != null) { this.m_dndContext.addContextMenu(contextMenu); } }, /** * Unregister event listeners for resize the container DOM element. * @param {Element} element DOM element * @private */ _unregisterResizeListener: function(element) { if (element && this._resizeHandler) { // remove existing listener oj.DomUtils.removeResizeListener(element, this._resizeHandler); } }, /** * Register event listeners for resize the container DOM element. * @param {Element} element DOM element * @private */ _registerResizeListener: function(element) { if (element) { if (this._resizeHandler == null) { this._resizeHandler = this._handleResize.bind(this); } oj.DomUtils.addResizeListener(element, this._resizeHandler); } }, /** * The resize handler. * @param {number} width the new width * @param {number} height the new height * @private */ _handleResize: function(width, height) { if (width > 0 && height > 0 && this.m_contentHandler != null) { this.m_contentHandler.HandleResize(width, height); } }, /** * Whether focus highlight should be applied * @return {boolean} true if should apply focus highlight, false otherwise * @protected */ ShouldApplyHighlight: function() { return true; }, /** * check Whether recent pointer acivity happened or not. * Only used for sliding navlist to avoid focus ring on new focusable item * after completing expand/collapse animation. * @protected */ RecentPointerCallback: function() { return function(){return false}; }, /** * Whether ListView should refresh if certain option is updated * @param {Object} options the options to check * @return {boolean} true if should refresh, false otherwise * @protected */ ShouldRefresh: function(options) { return (options['data'] != null || options['drillMode'] != null || options['groupHeaderPosition'] != null || options['item'] != null || options['scrollPolicy'] != null || options['scrollPolicyOptions'] != null); }, /** * Sets multiple options * Invoke by widget * @param {Object} options the options object * @param {Object} flags additional flags for option * @return {boolean} true to refresh, false otherwise */ setOptions: function(options, flags) { var self, elem, expanded, active, scroller, pos; if (this.ShouldRefresh(options)) { // if data option is updated, and that no update current or selection option // are specified, clear them if (options['data'] != null) { if (options['currentItem'] == null) { this.SetOption('currentItem', null); } if (options['selection'] == null) { this._clearSelection(true); } } // data updated, need to refresh return true; } if (options['expanded'] != null) { // should only apply if data is hierarchical // q: could expanded be change if drillMode is 'expanded'? if (this.m_contentHandler.IsHierarchical()) { // clear collapsed items var this._collapsedKeys = undefined; expanded = options['expanded']; if (Array.isArray(expanded)) { this.signalTaskStart(); // signal task start // collapse all expanded items first this._collapseAll(); // itemRenderComplete would check expanded option to expand nodes as needed // however, since options has not been updated yet this will cause previous // expanded nodes to expand // an option would be to clear the expanded option to null when doing collapseAll // but the issue is that optionChange would be fired AND even if we can suppress // the optionChange event, when the actual optionChange event is fired, the // previousValue param would be wrong (it would be null) // so instead we'll use to flag so that itemRenderComplete would detect and ignore // the expanded option this._ignoreExpanded = true; try { // expand each key self = this; $.each(expanded, function(index, value) { self.expandKey(value, true, true, true); }); } finally { this._ignoreExpanded = undefined; this.signalTaskEnd(); // signal task end } } } } if (options['currentItem'] != null) { elem = this.FindElementByKey(options["currentItem"]); if (elem != null) { elem = $(elem); if (!this.SkipFocus(elem)) { active= document.activeElement; // update tab index and focus only if listview currently has focus if (active && this.element.get(0).contains(active)) { this._activeAndFocus(elem, null); } else { // update internal state only this._setActive(elem, null); } } } } else if (options['currentItem'] === null) { // currentItem is deliberately set to null if this case is entered; deliberately clear active element and its focus this.UnhighlightActive(); this.m_active = null; this.SetRootElementTabIndex(); } this.HandleSelectionOption(options); if (options['selectionMode'] != null) { // clear existing selection if selection mode changes this._clearSelection(true); // reset wai aria properties this.SetAriaProperties(); } if (options['contextMenu'] != null) { this._addContextMenu(options['contextMenu']); } if (options['scrollTop'] != null) { scroller = this._getScroller(); pos = options['scrollTop']; if (pos != null && !isNaN(pos)) { scroller.scrollTop = pos; } } // if reorder switch to enabled/disabled, we'll need to make sure any reorder styling classes are added/removed from focused item if (this.m_dndContext != null && this.m_active != null && options['dnd'] != null && options['dnd']['reorder'] != null) { if (options['dnd']['reorder']['items'] === 'enabled') { this.m_dndContext._setItemDraggable(this.m_active['elem']); } else if (options['dnd']['reorder']['items'] === 'disabled') { this.m_dndContext._unsetItemDraggable(this.m_active['elem']); } } return false; }, /** * Set Selection option. Overriden by Navlist. * @param {Object} options the options object * @protected */ HandleSelectionOption: function(options) { var elem, selection, i; if (options['selection'] != null) { if (this._isSelectionEnabled()) { // remove any non-selectable items, this will effectively clone the selection as well, // which we'll need to do options['selection'] = this._filterSelection(options['selection']); selection = options['selection']; // clear selection first this._clearSelection(false); // selects each key for (i=0; i<selection.length; i++) { elem = this.FindElementByKey(selection[i]); if (elem != null) { this._applySelection(elem, selection[i]); } } } } }, /** * Trigger an event to fire. * @param {string} type the type of event * @param {Object} event the jQuery event to fire * @param {Object} ui the ui param * @protected */ Trigger: function(type, event, ui) { return this.ojContext._trigger(type, event, ui); }, /** * Sets an option on the widget * @param {string} key the option key * @param {Object} value the option value * @param {Object=} flags any optional parameters * @protected */ SetOption: function(key, value, flags) { this.ojContext.option(key, value, flags); }, /** * Gets the value of an option from the widget * @param {string} key the option key * @return {Object} the value of the option * @protected */ GetOption: function(key) { return this.ojContext.option(key); }, /** * Invoke whenever a task is started. Moves the component out of the ready state if necessary. */ signalTaskStart: function() { var self = this; if (this.readinessStack) { if (this.readinessStack.length == 0) { this.readyPromise = new Promise(function(resolve, reject) { self.readyResolve = resolve; }); } this.readinessStack.push(1); } }, /** * Invoke whenever a task finishes. Resolves the readyPromise if component is ready to move into ready state. */ signalTaskEnd: function() { if (this.readinessStack && this.readinessStack.length > 0) { this.readinessStack.pop(); if (this.readinessStack.length == 0) { this.readyResolve(null); } } }, /** * Gets an array of items based on specified ids. * @param {Array} ids an array of item ids. * @return {Array} an array of elements matching the item ids. */ getItems: function(ids) { var elem, self = this, items = []; $.each(ids, function(index, value) { elem = self.FindElementByKey(value); if (elem != null) { items.push(elem); } }); return items; }, /************************************** Core rendering ********************************/ /** * Initialize the content handler based on data type * @private */ _initContentHandler: function() { var data, fetchSize, self; this.signalTaskStart(); // signal method task start data = this.GetOption("data"); if (data != null) { // Check to make sure oj.TableDataSource or oj.TreeDataSource exists through require import if (typeof oj.TableDataSource === "undefined" || typeof oj.TreeDataSource === "undefined") { throw "oj.TableDataSource or oj.TreeDataSource not found. Ensure the required modules are imported"; } if (data instanceof oj.TableDataSource) { this.m_contentHandler = new oj.TableDataSourceContentHandler(this, this.element[0], data); } else if (data instanceof oj.TreeDataSource) { this.m_contentHandler = new oj.TreeDataSourceContentHandler(this, this.element[0], data); } else { throw "Invalid data"; } } else { // StaticContentHandler will handle cases where children are invalid or empty this.m_contentHandler = new oj.StaticContentHandler(this, this.element[0]); } // kick start rendering this.showStatusText(); this.m_contentHandler.RenderContent(); this.signalTaskEnd(); // signal method task end }, /** * Update active descendant attribute * @param {jQuery} elem the active item element * @protected */ UpdateActiveDescendant: function(elem) { this.element.attr("aria-activedescendant", elem.attr("id")); }, /** * Sets wai-aria properties on root element * @protected */ SetAriaProperties: function() { this.element.attr("aria-activedescendant", ""); if (this._isMultipleSelection()) { this.element.attr("aria-multiselectable", true); } else if (this._isSelectionEnabled()) { this.element.attr("aria-multiselectable", false); } }, /** * Removes wai-aria properties on root element * @protected */ UnsetAriaProperties: function() { this.element.removeAttr("aria-activedescendant") .removeAttr("aria-multiselectable"); }, /** * Build the elements inside and around the root * @param {Element} root the root element * @private */ _buildList: function(root) { var container, status, accInfo; container = this._getListContainer(); this.SetAriaProperties(); status = this._buildStatus(); container.append(status); // @HTMLUpdateOK this.m_status = status; accInfo = this._buildAccInfo(); container.append(accInfo); // @HTMLUpdateOK this.m_accInfo = accInfo; // touch specific instruction text for screen reader for reordering if (this._isTouchSupport() && this.m_dndContext != null) { container.append(this._buildAccInstructionText()); // @HTMLUpdateOK } }, /** * Build a status bar div * @return {jQuery} the root of the status bar * @private */ _buildStatus: function() { var root = $(document.createElement("div")); root.addClass("oj-listview-status-message oj-listview-status") .attr({"id": this._createSubId("status"), "role": "status"}); return root; }, /** * Build the accessible text info div * @return {jQuery} the root of the acc info div * @private */ _buildAccInfo: function() { var root = $(document.createElement("div")); root.addClass("oj-helper-hidden-accessible") .attr({"id": this._createSubId("info"), "role": "status"}); return root; }, /** * Build the accessible instruction text for touch devices * @return {jQuery} the root of the acc info div * @private */ _buildAccInstructionText: function() { var root = $(document.createElement("div")); root.addClass("oj-helper-hidden-accessible") .attr({"id": this._createSubId("instr")}); root.text(this.ojContext.getTranslatedString("accessibleReorderTouchInstructionText")); return root; }, /** * Sets the accessible text info * @param {string} text the text to set on accessible info div * @private */ _setAccInfoText: function(text) { if (text != "" && this.m_accInfo.text() != text) { this.m_accInfo.text(text); } }, /** * Displays the 'fetching' status message * @private */ showStatusText: function() { var msg = this.ojContext.getTranslatedString("msgFetchingData"); this.m_status.text(msg) .css("left", this.element.outerWidth()/2 - this.m_status.outerWidth()/2) .show(); }, /** * Hide the 'fetching' status message * @private */ hideStatusText: function() { this.m_status.hide(); }, /** * Retrieves the root element * Invoke by widget */ getRootElement: function() { return this._getListContainer(); }, /** * Retrieves the div around the root element, create one if needed. * @return {jQuery} the div around the root element * @private */ _getListContainer: function() { if (this.m_container == null) { this.m_container = this._createListContainer(); } return this.m_container; }, /** * Creates the div around the root element. * @return {jQuery} the div around the root element * @private */ _createListContainer: function() { var listContainer; if (this.OuterWrapper) { listContainer = $(this.OuterWrapper); } else { listContainer = $(document.createElement('div')); this.element.parent()[0].replaceChild(listContainer[0], this.element[0]); //@HTMLUpdateOK } listContainer.addClass(this.GetContainerStyleClass()).addClass("oj-component"); listContainer.prepend(this.element); //@HTMLUpdateOK return listContainer; }, /** * If the empty text option is 'default' return default empty translated text, * otherwise return the emptyText set in the options * @return {string} the empty text * @private */ _getEmptyText: function() { return this.ojContext.getTranslatedString("msgNoData"); }, /** * Build an empty text div and populate it with empty text * @return {Element} the empty text element * @private */ _buildEmptyText: function() { var emptyText, empty; emptyText = this._getEmptyText(); empty = document.createElement("li"); empty['id'] = this._createSubId("empty"); empty['className'] = this.getEmptyTextStyleClass() + " oj-listview-empty-text"; empty.textContent = emptyText; return empty; }, /** * Determines whether the specified item is expanded * @param {jQuery} item the item element * @return {number} 0 if item is expanded, 1 if item is collapsed, 2 if item cannot be expand or collapse. * @protected */ GetState: function(item) { var expanded = this.getFocusItem(item).attr("aria-expanded"); if (expanded == "true") { return this.STATE_EXPANDED; } else if (expanded == "false") { return this.STATE_COLLAPSED; } else { return this.STATE_NONE; } }, /** * Sets the disclosed state of the item * @param {jQuery} item the item element * @param {number} state 0 if item is expanded, 1 if item is collapsed, 2 if item cannot be expand or collapse. * @protected */ SetState: function(item, state) { var expandable = this.isExpandable(); if (state == this.STATE_EXPANDED) { this.getFocusItem(item).attr("aria-expanded", "true"); if (expandable) { item.removeClass("oj-collapsed") .addClass("oj-expanded"); } } else if (state == this.STATE_COLLAPSED) { this.getFocusItem(item).attr("aria-expanded", "false"); if (expandable) { item.removeClass("oj-expanded") .addClass("oj-collapsed"); } } }, /** * Gets the item option * @param {string} name the name of the option * @param {Object} context the context object * @param {boolean} resolve true evaluate if return value is a function, false otherwise * @return {function(Object)|Object|null} returns the item option * @private */ _getItemOption: function(name, context, resolve) { var option, value; option = this.options["item"]; value = option[name]; if (typeof value == 'function' && resolve) { return value.call(this, context); } return value; }, /** * Gets the item renderer * @return {function(Object)|null} returns the item renderer * @private */ _getItemRenderer: function() { var renderer = this._getItemOption("renderer", null, false); if (typeof renderer != 'function') { // cannot be non-function return null; } return renderer; }, /** * Called by content handler once the content of an item is rendered triggered by an insert event * @param {Element} elem the item element * @param {Object} context the context object used for the item */ itemInsertComplete: function(elem, context) { // hook for NavList }, /** * Called by content handler once the content of an item is removed triggered by an remove event * @param {Element} elem the item element */ itemRemoveComplete: function(elem) { var prop; // if it's the current focus item, clear currentItem option if (this.m_active != null && this.m_active['elem'] && $(this.m_active['elem']).get(0) == elem) { this.SetOption('currentItem', null); } // disassociate element from key map if (elem != null && elem.id && this.m_keyElemMap != null) { for (prop in this.m_keyElemMap) { if (this.m_keyElemMap.hasOwnProperty(prop)) { if (this.m_keyElemMap[prop] === elem.id) { delete this.m_keyElemMap[prop]; return; } } } } }, /** * Called by content handler once the content of an item is rendered * @param {Element} elem the item element * @param {Object} context the context object used for the item */ itemRenderComplete: function(elem, context) { var selection, selectedItems, i, index, clone, expanded, self, current; // dnd if (this.m_dndContext != null) { this.m_dndContext.itemRenderComplete(elem); } // make all tabbable elements non-tabbable, since we want to manage tab stops this._disableAllTabbableElements(elem); // update as selected if it is in selection, check if something already selected in single selection if (this._isSelectionEnabled()) { selection = this.GetOption("selection"); if (this.IsSelectable(elem)) { for (i=0; i<selection.length; i++) { if (selection[i] == context['key']) { this._applySelection(elem, selection[i]); // if it's single selection, then bail if (!this._isMultipleSelection()) { if (selection.length > 1) { // we'll have to modify the value selectedItems = $(this.FindElementByKey(context['key'])); this.SetOption("selection", [context['key']], {'_context': {originalEvent: null, internalSet: true, extraData: {'items': selectedItems}}, 'changed': true}); } break; } } } } else { // the selection is invalid, remove it from selection index = selection.indexOf(context['key']); if (index > -1) { // clone before modifying clone = selection.slice(0); clone.splice(index, 1); selectedItems = new Array(clone.length); for (i = 0; i < clone.length; i++) { selectedItems[i] = this.FindElementByKey(clone[i]); } this.SetOption("selection", clone, {'_context': {originalEvent: null, internalSet: true, extraData: {'items': $(selectedItems)}}, 'changed': true}); } } } // update if it is in expanded, ensure data is hierarchical if (this.m_contentHandler.IsHierarchical() && this._ignoreExpanded == undefined) { // checks if it is expandable && is collapsed if (this.GetState($(elem)) == this.STATE_COLLAPSED) { expanded = this.GetOption("expanded"); // checks if expand all if (this._isExpandAll()) { if (this._collapsedKeys == undefined) { // don't animate this.ExpandItem($(elem), null, false, null, false, false, false); } } else if (Array.isArray(expanded)) { // checks if specified expanded self = this; $.each(expanded, function(index, value) { // if it was explicitly collapsed if (value == context['key'] && (self._collapsedKeys == undefined || self._collapsedKeys.indexOf(value) == -1)) { // don't animate self.ExpandItem($(elem), null, false, null, false, false, false); } }); } } } // checks if the active element has changed, this could happen in TreeDataSource, where the element gets remove when collapsed if (this.m_active != null && context['key'] == this.m_active['key'] && this.m_active['elem'] != null && elem != this.m_active['elem'].get(0)) { this.m_active['elem'] = $(elem); } }, /** * Called by content handler once content of all items are rendered */ renderComplete: function() { var empty, current, elem; this.hideStatusText(); // remove any empty text div $(document.getElementById(this._createSubId('empty'))).remove(); // check if it's empty if (this.element[0].childElementCount == 0) { empty = this._buildEmptyText(); this.element.append(empty); // @HTMLUpdateOK // fire ready event this.Trigger("ready", null, {}); return; } // clear items cache this.m_items = null; // check if current is specified current = this.GetOption("currentItem"); if (current != null) { elem = this.FindElementByKey(current); if (elem == null) { // it's not valid anymore, reset current this.SetOption('currentItem', null); } else { // make sure item is focusable also if (this.m_active == null && !this.SkipFocus($(elem))) { this._activeAndFocus($(elem), null); } } } // if listview has focus but there's no active element, then set focusable item // this could happen after refresh from context menu if (this._getListContainer().hasClass("oj-focus-ancestor") && this.m_active == null) { this._initFocus(); } // update scroll position if it's not in sync this.syncScrollPosition(); // fire ready event this.Trigger("ready", null, {}); }, /** * Synchronize the scroll position * @protected */ syncScrollPosition: function() { var top, scroller; top = this.GetOption("scrollTop"); if (!isNaN(top)) { scroller = this._getScroller(); if (top != scroller.scrollTop) { scroller.scrollTop = top; // checks if further scrolling is needed if (scroller.scrollTop != top) { this._skipScrollUpdate = true; return; } } } this._skipScrollUpdate = false; }, /** * When an item is updated, if the item happens to be the current item, the active element needs to be updated. * @protected */ restoreCurrentItem: function() { var current = this.GetOption("currentItem"); if (current != null) { var elem = this.FindElementByKey(current); // make sure item is focusable also if (elem != null && !this.SkipFocus($(elem))) { this._activeAndFocus($(elem), null); } } }, /** * Called by content handler to reset the state of ListView * @private */ ClearCache: function() { // clear any element dependent cache this.m_items = null; this.m_groupItems = null; }, /********************* context menu methods *****************/ /** * @param {!Object} menu The JET Menu to open as a context menu. Always non-<code class="prettyprint">null</code>. * @param {!Event} event What triggered the menu launch. Always non-<code class="prettyprint">null</code>. * @param {string} eventType "mouse", "touch", or "keyboard". Never <code class="prettyprint">null</code>. * Invoked by widget */ notifyContextMenuGesture: function(menu, event, eventType) { var parent, openOptions, launcher; // first check if we are invoking on an editable or clickable element If so bail if (this.IsNodeEditableOrClickable($(event['target']))) { return false; } // set the item right click on active parent = $(event['target']).closest("."+this.getItemElementStyleClass()); if (parent.length > 0 && !this.SkipFocus($(parent[0]))) { this._activeAndFocus($(parent[0]), null); } launcher = this.element; if (this.m_active != null) { launcher = this.m_active['elem']; } openOptions = {"launcher": launcher, "initialFocus": "menu"}; if (eventType === "keyboard") { openOptions["position"] = {"my": "start top", "at": "start bottom", "of": this.m_active['elem']}; } this.ojContext._OpenContextMenu(event, eventType, openOptions); }, /** * Override helper for NavList to override checks for whether a node is editable or clickable. * @param {jQuery} node Node * @return {boolean} true or false * @protected */ IsElementEditableOrClickable: function(node) { var nodeName = node.prop("nodeName"); return (nodeName.match(/^INPUT|SELECT|OPTION|BUTTON|^A\b|TEXTAREA/) != null); }, /** * Return whether the node is editable or clickable. Go up the parent node as needed. * @param {jQuery} node Node * @return {boolean} true or false * @protected */ IsNodeEditableOrClickable: function(node) { var nodeName; while (null != node && node[0] != this.element[0] && (nodeName = node.prop("nodeName")) != "LI") { // If the node is a text node, move up the hierarchy to only operate on elements // (on at least the mobile platforms, the node may be a text node) if (node[0].nodeType == 3) // 3 is Node.TEXT_NODE { node = node.parent(); continue; } var tabIndex = node.attr('tabIndex'); // listview overrides the tab index, so we should check if the data-oj-tabindex is populated var origTabIndex = node.attr('data-oj-tabindex'); if (tabIndex != null && tabIndex >= 0 && !node.hasClass(this.getFocusedElementStyleClass())) { return true; } else if (this.IsElementEditableOrClickable(node)) { // ignore elements with tabIndex == -1 if (tabIndex != -1 || origTabIndex != -1) { return true; } } node = node.parent(); } return false; }, /********************* focusable/editable element related methods *****************/ /** * Make all tabbable elements within the specified cell un-tabbable * @param {Element} element * @private */ _disableAllTabbableElements: function(element) { var elem, selector, tabIndex; elem = $(element); // if it's a group item, inspect the direct div only so it will skip all children if (!elem.hasClass(this.getItemStyleClass())) { elem = $(elem.get(0).firstElementChild); } selector = "a, input, select, textarea, button, object, .oj-component-initnode"; elem.find(selector).each(function(index) { $(this).removeAttr("data-first").removeAttr("data-last"); tabIndex = parseInt($(this).attr("tabIndex"), 10); if (isNaN(tabIndex) || tabIndex >= 0) { $(this).attr("tabIndex", -1) .attr("data-tabmod", isNaN(tabIndex) ? -1 : tabIndex); } }); }, /** * Make all tabbable elements before and include current item un-tabbable * @param {Element} item * @private */ _disableAllTabbableElementsBeforeItem: function(item) { var items, index, i; items = this._getItemsCache(); index = items.index(item); // if -1 it will just bail for (i=0; i<=index; i++) { this._disableAllTabbableElements(items[i]); } }, /** * Make all tabbable elements after and include current item un-tabbable * @param {Element} item * @private */ _disableAllTabbableElementsAfterItem: function(item) { var items, index, i; items = this._getItemsCache(); index = items.index(item); if (index == -1) { return; } for (i=index; i<=items.length-1; i++) { this._disableAllTabbableElements(items[i]); } }, /** * Make all previously tabbable elements within the element tabbable again * @param {Element} elem * @private */ _enableAllTabbableElements: function(elem) { var elems, tabIndex; elems = $(elem).find("[data-tabmod]").each(function(index) { tabIndex = parseInt($(this).attr("data-tabmod"), 10); $(this).removeAttr("data-tabmod"); // restore tabIndex as needed if (tabIndex == -1) { $(this).removeAttr("tabIndex"); } else { $(this).attr("tabIndex", tabIndex); } }); // mark first and last tabbable element for fast retrieval later elems.first().attr("data-first", "true"); elems.last().attr("data-last", "true"); }, /** * Cleanup any attributes added by tabbing logic * @param {Element} elem the element to cleanup * @private */ _cleanupTabbableElementProperties: function(elem) { $(elem).find("[data-tabmod]") .removeAttr("tabIndex") .removeAttr("data-tabmod") .removeAttr("data-first") .removeAttr("data-last"); }, /** * Checks whether the element is focusable * @param {jQuery} item the item to check * @return {boolean} true if the item should not be focusable, false otherwise * @protected */ SkipFocus: function(item) { return item.hasClass("oj-skipfocus"); }, /*************************************** Event handlers *****************************/ /** * Determine whether the event is triggered by interaction with element inside ListView * Note that Firefox 48 does not support relatedTarget on blur event, see * _supportRelatedTargetOnBlur method * @param {Event} event the focus or blur event * @return {boolean} true if focus/blur is triggered by interaction with element within listview, false otherwise. * @private */ _isFocusBlurTriggeredByDescendent: function(event) { if (event.relatedTarget === undefined) return true; if (event.relatedTarget == null || !$.contains(this.ojContext.element.get(0), /** @type {Element} */ (event.relatedTarget))) return false; else return true; }, /** * Handler for focus event * @param {Event} event the focus event * @protected */ HandleFocus: function(event) { var item; this._getListContainer().addClass("oj-focus-ancestor"); // first time tab into listview, focus on first item if (this.m_active == null) { // checks whether there's pending click to active if (!this.m_preActive && !this._isFocusBlurTriggeredByDescendent(event)) { this._initFocus(event); } } else { // focus could be caused by pending click to active // do not do this on iOS or Android, otherwise VO/talkback will not work correctly if (!this.m_preActive && !this._isNonWindowTouch() && !this._isFocusBlurTriggeredByDescendent(event)) { this.HighlightActive(); } // remove tab index from root and restore tab index on focus item this.RemoveRootElementTabIndex(); this._setTabIndex(this.m_active['elem']); } }, /** * Initialize focus by finding the first focusable item and set focus on it * @private */ _initFocus: function(event) { var items, i, item; // ignore in touch if (this._isTouchSupport()) { return; } items = this._getItemsCache(); for (i=0; i<items.length; i++) { item = $(items[i]); // make sure item can receive focus if (!this.SkipFocus(item)) { this._activeAndFocus(item, event); break; } } }, /** * Handler for focus out event * @param {Event} event the focusout event * @protected */ HandleFocusOut: function(event) { this.HandleBlur(event); }, /** * Checks whether the browser supports relatedTarget field for blur event * @return {boolean} true if supported, false otherwise * @private */ _supportRelatedTargetOnBlur: function() { var agent = oj.AgentUtils.getAgentInfo(); if (agent['browser'] == oj.AgentUtils.BROWSER.FIREFOX && parseInt(agent['browserVersion'], 10) < 48) { return false; } return true; }, /** * Detects whether this is a double blur event fired by IE11 * @param {Event} event the blur event * @private */ _isExtraBlurEvent: function(event) { var agent = oj.AgentUtils.getAgentInfo(); if (event.relatedTarget == null && agent['browser'] == oj.AgentUtils.BROWSER.IE && event.target == this.ojContext.element.get(0)) { return true; } return false; }, /** * Handler for blur event * @param {Event} event the blur event * @protected */ HandleBlur: function(event) { // NOTE that prior to a fix in Firefox 48, relatedTarget is always null // just bail in case if it wasn't supported // NOTE also IE11 fires an extra blur event with null relatedTarget, should bail as well if (!this._supportRelatedTargetOnBlur() || this._isExtraBlurEvent(event)) { return; } // event.relatedTarget would be null if focus out of page // the other check is to make sure the blur is not caused by shifting focus within listview if (!this._isFocusBlurTriggeredByDescendent(event)) { this._getListContainer().removeClass("oj-focus-ancestor"); this.UnhighlightActive(); // remove tab index from focus item and restore tab index on list if (this.m_active != null) { this._resetTabIndex(this.m_active['elem']); } this.SetRootElementTabIndex(); } }, /** * Event handler for when user exits an item in list * @param {Event} event mouseout event * @private */ _handleMouseOut: function(event) { var item = this.FindItem(event.target); if (item != null) { this.m_hoverItem = null; this._unhighlightElem(item, "oj-hover"); } }, /** * Event handler for when user hovers over list * @param {Event} event mouseover event * @private */ _handleMouseOver: function(event) { // do this for real mouse enters, but not 300ms after a tap if (this._recentTouch()) { return; } var item = this.FindItem(event.target); if (item != null && !this.SkipFocus(item)) { // have to remember it so we can clear it when listview is detached from DOM this.m_hoverItem = item; this._highlightElem(item, "oj-hover"); } }, _recentTouch: function() { return Date.now() - this._lastTouch < 500; // must be at least 300 for the "300ms" delay }, /** * Event handler for when user press down a key * @param {Event} event keydown event * @protected */ HandleKeyDown: function(event) { var keyCode, current, processed; if (this.isExpandable()) { keyCode = event.keyCode; if (keyCode === this.LEFT_KEY || keyCode === this.RIGHT_KEY) { current = this.m_active['elem']; if (keyCode === this.LEFT_KEY) { if (this.GetState(current) == this.STATE_EXPANDED) { this.CollapseItem(current, event, true, this.m_active['key'], true, true); return; } } else { if (this.GetState(current) == this.STATE_COLLAPSED) { this.ExpandItem(current, event, true, this.m_active['key'], true, true, true); return; } } } } processed = this.HandleSelectionOrActiveKeyDown(event); // dnd if (this.m_dndContext != null) { processed = processed || this.m_dndContext.HandleKeyDown(event); } if (processed === true) { event.preventDefault(); } }, /** * @private */ _handleMouseUpOrPanMove: function(event) { // unhighlight item that got focus in mousedown if (this.m_preActiveItem) { this._unhighlightElem(this.m_preActiveItem, "oj-focus"); } // dnd if (this.m_dndContext != null) { this.m_dndContext._unsetDraggable($(event.target)); } }, /** * Event handler for when mouse down or touch start anywhere in the list * @param {Event} event mousedown or touchstart event * @protected */ HandleMouseDownOrTouchStart: function(event) { var item, target; // click on item target = $(event.target); // dnd if (this.m_dndContext != null) { this.m_dndContext._setDraggable(target); } // click on item, explicitly pass true on findItem // so that it will return non-null value if clickthrough disabled element or oj-component // is encountered item = this._findItem(target, true); // we'll still need to set the flag so that the focus do not shift if (item != null && this._isClickthroughDisabled(item)) { this.m_preActive = true; item = null; } if (item == null || item.length == 0 || this.SkipFocus(item) || target.hasClass("oj-listview-drag-handle")) { // one of the following happened: // 1) can't find item // 2) item cannot be focus // 3) target is an oj-component // 4) target or one of its ancestors has the oj-clickthrough-disabled marker class // 5) target is the drag handle return; } this.m_preActive = true; // make sure listview has focus if (!this._getListContainer().hasClass("oj-focus-ancestor")) { this._getListContainer().addClass("oj-focus-ancestor"); } // we'll need to remove focus in case the actual focus item is different this.m_preActiveItem = item; // apply focus this._highlightElem(item, "oj-focus"); // need this on touchend if (event.originalEvent.touches && event.originalEvent.touches.length > 0) { this.m_touchPos = {x: event.originalEvent.changedTouches[0].pageX, y: event.originalEvent.changedTouches[0].pageY}; } }, /** * Event handler for when touch end/cancel happened * @param {Event} event touchend or touchcancel event * @protected */ HandleTouchEndOrCancel: function(event) { var offset, action = "pointerUp", effect, elem, groupItem; // unhighlight item that got focus in touchstart if (this.m_preActiveItem != null) { this._unhighlightElem(this.m_preActiveItem, "oj-focus"); // start ripple effect if (this.m_touchPos != null) { offset = this.m_preActiveItem.offset(); // find where to start the ripple effect based on touch location effect = this.getAnimationEffect(action); effect['offsetX'] = ((this.m_touchPos.x) - offset['left']) + 'px'; effect['offsetY'] = ((this.m_touchPos.y) - offset['top']) + 'px'; groupItem = this.m_preActiveItem.children('.' + this.getGroupItemStyleClass()); if (groupItem.length > 0) { elem = /** @type {Element} */ (groupItem.get(0)); } else { elem = /** @type {Element} */ (this.m_preActiveItem.get(0)); } // we don't really care when animation ends oj.AnimationUtils.startAnimation(elem, action, effect); this.m_touchPos = null; } } // need this so that on mouse over handler would not apply the styles if the last touch was within the last n ms this._lastTouch = Date.now(); this._handleMouseOut(event); }, /** * Enters actionable mode * @private */ _enterActionableMode: function() { var current, first; current = this.m_active['elem']; // in case content has been updated under the cover this._disableAllTabbableElements(current); // re-enable all tabbable elements this._enableAllTabbableElements(current); // only go into actionable mode if there is something to focus first = current.find("[data-first]"); if (first.length > 0) { this._setActionableMode(true); } }, /** * Exits actionable mode * @private */ _exitActionableMode: function() { this._setActionableMode(false); // disable all tabbable elements in the item again this._disableAllTabbableElements(this.m_active['elem']); }, /** * Event handler for when mouse click anywhere in the list * @param {Event} event mouseclick event * @protected */ HandleMouseClick: function(event) { var collapseIconClass, expandIconClass, groupItemClass, target, item; //only perform events on left mouse, (right in rtl culture) if (event.button === 0) { collapseIconClass = this.getCollapseIconStyleClass(); expandIconClass = this.getExpandIconStyleClass(); groupItemClass = this.getGroupItemStyleClass(); target = $(event.target); if (target.hasClass(expandIconClass)) { this._collapse(event); event.preventDefault(); } else if (target.hasClass(collapseIconClass)) { this._expand(event); event.preventDefault(); } else { // click on item item = this._findItem(target); if (item == null || item.length == 0 || this.SkipFocus(item)) { // one of the following happened: // 1) can't find item // 2) item cannot be focus // 3) target is an oj-component // 4) target or one of its ancestors has the oj-clickthrough-disabled marker class return; } if (this._isActionableMode() && this.m_active != null && this.m_active['elem'].get(0) != item.get(0)) { // click on item other than current focus item should exit actionable mode this._exitActionableMode(); } // make sure listview has focus if (!this._getListContainer().hasClass("oj-focus-ancestor")) { this._getListContainer().addClass("oj-focus-ancestor"); } // check if selection is enabled if (this._isSelectionEnabled() && this.IsSelectable(item[0])) { if (this._isTouchSupport()) { this._handleTouchSelection(item, event); } else { this.HandleClickSelection(item, event); } } else { // if selection is disable, we'll still need to highlight the active item this.HandleClickActive(item, event); } // clicking on header will expand/collapse item if (this.isExpandable() && target.closest("."+groupItemClass)) { if (this.GetState(item) == this.STATE_COLLAPSED) { this._expand(event); } else if (this.GetState(item) == this.STATE_EXPANDED) { this._collapse(event); } } } } }, /*********************************** end Event handlers *****************************/ /*************************************** helper methods *****************************/ /** * Whether touch is supported * @return {boolean} true if touch is supported, false otherwise * @private */ _isTouchSupport: function() { return oj.DomUtils.isTouchSupported(); }, /** * Whether it is non-window touch device (iOS or Android) * @return {boolean} true if it is a non-window touch device * @private */ _isNonWindowTouch: function() { return this._isTouchSupport() && oj.AgentUtils.getAgentInfo()['os'] != oj.AgentUtils.OS.WINDOWS; }, /** * Returns either the ctrl key or the command key in Mac OS * @param {!Object} event * @private */ _ctrlEquivalent: function(event) { return oj.DomUtils.isMetaKeyPressed(event); }, /** * Helper method to create subid based on the root element's id * @param {string} subId the id to append to the root element id * @return {string} the subId to append to the root element id * @private */ _createSubId: function(subId) { var id = this.element.attr("id"); return [id, subId].join(":"); }, /** * Find the item element * @param {jQuery} elem * @return {jQuery|null} * @protected */ FindItem: function(elem) { return $(elem).closest("."+this.getItemElementStyleClass()); }, /** * Determine if click should be processed based on the element. * @param {jQuery} elem the element to check * @return {boolean} returns true if the element contains the special marker class or is a component, false otherwise. * @private */ _isClickthroughDisabled: function(elem) { return (elem.hasClass("oj-clickthrough-disabled") || elem.hasClass("oj-component-initnode") || elem.hasClass("oj-component")); }, /** * Find the item element from target, if target is an oj-component or contains the * oj-clickthrough-disabled class then returns null. * @param {jQuery} target the element to check * @param {boolean=} retElemOnClickthroughDisabled optional, set to true to force non-null value to return when * clickthrough-disabled or oj-component is encountered * @return {jQuery|null} the item element or null if click through is disabled for this element or one of its ancestors. * @private */ _findItem: function(target, retElemOnClickthroughDisabled) { var current = target; while (current.length > 0) { if (this._isClickthroughDisabled(current)) { if (retElemOnClickthroughDisabled) { return current; } return null; } if (current.hasClass(this.getItemElementStyleClass())) { return current; } current = current.parent(); } return null; }, /** * Compute the total top and bottom border width of the list container * @return {number} the sum of top and bottom border width of the list container * @private */ _getListContainerBorderWidth: function() { if (this.m_borderWidth == null) { this.m_borderWidth = parseInt(this._getListContainer().css("border-top-width"), 10) + parseInt(this._getListContainer().css("border-bottom-width"), 10); } return this.m_borderWidth; }, /** * Scroll as needed to make an element visible in the viewport * @param {Element} elem the element to make visible * @private */ _scrollToVisible: function(elem) { var top, height, container, containerScrollTop, containerHeight, headerTop, headerHeight, offset = 0, scrollTop; top = elem.offsetTop; height = elem.offsetHeight; container = this._getListContainer()[0]; containerScrollTop = container.scrollTop; containerHeight = container.offsetHeight; // if there's sticky header, make sure the elem is not behind it if (this.m_groupItemToPin != null) { headerTop = parseInt(this.m_groupItemToPin.style.top, 10); headerHeight = $(this.m_groupItemToPin).outerHeight(); if ((top <= headerTop && headerTop < top + height)) { offset = ((height + top) - headerTop) / 2; } else if ((top >= headerTop && top < headerTop + headerHeight)) { offset = ((headerTop + headerHeight) - top) / 2; } } // if it's within viewport do nothing if (top >= containerScrollTop && top+height <= containerScrollTop+containerHeight) { if (offset > 0) { container.scrollTop = containerScrollTop - offset; } return; } // how much need to scroll to see the entire element, and to make sure the element top is always visible scrollTop = Math.max(0, Math.min(top - offset, Math.abs((top + height) - containerHeight))); if (scrollTop > containerScrollTop) { scrollTop = scrollTop + this._getListContainerBorderWidth(); } container.scrollTop = scrollTop; }, /** * Get the key associated with an item element * @param {Element} elem the item element to retrieve the key * @return {Object|null} the key associated with the item element * @protected */ GetKey: function(elem) { return this.m_contentHandler.GetKey(elem); }, /** * Get the element associated with a key * @param {Object} key the key to retrieve the item element * @return {Element|null} the item element associated with the key * @protected */ FindElementByKey: function(key) { var id; if (this.m_keyElemMap != null) { id = this.m_keyElemMap[key]; if (id != null) { return document.getElementById(id); } } // ask the content handler return this.m_contentHandler.FindElementByKey(key); }, /************************************ end helper methods *****************************/ /*************************************** Navigation Common **************************/ /** * Determine whether the key code is an arrow key * @param {number} keyCode * @return {boolean} true if it's an arrow key, false otherwise * @protected */ IsArrowKey: function(keyCode) { return (keyCode == this.UP_KEY || keyCode == this.DOWN_KEY); }, /** * Retrieve the visible (flattened) items cache, create one if it is null. * @return {jQuery} a list of items * @private */ _getItemsCache: function() { var disclosureStyleClass, selector, isGroup; if (this.m_items == null) { disclosureStyleClass = this.getGroupCollapseStyleClass(); selector = "."+this.getItemElementStyleClass() + ":visible"; this.m_items = this.element.find(selector).filter(function(index) { isGroup = $(this).parent().hasClass(disclosureStyleClass); if (isGroup) { return !($(this).parent().parent().hasClass("oj-collapsed")); } return true; }); } return this.m_items; }, /** * Handles when navigate to the last item * @param {jQuery} item the item element */ _handleLastItemKeyboardFocus: function(item) { var next = item.get(0).nextElementSibling; if (next == null || !$(next).hasClass(this.getItemElementStyleClass())) { // it's the last element, check scroll bar to make sure it scrolls all the way to the bottom var scroller = this._getScroller(); if (scroller.scrollTop < scroller.scrollHeight) { scroller.scrollTop = scroller.scrollHeight; } } }, /** * Handles arrow keys navigation on item * @param {number} keyCode description * @param {boolean} isExtend * @param {Event} event the DOM event causing the arrow keys * @protected */ HandleArrowKeys: function(keyCode, isExtend, event) { var current, processed, items, currentIndex, next; // ensure that there's no outstanding fetch requests if (!this.m_contentHandler.IsReady()) { //act as if processed to prevent page scrolling before fetch done return true; } if (!isExtend || this.m_isNavigate) { current = this.m_active['elem']; } else { current = this.m_selectionFrontier; } // invoke different function for handling focusing on active item depending on whether selection is enabled processed = false; items = this._getItemsCache(); currentIndex = items.index(current); switch (keyCode) { case this.UP_KEY: currentIndex--; if (currentIndex >= 0) { next = $(items[currentIndex]); // make sure it's focusable, otherwise find the next focusable item while (this.SkipFocus(next)) { currentIndex--; if (currentIndex < 0) { return false; } next = $(items[currentIndex]); } if (isExtend) { this._extendSelection(next, event); this.m_isNavigate = false; } else { this._activeAndFocus(next, event); this.m_isNavigate = true; } } // according to James we should still consume the event even if list view did not perform any action processed = true; break; case this.DOWN_KEY: currentIndex++; if (currentIndex < items.length) { next = $(items[currentIndex]); // make sure it's focusable, otherwise find the next focusable item while (this.SkipFocus(next)) { currentIndex++; if (currentIndex == items.length) { return false; } next = $(items[currentIndex]); } if (isExtend) { this._extendSelection(next, event); this.m_isNavigate = false; } else { this._activeAndFocus(next, event); this.m_isNavigate = true; this._handleLastItemKeyboardFocus(next); } } // according to James we should still consume the event even if list view did not perform any action processed = true; break; } return processed; }, /** * Determine if the data grid is in actionable mode. * @return {boolean} true if the data grid is in actionable mode, false otherwise. * @private */ _isActionableMode: function() { return (this.m_keyMode == "actionable"); }, /** * Sets whether the data grid is in actionable mode * @param {boolean} flag true to set grid to actionable mode, false otherwise * @private */ _setActionableMode: function(flag) { this.m_keyMode = flag ? "actionable" : "navigation"; if (!flag) { // focus should be shift back to active descendant container this.element[0].focus(); } }, /************************************ end Navigation Common **************************/ /************************************ Active item ******************************/ /** * Returns the focus mode * @return {number} FOCUS_MODE_ITEM or FOCUS_MODE_LIST * @protected */ GetFocusMode: function() { // by default browser focus is on item not on listview root element return this.FOCUS_MODE_ITEM; }, /** * Retrieve the focus element * @param {jQuery} item the list item * @return {jQuery} the focus element * @private */ getFocusItem: function(item) { if (!item.hasClass(this.getFocusedElementStyleClass())) { return $(item.find('.'+this.getFocusedElementStyleClass()).first()); } else { return item; } }, /** * Sets the tab index attribute of the root element * To be change by NavList * @protected */ SetRootElementTabIndex: function() { this.element.attr("tabIndex", 0); }, /** * Removes the tab index attribute of the root element * To be change by NavList * @protected */ RemoveRootElementTabIndex: function() { this.element.removeAttr("tabIndex"); }, /** * Sets the tab index on focus item * @param {jQuery} item the focus item * @private */ _setTabIndex: function(item) { // note that page author should not set any tabindex on the item this.getFocusItem(item).attr("tabIndex", 0); }, /** * Resets the tab index set on focus item * @param {jQuery} item the focus item * @private */ _resetTabIndex: function(item) { var removeAttr, isGroupItem; removeAttr = true; if (item.attr("role") === "presentation") { removeAttr = false; } item = this.getFocusItem(item); if (removeAttr) { item.removeAttr("tabIndex"); } else { item.attr("tabIndex", -1); } }, /** * Focus an item * @param {jQuery|null} previousItem the item previously has focus * @param {jQuery} item the item to focus * @private */ _focusItem: function(previousItem, item) { if (this.GetFocusMode() === this.FOCUS_MODE_ITEM) { if (previousItem != null) { this._resetTabIndex(previousItem); } this._setTabIndex(item); // make sure ul is not tabbable this.RemoveRootElementTabIndex(); } else { // update activedescendant this.UpdateActiveDescendant(item); } }, /** * Determine the only focusable element inside an item, if the item does not have any or have * more than one focusable element, then just return the item. * @param {jQuery} item the list item * @return {jQuery} see above for what's get returned * @private */ getSingleFocusableElement: function(item) { var selector, childElements; selector = "a, input, select, textarea, button"; childElements = item.children(selector); if(childElements.length === 1 && // check for only one focusbale child childElements.first().find(selector).length === 0) { //check to ensure no nested focusable elements. return childElements.first(); } return item; }, /** * Sets the active item * @param {jQuery} item the item to set as active * @param {Event} event the event that triggers set active * @private */ _setActive: function(item, event) { var elem, key, ui, cancelled, active; // set key info if (item != null) { elem = item[0]; key = this.GetKey(elem); if ((this.m_active == null) || key != this.m_active['key']) { // fire beforecurrentItem ui = {'key': key, 'item': item}; if (this.m_active != null) { ui['previousKey'] = this.m_active['key']; ui['previousItem'] = this.m_active['elem']; // for touch, remove draggable when active item changed if (this.m_dndContext != null && this._isTouchSupport()) { this.m_dndContext._unsetDraggable(ui['previousItem']); } } cancelled = !this.Trigger("beforeCurrentItem", event, ui); if (cancelled) { return; } active = {'key': key, 'elem': item}; this.m_active = active; // for touch, set draggable when item becomes active if (this.m_dndContext != null && this._isTouchSupport()) { this.m_dndContext._setDraggable(item); } // update activedescendant this._focusItem(ui['previousItem'], item); // update current option this.SetOption("currentItem", key, {'_context': {originalEvent: event, internalSet: true, extraData: {'item': item}}, 'changed': true}); } else if (key == this.m_active['key']) { active = {'key': key, 'elem': item}; this.m_active = active; // update activedescendant this._focusItem(null, item); } } else { // item is null, just clears the current values this.m_active = null; } }, /** * Highlight active element * @param {boolean=} force whether to force active element to focus * @protected */ HighlightActive: function(force) { var item, target; // don't highlight and focus item if ancestor does not have focus if (this.m_active != null && this._getListContainer().hasClass("oj-focus-ancestor")) { force = force || false; item = this.m_active['elem']; this._highlightElem(item, "oj-focus"); if (this.GetFocusMode() === this.FOCUS_MODE_ITEM) { item = this.getFocusItem(item); target = document.activeElement; // Focus active element to focus only if specified, or target is not child of active element if (force || !item.get(0).contains(target)) { item.get(0).focus(); } // else targetting child of active element so let it focus } } }, /** * Unhighlight the active index, and turn the active index to selected instead if selectActive is true. * @protected */ UnhighlightActive: function() { if (this.m_active != null) { this._unhighlightElem(this.m_active['elem'], "oj-focus"); } }, HandleClickActive: function(item, event) { this._activeAndFocus(item, event); }, _activeAndFocus: function(item, event) { // make sure that it is visible this._scrollToVisible(item[0]); // unhighlight any previous active item this.UnhighlightActive(); // update active and frontier this._setActive(item, event); // highlight active this.HighlightActive(); }, /************************************ end Active item ******************************/ /************************************* Selection ***********************************************/ /** * Check if selection enabled by options on the list * @return {boolean} true if selection enabled * @private */ _isSelectionEnabled: function() { return (this.GetOption("selectionMode") != "none"); }, /** * Check whether multiple selection is allowed by options on the list * @return {boolean} true if multiple selection enabled * @private */ _isMultipleSelection: function() { return (this.GetOption("selectionMode") == "multiple"); }, /** * Check whether the item is selectable * @param {Element} item the item element * @return {boolean} true if item is selectable * @protected */ IsSelectable: function(item) { item = this.getFocusItem($(item)).get(0); return item.hasAttribute("aria-selected"); }, /** * Filter the array of selection. Remove any items that are not selectable, or if there are more than one items * when selectionMode is single. * @param {Array} selection array of selected items * @return {Array} filtered array of items * @private */ _filterSelection: function(selection) { var filtered, i, elem; filtered = []; for (i=0; i<selection.length; i++) { elem = this.FindElementByKey(selection[i]); if (elem != null) { if (this.IsSelectable(elem)) { filtered.push(selection[i]); // if single selection mode, we can stop if (!this._isMultipleSelection()) { break; } } } } return filtered; }, /** * Unhighlights the selection. Does not change selection, focus, anchor, or frontier * @private */ _unhighlightSelection: function() { var self, elem; if (this.m_keyElemMap == null) { return; } self = this; $.each(this.GetOption("selection"), function(index, value) { elem = self.FindElementByKey(value); if (elem != null) { self._unhighlightElem(elem, "oj-selected"); } }); }, _highlightElem: function(elem, style) { this.HighlightUnhighlightElem(elem, style, true); }, _unhighlightElem: function(elem, style) { this.HighlightUnhighlightElem(elem, style, false); }, /** * Highlight or unhighlight an element * @param {jQuery|Element} elem the element the highlight or unhighlight * @param {string} style the style to add or remove * @param {boolean} highlight true if it's to highlight, false if it's to unhighlight * @protected */ HighlightUnhighlightElem: function(elem, style, highlight) { var group; elem = $(elem); if (style == "oj-selected") { this.getFocusItem(elem).attr("aria-selected", highlight ? "true" : "false"); } // if item is a group, the highlight should be apply to the group item element group = elem.children("."+this.getGroupItemStyleClass()); if (group.length > 0) { elem = $(group[0]); } if (style === "oj-focus") { if (highlight) { // don't apply focus ring on item if we are in actionable mode if (this.m_keyMode != "actionable") { this._focusInHandler(elem); } } else { this._focusOutHandler(elem); } } else { if (highlight) { elem.addClass(style); } else { elem.removeClass(style); } } }, /** * Handles click to select multiple cells/rows * @param {jQuery} item the item clicked on * @param {Event} event the click event * @protected */ HandleClickSelection: function(item, event) { var ctrlKey, shiftKey; // make sure that it is visible this._scrollToVisible(item[0]); ctrlKey = this._ctrlEquivalent(event); shiftKey = event.shiftKey; if (this._isMultipleSelection()) { if (!ctrlKey && !shiftKey) { this.SelectAndFocus(item, event); } else if (!ctrlKey && shiftKey) { // active item doesn't change in this case this._extendSelection(item, event); } else { this._augmentSelectionAndFocus(item, event); } } else { this.SelectAndFocus(item, event); } }, /** * Handles tap to select multiple cells/rows * @param {jQuery} item the item clicked on * @param {Event} event the click event * @private */ _handleTouchSelection: function(item, event) { if (this._isMultipleSelection()) { // treat this as like ctrl+click this._augmentSelectionAndFocus(item, event); } else { this.SelectAndFocus(item, event); } }, /** * Clear the current selection. * @param {boolean} updateOption true if the underlying selection option should be updated, false otherwise. * @private */ _clearSelection: function(updateOption) { // unhighlight previous selection this._unhighlightSelection(); if (updateOption) { this.SetOption("selection", [], {'_context': {originalEvent: null, internalSet: true, extraData: {'items': $()}}, 'changed': true}); } // clear selection frontier also this.m_selectionFrontier = null; }, /** * Selects the focus on the specified element * Select and focus is an asynchronus call * @param {jQuery} item the item clicked on * @param {Event} event the click event * @protected */ SelectAndFocus: function(item, event) { // clear selection this._clearSelection(false); // add the elem to selection this._augmentSelectionAndFocus(item, event, []); }, /** * Shift+click to extend the selection * @param {jQuery} item the item to extend selection to * @param {Event} event the key event * @private */ _extendSelection: function(item, event) { var current; if (this.m_active == null) { return; } // checks if selection has changed current = this.m_selectionFrontier; if (current == item) { return; } // remove focus style on the item click on this._unhighlightElem(item, "oj-focus"); this._extendSelectionRange(this.m_active['elem'], item, event); }, /** * Extend the selection * @param {jQuery} from the item to extend selection from * @param {jQuery} to the item to extend selection to * @param {Event} event the event that triggers extend * @private */ _extendSelectionRange: function(from, to, event) { // clear selection as we'll be just re-highlight the entire range this._clearSelection(false); // update frontier this.m_selectionFrontier = to; // highlights the items between active item and new item this._highlightRange(from, to, event); this.HighlightActive(); }, /** * Highlight the specified range * @param {jQuery} start the start of the range * @param {jQuery} end the end of the range * @param {Event} event the event that triggers the highlight * @private */ _highlightRange: function(start, end, event) { var selection, selectedItems, items, startIndex, endIndex, from, to, i, item, key; selection = []; selectedItems = []; items = this._getItemsCache(); startIndex = items.index(start); endIndex = items.index(end); if (startIndex > endIndex) { from = endIndex; to = startIndex; } else { from = startIndex; to = endIndex; } // exclude start and include end for (i=from; i<=to; i++) { item = items[i]; if (this.IsSelectable(item)) { key = this.m_contentHandler.GetKey(item); this._applySelection(item, key); selection.push(key); selectedItems.push(item); } } // trigger the optionChange event this.SetOption("selection", selection, {'_context': {originalEvent: event, internalSet: true, extraData: {'items': $(selectedItems)}}, 'changed': true}); }, /** * Apply selection to the element * @param {jQuery|Element} element the item to apply selection * @param {Object} key the key of the item * @private */ _applySelection: function(element, key) { // update map that keeps track of key->element if (this.m_keyElemMap == null) { this.m_keyElemMap = {}; } this.m_keyElemMap[key] = $(element).attr("id"); // highlight selection this._highlightElem(element, 'oj-selected'); }, /** * Ctrl+click to add item to the current selection * @param {jQuery} item the item to augment selection to * @param {Event} event the event that triggers the selection * @param {Array=} selection the optional selection to augment, if not specified, use current selection * @private */ _augmentSelectionAndFocus: function(item, event, selection) { var active, key, index, selectedItems, i; active = item; key = this.GetKey(item[0]); if (selection == undefined) { selection = this.GetOption("selection").slice(0); } this.UnhighlightActive(); // update active cell and frontier this._setActive(active, event); // highlight index this.HighlightActive(); // checks if setActive was successful if (this.m_active == null || this.m_active['elem'].get(0) != active.get(0)) { // update selection if it was cleared if (selection != null && selection.length == 0) { this.SetOption("selection", selection, {'_context': {originalEvent: event, internalSet: true, extraData: {'items': $([])}}, 'changed': true}); } return; } index = selection.indexOf(key); if (index > -1) { // it was selected, deselect it this._unhighlightElem(item, "oj-selected"); selection.splice(index, 1); } else { this.m_selectionFrontier = item; this._applySelection(item, key); selection.push(key); } selectedItems = new Array(selection.length); for (i = 0; i < selection.length; i++) { selectedItems[i] = this.FindElementByKey(selection[i]); } // trigger option change this.SetOption("selection", selection, {'_context': {originalEvent: event, internalSet: true, extraData: {'items': $(selectedItems)}}, 'changed': true}); }, /** * Toggle selection of an item. If an item was selected, it deselects it. If an item was not selected, it selects it. * @param {Event} event the event that triggers the selection * @param {boolean} keepCurrentSelection true if selecting an item would not deselect other selected items, false otherwise * @param {boolean} skipIfNotSelected true if an selected item should not be deselected, false otherwise * @protected */ ToggleSelection: function(event, keepCurrentSelection, skipIfNotSelected) { // if it's currently selected, deselect it var selection, selectedItems, item, key, index, i; selection = this.GetOption("selection").slice(0); item = this.m_active['elem']; key = this.m_active['key']; index = selection.indexOf(key); if (index > -1) { if (skipIfNotSelected) { return; } // it was selected, deselect it this._unhighlightElem(item, "oj-selected"); selection.splice(index, 1); if (selection.length == 0) { this.m_selectionFrontier = null; } } else { if (this.IsSelectable(item[0])) { // deselect any selected items if (!keepCurrentSelection) { this._clearSelection(false); selection.length = 0; } this.m_selectionFrontier = item; // select current item this._applySelection(item, key); selection.push(key); } } selectedItems = new Array(selection.length); for (i = 0; i < selection.length; i++) { selectedItems[i] = this.FindElementByKey(selection[i]); } // trigger option change this.SetOption("selection", selection, {'_context': {originalEvent: event, internalSet: true, extraData: {'items': $(selectedItems)}}, 'changed': true}); }, /** * Handles key event for selection or active * @param {Event} event * @return {boolean} true if the event is processed * @protected */ HandleSelectionOrActiveKeyDown: function(event) { var keyCode, current, ctrlKey, shiftKey, processed = false, first, last, ui; // this could happen if nothing in the list is focusable if (this.m_active == null) { return false; } keyCode = event.keyCode; current = this.m_active['elem']; if (this._isActionableMode()) { // Esc key goes to navigation mode if (keyCode == this.ESC_KEY) { this._exitActionableMode(); // force focus back on the active cell this.HighlightActive(true); // make sure active item has tabindex set this._setTabIndex(current); processed = true; } else if (keyCode === this.TAB_KEY) { // check if it's the last element in the item first = current.find("[data-first]"); last = current.find("[data-last]"); if (event.shiftKey) { if (first.length > 0 && last.length > 0 && first != last && event.target == first[0]) { // recycle to last focusable element in the cell last[0].focus(); processed = true; } } else { if (first.length > 0 && last.length > 0 && first != last && event.target == last[0]) { // recycle to first focusable element in the cell first[0].focus(); processed = true; } } // otherwise don't process and let browser handles tab } } else { // F2 key goes to actionable mode if (keyCode == this.F2_KEY) { this._enterActionableMode(); // focus on first focusable item in the cell first = current.find("[data-first]"); if (first.length > 0) { first[0].focus(); current.removeClass("oj-focus-highlight"); } } else if (keyCode == this.SPACE_KEY && this._isSelectionEnabled()) { ctrlKey = this._ctrlEquivalent(event); shiftKey = event.shiftKey; if (shiftKey && !ctrlKey && this.m_selectionFrontier != null && this._isMultipleSelection()) { // selects contiguous items from last selected item to current item this._extendSelectionRange(this.m_selectionFrontier, this.m_active['elem'], event); } else { // toggle selection, deselect previous selected items this.ToggleSelection(event, ctrlKey && !shiftKey && this._isMultipleSelection(), false); } processed = true; } else if (keyCode == this.ENTER_KEY && this._isSelectionEnabled()) { // selects it if it's not selected, do nothing if it's already selected this.ToggleSelection(event, false, true); } else if (this.IsArrowKey(keyCode)) { ctrlKey = this._ctrlEquivalent(event); shiftKey = event.shiftKey; if (!ctrlKey) { processed = this.HandleArrowKeys(keyCode, (shiftKey && this._isSelectionEnabled() && this._isMultipleSelection()), event); } } else if (keyCode === this.TAB_KEY) { // content could have changed, disable all elements in items before or after the active item if (event.shiftKey) { this._disableAllTabbableElementsBeforeItem(current); } else { this._disableAllTabbableElementsAfterItem(current); } } } return processed; }, /********************************** End Selection **********************************************/ /********************************** Disclosure **********************************************/ /** * Whether the group item is currently in the middle of expanding/collapsing * @param {Object} key the key of the group item * @return {boolean} true if it's expanding/collapsing, false otherwise * @private */ _isDisclosing: function(key) { if (key && this.m_disclosing) { return (this.m_disclosing.indexOf(key) > -1); } return false; }, /** * Marks a group item as currently in the middle of expanding/collapsing * @param {Object} key the key of the group item * @param {boolean} flag true or false * @private */ _setDisclosing: function(key, flag) { var index; if (key == null) { return; } if (this.m_disclosing == null) { this.m_disclosing = []; } if (flag) { this.m_disclosing.push(key); } else { // there should be at most one entry, but just in case remove all occurrences index = this.m_disclosing.indexOf(key); while (index > -1) { this.m_disclosing.splice(index, 1); index = this.m_disclosing.indexOf(key); } } }, /** * Gets the animation effect for the specific action * @param {string} action the action to retrieve the effect * @return {Object} the animation effect for the action */ getAnimationEffect: function(action) { var defaultOptions; if (this.defaultAnimations == null) { defaultOptions = oj.ThemeUtils.parseJSONFromFontFamily(this.getOptionDefaultsStyleClass()); this.defaultAnimations = defaultOptions['animation']; } return this.defaultAnimations[action]; }, /** * Whether group items can be expand/collapse. * @return {boolean} true if group items can be expand/collapse, false otherwise. */ isExpandable: function() { return this.GetOption("drillMode") != "none"; }, /** * Whether ListView should expand all expandable items. * @return {boolean} true if expand all, false otherwise * @private */ _isExpandAll: function() { var expanded = this.GetOption("expanded"); if (expanded === 'auto') { // if drillMode is none and no expanded state is specified, expand all if (!this.isExpandable()) { return true; } } else if (expanded === 'all') { return true; } return false; }, /** * Expand an item with specified key. * Invoked by widget * @param {Object} key the key of the group item to expand * @param {boolean} beforeVetoable true if beforeExpand event can be veto, false otherwise * @param {boolean} fireBefore true if this should trigger a beforeExpand event * @param {boolean} fireAfter true if this should trigger an expand event * @param {boolean} animate true if animate the expand operation, false otherwise */ expandKey: function(key, beforeVetoable, fireBefore, fireAfter, animate) { var item = this.FindElementByKey(key); if (item != null) { this.ExpandItem($(item), null, animate, key, beforeVetoable, fireAfter, fireBefore); } }, /** * Handle expand operation * @param {Event} event the event that triggers the expand * @private */ _expand: function(event) { var item = this.FindItem(event.target); if (item != null && item.length > 0) { this.ExpandItem(item, event, true, null, true, true, true); } }, /** * Expand an item * @param {jQuery} item the item to expand * @param {Event} event the event that triggers expand. Note that event could be null in the case where this is programmatically done by the widget * @param {boolean} animate true if animate the expand operation, false otherwise * @param {Object|null} key the key of the item, if not specified, the logic will figure it out from the item * @param {boolean} beforeVetoable true if beforeExpand event can be veto, false otherwise * @param {boolean} fireEvent true if fire expand event, false otherwise * @param {boolean} fireBeforeEvent true if fire beforeexpand event, false otherwise * @protected */ ExpandItem: function(item, event, animate, key, beforeVetoable, fireEvent, fireBeforeEvent) { var ui, cancelled, index; // checks if it's already collapsed or not collapsible at all if (this.GetState(item) != this.STATE_COLLAPSED) { return; } // if key wasn't specified, find it if (key == null) { key = this.GetKey(item[0]); } // bail if it's in the middle of expanding/collapsing if (animate && this._isDisclosing(key)) { return; } ui = {"item": item, "key": key}; if (fireBeforeEvent) { cancelled = !this.Trigger("beforeExpand", event, ui); if (cancelled && beforeVetoable) { return; } } this.signalTaskStart(); // signal method task start if (animate) { this._setDisclosing(key, true); } this.m_contentHandler.Expand(item, function(groupItem){this._expandSuccess(groupItem, animate, event, ui, fireEvent)}.bind(this)); // clear items cache this.m_items = null; // prevent item click handler to trigger if (event != null) { event.stopPropagation(); } // update var that keeps track of collapsed items if (this._collapsedKeys != null) { index = this._collapsedKeys.indexOf(key); if (index != -1) { this._collapsedKeys.splice(index, 1); } } this.signalTaskEnd(); // signal method task end }, /** * @param {Element} groupItem * @param {boolean} animate * @param {Event} event * @param {Object} ui * @param {boolean} fireEvent * @private */ _expandSuccess: function(groupItem, animate, event, ui, fireEvent) { var item, collapseClass, expandClass, groupItemStyleClass, key, expanded, clone, animationPromise, self = this; this.signalTaskStart(); // signal method task start // save the key for use when expand complete groupItem.key = ui['key']; animationPromise = this.AnimateExpand($(groupItem), animate, event); item = groupItem.parentNode; item = $(item); // update aria expanded this.SetState(item, this.STATE_EXPANDED); // update icon collapseClass = this.getCollapseIconStyleClass(); expandClass = this.getExpandIconStyleClass(); groupItemStyleClass = this.getGroupItemStyleClass(); item.children("."+groupItemStyleClass).find("."+collapseClass).removeClass(collapseClass).addClass(expandClass); // fire expand event after expand animation completes if (fireEvent) { animationPromise.then(function() { self.Trigger("expand", event, ui); }); } animationPromise.then(function() { self.signalTaskEnd(); // signal method task end }); }, /** * Adjust the max height of ancestors of a group items. * @param {jQuery} groupItem the group item where we want to adjust its ancestors max height * @param {number} delta the height to increase * @private */ _adjustAncestorsMaxHeight: function(groupItem, delta) { var maxHeight; groupItem.parentsUntil("ul.oj-component-initnode", "ul."+this.getGroupStyleClass()).each(function(index) { maxHeight = parseInt($(this).css("maxHeight"), 10); if (maxHeight > 0) { $(this).css("maxHeight", (maxHeight + delta) +"px"); } }); }, /** * Animate expand operation * @param {jQuery} groupItem the group item that is expand (todo: not consistent with animateCollapse) * @param {boolean} animate true if animate expand, false otherwise * @param {Event} event the event that triggers expand. Note that event could be null in the case where this is programmatically done by the widget * @return {Promise} A Promise that resolves when expand animation completes * @protected */ AnimateExpand: function(groupItem, animate, event) { var totalHeight = 0, animationPromise, animationResolve, self = this, effect, elem, action = "expand", promise; animationPromise = new Promise(function(resolve, reject) { animationResolve = resolve; }); if (animate) { this.signalTaskStart(); // signal task start groupItem.children().each(function() { totalHeight = totalHeight + $(this).outerHeight(true); }); // for touch we'll need to re-adjust the max height of parent nodes since max height doesn't get remove if (this._isTouchSupport()) { this._adjustAncestorsMaxHeight(groupItem, totalHeight); } groupItem.css("maxHeight", totalHeight+"px"); effect = this.getAnimationEffect(action); this.signalTaskStart(); // signal expand animation started. Ends in _handleExpandTransitionEnd() // now show it elem = /** @type {Element} */ (groupItem.get(0)); promise = oj.AnimationUtils.startAnimation(elem, action, effect); promise.then(function(val) { self._handleExpandTransitionEnd(groupItem, animationResolve); }); this.signalTaskEnd(); // signal task end } else { // for touch it will need max height set initially in order for it to animate correctly if (this._isTouchSupport()) { groupItem.children().each(function() { totalHeight = totalHeight + $(this).outerHeight(true); }); groupItem.css("maxHeight", totalHeight+"px"); this._adjustAncestorsMaxHeight(groupItem, totalHeight); } else { groupItem.css("maxHeight", ""); } this.AnimateExpandComplete(groupItem); animationResolve(null); // resolve animationPromise } return animationPromise; }, _handleExpandTransitionEnd: function(groupItem, animationResolve) { var item; // on ios removing max-height will cause double animation if (!this._isTouchSupport()) { groupItem.css("maxHeight", ""); } this.AnimateExpandComplete(groupItem); animationResolve(null); // resolve animationPromise this.signalTaskEnd(); // signal expand animation ended. Started in this.AnimateExpand() }, /** * Invoked when expand animation is completed. Class who overrides AnimateExpand * must call this method upon finish animation. * @param {jQuery} groupItem the item to collapse * @protected */ AnimateExpandComplete: function(groupItem) { groupItem.removeClass(this.getGroupCollapseStyleClass()).addClass(this.getGroupExpandStyleClass()); this._setDisclosing(groupItem[0].key, false); }, /** * Collapse an item with specified key. * Invoked by widget * @param {Object} key the key of the group item to collapse * @param {boolean} fireBefore true if this should trigger a beforeCollapse event * @param {boolean} fireAfter true if this should trigger a collapse event * @param {boolean} animate true if animate the collapse operation, false otherwise */ collapseKey: function(key, fireBefore, fireAfter, animate) { var item = this.FindElementByKey(key); if (item != null) { this.CollapseItem($(item), null, animate, key, fireBefore, fireAfter); } }, _collapse: function(event) { var item = this.FindItem(event.target); if (item != null && item.length > 0) { this.CollapseItem(item, event, true, null, true, true); } }, /** * Collapse an item * @param {jQuery} item the item to expand * @param {Event} event the event that triggers collapse. Note that event could be null in the case where this is programmatically done by the widget * @param {boolean} animate true if animate the collapse operation, false otherwise * @param {Object|null} key the key of the item, if not specified, the logic will figure it out from the item * @param {boolean} beforeVetoable true if beforeCollapse event can be veto, false otherwise * @param {boolean} fireEvent true if fire collapse event, false otherwise * @protected */ CollapseItem: function(item, event, animate, key, beforeVetoable, fireEvent) { var ui, cancelled, collapseClass, expandClass, expanded, animationPromise, self = this; // checks if it's already collapsed or not collapsible at all if (this.GetState(item) != this.STATE_EXPANDED) { return; } // fire beforeCollapse event if (key == null) { key = this.GetKey(item[0]); } // bail if it is in the middle of expanding/collapsing if (animate && this._isDisclosing(key)) { return; } ui = {"item": item, "key": key}; cancelled = !this.Trigger("beforeCollapse", event, ui); if (cancelled && beforeVetoable) { return; } this.signalTaskStart(); // signal method task start if (animate) { this._setDisclosing(key, true); } // animate collapse animationPromise = this.AnimateCollapse(item, key, animate, event); // update aria expanded this.SetState(item, this.STATE_COLLAPSED); // update icon collapseClass = this.getCollapseIconStyleClass(); expandClass = this.getExpandIconStyleClass(); item.find("."+expandClass).first().removeClass(expandClass).addClass(collapseClass); // clear items cache this.m_items = null; // prevent item click handler to trigger if (event != null) { event.stopPropagation(); } // fire collapse event after collapse animation completes if (fireEvent) { animationPromise.then(function() { self.Trigger("collapse", event, ui); }) } // keep track of collapsed item if (this._collapsedKeys == undefined) { this._collapsedKeys = []; } if (this._collapsedKeys.indexOf(key) == -1) { this._collapsedKeys.push(key); } animationPromise.then(function() { self.signalTaskEnd(); // signal method task end }); }, /** * Animate collapse operation * To be change by NavList * @param {jQuery} item the item to collapse * @param {Object} key the key of the group item * @param {boolean} animate true if animate the collapse operation, false otherwise * @param {Event} event the event that triggers collapse. Note that event could be null in the case where this is programmatically done by the widget * @return {Promise} A Promise that resolves when collapse animation completes * @protected */ AnimateCollapse: function(item, key, animate, event) { var totalHeight = 0, groupItem, animationPromise, animationResolve, self = this, effect, elem, action = "collapse", promise; animationPromise = new Promise(function(resolve, reject) { animationResolve = resolve; }); groupItem = item.children("ul").first(); // save the key for collapse animation complete groupItem[0].key = key; if (animate) { this.signalTaskStart(); // signal task start groupItem.children().each(function() { totalHeight = totalHeight + $(this).outerHeight(); }); groupItem.css("maxHeight", totalHeight+"px"); effect = this.getAnimationEffect(action); // max-height = 0 needs to stick around, especially needed for static content effect['persist'] = 'all'; this.signalTaskStart(); // signal collapse animation started. Ends in _handleCollapseTransitionEnd() // now hide it elem = /** @type {Element} */ (groupItem.get(0)); promise = oj.AnimationUtils.startAnimation(elem, action, effect); promise.then(function(val) { self._handleCollapseTransitionEnd(groupItem, animationResolve); }); this.signalTaskEnd(); // signal task end } else { groupItem.css("maxHeight", "0px"); this.AnimateCollapseComplete(groupItem); animationResolve(null); // resolve animationPromise } return animationPromise }, _handleCollapseTransitionEnd: function(groupItem, animationResolve) { var item; this.AnimateCollapseComplete(groupItem); animationResolve(null); // resolve animationPromise this.signalTaskEnd(); // signal collapse animation ended. Started in AnimateCollapse() }, /** * Invoked when collapse animation is completed. Class who overrides AnimateCollapse * must call this method upon finish animation. * @param {jQuery} groupItem the item to collapse * @private */ AnimateCollapseComplete: function(groupItem) { groupItem.removeClass(this.getGroupExpandStyleClass()).addClass(this.getGroupCollapseStyleClass()); // ask the content handler to do the collapse operation // content handler might have been destroyed if animation ended after destroy is called if (this.m_contentHandler != null) { this.m_contentHandler.Collapse(groupItem); } this._setDisclosing(groupItem[0].key, false); }, /** * Collapse all currently expanded items * @private */ _collapseAll: function() { var self, items; this.signalTaskStart(); // signal method task start self = this; items = this._getItemsCache(); items.each(function() { // collapseItem checks whether item is expanded self.CollapseItem($(this), null, false, null, false, false); }); this.signalTaskEnd(); // signal method task end }, /** * Gets the keys of currently expanded items. * Invoke by widget * @return {Array} array of keys of currently expanded items. */ getExpanded: function() { var expanded, self, items, item; expanded = []; self = this; items = this._getItemsCache(); items.each(function() { item = $(this); if (self.GetState(item) == self.STATE_EXPANDED) { expanded.push(self.GetKey(item[0])); } }); return expanded; }, /********************************* End Disclosure *******************************************/ /** * Returns widget constructor. Used by ContentHandler */ getWidgetConstructor: function () { return oj.Components.getWidgetConstructor(this.element); }, /*********************************** Style Classes *********************************************/ /** * To be change by NavList * @return {string} the container style class * @protected */ GetContainerStyleClass: function() { // do not set overflow to scroll for windows touch enabled devices if (this._isNonWindowTouch()) { return "oj-listview oj-listview-container-touch"; } else { return "oj-listview oj-listview-container"; } }, /** * To be change by NavList * @return {string} the main element style class * @protected */ GetStyleClass: function() { return "oj-listview-element"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the list item style class */ getItemStyleClass: function() { return "oj-listview-item"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the focused element style class */ getFocusedElementStyleClass: function() { return "oj-listview-focused-element"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the list item element style class */ getItemElementStyleClass: function() { return "oj-listview-item-element"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the group item element style class */ getGroupItemStyleClass: function() { return "oj-listview-group-item"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the group element style class */ getGroupStyleClass: function() { return "oj-listview-group"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the group expand style class */ getGroupExpandStyleClass: function() { return "oj-listview-collapsible-transition"; }, /** * To be change by NavList. Access by ContentHandler. * @return {string} the group collapse style class */ getGroupCollapseStyleClass: function() { return this.getGroupExpandStyleClass(); }, /** * To be change by NavList * @return {string} the collapse icon style class */ getCollapseIconStyleClass: function() { return "oj-listview-collapse-icon"; }, /** * To be change by NavList * @return {string} the expand icon style class */ getExpandIconStyleClass: function() { return "oj-listview-expand-icon"; }, /** * To be change by NavList * @return {string} the empty text style class */ getEmptyTextStyleClass: function() { return "oj-listview-no-data-message"; }, /** * To be change by NavList * @return {string} the depth style class */ getDepthStyleClass: function(depth) { return ""; }, /** * To be change by NavList * @return {string} the option defaults style class */ getOptionDefaultsStyleClass: function() { return "oj-listview-option-defaults"; }, /********************************* End Style Classes *******************************************/ /*********************************** Pin Header *********************************************/ /** * Helper method to prevent scroll by mouse wheel causes the page to scroll because it has reached the start/end of the list * @param {Element} scroller the scroller * @param {Event} event the mouse wheel event * @private */ _preventMouseWheelOverscroll: function(scroller, event) { var delta = event.originalEvent.wheelDelta; if (isNaN(delta)) { return; } if (delta < 0) { // scroll down if ((scroller.scrollTop + scroller.clientHeight + Math.abs(delta)) >= scroller.scrollHeight) { scroller.scrollTop = scroller.scrollHeight; event.preventDefault(); } } else { // scroll up if ((scroller.scrollTop - delta) <= 0) { scroller.scrollTop = 0; event.preventDefault(); } } }, /** * Retrieve the element where the scroll listener is registered on. * @private */ _getScrollEventElement: function() { var scroller = this._getScroller(); // if scroller is the body, listen for window scroll event. This is the only way that works consistently across all browsers. if (scroller == document.body || scroller == document.documentElement) { return window; } else { return scroller; } }, /** * Register scroll listener * @private */ _registerScrollHandler: function() { var self = this, scrollElem; scrollElem = $(this._getScrollEventElement()); this.ojContext._off(scrollElem, "scroll mousewheel"); this.ojContext._on(scrollElem, { "scroll": function(event) { // update scrollPosition, don't if scroll isn't complete if (!self._skipScrollUpdate) { self.SetOption('scrollTop', self._getScroller().scrollTop, {'_context': {originalEvent: event, internalSet: true}}); } self._skipScrollUpdate = false; // handle pinning group header if (self._isPinGroupHeader()) { self._handlePinGroupHeader(); } } }); // only do this for highwatermark scrolling, other cases we have (and should not care) no knowledge about the scroller if (this.options['scrollPolicy'] == "loadMoreOnScroll") { this.ojContext._on(scrollElem, { "mousewheel": function(event) { self._preventMouseWheelOverscroll(self._getScroller(), event); } }); } }, /** * Whether group header should be pin * @return {boolean} true if group header should be pin or false otherwise * @private */ _isPinGroupHeader: function() { return (this.GetOption("groupHeaderPosition") != "static"); }, /** * Retrieve the visible (flattened) group items cache, create one if it is null. * @return {jQuery} a list of group items * @private */ _getGroupItemsCache: function() { var selector; if (this.m_groupItems == null) { selector = "."+this.getGroupItemStyleClass() + ":visible"; this.m_groupItems = this.element.find(selector).filter(function(index) { // if it's expanded and it has children if (!$(this).parent().hasClass("oj-collapsed")) { if ($(this).next().children().length > 0) { return true; } } return false; }); } return this.m_groupItems; }, /** * Unpin a pinned group header * @param {Element} groupItem the group header element to unpin * @private */ _unpinGroupItem: function(groupItem) { $(groupItem).removeClass("oj-pinned"); groupItem.style.top = "auto"; groupItem.style.width = "auto"; }, /** * Gets the next group item. This could be a group item from a different parent. * @param {Element} groupItem the reference group item. * @return {Element|null} the next group item or null if one cannot be found * @private */ _getNextGroupItem: function(groupItem) { var groupItems, index; groupItems = this._getGroupItemsCache(); index = groupItems.index(groupItem); if (index > -1 && index < groupItems.length-1) { return groupItems[index+1]; } return null; }, /** * Pin a group header * @param {Element} groupItem the group header element to pin * @param {number} scrollTop the scrolltop position of the listview container * @private */ _pinGroupItem: function(groupItem, scrollTop) { var width, height, next; width = groupItem.offsetWidth; height = groupItem.offsetHeight; next = this._getNextGroupItem(groupItem); // todo: get rid of 5 if (next != null && next.offsetTop <= scrollTop + height + 5) { scrollTop = scrollTop - height; } $(groupItem).addClass("oj-pinned"); groupItem.style.top = scrollTop + 'px'; groupItem.style.width = width + 'px'; }, /** * Pin the header as neccessary when user scrolls. * @private */ _handlePinGroupHeader: function() { var scroller, scrollTop, groupItemToPin, groupItems, pinHeaderHeight, i, groupItem, top, bottom, next; scroller = this._getScroller(); scrollTop = scroller.scrollTop; // see if we are at the top if (this.m_groupItemToPin != null && scrollTop == 0) { this._unpinGroupItem(this.m_groupItemToPin); this.m_groupItemToPin = null; return; } // find the group item to pin groupItems = this._getGroupItemsCache(); pinHeaderHeight = 0; if (this.m_groupItemToPin != null) { pinHeaderHeight = this.m_groupItemToPin.offsetHeight; } for (i=0; i<groupItems.length; i++) { groupItem = groupItems[i]; if (this.m_groupItemToPin == groupItem) { continue; } top = groupItems[i].offsetTop; bottom = top + groupItem.parentNode.offsetHeight; // if bottom half is in view but not the top half if (top < scrollTop && bottom > scrollTop + pinHeaderHeight) { groupItemToPin = groupItem; break; } } // found the group item to pin if (groupItemToPin != null && groupItemToPin != this.m_groupItemToPin) { // unpin the previous item if (this.m_groupItemToPin != null) { this._unpinGroupItem(this.m_groupItemToPin); } this._pinGroupItem(groupItemToPin, scrollTop); this.m_groupItemToPin = groupItemToPin; } else if (this.m_groupItemToPin != null) { // is the current pin header touching the next item next = this._getNextGroupItem(this.m_groupItemToPin); if (next != null && next.offsetTop <= scrollTop + pinHeaderHeight) { // make sure they really touches this.m_groupItemToPin.style.top = (next.offsetTop - pinHeaderHeight) + 'px'; return; } this.m_groupItemToPin.style.top = scrollTop + 'px'; } }, /** * Gets the scroller element, which is either the listview container or the scroller element * specified in scrollPolicyOptions * @return {Element} the scroller element * @private */ _getScroller: function() { var options, scroller; options = this.GetOption("scrollPolicyOptions"); if (options != null) { scroller = options['scroller']; if (scroller != null) { return scroller; } } return this._getListContainer().get(0); }, /** * Scroll to the specified group header * @param {Element} groupHeader the group header div element * @private */ _scrollToGroupHeader: function(groupHeader) { var scroller, currentScrollTop; scroller = this._getScroller(); currentScrollTop = scroller.scrollTop; // unpin any pinned group header first before scroll to header if (this.m_groupItemToPin != null) { this._unpinGroupItem(this.m_groupItemToPin); this.m_groupItemToPin = null; } scroller.scrollTop = groupHeader.offsetTop; // if it wasn't scroll (ex: already at the end), we'll have to explicitly try to see if we need to pin again if (this._isPinGroupHeader() && currentScrollTop == scroller.scrollTop) { this._handlePinGroupHeader(); } // set the first item in group current this._setFirstFocusableItemInGroupCurrent(groupHeader); }, /** * Find the first focusable item within the group and make it current * @param {Element} groupHeader the group header * @private */ _setFirstFocusableItemInGroupCurrent: function(groupHeader) { var self = this, items, item; items = $(groupHeader).next().children(); items.each(function() { item = $(this); // make sure item can receive focus if (!self.SkipFocus(item)) { self.SetOption('currentItem', this.key); return false; } }); } /********************************* End Pin Header *******************************************/ }); /** * Copyright (c) 2015, Oracle and/or its affiliates. * All rights reserved. */ /** * @ojcomponent oj.ojListView * @augments oj.baseComponent * @since 1.1.0 * * @classdesc * <h3 id="listViewOverview-section"> * JET ListView Component * <a class="bookmarkable-link" title="Bookmarkable Link" href="#listViewOverview-section"></a> * </h3> * * <p>Description: The JET ListView enhances a HTML list element into a themable, WAI-ARIA compliant, mobile friendly component with advance interactive features.</p> * * <h3 id="data-section"> * Data * <a class="bookmarkable-link" title="Bookmarkable Link" href="#data-section"></a> * </h3> * <p>The JET ListView gets its data in three different ways. The first way is from a TableDataSource. There are several types of TableDataSource that * are available out of the box:</p> * <ul> * <li>oj.ArrayTableDataSource</li> * <li>oj.CollectionTableDataSource</li> * <li>oj.PagingTableDataSource</li> * </ul> * * <p><b>oj.ArrayTableDataSource</b> - Use this when the underlying data is an array object or an observableArray. In the observableArray case, ListView will automatically react * when items are added or removed from the array. See the documentation for oj.ArrayTableDataSource for more details on the available options.</p> * * <p><b>oj.CollectionTableDataSource</b> - Use this when oj.Collection is the model for the underlying data. Note that the ListView will automatically react to model event from * the underlying oj.Collection. See the documentation for oj.CollectionTableDataSource for more details on the available options.</p> * * <p><b>oj.PagingTableDataSource</b> - Use this when the ListView is driven by an associating ojPagingControl. See the documentation for oj.PagingTableDataSource for more * details on the available options.</p> * * <p>The second way is from a TreeDataSource. This is typically used to display data that are logically categorized in groups. There are several types * of TreeDataSource that are available out of the box:</p> * <ul> * <li>oj.JsonTreeDataSource</li> * <li>oj.CollectionTreeDataSource</li> * </ul> * * <p><b>oj.JsonTreeDataSource</b> - Use this when the underlying data is a JSON object. See the documentation for oj.JsonTreeDataSource for more details on the available options.</p> * * <p><b>oj.CollectionTreeDataSource</b> - Use this when oj.Collection is the model for each group of data. See the documentation for oj.CollectionTableDataSource * for more details on the available options.</p> * * <p>Finally, ListView also supports static HTML content as data. The structure of the content can be either flat or hierarhical.</p> * * <p>Example of flat static content</p> * <pre class="prettyprint"> * <code>&lt;ul id="listView" data-bind="ojComponent: {component: 'ojListView'}"> * &lt;li>&lt;a id="item1" href="#">Item 1&lt;/a>&lt;/li> * &lt;li>&lt;a id="item2" href="#">Item 2&lt;/a>&lt;/li> * &lt;li>&lt;a id="item3" href="#">Item 3&lt;/a>&lt;/li> * &lt;/ul> * </code></pre> * * <p>Example of hierarchical static content</p> * <pre class="prettyprint"> * <code>&lt;ul id="listView" data-bind="ojComponent: {component: 'ojListView'}"> * &lt;li>&lt;a id="group1" href="#">Group 1&lt;/a> * &lt;ul> * &lt;li>&lt;a id="item1-1" href="#">Item 1-1&lt;/a>&lt;/li> * &lt;li>&lt;a id="item1-2" href="#">Item 1-2&lt;/a>&lt;/li> * &lt;/ul> * &lt;/li> * &lt;li>&lt;a id="group2" href="#">Group 2&lt;/a> * &lt;ul> * &lt;li>&lt;a id="item2-1" href="#">Item 2-1&lt;/a>&lt;/li> * &lt;li>&lt;a id="item2-2" href="#">Item 2-2&lt;/a>&lt;/li> * &lt;/ul> * &lt;/li> * &lt;/ul> * </code></pre> * * <h3 id="touch-section"> * Touch End User Information * <a class="bookmarkable-link" title="Bookmarkable Link" href="#touch-section"></a> * </h3> * * {@ojinclude "name":"touchDoc"} * * <h3 id="keyboard-section"> * Keyboard End User Information * <a class="bookmarkable-link" title="Bookmarkable Link" href="#keyboard-section"></a> * </h3> * * {@ojinclude "name":"keyboardDoc"} * * <h3 id="context-section"> * Item Context * <a class="bookmarkable-link" title="Bookmarkable Link" href="#context-section"></a> * </h3> * * <p>For all item options, developers can specify a function as the return value. The function takes a single argument, which is an object that contains contextual information about the particular item. This gives developers the flexibility to return different value depending on the context.</p> * * <p>The context paramter contains the following keys:</p> * <table class="keyboard-table"> * <thead> * <tr> * <th>Key</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><kbd>component</kbd></td> * <td>A reference to the ListView widget constructor.</td> * </tr> * <tr> * <td><kbd>datasource</kbd></td> * <td>A reference to the data source object. (Not available for static content)</td> * </tr> * <tr> * <td><kbd>index</kbd></td> * <td>The index of the item, where 0 is the index of the first item. In the hierarchical case the index is relative to its parent.</td> * </tr> * <tr> * <td><kbd>key</kbd></td> * <td>The key of the item.</td> * </tr> * <tr> * <td><kbd>data</kbd></td> * <td>The data object for the item.</td> * </tr> * <tr> * <td><kbd>parentElement</kbd></td> * <td>The list item element. The renderer can use this to directly append content.</td> * </tr> * </tbody> * </table> * * <p></p> * <p>If the data is hierarchical, the following additional contextual information are available:</p> * <table class="keyboard-table"> * <thead> * <tr> * <th>Key</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><kbd>depth</kbd></td> * <td>The depth of the item. The depth of the first level children under the invisible root is 1.</td> * </tr> * <tr> * <td><kbd>parentKey</kbd></td> * <td>The key of the parent item. The parent key is null for root node.</td> * </tr> * <tr> * <td><kbd>leaf</kbd></td> * <td>Whether the item is a leaf or a group item.</td> * </tr> * </tbody> * </table> * * <h3 id="accessibility-section"> * Accessibility * <a class="bookmarkable-link" title="Bookmarkable Link" href="#accessibility-section"></a> * </h3> * * <p>Application must ensure that the context menu is available and setup with the * appropriate clipboard menu items so that keyboard-only users are able to reorder items * just by using the keyboard. * * <h3 id="perf-section"> * Performance * <a class="bookmarkable-link" title="Bookmarkable Link" href="#perf-section"></a> * </h3> * * <h4>Data Set Size</h4> * <p>As a rule of thumb, it's recommended that applications limit the amount of data to display. Displaying large * number of items in ListView makes it hard for user to find what they are looking for, but affects the load time and * scrolling performance as well. If displaying large number of items is neccessary, use a paging control with ListView * to limit the number of items to display at a time. Setting <code class="prettyprint">scrollPolicy</code> to * 'loadMoreOnScroll' will also reduce the number of items to display initially.</p> * * <h4>Item Content</h4> * <p>ListView allows developers to specify arbitrary content inside its item. In order to minimize any negative effect on * performance, you should avoid putting a large number of heavy-weight components inside because as you add more complexity * to the structure, the effect will be multiplied because there can be many items in the ListView.</p> * * <h4>Expand All</h4> * <p>While ListView provides a convenient way to initially expand all group items in the ListView, it might have an impact * on the initial rendering performance since expanding each group item might cause a fetch from the server depending on * the TreeDataSource. Other factors that could impact performance includes the depth of the tree, and the number of children * in each level.</p> * * <h3 id="animation-section"> * Animation * <a class="bookmarkable-link" title="Bookmarkable Link" href="#animation-section"></a> * </h3> * * <p>Applications can customize animations triggered by actions in ListView by either listening for <code class="prettyprint">animateStart/animateEnd</code> * events or overriding action specific style classes on the animated item. See the documentation of <a href="oj.AnimationUtils.html">oj.AnimationUtils</a> * class for details.</p> * * <p>The following are actions and their corresponding sass variables in which applications can use to customize animation effects. * <table class="keyboard-table"> * <thead> * <tr> * <th>Action</th> * <th>Sass Variable</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><kbd>add</kbd></td> * <td>$listViewAddAnimation</td> * <td>When a new item is added to the oj.TableDataSource associated with ListView.</td> * </tr> * <tr> * <td><kbd>remove</kbd></td> * <td>$listViewRemoveAnimation</td> * <td>When an existing item is removed from the oj.TableDataSource associated with ListView.</td> * </tr> * <tr> * <td><kbd>update</kbd></td> * <td>$listViewUpdateAnimation</td> * <td>When an existing item is updated in the oj.TableDataSource associated with ListView.</td> * </tr> * <tr> * <td><kbd>expand</kbd></td> * <td>$listViewExpandAnimation</td> * <td>When user expands a group item.</td> * </tr> * <tr> * <td><kbd>collapse</kbd></td> * <td>$listViewCollapseAnimation</td> * <td>When user collapses a group item.</td> * </tr> * <tr> * <td><kbd>pointerUp</kbd></td> * <td>$listViewPointerUpAnimation</td> * <td>When user finish pressing an item (on touch).</td> * </tr> * </tbody> * </table> */ oj.__registerWidget('oj.ojListView', $['oj']['baseComponent'], { widgetEventPrefix: 'oj', options: { /** * The current item. This is typically the item the user navigated to. Note that if current * is set to an item that is currently not available (not fetched in highwater mark scrolling case or * inside a collapsed parent node), then the value is ignored. * * @expose * @public * @instance * @memberof! oj.ojListView * @type {Object} * @default <code class="prettyprint">null</code> * * @example <caption>Get the current item:</caption> * $( ".selector" ).ojListView("option", "currentItem"); * * @example <caption>Set the current item on the ListView during initialization:</caption> * $(".selector").ojListView({"currentItem", "item2"}); */ currentItem: null, /** * The data source for the ListView accepts either a oj.TableDataSource or oj.TreeDataSource. * See the data source section in the introduction for out of the box data source types. * If the data attribute is not specified, the child elements are used as content. If there's no * content specified, then an empty list is rendered. * * @expose * @memberof! oj.ojListView * @instance * @type {oj.TableDataSource|oj.TreeDataSource} * @default <code class="prettyprint">null</code> * * @example <caption>Initialize the ListView with a one-dimensional array:</caption> * $( ".selector" ).ojListView({ "data": new oj.ArrayTableDataSource([1,2,3])}); * * @example <caption>Initialize the ListView with an oj.Collection:</caption> * $( ".selector" ).ojListView({ "data": new oj.CollectionTableDataSource(collection)}); */ data: null, /** * Enable drag and drop functionality.<br><br> * JET provides support for HTML5 Drag and Drop events. Please refer to {@link https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_and_drop third party documentation} * on HTML5 Drag and Drop to learn how to use it. * * @expose * @memberof! oj.ojListView * @instance */ dnd: { /** * @expose * @alias dnd.drag * @memberof! oj.ojListView * @instance * @type {Object} * @default <code class="prettyprint">null</code> * @property {Object} items If this object is specified, listview will initiate drag operation when the user drags on either a drag handle, which is an element with oj-listview-drag-handle class, or * selected items if no drag handle is set on the item. * @property {string | Array.string} items.dataTypes (optional) The MIME types to use for the dragged data in the dataTransfer object. This can be a string if there is only one * type, or an array of strings if multiple types are needed.<br><br> * For example, if selected items of employee data are being dragged, dataTypes could be "application/employees+json". Drop targets can examine the data types and decide * whether to accept the data. A text input may only accept "text" data type, while a chart for displaying employee data may be configured to accept the "application/employees+json" type.<br><br> * For each type in the array, dataTransfer.setData will be called with the specified type and the JSON version of the selected item data as the value. The selected item data * is an array of objects, with each object representing a model object from the underlying data source. For example, if the underlying data is an oj.Collection, then this * would be a oj.Model object. Note that when static HTML is used, then the value would be the html string of the selected item.<br><br> * This property is required unless the application calls setData itself in a dragStart callback function. * @property {function} items.dragStart (optional) A callback function that receives the "dragstart" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">items</code>: An array of objects, with each object representing the data of one selected item * </li> * </ul><br><br> * This function can set its own data and drag image as needed. If dataTypes is specified, event.dataTransfer is already populated with the default data when this function is invoked. * If dataTypes is not specified, this function must call event.dataTransfer.setData to set the data or else the drag operation will be cancelled. In either case, the drag image is * set to an image of the dragged rows on the listview. * @property {function} items.drag (optional) A callback function that receives the "drag" event as argument:<br><br> * <code class="prettyprint">function(event)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object * @property {function} items.dragEnd (optional) A callback function that receives the "dragend" event as argument:<br><br> * <code class="prettyprint">function(event)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br> * * @example <caption>Initialize the ListView such that only leaf items are focusable:</caption> * $( ".selector" ).ojListView({ "data":data, "dnd": {"drag": {"items": { "dataTypes": ["application/ojlistviewitems+json"], * "dragEnd": handleDragEnd}}}); */ drag: null, /** * @expose * @alias dnd.drop * @memberof! oj.ojListView * @instance * @type {Object} * @default <code class="prettyprint">null</code> * @property {Object} items An object that specifies callback functions to handle dropping items<br><br> * @property {string | Array.string} items.dataTypes A data type or an array of data types this component can accept.<br><br> * This property is required unless dragEnter, dragOver, and drop callback functions are specified to handle the corresponding events. * @property {function} items.dragEnter (optional) A callback function that receives the "dragenter" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">item</code>: the item being entered * </li> * </ul><br><br> * This function should return false to indicate the dragged data can be accepted or true otherwise. Any explict return value will be passed back to jQuery. Returning false * will cause jQuery to call stopPropagation and preventDefault on the event, and calling preventDefault is required by HTML5 Drag and Drop to indicate acceptance of data.<br><br> * If this function doesn't return a value, dataTypes will be matched against the drag data types to determine if the data is acceptable. If there is a match, event.preventDefault * will be called to indicate that the data can be accepted. * @property {function} items.dragOver (optional) A callback function that receives the "dragover" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">item</code>: the item being dragged over * </li> * </ul><br><br> * Similar to dragEnter, this function should return false to indicate the dragged data can be accepted or true otherwise. If this function doesn't return a value, * dataTypes will be matched against the drag data types to determine if the data is acceptable. * @property {function} items.dragLeave (optional) A callback function that receives the "dragleave" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">item</code>: the item that was last entered * </li> * </ul><br><br> * @property {function} items.drop (required) A callback function that receives the "drop" event and context information as arguments:<br><br> * <code class="prettyprint">function(event, ui)</code><br><br> * Parameters:<br><br> * <code class="prettyprint">event</code>: The jQuery event object<br><br> * <code class="prettyprint">ui</code>: Context object with the following properties:<br> * <ul> * <li><code class="prettyprint">item</code>: the item being dropped on * <li><code class="prettyprint">position</code>: the drop position relative to the item being dropped on * <li><code class="prettyprint">reorder</code>: true if the drop was a reorder in the same listview, false otherwise * </li> * </ul><br><br> * This function should return false to indicate the dragged data is accepted or true otherwise.<br><br> * If the application needs to look at the data for the item being dropped on, it can use the getDataForVisibleItem method. * * @example <caption>Initialize the ListView such that only leaf items are focusable:</caption> * $( ".selector" ).ojListView({ "data":data, "dnd": {"drop": {"items": { "dataTypes": ["application/ojlistviewitems+json"], * "drop": handleDrop}}}); */ drop: null, /** * The reorder option contains a subset of options for reordering items. * * @expose * @alias dnd.reorder * @memberof! oj.ojListView * @instance * @type {Object} */ reorder: { /** * Enable or disable reordering the items within the same listview using drag and drop.<br><br> * Specify 'enabled' to enable reordering. Setting the value 'disabled' or setting the <code class="prettyprint">"dnd"</code> property * to <code class="prettyprint">null</code> (or omitting it), disables reordering support. * * @expose * @alias dnd.reorder.items * @memberof! oj.ojListView * @instance * @type {string} * @default <code class="prettyprint">disabled</code> * * @example <caption>Initialize the listview to enable item reorder:</caption> * $( ".selector" ).ojListView({ "data":data, "dnd" : {"reorder":{"items":"enabled"}}}); */ items:'disabled' } }, /** * Changes the expand and collapse operations on ListView. If "none" is specified, then * the current expanded state is fixed and user cannot expand or collapse an item. * * @expose * @memberof! oj.ojListView * @instance * @type {string} * @default <code class="prettyprint">collapsible</code> * @ojvalue {string} "collapsible" group item can be expanded or collapsed by user. * @ojvalue {string} "none" the expand state of a group item cannot be changed by user. * * @example <caption>Initialize the list view with a fixed expanded state:</caption> * $( ".selector" ).ojListView({ "drillMode": "none" }); */ drillMode: "collapsible", /** * Specifies which items in ListView should be expanded. Specifies "all" value to expand all items. Specifies * an array of keys to expand specific items. * * The default value is "auto", which means that ListView will determine which items are expanded by default. * Specifically, if drillMode is set to "none", then all items are expanded, any other values for * drillMode will not cause any items to expand by default. * * Note that expanded does not return the currently expanded items. This only returns what is specified * by default. To retrieve the keys of currently expanded items, use the <code class="prettyprint">getExpanded</code> * method. * * @expose * @memberof! oj.ojListView * @instance * @type {Array.<Object>|string} * @default <code class="prettyprint">[]</code> * * @example <caption>Initialize the list view with a fixed expanded state:</caption> * $( ".selector" ).ojListView({ "expanded": ["group1", "group2"] }); */ expanded: "auto", /** * Specifies how the group header should be positioned. If "sticky" is specified, then the group header * is fixed at the top of the ListView as the user scrolls. * * @expose * @memberof! oj.ojListView * @instance * @default <code class="prettyprint">sticky</code> * @ojvalue {string} "static" The group header position updates as user scrolls. * @ojvalue {string} "sticky" this is the default. The group header is fixed at the top when user scrolls. */ groupHeaderPosition: "sticky", /** * The item option contains a subset of options for items. * * @expose * @memberof! oj.ojListView * @instance */ item: { /** * Whether the item is focusable. An item that is not focusable cannot be clicked on or navigated to. * See <a href="#context-section">itemContext</a> in the introduction to see the object passed into the focusable function. * * @expose * @alias item.focusable * @memberof! oj.ojListView * @instance * @type {function(Object)|boolean} * @default <code class="prettyprint">true</code> * * @example <caption>Initialize the ListView such that only leaf items are focusable:</caption> * $( ".selector" ).ojListView({ "data":data, "item": { "focusable": function(itemContext) { * return itemContext['leaf'];}}}); */ focusable: true, /** * The renderer function that renders the content of the item. See <a href="#context-section">itemContext</a> * in the introduction to see the object passed into the renderer function. * The function returns either a String or a DOM element of the content inside the item. * If the developer chooses to manipulate the list element directly, the function should return * nothing. If no renderer is specified, ListView will treat the data as a String. * * @expose * @alias item.renderer * @memberof! oj.ojListView * @instance * @type {function(Object)|null} * @default <code class="prettyprint">null</code> * * @example <caption>Initialize the ListView with a renderer:</caption> * $( ".selector" ).ojListView({ "data":data, "item": { "renderer": function(itemContext) { * return itemContext['data'].get('FIRST_NAME');}}}); * * @example <caption>Get or set the <code class="prettyprint">renderer</code> option, after initialization:</caption> * // set the renderer function * $( ".selector" ).ojListView( "option", "item.renderer", myFunction}); */ renderer: null, /** * Whether the item is selectable. Note that if selectionMode is set to "none" this option is ignored. In addition, * if selectable is set to true, then the focusable option is automatically overridden and set to true. * See <a href="#context-section">itemContext</a> in the introduction to see the object passed into the selectable function. * * @expose * @alias item.selectable * @memberof! oj.ojListView * @instance * @type {function(Object)|boolean} * @default <code class="prettyprint">true</code> * * @example <caption>Initialize the ListView such that the first 3 items are not selectable:</caption> * $( ".selector" ).ojListView({ "data":data, "item": { "selectable": function(itemContext) { * return itemContext['index'] > 3;}}}); */ selectable: true /** * The knockout template used to render the content of the item. * * This attribute is only exposed via the <code class="prettyprint">ojComponent</code> binding, and is not a * component option. * * @ojbindingonly * @name item.template * @memberof! oj.ojListView * @instance * @type {string|null} * @default <code class="prettyprint">null</code> * * @example <caption>Specify the <code class="prettyprint">template</code> when initializing ListView:</caption> * // set the template * &lt;ul id="listview" data-bind="ojComponent: {component: 'ojListView', data: dataSource, item: {template: 'my_template'}}"&gt;&lt;/ul&gt; */ }, /** * Specifies the mechanism used to scroll the data inside the list view. Possible values are: auto and loadMoreOnScroll. * When loadMoreOnScroll is specified, additional data is fetched when the user scrolls to the bottom of the ListView. * Note that currently this option is only available when TableDataSource is used. * * @expose * @memberof! oj.ojListView * @instance * @type {string|null} * @default <code class="prettyprint">auto</code> * @ojvalue {string} "auto" the behavior is determined by the component. * @ojvalue {string} "loadMoreOnScroll" additional data is fetched when the user scrolls to the bottom of the ListView. * * @example <caption>Initialize the list view with a fixed expanded state:</caption> * $( ".selector" ).ojListView({ "scrollPolicy": "loadMoreOnScroll" }); */ scrollPolicy: "auto", /** * scrollPolicy options. * <p> * The following options are supported: * <ul> * <li>fetchSize: Fetch size for scroll.</li> * <li>maxCount: Maximum rows which will be displayed before fetching more rows will be stopped.</li> * <li>scroller: The element which listview uses to determine the scroll position as well as the maximum scroll position where scroll to the end will trigger a fetch. If not specified then the widget element of listview is used.</li> * </ul> * When scrollPolicy is loadMoreOnScroll, the next block of rows is fetched * when the user scrolls to the end of the list/scroller. The fetchSize option * determines how many rows are fetched in each block. * Note that currently this option is only available when TableDataSource is used. * * @expose * @instance * @memberof! oj.ojListView * @type {Object.<string, number>|null} * @property {number} fetchSize the number of rows to fetch in each block of rows * @default <code class="prettyprint">25</code> * @property {number} maxCount the maximum total number of rows to fetch * @default <code class="prettyprint">500</code> * @property {Element|null} scroller the element which listview uses to determine the scroll position as well as the maximum scroll position. For example in a lot of mobile use cases where ListView occupies the entire screen, developers should set the scroller option to document.body */ scrollPolicyOptions: {'fetchSize': 25, 'maxCount': 500}, /** * The vertical scroll position of ListView. * * @expose * @memberof! oj.ojListView * @instance * @type {number} * @default <code class="prettyprint">0</code> * * @example <caption>Initialize the list view to a specific scroll position:</caption> * $( ".selector" ).ojListView({ "scrollTop": 100 }); */ scrollTop: 0, /** * The current selections in the ListView. An empty array indicates nothing is selected. * * @expose * @memberof! oj.ojListView * @instance * @type {Array.<Object>} * @default <code class="prettyprint">[]</code> * * @example <caption>Initialize the list view with specific selection:</caption> * $( ".selector" ).ojListView({ "data":data, "selection": ["item1", "item2"] }); */ selection: [], /** * Specifies whether selection can be made and the cardinality of selection in the ListView. * Selection is initially disabled, but setting the value to null will disable selection. * * @expose * @memberof! oj.ojListView * @instance * @type {string} * @default <code class="prettyprint">none</code> * @ojvalue {string} "none" selection is disabled. * @ojvalue {string} "single" only one item can be selected at a time. * @ojvalue {string} "multiple": multiple items can be selected at the same time. * * @example <caption>Initialize the list view to enable multiple selection:</caption> * $( ".selector" ).ojListView({ "data":data, "selectionMode": "multiple" }); */ selectionMode: "none", /** * Triggered when the default animation of a particular action is about to start. The default animation can be cancelled by calling event.preventDefault. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.action the action that starts the animation. See <a href="#animation-section">animation</a> section for a list of actions. * @property {function} ui.endCallback if the event listener calls event.preventDefault to cancel the default animation, it must call the endCallback function when it finishes its own animation handling and when any custom animation ends. * * @example <caption>Initialize the ListView with the <code class="prettyprint">animateStart</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "animateStart": function( event, ui ) { * // call event.preventDefault to stop default animation * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojanimatestart</code> event:</caption> * $( ".selector" ).on( "ojanimatestart", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ animateStart: null, /** * Triggered when the default animation of a particular action has ended. Note this event will not be triggered if application cancelled the default animation on animateStart. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.action the action that started the animation. See <a href="#animation-section">animation</a> section for a list of actions. * * @example <caption>Initialize the ListView with the <code class="prettyprint">animateEnd</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "animateEnd": function( event, ui ) { * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojanimateend</code> event:</caption> * $( ".selector" ).on( "ojanimateend", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ animateEnd: null, /** * Triggered before the current item is changed via the <code class="prettyprint">current</code> option or via the UI. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.previousKey the key of the previous item * @property {jQuery} ui.previousItem the previous item * @property {Object} ui.key the key of the new current item * @property {jQuery} ui.item the new current item * * @example <caption>Initialize the ListView with the <code class="prettyprint">beforeCurrentItem</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "beforeCurrentItem": function( event, ui ) { * // return false to veto the event, which prevents the item to become focus * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforecurrentitem</code> event:</caption> * $( ".selector" ).on( "ojbeforecurrentitem", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ beforeCurrentItem: null, /** * Triggered before an item is expanded via the <code class="prettyprint">expanded</code> option, * the <code class="prettyprint">expand</code> method, or via the UI. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.key the key of the item to be expanded * @property {jQuery} ui.item the item to be expanded * * @example <caption>Initialize the ListView with the <code class="prettyprint">beforeExpand</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "beforeExpand": function( event, ui ) { * // return false to veto the event, which prevents the item to expand * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforeexpand</code> event:</caption> * $( ".selector" ).on( "ojbeforeexpand", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ beforeExpand: null, /** * Triggered before an item is collapsed via the <code class="prettyprint">expanded</code> option, * the <code class="prettyprint">collapse</code> method, or via the UI. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.key the key of the item to be collapsed * @property {jQuery} ui.item the item to be collapsed * * @example <caption>Initialize the ListView with the <code class="prettyprint">beforeCollapse</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "beforeCollapse": function( event, ui ) { * // return false to veto the event, which prevents the item to collapse * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojbeforecollapse</code> event:</caption> * $( ".selector" ).on( "ojbeforecollapse", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ beforeCollapse: null, /** * Triggered after an item has been collapsed via the <code class="prettyprint">expanded</code> option, * the <code class="prettyprint">collapse</code> method, or via the UI. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.key The key of the item that was just collapsed. * @property {jQuery} ui.item The list item that was just collapsed. * * @example <caption>Initialize the ListView with the <code class="prettyprint">expand</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "collapse": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojcollapse</code> event:</caption> * $( ".selector" ).on( "ojcollapse", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ collapse: null, /** * Triggered when the copy action is performed on an item via context menu or keyboard shortcut. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Element[]} ui.items an array of items in which the copy action is performed on * * @example <caption>Initialize the ListView with the <code class="prettyprint">copy</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "copy": function( event, ui ) { * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojcopy</code> event:</caption> * $( ".selector" ).on( "ojcopy", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ copy: null, /** * Triggered when the cut action is performed on an item via context menu or keyboard shortcut. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Element[]} ui.items an array of items in which the cut action is performed on * * @example <caption>Initialize the ListView with the <code class="prettyprint">cut</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "cut": function( event, ui ) { * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojcut</code> event:</caption> * $( ".selector" ).on( "ojcut", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ cut: null, /** * Triggered after an item has been expanded via the <code class="prettyprint">expanded</code> option, * the <code class="prettyprint">expand</code> method, or via the UI. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Object} ui.key The key of the item that was just expanded. * @property {jQuery} ui.item The list item that was just expanded. * * @example <caption>Initialize the ListView with the <code class="prettyprint">expand</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "expand": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojexpand</code> event:</caption> * $( ".selector" ).on( "ojexpand", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ expand: null, /** * Fired whenever a supported component option changes, whether due to user interaction or programmatic * intervention. If the new value is the same as the previous value, no event will be fired. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {string} ui.option the name of the option that is changing * @property {boolean} ui.previousValue the previous value of the option * @property {boolean} ui.value the current value of the option * @property {jQuery} ui.item the current item (only available for option <code class="prettyprint">"currentItem"</code>) * @property {jQuery} ui.items the selected items (only available for option <code class="prettyprint">"selection"</code>) * @property {Object} ui.optionMetadata information about the option that is changing * @property {string} ui.optionMetadata.writeback <code class="prettyprint">"shouldWrite"</code> or * <code class="prettyprint">"shouldNotWrite"</code>. For use by the JET writeback mechanism. * * @example <caption>Initialize component with the <code class="prettyprint">optionChange</code> callback</caption> * $(".selector").ojListView({ * 'optionChange': function (event, data) { * if (data['option'] === 'selection') { // handle selection change } * } * }); * @example <caption>Bind an event listener to the ojoptionchange event</caption> * $(".selector").on({ * 'ojoptionchange': function (event, data) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) { * window.console.log("option that changed is: " + data['option']); * } * }; * }); */ optionChange: null, /** * Triggered when the paste action is performed on an item via context menu or keyboard shortcut. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Element} ui.item the element in which the paste action is performed on * * @example <caption>Initialize the ListView with the <code class="prettyprint">paste</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "paste": function( event, ui ) { * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojpaste</code> event:</caption> * $( ".selector" ).on( "ojpaste", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ paste: null, /** * Triggered after all items in the ListView has been rendered. Note that in the highwatermark scrolling case, * all items means the items that are fetched so far. * * @expose * @event * @deprecated Use the <a href="#whenReady">whenReady</a> method instead. * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * * @example <caption>Initialize the ListView with the <code class="prettyprint">ready</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "ready": function( event, ui ) {} * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojready</code> event:</caption> * $( ".selector" ).on( "ojready", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ ready: null, /** * Triggered after items are reorder within listview via drag and drop or cut and paste. * * @expose * @event * @memberof oj.ojListView * @instance * @property {Event} event <code class="prettyprint">jQuery</code> event object * @property {Object} ui Parameters * @property {Element[]} ui.items an array of items that are moved * @property {string} ui.position the drop position relative to the reference item. Possible values are "before", "after", "inside" * @property {Element} ui.reference the item where the moved items are drop on * * @example <caption>Initialize the ListView with the <code class="prettyprint">reorder</code> callback specified:</caption> * $( ".selector" ).ojListView({ * "reorder": function( event, ui ) { * } * }); * * @example <caption>Bind an event listener to the <code class="prettyprint">ojreorder</code> event:</caption> * $( ".selector" ).on( "ojreorder", function( event, ui ) { * // verify that the component firing the event is a component of interest * if ($(event.target).is(".mySelector")) {} * }); */ reorder: null }, /** * Create the listview * @override * @memberof! oj.ojListView * @protected */ _ComponentCreate: function() { this._super(); this._setup(); }, /** * Initialize the listview * @private */ _setup: function() { var opts = {}; opts.element = this.element; opts.OuterWrapper = this.OuterWrapper; opts.ojContext = this; opts = $.extend(this.options, opts); this.listview = new oj._ojListView(); this.listview.init(opts); }, /** * Initialize the listview after creation * @protected * @override * @memberof! oj.ojListView */ _AfterCreate: function () { this._super(); this.listview.afterCreate(); }, /** * Destroy the list view * @memberof! oj.ojListView * @private */ _destroy: function() { this.listview.destroy(); this._super(); }, /** * When the <a href="#contextMenu">contextMenu</a> option is set, this method is called when the user invokes the context menu via * the default gestures: right-click, pressHold, and <kbd>Shift-F10</kbd>. Components should not call this method directly. * * @param {!Object} menu The JET Menu to open as a context menu. Always non-<code class="prettyprint">null</code>. * @param {!Event} event What triggered the menu launch. Always non-<code class="prettyprint">null</code>. * @param {string} eventType "mouse", "touch", or "keyboard". Never <code class="prettyprint">null</code>. * @private */ _NotifyContextMenuGesture: function(menu, event, eventType) { this.listview.notifyContextMenuGesture(menu, event, eventType); }, /** * Sets multiple options * @param {Object} options the options object * @param {Object} flags additional flags for option * @override * @private */ _setOptions: function(options, flags) { var needRefresh = this.listview.setOptions(options, flags); // updates the options last this._super(options, flags); if (needRefresh) { this.listview.refresh(); this._fireIndexerModelChangeEvent(); } }, /** * Sets a single option * @param {Object} key the key for the option * @param {Object} value the value for the option * @param {Object} flags any flags specified for the option * @override * @private */ _setOption: function(key, value, flags) { // checks whether value is valid for the key var valid = true; if (key == "selectionMode") { valid = (value == "none" || value == "single" || value == "multiple"); } else if (key == "drillMode") { valid = (value == "collapsible" || value == "none"); } else if (key == "scrollPolicy") { valid = (value == "auto" || value == "loadMoreOnScroll"); } else if (key == "groupHeaderPosition") { valid = (value == "static" || value == "sticky"); } // update option if it's valid otherwise throw an error if (valid) { // inject additional metadata for selection if (key == "selection") { flags = {'_context': {extraData: {'items': $(this.listview.getItems(value))}}} } this._super(key, value, flags); } else { throw "Invalid value: "+value+" for key: "+key; } }, /** * Invoked when application calls oj.Components.subtreeAttached. * @override * @private */ _NotifyAttached: function() { this.listview.notifyAttached(); }, /** * In browsers [Chrome v35, Firefox v24.5, IE9, Safari v6.1.4], blur and mouseleave events are generated for hidden content but not detached content, * so for detached content only, we must use this hook to remove the focus and hover classes. * @override * @private */ _NotifyDetached: function() { this.listview.notifyDetached(); }, /** * Invoked when application calls oj.Components.subtreeShown. * @override * @private */ _NotifyShown: function() { this.listview.notifyShown(); }, /********************************* public methods **************************************/ /** * Returns a jQuery object containing the root dom element of the listview. * * <p>This method does not accept any arguments. * * @expose * @override * @memberof oj.ojListView * @instance * @return {jQuery} the root DOM element of list */ 'widget' : function () { return this.listview.getRootElement(); }, /** * Redraw the entire list view after having made some external modifications. * * <p>This method does not accept any arguments. * * @expose * @memberof oj.ojListView * @instance * * @example <caption>Invoke the <code class="prettyprint">refresh</code> method:</caption> * $( ".selector" ).ojListView( "refresh" ); */ refresh: function() { this._super(); this.listview.refresh(); this._fireIndexerModelChangeEvent(); }, /** * Returns a Promise that resolves when the component is ready, i.e. after data fetching, rendering, and animations complete. * Note that in the highwatermark scrolling case, component is ready after data fetching, rendering, and associated animations of items fetched so far are complete. * * <p>This method does not accept any arguments. * * @expose * @memberof oj.ojListView * @instance * @return {Promise} A Promise that resolves when the component is ready. */ whenReady: function() { return this.listview.whenReady(); }, /** * Return the subcomponent node represented by the documented locator attribute values. * <p> * To lookup the disclosure icon the locator object should have the following: * <ul> * <li><b>subId</b>: 'oj-listview-disclosure'</li> * <li><b>key</b>: the key of the item</li> * </ul> * * @expose * @memberof oj.ojListView * @instance * @override * @param {Object} locator An Object containing at minimum a subId property * whose value is a string, documented by the component, that allows * the component to look up the subcomponent associated with that * string. It contains:<p> * component: optional - in the future there may be more than one * component contained within a page element<p> * subId: the string, documented by the component, that the component * expects in getNodeBySubId to locate a particular subcomponent * @returns {Array.<(Element|null)>|Element|null} the subcomponent located by the subId string passed * in locator, if found.<p> */ getNodeBySubId: function(locator) { return this.listview.getNodeBySubId(locator); }, /** * <p>Returns the subId string for the given child DOM node. For more details, see * <a href="#getNodeBySubId">getNodeBySubId</a>. * * @expose * @memberof oj.ojListView * @instance * @override * @param {!Element} node - child DOM node * @return {Object|null} The subId for the DOM node, or <code class="prettyprint">null</code> when none is found. */ getSubIdByNode: function(node) { return this.listview.getSubIdByNode(node); }, /** * {@ojinclude "name":"nodeContextDoc"} * @param {!Element} node - {@ojinclude "name":"nodeContextParam"} * @returns {Object|null} {@ojinclude "name":"nodeContextReturn"} * * @example {@ojinclude "name":"nodeContextExample"} * * @expose * @instance * @memberof oj.ojListView */ getContextByNode: function(node) { return this.listview.getContextByNode(node); }, /** * Return the raw data for an item in ListView. * @param {Object} context the context of the item to retrieve raw data. * @param {Number} context.index the index of the item relative to its parent. * @param {jQuery|Element|string|undefined} context.parent the jQuery wrapped parent node, not required if parent is the root. * @returns {Object | null} item data<p> * @export * @expose * @memberof oj.ojListView * @instance * @example <caption>Invoke the <code class="prettyprint">getDataForVisibleItem</code> method:</caption> * $( ".selector" ).ojListView( "getDataForVisibleItem", {'index': 2} ); */ getDataForVisibleItem: function(context) { return this.listview.getDataForVisibleItem(context); }, /** * Expand an item.<p> * Note when vetoable is set to false, beforeExpand event will still be fired but the event cannot be veto.<p> * * @expose * @memberof oj.ojListView * @instance * @param {Object} key the key of the item to expand * @param {boolean} vetoable whether the event should be vetoable */ expand: function (key, vetoable) { this.listview.expandKey(key, vetoable, true, true); }, /** * Collapse an item.<p> * Note when vetoable is set to false, beforeCollapse event will still be fired but the event cannot be veto.<p> * * @expose * @memberof oj.ojListView * @instance * @param {Object} key the key of the item to collapse * @param {boolean} vetoable whether the event should be vetoable */ collapse: function (key, vetoable) { this.listview.collapseKey(key, vetoable, true); }, /** * Gets the key of currently expanded items. * * @expose * @memberof oj.ojListView * @instance * @return {Array} array of keys of currently expanded items */ getExpanded: function () { return this.listview.getExpanded(); }, /** * Gets the IndexerModel which can be used with the ojIndexer. The IndexerModel provided by ListView * by defaults returns a list of locale dependent characters. See translations for the key used to return * all characters. When a user selects a character in the ojIndexer ListView will scroll to the group * header (or the closest one) with the character as its prefix. * * @expose * @memberof oj.ojListView * @instance * @return {Object} ListView's IndexerModel to be used with the ojIndexer */ getIndexerModel: function () { if (this.indexerModel == null && oj.ListViewIndexerModel) { this.indexerModel = new oj.ListViewIndexerModel(this.listview); } return this.indexerModel; }, /** * Fires a change event on the IndexerModel * * @private */ _fireIndexerModelChangeEvent: function () { if (this.indexerModel != null && this.indexerModel.fireChangeEvent) { this.indexerModel.fireChangeEvent(); } } // Fragments /** * <table class="keyboard-table"> * <thead> * <tr> * <th>Target</th> * <th>Gesture</th> * <th>Action</th> * </tr> * </thead> * <tbody> * <tr> * <td rowspan="2">List Item</td> * <td><kbd>Tap</kbd></td> * <td>Focus on the item. If <code class="prettyprint">selectionMode</code> is enabled, selects the item as well.</td> * </tr> * <tr> * <td><kbd>Press & Hold</kbd></td> * <td>Display context menu</td> * </tr> * <tr> * <td rowspan="2">Group Item</td> * <td><kbd>Tap</kbd></td> * <td>Expand or collapse the group item if <code class="prettyprint">drillMode</code> is set to collapsible.</td> * </tr> * <tr> * <td><kbd>Press & Hold</kbd></td> * <td>Display context menu</td> * </tr> * </tbody> * </table> * * @ojfragment touchDoc - Used in touch gesture section of classdesc, and standalone gesture doc * @memberof oj.ojListView */ /** * <table class="keyboard-table"> * <thead> * <tr> * <th>Target</th> * <th>Key</th> * <th>Action</th> * </tr> * </thead> * <tbody> * <tr> * <td rowspan = "16" nowrap>List Item</td> * <td><kbd>F2</kbd></td> * <td>Enters Actionable mode. This enables keyboard action on elements inside the item, including navigate between focusable elements inside the item.</td> * </tr> * <tr> * <td><kbd>Esc</kbd></td> * <td>Exits Actionable mode.</td> * </tr> * <tr> * <td><kbd>Tab</kbd></td> * <td>When in Actionable Mode, navigates to next focusable element within the item. If the last focusable element is reached, shift focus back to the first focusable element. * When not in Actionable Mode, navigates to next focusable element on page (outside ListView).</td> * </tr> * <tr> * <td><kbd>Shift+Tab</kbd></td> * <td>When in Actionable Mode, navigates to previous focusable element within the item. If the first focusable element is reached, shift focus back to the last focusable element. * When not in Actionable Mode, navigates to previous focusable element on page (outside ListView).</td> * </tr> * <tr> * <td><kbd>DownArrow</kbd></td> * <td>Move focus to the item below.</td> * </tr> * <tr> * <td><kbd>UpArrow</kbd></td> * <td>Move focus to the item above.</td> * </tr> * <tr> * <td><kbd>Shift+DownArrow</kbd></td> * <td>Extend the selection to the item below.</td> * </tr> * <tr> * <td><kbd>Shift+UpArrow</kbd></td> * <td>Extend the selection to the item above.</td> * </tr> * <tr> * <td><kbd>Shift+F10</kbd></td> * <td>Launch the context menu if there is one associated with the current item.</td> * </tr> * <tr> * <td><kbd>Enter</kbd></td> * <td>Selects the current item. No op if the item is already selected.</td> * </tr> * <tr> * <td><kbd>Space</kbd></td> * <td>Toggles to select and deselect the current item. If previous items have been selected, deselects them and selects the current item.</td> * </tr> * <tr> * <td><kbd>Shift+Space</kbd></td> * <td>Selects contiguous items from the last selected item to the current item.</td> * </tr> * <tr> * <td><kbd>Ctrl+Space</kbd></td> * <td>Toggles to select and deselect the current item while maintaining previous selected items.</td> * </tr> * <tr> * <td><kbd>Ctrl+X</kbd></td> * <td>Marks the selected items to move if dnd.reorder is enabled.</td> * </tr> * <tr> * <td><kbd>Ctrl+C</kbd></td> * <td>Marks the selected items to copy if dnd.reorder is enabled.</td> * </tr> * <tr> * <td><kbd>Ctrl+V</kbd></td> * <td>Paste the items that are marked to directly before the current item (or as the last item if the current item is a folder).</td> * </tr> * <tr> * <td rowspan = "2" nowrap>Group Item</td> * <td><kbd>LeftArrow</kbd></td> * <td>Collapse the current item if it is expanded and is collapsible. For non-hierarchical data, do nothing.</td> * </tr> * <tr> * <td><kbd>RightArrow</kbd></td> * <td>Expand the current item if it has children and is expandable. For non-hierarchical data, do nothing.</td> * </tr> * </tbody> * </table> * * @ojfragment keyboardDoc - Used in keyboard section of classdesc, and standalone gesture doc * @memberof oj.ojListView */ }); ////////////////// SUB-IDS ////////////////// /** * <p>Sub-ID for the ojListView component's disclosure icon in group items. See the <a href="#getNodeBySubId">getNodeBySubId</a> * method for details.</p> * * @deprecated Use the <a href="#oj-listview-disclosure">oj-listview-disclosure</a> option instead. * @ojsubid oj-listview-icon * @memberof oj.ojListView * * @example <caption>Get the disclosure icon for the group item with key 'foo':</caption> * var node = $( ".selector" ).ojListView( "getNodeBySubId", {'subId': 'oj-listview-icon', 'key': 'foo'} ); */ /** * <p>Sub-ID for the ojListView component's disclosure icon in group items. See the <a href="#getNodeBySubId">getNodeBySubId</a> * method for details.</p> * * @ojsubid oj-listview-disclosure * @memberof oj.ojListView * * @example <caption>Get the disclosure icon for the group item with key 'foo':</caption> * var node = $( ".selector" ).ojListView( "getNodeBySubId", {'subId': 'oj-listview-disclosure', 'key': 'foo'} ); */ /** * <p>Context for the ojListView component's items.</p> * * @property {number} index the zero based item index relative to its parent * @property {Object} key the key of the item * @property {Element} parent the parent group item. Only available if item has a parent. * @property {boolean} group whether the item is a group. * * @ojnodecontext oj-listview-item * @memberof oj.ojListView */ (function() { var ojListViewMeta = { "properties": { "currentItem": { "type": "Object" }, "data": {}, "dnd": {}, "drillMode": { "type": "string" }, "expanded": { "type": "Array<Object>|string" }, "groupHeaderPosition": {}, "item": {}, "scrollPolicy": { "type": "string" }, "scrollPolicyOptions": { "type": "Object<string, number>" }, "scrollTop": { "type": "number" }, "selection": { "type": "Array<Object>" }, "selectionMode": { "type": "string" } }, "methods": { "collapse": {}, "expand": {}, "getContextByNode": {}, "getDataForVisibleItem": {}, "getExpanded": {}, "getIndexerModel": {}, "getNodeBySubId": {}, "getSubIdByNode": {}, "refresh": {}, "whenReady": {}, "widget": {} }, "extension": { "_hasWrapper": true, "_innerElement": 'ul', "_widgetName": "ojListView" } }; oj.Components.registerMetadata('ojListView', 'baseComponent', ojListViewMeta); oj.Components.register('oj-list-view', oj.Components.getMetadata('ojListView')); })(); });
const gulp = require('gulp'); const sass = require('gulp-sass'); const cleancss = require('gulp-clean-css'); const shell = require('gulp-shell'); const uglify = require('gulp-uglify'); const del = require('del'); const autoprefixer = require('gulp-autoprefixer'); const pump = require('pump'); const cp = require('child_process'); // Clean function clean() { return del(['css', 'js/vendor']); } // Styles function styles() { return gulp.src('scss/app.scss') .pipe(sass({ includePaths: ['bower_components/foundation/scss'] }) .on('error', sass.logError) ) .pipe(autoprefixer({ cascade: false })) .pipe(cleancss({ debug: true }, (details) => { console.log(`Original - ${details.name}: ${details.stats.originalSize}`); console.log(`Minified - ${details.name}: ${details.stats.minifiedSize}`); })) .pipe(gulp.dest('css')); } // Scripts + Uglify function scripts(cb) { // Pump will pipe streams together and close all of them if one of them closes return pump( [ gulp.src('bower_components/modernizr/modernizr.js'), uglify(), gulp.dest('js/vendor') ], cb ) } // Templates function templates() { return gulp .src('*.js', { read: false }) .pipe(shell(['handlebars templates/ -f js/templates.js'])); } // Watch function watch() { // Watch .scss files gulp.watch([ 'bower_components/foundation/scss/**/*.scss', 'scss/**/*.scss' ], styles); // Watch .handlebars files gulp.watch([ 'templates/**/*.handlebars' ], gulp.parallel(templates, scripts)); } /* * Specify if tasks run in series or parallel using `gulp.series` and `gulp.parallel` */ var build = gulp.series( clean, gulp.parallel( templates, styles, scripts ) ); /* * You can use CommonJS `exports` module notation to declare tasks */ exports.clean = clean; exports.styles = styles; exports.scripts = scripts; exports.templates = templates; exports.watch = watch; exports.build = build; /* * Define default task that can be called by just running `gulp` from cli */ exports.default = build;
module('Basic tests'); test('Test factory creates HeartBeater instance', 1, function(){ var hb = $.createHeartBeater(); ok(hb instanceof $.Acheta.HeartBeater, 'Object is instance of HeartBeater'); }); test('Test start and pause', 10, function(){ var hb = $.createHeartBeater(); stop(3) $(hb).on('heartBeatStarted', function(){ ok(true, 'Event triggered'); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'HB is running.'); start(); }); $(hb).on('heartBeatPaused', function(){ ok(true, 'Event triggered'); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_PAUSED, 'HB is paused.'); start(); }); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'HB is running.'); hb.pause(); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_PAUSED, 'HB is paused.'); hb.start(); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'HB is running.'); hb.pause(); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_PAUSED, 'HB is paused.'); }); test('Test heartBeats remaining returning false when no limit used', 2, function(){ var hb = $.createHeartBeater({ heartBeatInterval: 20, }); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'Check the status is running'); equal(hb.getHeartBeatsRemaining(), false, 'Check remaining counter returns false'); }); test('Test disabled autostart', function(){ var hb = $.createHeartBeater({autoStart:false}); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_PAUSED, 'Check status is paused after creation.'); hb.start(); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'Check status is running after start.'); }); test('Test parameter validation', function(){ throws(function(){new $.Acheta.HeartBeater({checkUserActivity: true}, 'fakeUserChecker');}, /Instance of UserActivityChecker is required/ , 'Validate user checker object' ); throws(function(){new $.Acheta.HeartBeater({heartBeatInterval: 0}, $.createUserActivityChecker(100));}, /HeartBeatInterval must be a number greater than zero/ , 'Validate heart beat interval.' ); throws(function(){new $.Acheta.HeartBeater({limit: 'None'}, $.createUserActivityChecker(100));}, /Limit must be a number greater or equal to zero/ , 'Validate limit.' ); throws(function(){new $.Acheta.HeartBeater({checkUserActivity: true, checkUserActivityInterval: 0}, $.createUserActivityChecker(100));}, /User activity check interval must be greater than zero/ , 'Validate user activity check interval.' ); throws(function(){new $.Acheta.UserActivityChecker(100, 'fakeDoc');}, /Document must be an object/ , 'Validate document is an object.' ); throws(function(){new $.Acheta.UserActivityChecker(100, {});}, /Document must be an object/ , 'Validate document is an object with hasFocus function.' ); }); module('Events tests'); asyncTest('Test user became active', 2, function(){ var mockDocument = { focus: false, hasFocus: function(){return this.focus} }; var checker = $.createUserActivityChecker(100, mockDocument); var hb = $.createHeartBeater({ heartBeatInterval: 2000, checkUserActivity: true, checkUserActivityInterval: 100, }, checker); $(hb).on($.Acheta.UserActivityChecker.EVENT_USER_BECAME_ACTIVE, function(){ ok(true, 'Event triggered'); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_RUNNING, 'HB is running.'); start(); }); mockDocument.focus = true; }); asyncTest('Test user became inactive', 2, function(){ var mockDocument = { focus: true, hasFocus: function(){return this.focus} }; var checker = $.createUserActivityChecker(100, mockDocument); var hb = $.createHeartBeater({ heartBeatInterval: 2000, checkUserActivity: true, checkUserActivityInterval: 100, }, checker); $(hb).on($.Acheta.UserActivityChecker.EVENT_USER_BECAME_INACTIVE, function(){ ok(true, 'Event triggered'); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_INACTIVE, 'HB is inactive.'); start(); }); mockDocument.focus = false; }); asyncTest('Test basic heart beat', 1, function(){ var hb = $.createHeartBeater({ heartBeatInterval: 100, checkUserActivity: false }); $(hb).on($.Acheta.HeartBeater.EVENT_HEARTBEAT , function(){ ok(true, 'Event triggered'); hb.pause(); start(); }); }); test('Test limited heart beats', function(){ var limit = 10; // Increase number of assertions. stop(limit+1); var hb = $.createHeartBeater({ heartBeatInterval: 10, checkUserActivity: false, limit: limit, autoStart: false }); $(hb).on($.Acheta.HeartBeater.EVENT_HEARTBEAT, function(){ ok(true, 'Beat '+hb.getHeartBeatsCount()+' triggered'); equal(limit - hb.getHeartBeatsCount(), hb.getHeartBeatsRemaining(), 'Check math limit '+limit+' - beatsCount '+hb.getHeartBeatsCount()+ ' = remaining '+ hb.getHeartBeatsRemaining()); start(); }); $(hb).on($.Acheta.HeartBeater.EVENT_HEARTBEAT_LIMIT_REACHED, function(){ ok(true, 'HeartBeatLimitReached Event triggered'); equal(hb.getHeartBeatsCount() + hb.getHeartBeatsRemaining(), limit, 'Check count + remaining = limit'); equal(hb.getHeartBeatsRemaining(), 0, 'Zero beats remaining'); start(); }); hb.start(); }); asyncTest('Test limited heart beats with user activity', function(){ var limit = 10; var mockDocument = { focus: true, hasFocus: function(){return this.focus} }; var checker = $.createUserActivityChecker(10, mockDocument); // Increase number of assertions. User will become inactive after 5 beats. stop(5); var hb = $.createHeartBeater({ heartBeatInterval: 20, checkUserActivity: true, checkUserActivityInterval: 10, limit: limit, autoStart: false }, checker); $(hb).on($.Acheta.HeartBeater.EVENT_HEARTBEAT, function(e){ ok(true, 'Beat '+hb.getHeartBeatsCount()+' triggered'); start(); if(hb.getHeartBeatsCount() == 5) { mockDocument.focus = false; } }); hb.start(); setTimeout(function(){ equal(hb.getHeartBeatsCount(), 5); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_INACTIVE); hb.pause(); equal(hb.getStatus(), $.Acheta.HeartBeater.STATUS_PAUSED); start(); }, 200); });
'use strict' const { expect } = require('chai'); const { execSync } = require('child_process'); describe('cal', () => { describe('CLI', () => { it('should handle the current month', () => { const goal = execSync('cal').toString(); const output = execSync('./cal.js').toString(); expect(output).to.equal(goal); }); }); describe('March 4301', () => { it('Computer Cal should equal my Cal', () => { const goal = execSync('cal 3 4301').toString(); const output = execSync('./cal.js 3 4301').toString(); expect(output).to.equal(goal); }); }); describe('August 1879', () => { it('Computer Cal should equal my Cal', () => { const goal = execSync('cal 8 1879').toString(); const output = execSync('./cal.js 8 1879').toString(); expect(output).to.equal(goal); }); }); describe('February 1872', () => { it('Computer Cal should equal my Cal', () => { const goal = execSync('cal 2 1872').toString(); const output = execSync('./cal.js 2 1872').toString(); expect(output).to.equal(goal); }); }); describe('April 1923', () => { it('Computer Cal should equal my Cal', () => { const goal = execSync('cal 4 1923').toString(); const output = execSync('./cal.js 4 1923').toString(); expect(output).to.equal(goal); }); }); describe('November 2015', () => { it('Computer Cal should equal my Cal', () => { const goal = execSync('cal 11 2015').toString(); const output = execSync('./cal.js 11 2015').toString(); expect(output).to.equal(goal); }); }); }); describe("Zeller's congruence", () => { const zellers = require('../zellers.js'); describe("Modified month", () => { it('returns 13 for January', () => { expect(zellers.modifiedMonth(1)).to.equal(13); expect(zellers.modifiedMonth(2)).to.equal(14); expect(zellers.modifiedMonth(3)).to.equal(3); }); }); describe('.modifiedYear', () => { it('returns 2015 for Jan 2014', () => { expect(zellers.modifiedYear(2015, 1)).to.equal(2014); expect(zellers.modifiedYear(2016, 2)).to.equal(2015); expect(zellers.modifiedYear(2017, 3)).to.equal(2017); }); }); describe('.getDay', () => { it('returns 0 (Starts on Saturday) for October 1, 2016', () => { expect(zellers.getDay(2016, 10, 1)).to.equal(0); }); }); describe('.getDay', () => { it('returns 0 (Starts on Saturday) for March 1, 2014', () => { expect(zellers.getDay(2016, 10, 1)).to.equal(0); }); }); describe('.getDay', () => { it('returns 1 (Starts on Sunday) for Jan 1, 2017', () => { expect(zellers.getDay(2017, 1, 1)).to.equal(1); }); }); describe('.getDay', () => { it('returns 2 (Starts on Monday) for March 1, 2100', () => { expect(zellers.getDay(2100, 3, 1)).to.equal(2); }); }); describe('.getDay', () => { it('returns 2 (Starts on Monday) for Feb 1, 2016', () => { expect(zellers.getDay(2016, 2, 1)).to.equal(2); }); }); describe('.getDay', () => { it('returns 3 (Start on Tuesday) for March 1, 2016', () => { expect(zellers.getDay(2016, 3, 1)).to.equal(3); }); }); describe('.getDay', () => { it('returns 4 (Starts on Wednesday) for March 1, 2000', () => { expect(zellers.getDay(2000, 3, 1)).to.equal(4); }); }); describe('.getDay', () => { it('returns 5 (Starts on Thursday) for March 1, 2300', () => { expect(zellers.getDay(2300, 3, 1)).to.equal(5); }); }); describe('.getDay', () => { it('returns 5 (Starts on Thursday) for Feb 1, 2032', () => { expect(zellers.getDay(2012, 3, 1)).to.equal(5); }); }); describe('.getDay', () => { it('returns 6 (Starts on Friday) for Jan 1, 2016', () => { expect(zellers.getDay(2016, 1, 1)).to.equal(6); }); }); }); describe("Is it a leap year?", () => { const zellers = require('../zellers.js'); describe(".isLeapYear", () => { it('testing 2016', () => { expect(zellers.isLeapYear(2016)).to.be.true; }); }); describe(".isLeapYear", () => { it('testing 2032', () => { expect(zellers.isLeapYear(2032)).to.be.true; }); }); describe(".isLeapYear", () => { it('testing 2017', () => { expect(zellers.isLeapYear(2017)).to.be.false; }); }); describe(".isLeapYear", () => { it('testing 2101', () => { expect(zellers.isLeapYear(2017)).to.be.false; }); }); }); //describe('.center', () => { //it('should handle January', () => { //expect(center('January 2016')).to.equal(' January 2016'); //}); //});
define([ 'ractive', 'viewmodel/Viewmodel', 'virtualdom/Fragment', 'virtualdom/items/Element/_Element', 'virtualdom/items/Triple/_Triple', 'config/types' ], function ( Ractive, Viewmodel, Fragment, Element, Triple, types ) { 'use strict'; return function () { var fixture; module( 'rebind' ); // some set-up fixture = document.getElementById( 'qunit-fixture' ); function contextUpdate(opt){ test( 'update context path: ' + opt.test, function ( t ) { var resolved, fragment, el, triple; fragment = { context: opt.target, items: [], root: { '_liveQueries': [], '_deps': [] , '_depsMap': [], '_cache': [], '_computations': [], '_wrapped': [], '_evaluators': [], el: { namespaceURI: 'http://www.w3.org/1999/xhtml' }, adapt: [] }, indexRefs: { i: opt.oldKeypath.replace('items.','')} }; fragment.root.viewmodel = new Viewmodel( fragment.root ); el = new Element({ parentFragment: fragment, template: { e: 'div' } }); triple = new Triple({ parentFragment: fragment, template: { t: types.TRIPLE, r: '.' } }); triple.resolve = function(keypath){ resolved = keypath }; fragment.items.push(el, triple); fragment.render = Fragment.prototype.render; fragment.rebind = Fragment.prototype.rebind; fragment.bubble = Fragment.prototype.bubble; fragment.getNode = function () { return fixture; }; fragment.findNextNode = function () { return null; }; fragment.render(); fragment.rebind( 'i', opt.newKeypath.replace('items.',''), opt.oldKeypath, opt.newKeypath); t.equal( fragment.context, opt.expected ); t.equal( fragment.items[0].node._ractive.keypath, opt.expected ); if(opt.target!==opt.newKeypath){ t.equal( resolved, opt.expected ); } t.htmlEqual( fixture.innerHTML, '' ); }); } contextUpdate({ test: 'exact match replace', target: 'items.11', oldKeypath: 'items.11', newKeypath: 'items.21', expected: 'items.21' }); contextUpdate({ test: 'partial replace', target: 'items.1.foo', oldKeypath: 'items.1', newKeypath: 'items.11', expected: 'items.11.foo' }); contextUpdate({ test: 'overlapping replace', target: 'items.11', oldKeypath: 'items.1', newKeypath: 'items.11', expected: 'items.11' }); test('Section with item that has expression only called once when created', function(t){ var called = 0, ractive = new Ractive({ el: fixture, template: '{{#items}}{{format(.)}}{{/items}}', data: { items: [], format: function(){ called++; } } }); ractive.get('items').push('item'); t.equal( called, 1 ); }) test('Section with item indexRef expression changes correctly', function(t){ var ractive = new Ractive({ el: fixture, template: '{{#items:i}}{{format(.,i)}},{{/items}}', data: { items: [1,2,3,4,5], format: function(x,i){ return x+i; } } }); t.htmlEqual( fixture.innerHTML, '1,3,5,7,9,'); var items = ractive.get('items'); items.splice(1,2,10); t.deepEqual(items, [1,10,4,5]); t.htmlEqual( fixture.innerHTML, '1,11,6,8,'); }) test('Section updates child keypath expression', function(t){ var ractive = new Ractive({ el: fixture, template: '{{#items:i}}{{foo[bar]}},{{/}}', data: { bar: 'name', items: [ { foo: { name: 'bob' } }, { foo: { name: 'bill' } }, { foo: { name: 'betty' } } ] } }); t.htmlEqual( fixture.innerHTML, 'bob,bill,betty,'); var items = ractive.get('items'); items.splice(1,2, { foo: { name: 'jill' } } ); t.htmlEqual( fixture.innerHTML, 'bob,jill,'); }) test('Section with nested sections and inner context does splice()', function(t){ var template = '{{#model:i}}{{#thing}}' + '{{# .inner.length > 1}}' + '<p>{{{format(inner)}}}</p>' + '{{/ inner}}' + '{{/thing}}{{/model}}' var called = 0 var ractive = new Ractive({ el: fixture, template: template, data: { model: [ { thing: { inner: [3,4] } } ], format: function(a){ called++; return a; } } }); t.htmlEqual( fixture.innerHTML, '<p>3,4</p>'); ractive.get('model').splice(0, 0, {thing: {inner: [1,2]}}); t.htmlEqual( fixture.innerHTML, '<p>1,2</p><p>3,4</p>'); }) test( 'Components in a list can be rebound', function ( t ) { var ractive = new Ractive({ el: fixture, template: '{{#items}}<widget letter="{{.}}"/>{{/items}}', data: { items: [ 'a', 'b', 'c' ] }, components: { widget: Ractive.extend({ template: '<p>{{letter}}</p>' }) } }); t.htmlEqual( fixture.innerHTML, '<p>a</p><p>b</p><p>c</p>' ); ractive.get( 'items' ).splice( 1, 1 ); t.htmlEqual( fixture.innerHTML, '<p>a</p><p>c</p>' ); ractive.set( 'items[0]', 'd' ); ractive.set( 'items[1]', 'e' ); t.htmlEqual( fixture.innerHTML, '<p>d</p><p>e</p>' ); }); test( 'Index references can be used as key attributes on components, and rebinding works', function ( t ) { var ractive = new Ractive({ el: fixture, template: '{{#items:i}}<widget index="{{i}}" letter="{{.}}"/>{{/items}}', data: { items: [ 'a', 'b', 'c' ] }, components: { widget: Ractive.extend({ template: '<p>{{index}}: {{letter}}</p>' }) } }); t.htmlEqual( fixture.innerHTML, '<p>0: a</p><p>1: b</p><p>2: c</p>' ); ractive.get( 'items' ).splice( 1, 1 ); t.htmlEqual( fixture.innerHTML, '<p>0: a</p><p>1: c</p>' ); }); test('Section with partials that use indexRef update correctly', function(t){ var ractive = new Ractive({ el: fixture, template: '{{#items:i}}{{>partial}},{{/items}}', partials: { partial: '{{i}}' }, data: { items: [1,2,3,4,5] } }); t.htmlEqual( fixture.innerHTML, '0,1,2,3,4,'); var items = ractive.get('items'); items.splice(1,2,10); t.deepEqual(items, [1,10,4,5]); t.htmlEqual( fixture.innerHTML, '0,1,2,3,'); }) test( 'Expressions with unresolved references can be rebound (#630)', function ( t ) { var ractive = new Ractive({ el: fixture, template: '{{#list}}{{#check > length}}true{{/test}}{{/list}}', data: {list:[1,2], check:3} }); ractive.get('list').unshift(3); t.ok(true); }); test( 'Regression test for #697', function ( t ) { var ractive = new Ractive({ el: fixture, template: '{{#model}}{{#thing}}{{# foo && bar }}<p>works</p>{{/inner}}{{/thing}}{{/model}}', data: { model: [{ thing: { bar: true }, foo: true }] } }); ractive.get('model').unshift({ thing: { bar: true }, foo: false }); t.ok( true ); }); test( 'Regression test for #715', function ( t ) { var ractive = new Ractive({ el: fixture, template: '{{#items}}{{#test}}{{# .entries > 1 }}{{{ foo }}}{{/ .entries }}{{/test}}{{/items}}', data: { items: [ {test: [{"entries": 2}]}, {test: [{}]} ], foo: 'bar' } }); ractive.get( 'items' ).unshift({}); t.ok( true ); }); test( 'Items are not unrendered and rerendered unnecessarily in cases like #715', function ( t ) { var ractive, renderCount = 0, unrenderCount = 0; ractive = new Ractive({ el: fixture, template: '{{#items}}{{#test}}{{# .entries > 1 }}<p intro="rendered" outro="unrendered">foo</p>{{/ .entries }}{{/test}}{{/items}}', data: { items: [ {test: [{"entries": 2}]}, {test: [{}]} ], foo: 'bar' }, transitions: { rendered: function () { renderCount += 1; }, unrendered: function () { unrenderCount += 1; } } }); t.equal( renderCount, 1 ); t.equal( unrenderCount, 0 ); ractive.get( 'items' ).unshift({}); t.equal( renderCount, 1 ); t.equal( unrenderCount, 0 ); }); test( 'Regression test for #729 (part one) - rebinding silently-created elements', function ( t ) { var items, ractive; items = [{test: { bool: false }}]; ractive = new Ractive({ el: fixture, template: '{{#items}}{{#test}}{{#bool}}<p>true</p>{{/bool}}{{^bool}}<p>false</p>{{/bool}}{{/test}}{{/items}}', data: { items: items } }); items[0].test = { bool: true }; items.unshift({}); t.ok( true ); }); test( 'Regression test for #729 (part two) - inserting before silently-created elements', function ( t ) { var items, ractive; items = []; ractive = new Ractive({ el: fixture, template: '{{#items}}{{#bool}}{{{foo}}}{{/bool}}{{/items}}', data: { items: items } }); ractive.set('items.0', {bool: false}); items[0].bool = true; items.unshift({}); t.ok( true ); }); test( 'Regression test for #756 - fragment contexts are not rebound to undefined', function ( t ) { var ractive, new_items; ractive = new Ractive({ el: fixture, template: ` {{#items}} <div class="{{foo?'foo':''}}"> {{#test}}{{# .list.length === 1 }}[ {{list.0.thing}} ]{{/ .list.length }}{{/test}} </div> {{/items}}`, data: { items:[{},{}] } }); new_items = [{"test":{"list":[{"thing":"Z"},{"thing":"Z"}]},"foo":false}, {"test":{"list":[{"thing":"Z"},{"thing":"Z"}]},"foo":false}] ractive.set('items', new_items) new_items[1].test = {"list":[{"thing":"Z"}]} ractive.update(); t.htmlEqual( fixture.innerHTML, '<div class></div><div class>[ Z ]</div>' ); }); }; });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.lang['sr'] = { "dir": "ltr", "editor": "Rich Text Editor", "common": { "editorHelp": "Press ALT 0 for help", "browseServer": "Претражи сервер", "url": "УРЛ", "protocol": "Протокол", "upload": "Пошаљи", "uploadSubmit": "Пошаљи на сервер", "image": "Слика", "flash": "Флеш елемент", "form": "Форма", "checkbox": "Поље за потврду", "radio": "Радио-дугме", "textField": "Текстуално поље", "textarea": "Зона текста", "hiddenField": "Скривено поље", "button": "Дугме", "select": "Изборно поље", "imageButton": "Дугме са сликом", "notSet": "<није постављено>", "id": "Ид", "name": "Назив", "langDir": "Смер језика", "langDirLtr": "С лева на десно (LTR)", "langDirRtl": "С десна на лево (RTL)", "langCode": "Kôд језика", "longDescr": "Пун опис УРЛ", "cssClass": "Stylesheet класе", "advisoryTitle": "Advisory наслов", "cssStyle": "Стил", "ok": "OK", "cancel": "Oткажи", "close": "Затвори", "preview": "Изглед странице", "resize": "Resize", "generalTab": "Опште", "advancedTab": "Напредни тагови", "validateNumberFailed": "Ова вредност није цигра.", "confirmNewPage": "Any unsaved changes to this content will be lost. Are you sure you want to load new page?", "confirmCancel": "Some of the options have been changed. Are you sure to close the dialog?", "options": "Опције", "target": "Meтa", "targetNew": "New Window (_blank)", "targetTop": "Topmost Window (_top)", "targetSelf": "Same Window (_self)", "targetParent": "Parent Window (_parent)", "langDirLTR": "С лева на десно (LTR)", "langDirRTL": "С десна на лево (RTL)", "styles": "Стил", "cssClasses": "Stylesheet класе", "width": "Ширина", "height": "Висина", "align": "Равнање", "alignLeft": "Лево", "alignRight": "Десно", "alignCenter": "Средина", "alignTop": "Врх", "alignMiddle": "Средина", "alignBottom": "Доле", "invalidValue": "Invalid value.", "invalidHeight": "Height must be a number.", "invalidWidth": "Width must be a number.", "invalidCssLength": "Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).", "invalidHtmlLength": "Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).", "invalidInlineStyle": "Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.", "cssLengthTooltip": "Enter a number for a value in pixels or a number with a valid CSS unit (px, %, in, cm, mm, em, ex, pt, or pc).", "unavailable": "%1<span class=\"cke_accessibility\">, unavailable</span>" }, "about": { "copy": "Copyright &copy; $1. All rights reserved.", "dlgTitle": "About CKEditor", "help": "Check $1 for help.", "moreInfo": "For licensing information please visit our web site:", "title": "About CKEditor", "userGuide": "CKEditor User's Guide" }, "basicstyles": { "bold": "Подебљано", "italic": "Курзив", "strike": "Прецртано", "subscript": "Индекс", "superscript": "Степен", "underline": "Подвучено" }, "blockquote": {"toolbar": "Block Quote"}, "clipboard": { "copy": "Копирај", "copyError": "Сигурносна подешавања Вашег претраживача не дозвољавају операције аутоматског копирања текста. Молимо Вас да користите пречицу са тастатуре (Ctrl/Cmd+C).", "cut": "Исеци", "cutError": "Сигурносна подешавања Вашег претраживача не дозвољавају операције аутоматског исецања текста. Молимо Вас да користите пречицу са тастатуре (Ctrl/Cmd+X).", "paste": "Залепи", "pasteArea": "Залепи зону", "pasteMsg": "Молимо Вас да залепите унутар доње површине користећи тастатурну пречицу (<STRONG>Ctrl/Cmd+V</STRONG>) и да притиснете <STRONG>OK</STRONG>.", "securityMsg": "Због сигурносних подешавања претраживача, едитор не може да приступи оставу. Требате да га поново залепите у овом прозору.", "title": "Залепи" }, "contextmenu": {"options": "Context Menu Options"}, "toolbar": { "toolbarCollapse": "Склопи алатну траку", "toolbarExpand": "Прошири алатну траку", "toolbarGroups": { "document": "Document", "clipboard": "Clipboard/Undo", "editing": "Editing", "forms": "Forms", "basicstyles": "Basic Styles", "paragraph": "Paragraph", "links": "Links", "insert": "Insert", "styles": "Styles", "colors": "Colors", "tools": "Tools" }, "toolbars": "Едитор алатне траке" }, "elementspath": {"eleLabel": "Elements path", "eleTitle": "%1 element"}, "format": { "label": "Формат", "panelTitle": "Формат", "tag_address": "Adresa", "tag_div": "Нормално (DIV)", "tag_h1": "Heading 1", "tag_h2": "Heading 2", "tag_h3": "Heading 3", "tag_h4": "Heading 4", "tag_h5": "Heading 5", "tag_h6": "Heading 6", "tag_p": "Normal", "tag_pre": "Formatirano" }, "horizontalrule": {"toolbar": "Унеси хоризонталну линију"}, "image": { "alertUrl": "Унесите УРЛ слике", "alt": "Алтернативни текст", "border": "Оквир", "btnUpload": "Пошаљи на сервер", "button2Img": "Да ли желите да промените одабрану слику дугмета као једноставну слику?", "hSpace": "HSpace", "img2Button": "Да ли желите да промените одабрану слику у слику дугмета?", "infoTab": "Инфо слике", "linkTab": "Линк", "lockRatio": "Закључај однос", "menu": "Особине слика", "resetSize": "Ресетуј величину", "title": "Особине слика", "titleButton": "Особине дугмета са сликом", "upload": "Пошаљи", "urlMissing": "Недостаје УРЛ слике.", "vSpace": "VSpace", "validateBorder": "Ивица треба да буде цифра.", "validateHSpace": "HSpace треба да буде цифра.", "validateVSpace": "VSpace треба да буде цифра." }, "indent": {"indent": "Увећај леву маргину", "outdent": "Смањи леву маргину"}, "fakeobjects": { "anchor": "Anchor", "flash": "Flash Animation", "hiddenfield": "Hidden Field", "iframe": "IFrame", "unknown": "Unknown Object" }, "link": { "acccessKey": "Приступни тастер", "advanced": "Напредни тагови", "advisoryContentType": "Advisory врста садржаја", "advisoryTitle": "Advisory наслов", "anchor": { "toolbar": "Унеси/измени сидро", "menu": "Особине сидра", "title": "Особине сидра", "name": "Име сидра", "errorName": "Молимо Вас да унесете име сидра", "remove": "Remove Anchor" }, "anchorId": "Пo Ид-jу елемента", "anchorName": "По називу сидра", "charset": "Linked Resource Charset", "cssClasses": "Stylesheet класе", "emailAddress": "Адреса електронске поште", "emailBody": "Садржај поруке", "emailSubject": "Наслов", "id": "Ид", "info": "Линк инфо", "langCode": "Смер језика", "langDir": "Смер језика", "langDirLTR": "С лева на десно (LTR)", "langDirRTL": "С десна на лево (RTL)", "menu": "Промени линк", "name": "Назив", "noAnchors": "(Нема доступних сидра)", "noEmail": "Откуцајте адресу електронске поште", "noUrl": "Унесите УРЛ линка", "other": "<друго>", "popupDependent": "Зависно (Netscape)", "popupFeatures": "Могућности искачућег прозора", "popupFullScreen": "Приказ преко целог екрана (ИE)", "popupLeft": "Од леве ивице екрана (пиксела)", "popupLocationBar": "Локација", "popupMenuBar": "Контекстни мени", "popupResizable": "Величина се мења", "popupScrollBars": "Скрол бар", "popupStatusBar": "Статусна линија", "popupToolbar": "Toolbar", "popupTop": "Од врха екрана (пиксела)", "rel": "Однос", "selectAnchor": "Одабери сидро", "styles": "Стил", "tabIndex": "Таб индекс", "target": "Meтa", "targetFrame": "<оквир>", "targetFrameName": "Назив одредишног фрејма", "targetPopup": "<искачући прозор>", "targetPopupName": "Назив искачућег прозора", "title": "Линк", "toAnchor": "Сидро на овој страници", "toEmail": "Eлектронска пошта", "toUrl": "УРЛ", "toolbar": "Унеси/измени линк", "type": "Врста линка", "unlink": "Уклони линк", "upload": "Пошаљи" }, "list": {"bulletedlist": "Ненабројива листа", "numberedlist": "Набројиву листу"}, "magicline": {"title": "Insert paragraph here"}, "maximize": {"maximize": "Maximize", "minimize": "Minimize"}, "pastetext": {"button": "Залепи као чист текст", "title": "Залепи као чист текст"}, "pastefromword": { "confirmCleanup": "The text you want to paste seems to be copied from Word. Do you want to clean it before pasting?", "error": "It was not possible to clean up the pasted data due to an internal error", "title": "Залепи из Worda", "toolbar": "Залепи из Worda" }, "removeformat": {"toolbar": "Уклони форматирање"}, "sourcearea": {"toolbar": "Kôд"}, "specialchar": { "options": "Опције специјалног карактера", "title": "Одаберите специјални карактер", "toolbar": "Унеси специјални карактер" }, "scayt": { "about": "About SCAYT", "aboutTab": "About", "addWord": "Add Word", "allCaps": "Ignore All-Caps Words", "dic_create": "Create", "dic_delete": "Delete", "dic_field_name": "Dictionary name", "dic_info": "Initially the User Dictionary is stored in a Cookie. However, Cookies are limited in size. When the User Dictionary grows to a point where it cannot be stored in a Cookie, then the dictionary may be stored on our server. To store your personal dictionary on our server you should specify a name for your dictionary. If you already have a stored dictionary, please type its name and click the Restore button.", "dic_rename": "Rename", "dic_restore": "Restore", "dictionariesTab": "Dictionaries", "disable": "Disable SCAYT", "emptyDic": "Dictionary name should not be empty.", "enable": "Enable SCAYT", "ignore": "Ignore", "ignoreAll": "Ignore All", "ignoreDomainNames": "Ignore Domain Names", "langs": "Languages", "languagesTab": "Languages", "mixedCase": "Ignore Words with Mixed Case", "mixedWithDigits": "Ignore Words with Numbers", "moreSuggestions": "More suggestions", "opera_title": "Not supported by Opera", "options": "Options", "optionsTab": "Options", "title": "Spell Check As You Type", "toggle": "Toggle SCAYT", "noSuggestions": "No suggestion" }, "stylescombo": { "label": "Стил", "panelTitle": "Formatting Styles", "panelTitle1": "Block Styles", "panelTitle2": "Inline Styles", "panelTitle3": "Object Styles" }, "table": { "border": "Величина оквира", "caption": "Наслов табеле", "cell": { "menu": "Cell", "insertBefore": "Insert Cell Before", "insertAfter": "Insert Cell After", "deleteCell": "Обриши ћелије", "merge": "Спој ћелије", "mergeRight": "Merge Right", "mergeDown": "Merge Down", "splitHorizontal": "Split Cell Horizontally", "splitVertical": "Split Cell Vertically", "title": "Cell Properties", "cellType": "Cell Type", "rowSpan": "Rows Span", "colSpan": "Columns Span", "wordWrap": "Word Wrap", "hAlign": "Horizontal Alignment", "vAlign": "Vertical Alignment", "alignBaseline": "Baseline", "bgColor": "Background Color", "borderColor": "Border Color", "data": "Data", "header": "Header", "yes": "Yes", "no": "No", "invalidWidth": "Cell width must be a number.", "invalidHeight": "Cell height must be a number.", "invalidRowSpan": "Rows span must be a whole number.", "invalidColSpan": "Columns span must be a whole number.", "chooseColor": "Choose" }, "cellPad": "Размак ћелија", "cellSpace": "Ћелијски простор", "column": { "menu": "Column", "insertBefore": "Insert Column Before", "insertAfter": "Insert Column After", "deleteColumn": "Обриши колоне" }, "columns": "Kолона", "deleteTable": "Обриши таблу", "headers": "Поглавља", "headersBoth": "Оба", "headersColumn": "Прва колона", "headersNone": "None", "headersRow": "Први ред", "invalidBorder": "Величина ивице треба да буде цифра.", "invalidCellPadding": "Пуњење ћелије треба да буде позитивна цифра.", "invalidCellSpacing": "Размак ћелије треба да буде позитивна цифра.", "invalidCols": "Број колона треба да буде цифра већа од 0.", "invalidHeight": "Висина табеле треба да буде цифра.", "invalidRows": "Број реда треба да буде цифра већа од 0.", "invalidWidth": "Ширина табеле треба да буде цифра.", "menu": "Особине табеле", "row": { "menu": "Row", "insertBefore": "Insert Row Before", "insertAfter": "Insert Row After", "deleteRow": "Обриши редове" }, "rows": "Редова", "summary": "Резиме", "title": "Особине табеле", "toolbar": "Табела", "widthPc": "процената", "widthPx": "пиксела", "widthUnit": "јединица ширине" }, "undo": {"redo": "Понови акцију", "undo": "Поништи акцију"}, "wsc": { "btnIgnore": "Игнориши", "btnIgnoreAll": "Игнориши све", "btnReplace": "Замени", "btnReplaceAll": "Замени све", "btnUndo": "Врати акцију", "changeTo": "Измени", "errorLoading": "Error loading application service host: %s.", "ieSpellDownload": "Провера спеловања није инсталирана. Да ли желите да је скинете са Интернета?", "manyChanges": "Провера спеловања завршена: %1 реч(и) је измењено", "noChanges": "Провера спеловања завршена: Није измењена ниједна реч", "noMispell": "Провера спеловања завршена: грешке нису пронађене", "noSuggestions": "- Без сугестија -", "notAvailable": "Sorry, but service is unavailable now.", "notInDic": "Није у речнику", "oneChange": "Провера спеловања завршена: Измењена је једна реч", "progress": "Провера спеловања у току...", "title": "Spell Check", "toolbar": "Провери спеловање" } };
'use strict' /** * Exposes the apv APIs for the automation. */ exports.update = require('./lib/update').update exports.setVersion = require('./lib/set').setVersion exports.setStatus = require('./lib/set').setStatus
// jshint esversion: 6 import * as THREE from '../../../../../lib/threejs_125/build/three.module.js'; import { GUI } from '../../../../../lib/threejs_125/examples/jsm/libs/dat.gui.module.js'; import { OrbitControls } from '../../../../../lib/threejs_125/examples/jsm/controls/OrbitControls.js'; (function(window) { let config = { 'CAMERA_FOV': 70, 'CAMERA_NEAR_PLANE': 0.1, 'CAMERA_FAR_PLANE': 500 }; let properties = { 'fogColor': '#FFFFFF', 'fogNear': 0.1, 'fogFar': 35, 'cubePositionX': 0, 'cubePositionY': 0, 'cubePositionZ': 0, 'cubeRotationX': 0, 'cubeRotationY': 0, 'cubeRotationZ': 0, 'cubeScaleX': 1, 'cubeScaleY': 1, 'cubeScaleZ': 1 }; let Main = function(canvas) { this.canvas = canvas; this.camera = null; this.controls = null; this.gui = null; this.renderer = null; this.scene = null; this.hemisphereLight = null; this.cube = null; this.plane = null; }; Main.prototype.init = function() { this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(config.CAMERA_FOV, this.getCameraAspect(), config.CAMERA_NEAR_PLANE, config.CAMERA_FAR_PLANE); this.camera.position.set(0, 10, 20); this.renderer = new THREE.WebGLRenderer({antialias: true}); this.renderer.setClearColor(0x000000, 1); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.setSize(this.getCanvasWidth(), this.getCanvasHeight()); this.controls = new OrbitControls(this.camera, this.renderer.domElement); this.gui = new GUI({ width: 400 }); this.gui.close(); // add renderer to the DOM-Tree this.canvas.appendChild(this.renderer.domElement); window.addEventListener('resize', this.onResizeHandler.bind(this), false); this.createGui(); this.createFog(); this.createObject(); this.createLight(); this.render(); }; Main.prototype.createFog = function() { this.scene.fog = new THREE.Fog( properties.fogColor, properties.fogNear, properties.fogFar ); }; Main.prototype.createObject = function() { this.plane = new THREE.Mesh( new THREE.PlaneGeometry(50, 50, 50, 50), new THREE.MeshPhongMaterial( { color: 0xAAAAAA, side: THREE.DoubleSide } ) ); this.plane.rotation.x = Math.PI / 2; this.scene.add(this.plane); this.cube = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1, 1, 1, 1), new THREE.MeshPhongMaterial( { color: 0xFFFFFF } ) ); this.scene.add(this.cube); }; Main.prototype.createGui = function() { let self = this; let folderProperties = this.gui.addFolder('Fog Properties'); folderProperties.addColor(properties, 'fogColor').onChange(function(value) { self.scene.fog.color.set(value); }); folderProperties.add(properties, 'fogNear', 0.1, 50).step(0.1).onChange(function(value) { self.scene.fog.near = value; }); folderProperties.add(properties, 'fogFar', 0.1, 50).step(0.1).onChange(function(value) { self.scene.fog.far = value; }); let folderTransformation = this.gui.addFolder('Cube Transformation'); folderTransformation.add(properties, 'cubePositionX', -10, 10).step(0.1).onChange(function(value) { self.cube.position.x = value; }); folderTransformation.add(properties, 'cubePositionY', -10, 10).step(0.1).onChange(function(value) { self.cube.position.y = value; }); folderTransformation.add(properties, 'cubePositionZ', -10, 10).step(0.1).onChange(function(value) { self.cube.position.z = value; }); folderTransformation.add(properties, 'cubeRotationX', 0, 2*Math.PI).step(0.01).onChange(function(value) { self.cube.rotation.x = value; }); folderTransformation.add(properties, 'cubeRotationY', 0, 2*Math.PI).step(0.01).onChange(function(value) { self.cube.rotation.y = value; }); folderTransformation.add(properties, 'cubeRotationZ', 0, 2*Math.PI).step(0.01).onChange(function(value) { self.cube.rotation.z = value; }); folderTransformation.add(properties, 'cubeScaleX', 0.1, 10).step(0.1).onChange(function(value) { self.cube.scale.x = value; }); folderTransformation.add(properties, 'cubeScaleY', 0.1, 10).step(0.1).onChange(function(value) { self.cube.scale.y = value; }); folderTransformation.add(properties, 'cubeScaleZ', 0.1, 10).step(0.1).onChange(function(value) { self.cube.scale.z = value; }); }; Main.prototype.createLight = function() { this.hemisphereLight = new THREE.HemisphereLight(0xDDEEFF, 0x0F0E0D, 0.5); this.scene.add(this.hemisphereLight); }; Main.prototype.render = function() { requestAnimationFrame(this.render.bind(this)); this.renderer.render(this.scene, this.camera); }; Main.prototype.getCanvasHeight = function() { return this.canvas.offsetHeight; }; Main.prototype.getCanvasWidth = function() { return this.canvas.offsetWidth; }; Main.prototype.getCameraAspect = function() { return this.getCanvasWidth() / this.getCanvasHeight(); }; Main.prototype.onResizeHandler = function(event) { this.camera.aspect = this.getCameraAspect(); this.camera.updateProjectionMatrix(); this.renderer.setSize(this.getCanvasWidth(), this.getCanvasHeight()); }; let main = new Main(document.getElementById('webGlCanvas')); document.addEventListener('DOMContentLoaded', function() { main.init(); }); }(window));
var RPCLib = require('rpclib'), SkyRPCClient = require('skyrpcclient'), authClient = new SkyRPCClient('auth-api.services.example'), Log = require('modulelog')('robthebuilder'); module.exports = function(rpc) { rpc.setPreProcessor(function(request, response) { if (!request.params || !request.params.hasOwnProperty('userID')) { return; } //if they already passed a user then don't fetch one if (request.params.params && request.params.params.hasOwnProperty('user')) { return; } Log.debug('calling User.GetUserByID', {userID: request.params.userID}); return new Promise(function(resolve) { authClient.call('User.GetUserByID', {userID: request.params.userID}, function(err, res) { if (err) { Log.error('Error from User.GetUserByID', err); if (err.code === -2) { response.reject(1, 'User not found'); } else { response.reject(RPCLib.ERROR_INTERNAL_ERROR); } } else { response.set('user', res); } //always resolve since we are rejecting the response above if it actually failed resolve(res); }).setTimeout(5000); }); }); };
var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; (function (global, factory) { typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory(require("backbone"), require("cookies-js")) : typeof define === "function" && define.amd ? define(["backbone", "cookies-js"], factory) : global.SimpleAuth = factory(global.Backbone, global.cookies); })(this, function (Backbone, cookies) { "use strict"; var SimpleAuth = (function (_Backbone$Model) { function SimpleAuth() { _get(Object.getPrototypeOf(SimpleAuth.prototype), "constructor", this).apply(this, arguments); this.determineAuth(); this._configureAjax(); } _inherits(SimpleAuth, _Backbone$Model); _prototypeProperties(SimpleAuth, null, { defaults: { get: function () { return { cookieName: "token", token: undefined, authenticated: false }; }, configurable: true }, determineAuth: { // Determine if we're authenticated based on the cookie value: function determineAuth() { var token = cookies.get(this.get("cookieName")); // Fix for a bug in cookies-js: // https://github.com/ScottHamper/Cookies/issues/37 if (token === "undefined") { token = undefined; } this.set({ authenticated: !!token, token: token }); if (!token) { return; } this.trigger("authenticate", this.get("token")); }, writable: true, configurable: true }, logout: { // Log us out by destroying the token value: function logout() { cookies.expire(this.get("cookieName")); this.set({ token: undefined, authenticated: false }); this.trigger("logout"); }, writable: true, configurable: true }, _configureAjax: { // Include our token in every request value: function _configureAjax() { var auth = this; Backbone.$.ajaxSetup({ beforeSend: function beforeSend(jqXHR) { if (auth.get("authenticated")) { jqXHR.setRequestHeader("Authorization", "Bearer " + auth.get("token")); } return true; } }); }, writable: true, configurable: true } }); return SimpleAuth; })(Backbone.Model); var backbone_simple_auth = SimpleAuth; return backbone_simple_auth; }); //# sourceMappingURL=./backbone.simple-auth.js.map
var util = require('util'); var port = parseInt(process.argv[2], 10); var filename = process.argv[3]; var worker = require("./tcpworker").startWorker(port); var processes = []; worker.onmessage = function (filename) { port = port + 1; var curPort = port; util.error("Starting child "+curPort); var child = process.createChildProcess("node", [filename, curPort]); child.addListener("error", function (data) { util.error(data); }); var init = false; child.addListener("output", function (data) { if(!init) { init = true; worker.postMessage(curPort); } util.puts(data); }); child.addListener("exit", function (data) { child.dead = true; }); processes.push(child); } process.addListener("exit", function () { processes.forEach(function (child) { if(child && !child.dead) { child.kill(); } }) })
#!/usr/bin/env nodejs const express = require('express'); const bodyParser = require('body-parser'); const port = process.env.PORT || 8080; const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use(express.static('public')); app.use(express.static('public/favicon')); app.use((request, response) => { response.sendFile(`${__dirname}/public/index.html`); }); app.listen(port, () => { console.log(`App listening on port ${port}`); });
/*global module:false*/ module.exports = function(grunt) { // Project configuration. grunt.initConfig({ // Metadata. pkg: grunt.file.readJSON('package.json'), banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */\n', // Task configuration. concat: { options: { banner: '<%= banner %>', stripBanners: true }, js : { src : [ 'src/*' ], dest: 'build/industrial-validation.js' }, dist: { src: ['lib/<%= pkg.name %>.js'], dest: 'dist/<%= pkg.name %>.js' } }, uglify: { options: { banner: '<%= banner %>' }, dist: { src: '<%= concat.dist.dest %>', dest: 'dist/<%= pkg.name %>.min.js' } }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, unused: true, boss: true, eqnull: true, browser: true, globals: {} }, gruntfile: { src: 'Gruntfile.js' }, }, qunit: { files: ['test/**/*.html'] }, watch: { gruntfile: { files: '<%= jshint.gruntfile.src %>', tasks: ['jshint:gruntfile'] }, lib_test: { files: '<%= jshint.lib_test.src %>', tasks: ['jshint:lib_test', 'qunit'] } } }); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-watch'); // Default task. grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify']); };
function StringIterator(str){ this.str = str; this.current = 0; this.last = str.length - 1; this.done = function(){ if (this.current > this.last) return true; else return false; }; this.next = function(){ if (this.current > this.last) throw StopIteration; else return this.str[this.current++]; }; } var Tape = function() { var pos = 0, tape = [0]; this.inc = function(x) { tape[pos] += x; } this.move = function(x) { pos += x; while (pos >= tape.length) tape.push(0); } this.get = function() { return tape[pos]; } } const INC = 1; const MOVE = 2; const LOOP = 3; const PRINT = 4; function Op(op, v) { this.op = op; this.v = v; } var Brainfuck = function(text) { var me = this; var parse = function(iterator) { var res = []; while (!iterator.done()) { switch(iterator.next()) { case '+': res.push(new Op(INC, 1)); break; case '-': res.push(new Op(INC, -1)); break; case '>': res.push(new Op(MOVE, 1)); break; case '<': res.push(new Op(MOVE, -1)); break; case '.': res.push(new Op(PRINT, 0)); break; case '[': res.push(new Op(LOOP, parse(iterator))); break; case ']': return res; } } return res; } me.ops = parse(new StringIterator(text)); var _run = function(ops, tape) { for (var i = 0; i < ops.length; i++) { var op = ops[i]; switch(op.op) { case INC: tape.inc(op.v); break; case MOVE: tape.move(op.v); break; case LOOP: while (tape.get() != 0) _run(op.v, tape); break; case PRINT: process.stdout.write(String.fromCharCode(tape.get())); break; } } }; me.run = function() { _run(me.ops, new Tape()); }; } var text = require('fs').readFileSync(process.argv[2].toString()).toString(); var brainfuck = new Brainfuck(text); brainfuck.run();
var assert = require('assert'); var path = require('path'); var fs = require('fs'); describe('test of test', function() { it('test 1', function(done) { this.timeout(10000); assert.equal(1, 1); done(); }); });
export const ic_device_hub_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0zm0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M17 16l-4-4V8.82C14.16 8.4 15 7.3 15 6c0-1.66-1.34-3-3-3S9 4.34 9 6c0 1.3.84 2.4 2 2.82V12l-4 4H3v5h5v-3.05l4-4.2 4 4.2V21h5v-5h-4z"},"children":[]}]};
/** * Load CSS asynchronously without render blocking. * This variant uses <link> tag. * * If you want to import multiple styles for "progressive loading" * recommended to move all function calls before </body>. */ import { document, root } from './lib/globals'; import onBodyReady from './lib/on-body-ready'; import onStyleLoad from './lib/on-style-load'; let queue = []; window.importCSS = (href, media) => { const link = document.createElement('link'); let loaded = false; link.rel = 'stylesheet'; link.href = href; link.media = 'only x'; // temporarily set media to something inapplicable to ensure it'll fetch without blocking render queue.push(() => { if (loaded) { link.media = media || 'all'; } return loaded; }); // `insertBefore` is used instead of `appendChild`, // for safety re: http://www.paulirish.com/2011/surefire-dom-element-insertion/ onBodyReady(() => { root.insertBefore(link, null); }); function onLoad() { if (link.addEventListener) { link.removeEventListener('load', onLoad); } loaded = true; let prev = true; queue = queue.filter(_ => !(prev = prev && _()) ); } // once loaded, set link's media back to `all` // so that the stylesheet applies once it loads if (link.addEventListener) { link.addEventListener('load', onLoad); } onStyleLoad(link.href, onLoad); };
var http = require('http'); var url = require('url'); function start(route) { function onRequest(request, response) { var pathname = url.parse(request.url).pathname; console.log('Request for' + pathname + 'received.'); route(pathname); response.writeHeader(200, {'Content-Type': 'text/plain'}); response.write('hello world'); response.end(); } http.createServer(onRequest).listen(8088); console.log('Server is running at 8088'); // __filename: 输出脚本所在位置的绝对路径 console.log('server filename:', __filename); // __dirname: 输出脚本所在目录 console.log('server dirname', __dirname); } exports.start = start;
import {expect} from 'chai' import { addConflict, alignCoordinates, balance, findSmallestWidthAlignment, findType1Conflicts, findType2Conflicts, hasConflict, horizontalCompaction, positionX, verticalAlignment } from 'ciena-dagre/position/bk' import {buildLayerMatrix} from 'ciena-dagre/util' import {Graph} from 'ciena-graphlib' import {beforeEach, describe, it} from 'mocha' describe('position/bk', function () { let g beforeEach(function () { g = new Graph().setGraph({}) }) describe('findType1Conflicts', function () { let layering beforeEach(function () { g .setDefaultEdgeLabel(function () { return {} }) .setNode('a', {rank: 0, order: 0}) .setNode('b', {rank: 0, order: 1}) .setNode('c', {rank: 1, order: 0}) .setNode('d', {rank: 1, order: 1}) // Set up crossing .setEdge('a', 'd') .setEdge('b', 'c') layering = buildLayerMatrix(g) }) it('should not mark edges that have no conflict', function () { g.removeEdge('a', 'd') g.removeEdge('b', 'c') g.setEdge('a', 'c') g.setEdge('b', 'd') const conflicts = findType1Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'c')).to.equal(false) expect(hasConflict(conflicts, 'b', 'd')).to.equal(false) }) it('should not mark type-0 conflicts (no dummies)', function () { const conflicts = findType1Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'd')).to.equal(false) expect(hasConflict(conflicts, 'b', 'c')).to.equal(false) }) ;['a', 'b', 'c', 'd'].forEach(v => { it('should not mark type-0 conflicts (' + v + ' is dummy)', function () { g.node(v).dummy = true const conflicts = findType1Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'd')).to.equal(false) expect(hasConflict(conflicts, 'b', 'c')).to.equal(false) }) }) ;['a', 'b', 'c', 'd'].forEach(v => { it('should mark type-1 conflicts (' + v + ' is non-dummy)', function () { ;['a', 'b', 'c', 'd'].forEach(w => { if (v !== w) { g.node(w).dummy = true } }) const conflicts = findType1Conflicts(g, layering) if (v === 'a' || v === 'd') { expect(hasConflict(conflicts, 'a', 'd')).to.equal(true) expect(hasConflict(conflicts, 'b', 'c')).to.equal(false) } else { expect(hasConflict(conflicts, 'a', 'd')).to.equal(false) expect(hasConflict(conflicts, 'b', 'c')).to.equal(true) } }) }) it('should not mark type-2 conflicts (all dummies)', function () { ;['a', 'b', 'c', 'd'].forEach(v => { g.node(v).dummy = true }) const conflicts = findType1Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'd')).to.equal(false) expect(hasConflict(conflicts, 'b', 'c')).to.equal(false) findType1Conflicts(g, layering) }) }) describe('findType2Conflicts', function () { let layering beforeEach(function () { g .setDefaultEdgeLabel(function () { return {} }) .setNode('a', {rank: 0, order: 0}) .setNode('b', {rank: 0, order: 1}) .setNode('c', {rank: 1, order: 0}) .setNode('d', {rank: 1, order: 1}) // Set up crossing .setEdge('a', 'd') .setEdge('b', 'c') layering = buildLayerMatrix(g) }) it('should mark type-2 conflicts favoring border segments #1', function () { ;['a', 'd'].forEach(v => { g.node(v).dummy = true }) ;['b', 'c'].forEach(v => { g.node(v).dummy = 'border' }) const conflicts = findType2Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'd')).to.equal(true) expect(hasConflict(conflicts, 'b', 'c')).to.equal(false) findType1Conflicts(g, layering) }) it('should mark type-2 conflicts favoring border segments #2', function () { ;['b', 'c'].forEach(v => { g.node(v).dummy = true }) ;['a', 'd'].forEach(v => { g.node(v).dummy = 'border' }) const conflicts = findType2Conflicts(g, layering) expect(hasConflict(conflicts, 'a', 'd')).to.equal(false) expect(hasConflict(conflicts, 'b', 'c')).to.equal(true) findType1Conflicts(g, layering) }) }) describe('hasConflict', function () { it('should test for a type-1 conflict regardless of edge orientation', function () { const conflicts = {} addConflict(conflicts, 'b', 'a') expect(hasConflict(conflicts, 'a', 'b')).to.equal(true) expect(hasConflict(conflicts, 'b', 'a')).to.equal(true) }) it('should work for multiple conflicts with the same node', function () { const conflicts = {} addConflict(conflicts, 'a', 'b') addConflict(conflicts, 'a', 'c') expect(hasConflict(conflicts, 'a', 'b')).to.equal(true) expect(hasConflict(conflicts, 'a', 'c')).to.equal(true) }) }) describe('verticalAlignment', function () { it('should align with itself if the node has no adjacencies', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 1, order: 0}) let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'b'}, align: {a: 'a', b: 'b'} }) }) it('should align with its sole adjacency', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 1, order: 0}) g.setEdge('a', 'b') let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'a'}, align: {a: 'b', b: 'a'} }) }) it('should align with its left median when possible', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 0, order: 1}) g.setNode('c', {rank: 1, order: 0}) g.setEdge('a', 'c') g.setEdge('b', 'c') let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'b', c: 'a'}, align: {a: 'c', b: 'b', c: 'a'} }) }) it('should align correctly even regardless of node name / insertion order', function () { // This test ensures that we're actually properly sorting nodes by // position when searching for candidates. Many of these tests previously // passed because the node insertion order matched the order of the nodes // in the layering. g.setNode('b', {rank: 0, order: 1}) g.setNode('c', {rank: 1, order: 0}) g.setNode('z', {rank: 0, order: 0}) g.setEdge('z', 'c') g.setEdge('b', 'c') let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {z: 'z', b: 'b', c: 'z'}, align: {z: 'c', b: 'b', c: 'z'} }) }) it('should align with its right median when left is unavailable', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 0, order: 1}) g.setNode('c', {rank: 1, order: 0}) g.setEdge('a', 'c') g.setEdge('b', 'c') let layering = buildLayerMatrix(g) let conflicts = {} addConflict(conflicts, 'a', 'c') const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'b', c: 'b'}, align: {a: 'a', b: 'c', c: 'b'} }) }) it('should align with neither median if both are unavailable', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 0, order: 1}) g.setNode('c', {rank: 1, order: 0}) g.setNode('d', {rank: 1, order: 1}) g.setEdge('a', 'd') g.setEdge('b', 'c') g.setEdge('b', 'd') let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) // c will align with b, so d will not be able to align with a, because // (a,d) and (c,b) cross. expect(result).to.eql({ root: {a: 'a', b: 'b', c: 'b', d: 'd'}, align: {a: 'a', b: 'c', c: 'b', d: 'd'} }) }) it('should align with the single median for an odd number of adjacencies', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 0, order: 1}) g.setNode('c', {rank: 0, order: 2}) g.setNode('d', {rank: 1, order: 0}) g.setEdge('a', 'd') g.setEdge('b', 'd') g.setEdge('c', 'd') let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'b', c: 'c', d: 'b'}, align: {a: 'a', b: 'd', c: 'c', d: 'b'} }) }) it('should align blocks across multiple layers', function () { g.setNode('a', {rank: 0, order: 0}) g.setNode('b', {rank: 1, order: 0}) g.setNode('c', {rank: 1, order: 1}) g.setNode('d', {rank: 2, order: 0}) g.setPath(['a', 'b', 'd']) g.setPath(['a', 'c', 'd']) let layering = buildLayerMatrix(g) let conflicts = {} const result = verticalAlignment(g, layering, conflicts, g.predecessors.bind(g)) expect(result).to.eql({ root: {a: 'a', b: 'a', c: 'c', d: 'a'}, align: {a: 'b', b: 'd', c: 'c', d: 'a'} }) }) }) describe('horizonalCompaction', function () { it('should place the center of a single node graph at origin (0,0)', function () { const root = {a: 'a'} const align = {a: 'a'} g.setNode('a', {rank: 0, order: 0}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) }) it('should separate adjacent nodes by specified node separation', function () { const root = {a: 'a', b: 'b'} const align = {a: 'a', b: 'b'} g.graph().nodesep = 100 g.setNode('a', {rank: 0, order: 0, width: 100}) g.setNode('b', {rank: 0, order: 1, width: 200}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(100 / 2 + 100 + 200 / 2) }) it('should separate adjacent edges by specified node separation', function () { const root = {a: 'a', b: 'b'} const align = {a: 'a', b: 'b'} g.graph().edgesep = 20 g.setNode('a', {rank: 0, order: 0, width: 100, dummy: true}) g.setNode('b', {rank: 0, order: 1, width: 200, dummy: true}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(100 / 2 + 20 + 200 / 2) }) it('should align the centers of nodes in the same block', function () { const root = {a: 'a', b: 'a'} const align = {a: 'b', b: 'a'} g.setNode('a', {rank: 0, order: 0, width: 100}) g.setNode('b', {rank: 1, order: 0, width: 200}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(0) }) it('should separate blocks with the appropriate separation', function () { const root = {a: 'a', b: 'a', c: 'c'} const align = {a: 'b', b: 'a', c: 'c'} g.graph().nodesep = 75 g.setNode('a', {rank: 0, order: 0, width: 100}) g.setNode('b', {rank: 1, order: 1, width: 200}) g.setNode('c', {rank: 1, order: 0, width: 50}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(50 / 2 + 75 + 200 / 2) expect(xs.b).to.equal(50 / 2 + 75 + 200 / 2) expect(xs.c).to.equal(0) }) it('should separate classes with the appropriate separation', function () { const root = {a: 'a', b: 'b', c: 'c', d: 'b'} const align = {a: 'a', b: 'd', c: 'c', d: 'b'} g.graph().nodesep = 75 g.setNode('a', {rank: 0, order: 0, width: 100}) g.setNode('b', {rank: 0, order: 1, width: 200}) g.setNode('c', {rank: 1, order: 0, width: 50}) g.setNode('d', {rank: 1, order: 1, width: 80}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(100 / 2 + 75 + 200 / 2) expect(xs.c).to.equal(100 / 2 + 75 + 200 / 2 - 80 / 2 - 75 - 50 / 2) expect(xs.d).to.equal(100 / 2 + 75 + 200 / 2) }) it('should shift classes by max sep from the adjacent block #1', function () { const root = {a: 'a', b: 'b', c: 'a', d: 'b'} const align = {a: 'c', b: 'd', c: 'a', d: 'b'} g.graph().nodesep = 75 g.setNode('a', {rank: 0, order: 0, width: 50}) g.setNode('b', {rank: 0, order: 1, width: 150}) g.setNode('c', {rank: 1, order: 0, width: 60}) g.setNode('d', {rank: 1, order: 1, width: 70}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(50 / 2 + 75 + 150 / 2) expect(xs.c).to.equal(0) expect(xs.d).to.equal(50 / 2 + 75 + 150 / 2) }) it('should shift classes by max sep from the adjacent block #2', function () { const root = {a: 'a', b: 'b', c: 'a', d: 'b'} const align = {a: 'c', b: 'd', c: 'a', d: 'b'} g.graph().nodesep = 75 g.setNode('a', {rank: 0, order: 0, width: 50}) g.setNode('b', {rank: 0, order: 1, width: 70}) g.setNode('c', {rank: 1, order: 0, width: 60}) g.setNode('d', {rank: 1, order: 1, width: 150}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(60 / 2 + 75 + 150 / 2) expect(xs.c).to.equal(0) expect(xs.d).to.equal(60 / 2 + 75 + 150 / 2) }) it('should cascade class shift', function () { const root = {a: 'a', b: 'b', c: 'c', d: 'd', e: 'b', f: 'f', g: 'd'} const align = {a: 'a', b: 'e', c: 'c', d: 'g', e: 'b', f: 'f', g: 'd'} g.graph().nodesep = 75 g.setNode('a', {rank: 0, order: 0, width: 50}) g.setNode('b', {rank: 0, order: 1, width: 50}) g.setNode('c', {rank: 1, order: 0, width: 50}) g.setNode('d', {rank: 1, order: 1, width: 50}) g.setNode('e', {rank: 1, order: 2, width: 50}) g.setNode('f', {rank: 2, order: 0, width: 50}) g.setNode('g', {rank: 2, order: 1, width: 50}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) // Use f as 0, everything is relative to it expect(xs.a).to.equal(xs.b - 50 / 2 - 75 - 50 / 2) expect(xs.b).to.equal(xs.e) expect(xs.c).to.equal(xs.f) expect(xs.d).to.equal(xs.c + 50 / 2 + 75 + 50 / 2) expect(xs.e).to.equal(xs.d + 50 / 2 + 75 + 50 / 2) expect(xs.g).to.equal(xs.f + 50 / 2 + 75 + 50 / 2) }) it('should handle labelpos = l', function () { const root = {a: 'a', b: 'b', c: 'c'} const align = {a: 'a', b: 'b', c: 'c'} g.graph().edgesep = 50 g.setNode('a', {rank: 0, order: 0, width: 100, dummy: 'edge'}) g.setNode('b', { rank: 0, order: 1, width: 200, dummy: 'edge-label', labelpos: 'l' }) g.setNode('c', {rank: 0, order: 2, width: 300, dummy: 'edge'}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(xs.a + 100 / 2 + 50 + 200) expect(xs.c).to.equal(xs.b + 0 + 50 + 300 / 2) }) it('should handle labelpos = c', function () { const root = {a: 'a', b: 'b', c: 'c'} const align = {a: 'a', b: 'b', c: 'c'} g.graph().edgesep = 50 g.setNode('a', {rank: 0, order: 0, width: 100, dummy: 'edge'}) g.setNode('b', { rank: 0, order: 1, width: 200, dummy: 'edge-label', labelpos: 'c' }) g.setNode('c', {rank: 0, order: 2, width: 300, dummy: 'edge'}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(xs.a + 100 / 2 + 50 + 200 / 2) expect(xs.c).to.equal(xs.b + 200 / 2 + 50 + 300 / 2) }) it('should handle labelpos = r', function () { const root = {a: 'a', b: 'b', c: 'c'} const align = {a: 'a', b: 'b', c: 'c'} g.graph().edgesep = 50 g.setNode('a', {rank: 0, order: 0, width: 100, dummy: 'edge'}) g.setNode('b', { rank: 0, order: 1, width: 200, dummy: 'edge-label', labelpos: 'r' }) g.setNode('c', {rank: 0, order: 2, width: 300, dummy: 'edge'}) const xs = horizontalCompaction(g, buildLayerMatrix(g), root, align) expect(xs.a).to.equal(0) expect(xs.b).to.equal(xs.a + 100 / 2 + 50 + 0) expect(xs.c).to.equal(xs.b + 200 + 50 + 300 / 2) }) }) describe('alignCoordinates', function () { it('should align a single node', function () { let xss = { ul: {a: 50}, ur: {a: 100}, dl: {a: 50}, dr: {a: 200} } alignCoordinates(xss, xss.ul) expect(xss.ul).to.eql({a: 50}) expect(xss.ur).to.eql({a: 50}) expect(xss.dl).to.eql({a: 50}) expect(xss.dr).to.eql({a: 50}) }) it('should align multiple nodes', function () { let xss = { ul: {a: 50, b: 1000}, ur: {a: 100, b: 900}, dl: {a: 150, b: 800}, dr: {a: 200, b: 700} } alignCoordinates(xss, xss.ul) expect(xss.ul).to.eql({a: 50, b: 1000}) expect(xss.ur).to.eql({a: 200, b: 1000}) expect(xss.dl).to.eql({a: 50, b: 700}) expect(xss.dr).to.eql({a: 500, b: 1000}) }) }) describe('findSmallestWidthAlignment', function () { it('should find the alignment with the smallest width', function () { g.setNode('a', {width: 50}) g.setNode('b', {width: 50}) let xss = { ul: {a: 0, b: 1000}, ur: {a: -5, b: 1000}, dl: {a: 5, b: 2000}, dr: {a: 0, b: 200} } expect(findSmallestWidthAlignment(g, xss)).to.eql(xss.dr) }) it('should take node width into account', function () { g.setNode('a', {width: 50}) g.setNode('b', {width: 50}) g.setNode('c', {width: 200}) let xss = { ul: {a: 0, b: 100, c: 75}, ur: {a: 0, b: 100, c: 80}, dl: {a: 0, b: 100, c: 85}, dr: {a: 0, b: 100, c: 90} } expect(findSmallestWidthAlignment(g, xss)).to.eql(xss.ul) }) }) describe('balance', function () { it('should align a single node to the shared median value', function () { let xss = { ul: {a: 0}, ur: {a: 100}, dl: {a: 100}, dr: {a: 200} } expect(balance(xss)).to.eql({a: 100}) }) it('should align a single node to the average of different median values', function () { let xss = { ul: {a: 0}, ur: {a: 75}, dl: {a: 125}, dr: {a: 200} } expect(balance(xss)).to.eql({a: 100}) }) it('should balance multiple nodes', function () { let xss = { ul: {a: 0, b: 50}, ur: {a: 75, b: 0}, dl: {a: 125, b: 60}, dr: {a: 200, b: 75} } expect(balance(xss)).to.eql({a: 100, b: 55}) }) }) describe('positionX', function () { it('should position a single node at origin', function () { g.setNode('a', {rank: 0, order: 0, width: 100}) expect(positionX(g)).to.eql({a: 0}) }) it('should position a single node block at origin', function () { g.setNode('a', {rank: 0, order: 0, width: 100}) g.setNode('b', {rank: 1, order: 0, width: 100}) g.setEdge('a', 'b') expect(positionX(g)).to.eql({a: 0, b: 0}) }) it('should position a single node block at origin even when their sizes differ', function () { g.setNode('a', {rank: 0, order: 0, width: 40}) g.setNode('b', {rank: 1, order: 0, width: 500}) g.setNode('c', {rank: 2, order: 0, width: 20}) g.setPath(['a', 'b', 'c']) expect(positionX(g)).to.eql({a: 0, b: 0, c: 0}) }) it('should center a node if it is a predecessor of two same sized nodes', function () { g.graph().nodesep = 10 g.setNode('a', {rank: 0, order: 0, width: 20}) g.setNode('b', {rank: 1, order: 0, width: 50}) g.setNode('c', {rank: 1, order: 1, width: 50}) g.setEdge('a', 'b') g.setEdge('a', 'c') let pos = positionX(g) const a = pos.a expect(pos).to.eql({a: a, b: a - (25 + 5), c: a + (25 + 5)}) }) it('should shift blocks on both sides of aligned block', function () { g.graph().nodesep = 10 g.setNode('a', {rank: 0, order: 0, width: 50}) g.setNode('b', {rank: 0, order: 1, width: 60}) g.setNode('c', {rank: 1, order: 0, width: 70}) g.setNode('d', {rank: 1, order: 1, width: 80}) g.setEdge('b', 'c') let pos = positionX(g) const b = pos.b const c = b expect(pos).to.eql({ a: b - 60 / 2 - 10 - 50 / 2, b: b, c: c, d: c + 70 / 2 + 10 + 80 / 2 }) }) it('should align inner segments', function () { g.graph().nodesep = 10 g.setNode('a', {rank: 0, order: 0, width: 50, dummy: true}) g.setNode('b', {rank: 0, order: 1, width: 60}) g.setNode('c', {rank: 1, order: 0, width: 70}) g.setNode('d', {rank: 1, order: 1, width: 80, dummy: true}) g.setEdge('b', 'c') g.setEdge('a', 'd') let pos = positionX(g) const a = pos.a const d = a expect(pos).to.eql({ a: a, b: a + 50 / 2 + 10 + 60 / 2, c: d - 70 / 2 - 10 - 80 / 2, d: d }) }) }) })
import { RichUtils } from "draft-js"; const leaveList = editorState => { const contentState = editorState.getCurrentContent(); const selection = editorState.getSelection(); const key = selection.getStartKey(); const currentBlock = contentState.getBlockForKey(key); const type = currentBlock.getType(); return RichUtils.toggleBlockType(editorState, type); }; export default leaveList;
/*globals casper */ /** * Casper Tests * * Functional browser tests for checking that the Ghost Admin UI is working as expected * The setup of these tests is a little hacky for now, which is why they are not wired in to grunt * Requires that you are running Ghost locally and have already registered a single user * * Usage (from test/functional): * * casperjs test admin/ --includes=base.js [--host=localhost --port=2368 --noPort=false --email=ghost@tryghost.org --password=Sl1m3r] * * --host - your local host address e.g. localhost or local.tryghost.org * --port - port number of your local Ghost * --email - the email address your admin user is registered with * --password - the password your admin user is registered with * --noPort - don't include a port number * * Requirements: * you must have phantomjs 1.9.1 and casperjs 1.1.0-DEV installed in order for these tests to work */ var DEBUG = false, // TOGGLE THIS TO GET MORE SCREENSHOTS host = casper.cli.options.host || 'localhost', noPort = casper.cli.options.noPort || false, port = casper.cli.options.port || '2368', email = casper.cli.options.email || 'jbloggs@example.com', password = casper.cli.options.password || 'Sl1m3rson', url = 'http://' + host + (noPort ? '/' : ':' + port + '/'), newUser = { name: 'Test User', slug: 'test-user', email: email, password: password }, newSetup = { 'blog-title': 'Test Blog', name: 'Test User', email: email, password: password }, user = { identification: email, password: password }, falseUser = { identification: email, password: 'letmethrough' }, testPost = { title: 'Bacon ipsum dolor sit amet', html: 'I am a test post.\n#I have some small content' }, screens; screens = { 'root': { url: 'ghost/', linkSelector: '#main-menu > li.content a', selector: '#main-menu .content.active' }, 'content': { url: 'ghost/content/', linkSelector: '#main-menu > li.content a', selector: '#main-menu .content.active' }, 'editor': { url: 'ghost/editor/', linkSelector: '#main-menu > li.editor a', selector: '#entry-title' }, 'settings': { url: 'ghost/settings/', linkSelector: '#main-menu > li.settings a', selector: '.settings-content' }, 'settings.general': { url: 'ghost/settings/general', selector: '.settings-content .settings-general' }, 'settings.user': { url: 'ghost/settings/user', linkSelector: '#user-menu li.usermenu-profile a', selector: '.settings-content .settings-user' }, 'signin': { url: 'ghost/signin/', selector: '.button-save' }, 'signin-authenticated': { url: 'ghost/signin/', //signin with authenticated user redirects to posts selector: '#main-menu .content.active' }, 'signout': { url: 'ghost/signout/', linkSelector: '#user-menu li.usermenu-signout a', // When no user exists we get redirected to setup which has button-add selector: '.button-save, .button-add' }, 'signup': { url: 'ghost/signup/', selector: '.button-save' }, 'setup': { url: 'ghost/setup/', selector: '.button-add' }, 'setup-authenticated': { url: 'ghost/setup/', selector: '#main-menu .content.active' } }; casper.writeContentToCodeMirror = function (content) { var lines = content.split('\n'); casper.waitForSelector('.CodeMirror-wrap textarea', function onSuccess() { casper.each(lines, function (self, line) { self.sendKeys('.CodeMirror-wrap textarea', line, {keepFocus: true}); self.sendKeys('.CodeMirror-wrap textarea', casper.page.event.key.Enter, {keepFocus: true}); }); return this; }, function onTimeout() { casper.test.fail('CodeMirror was not found.'); }, 2000); }; casper.waitForOpacity = function (classname, opacity, then, timeout) { timeout = timeout || casper.failOnTimeout(casper.test, 'waitForOpacity failed on ' + classname + ' ' + opacity); casper.waitForSelector(classname).then(function () { casper.waitFor(function checkOpaque() { var value = this.evaluate(function (element, opacity) { var target = document.querySelector(element); if (target === null) { return null; } return window.getComputedStyle(target).getPropertyValue('opacity') === opacity; }, classname, opacity); if (value !== true && value !== false) { casper.test.fail('Unable to find element: ' + classname); } return value; }, then, timeout); }); }; casper.waitForOpaque = function (classname, then, timeout) { casper.waitForOpacity(classname, '1', then, timeout); }; casper.waitForTransparent = function (classname, then, timeout) { casper.waitForOpacity(classname, '0', then, timeout); }; // ### Then Open And Wait For Page Load // Always wait for the `#main` element as some indication that the ember app has loaded. casper.thenOpenAndWaitForPageLoad = function (screen, then, timeout) { then = then || function () {}; timeout = timeout || casper.failOnTimeout(casper.test, 'Unable to load ' + screen); return casper.thenOpen(url + screens[screen].url).then(function () { // Some screens fade in return casper.waitForOpaque(screens[screen].selector, then, timeout, 10000); }); }; casper.thenTransitionAndWaitForScreenLoad = function (screen, then, timeout) { then = then || function () {}; timeout = timeout || casper.failOnTimeout(casper.test, 'Unable to load ' + screen); return casper.thenClick(screens[screen].linkSelector).then(function () { // Some screens fade in return casper.waitForOpaque(screens[screen].selector, then, timeout, 10000); }); }; casper.failOnTimeout = function (test, message) { return function onTimeout() { test.fail(message); }; }; // ### Fill And Save // With Ember in place, we don't want to submit forms, rather press the button which always has a class of // 'button-save'. This method handles that smoothly. casper.fillAndSave = function (selector, data) { casper.then(function doFill() { casper.fill(selector, data, false); casper.thenClick('.button-save'); }); }; // ### Fill And Add // With Ember in place, we don't want to submit forms, rather press the green button which always has a class of // 'button-add'. This method handles that smoothly. casper.fillAndAdd = function (selector, data) { casper.then(function doFill() { casper.fill(selector, data, false); casper.thenClick('.button-add'); }); }; // ## Debugging var jsErrors = [], pageErrors = [], resourceErrors = []; // ## Echo Concise // Does casper.echo but checks for the presence of the --concise flag casper.echoConcise = function (message, style) { if (!casper.cli.options.concise) { casper.echo(message, style); } }; // pass through all console.logs casper.on('remote.message', function (msg) { casper.echoConcise('CONSOLE LOG: ' + msg, 'INFO'); }); // output any errors casper.on('error', function (msg, trace) { casper.echoConcise('ERROR, ' + msg, 'ERROR'); if (trace) { casper.echoConcise('file: ' + trace[0].file, 'WARNING'); casper.echoConcise('line: ' + trace[0].line, 'WARNING'); casper.echoConcise('function: ' + trace[0]['function'], 'WARNING'); } jsErrors.push(msg); }); // output any page errors casper.on('page.error', function (msg, trace) { casper.echoConcise('PAGE ERROR: ' + msg, 'ERROR'); if (trace) { casper.echoConcise('file: ' + trace[0].file, 'WARNING'); casper.echoConcise('line: ' + trace[0].line, 'WARNING'); casper.echoConcise('function: ' + trace[0]['function'], 'WARNING'); } pageErrors.push(msg); }); casper.on('resource.received', function(resource) { var status = resource.status; if(status >= 400) { casper.echoConcise('RESOURCE ERROR: ' + resource.url + ' failed to load (' + status + ')', 'ERROR'); resourceErrors.push({ url: resource.url, status: resource.status }); } }); casper.captureScreenshot = function (filename, debugOnly) { debugOnly = debugOnly !== false; // If we are in debug mode, OR debugOnly is false if (DEBUG || debugOnly === false) { filename = filename || 'casper_test_fail.png'; casper.then(function () { casper.capture(new Date().getTime() + '_' + filename); }); } }; // on failure, grab a screenshot casper.test.on('fail', function captureFailure() { casper.captureScreenshot(casper.test.filename || 'casper_test_fail.png', false); casper.then(function () { console.log(casper.getHTML()); casper.exit(1); }); }); // on exit, output any errors casper.test.on('exit', function() { if (jsErrors.length > 0) { casper.echo(jsErrors.length + ' Javascript errors found', 'WARNING'); } else { casper.echo(jsErrors.length + ' Javascript errors found', 'INFO'); } if (pageErrors.length > 0) { casper.echo(pageErrors.length + ' Page errors found', 'WARNING'); } else { casper.echo(pageErrors.length + ' Page errors found', 'INFO'); } if (resourceErrors.length > 0) { casper.echo(resourceErrors.length + ' Resource errors found', 'WARNING'); } else { casper.echo(resourceErrors.length + ' Resource errors found', 'INFO'); } }); var CasperTest = (function () { var _beforeDoneHandler, _noop = function noop() { }, _isUserRegistered = false; // Always log out at end of test. casper.test.tearDown(function (done) { casper.then(_beforeDoneHandler); CasperTest.Routines.signout.run(); casper.run(done); }); // Wrapper around `casper.test.begin` function begin(testName, expect, suite, doNotAutoLogin) { _beforeDoneHandler = _noop; var runTest = function (test) { test.filename = testName.toLowerCase().replace(/ /g, '-').concat('.png'); casper.start('about:blank').viewport(1280, 1024); if (!doNotAutoLogin) { // Only call register once for the lifetime of CasperTest if (!_isUserRegistered) { CasperTest.Routines.signout.run(); CasperTest.Routines.setup.run(); _isUserRegistered = true; } /* Ensure we're logged out at the start of every test or we may get unexpected failures. */ CasperTest.Routines.signout.run(); CasperTest.Routines.signin.run(); } suite.call(casper, test); casper.run(function () { test.done(); }); }; if (typeof expect === 'function') { doNotAutoLogin = suite; suite = expect; casper.test.begin(testName, runTest); } else { casper.test.begin(testName, expect, runTest); } } // Sets a handler to be invoked right before `test.done` is invoked function beforeDone(fn) { if (fn) { _beforeDoneHandler = fn; } else { _beforeDoneHandler = _noop; } } return { begin: begin, beforeDone: beforeDone }; }()); CasperTest.Routines = (function () { function setup() { casper.thenOpenAndWaitForPageLoad('setup', function then() { casper.captureScreenshot('setting_up1.png'); casper.waitForOpaque('.setup-box', function then() { this.fillAndAdd('#setup', newSetup); }); casper.captureScreenshot('setting_up2.png'); casper.waitForSelectorTextChange('.notification-error', function onSuccess() { var errorText = casper.evaluate(function () { return document.querySelector('.notification-error').innerText; }); casper.echoConcise('It appears as though a user is already registered. Error text: ' + errorText); }, function onTimeout() { casper.echoConcise('It appears as though a user was not already registered.'); }, 2000); casper.captureScreenshot('setting_up3.png'); }); } function signin() { casper.thenOpenAndWaitForPageLoad('signin', function then() { casper.waitForOpaque('.login-box', function then() { casper.captureScreenshot('signing_in.png'); this.fillAndSave('#login', user); casper.captureScreenshot('signing_in2.png'); }); casper.waitForResource(/posts\/\?status=all&staticPages=all/, function then() { casper.captureScreenshot('signing_in.png'); }, function timeout() { casper.test.fail('Unable to signin and load admin panel'); }); }); } function signout() { casper.thenOpenAndWaitForPageLoad('signout', function then() { casper.captureScreenshot('ember_signing_out.png'); }); } // This will need switching over to ember once settings general is working properly. function togglePermalinks(state) { casper.thenOpenAndWaitForPageLoad('settings.general', function then() { var currentState = this.evaluate(function () { return document.querySelector('#permalinks') && document.querySelector('#permalinks').checked ? 'on' : 'off'; }); if (currentState !== state) { casper.thenClick('#permalinks'); casper.thenClick('.button-save'); casper.captureScreenshot('saving.png'); casper.waitForSelector('.notification-success', function () { casper.captureScreenshot('saved.png'); }); } }); } function createTestPost(publish) { casper.thenOpenAndWaitForPageLoad('editor', function createTestPost() { casper.sendKeys('#entry-title', testPost.title); casper.writeContentToCodeMirror(testPost.html); casper.sendKeys('#entry-tags input.tag-input', 'TestTag'); casper.sendKeys('#entry-tags input.tag-input', casper.page.event.key.Enter); }); casper.waitForSelectorTextChange('.entry-preview .rendered-markdown'); if (publish) { // Open the publish options menu; casper.thenClick('.js-publish-splitbutton .options.up'); casper.waitForOpaque('.js-publish-splitbutton .open'); // Select the publish post button casper.thenClick('.js-publish-splitbutton li:first-child a'); casper.waitForSelectorTextChange('.js-publish-button', function onSuccess() { casper.thenClick('.js-publish-button'); }); } else { casper.thenClick('.js-publish-button'); } casper.waitForResource(/posts\/\?include=tags$/); } function _createRunner(fn) { fn.run = function run(test) { var routine = this; casper.then(function () { routine.call(casper, test); }); }; return fn; } return { setup: _createRunner(setup), signin: _createRunner(signin), signout: _createRunner(signout), createTestPost: _createRunner(createTestPost), togglePermalinks: _createRunner(togglePermalinks) }; }());
'use strict'; angular.module('core').controller('calendarController', function($scope) { $scope.name = "blah" }); angular.module('core').directive('chart', function() { return { restrict: 'A', link: function($scope, $elm, $attr) { // Create the data table. var data = new google.visualization.DataTable(); data.addColumn({ type: 'string', id: 'President' }); data.addColumn({ type: 'date', id: 'Start' }); data.addColumn({ type: 'date', id: 'End' }); data.addRows([ [ 'Washington', new Date(1789, 3, 29), new Date(1797, 2, 3) ], [ 'Adams', new Date(1797, 2, 3), new Date(1801, 2, 3) ], [ 'Jefferson', new Date(1801, 2, 3), new Date(1809, 2, 3) ]]); // Set chart options var options = {'title':'Timeline', 'width':800, 'height':800}; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.Timeline($elm[0]); chart.draw(data, options); } } }); // google.setOnLoadCallback(function() { // angular.bootstrap(document.body, ['myapp']); // }); google.load('visualization', '1', {packages: ['timeline']});
( function () { 'use strict'; describe( 'CompetencyTest', function () { it( "First assertion",function () { expect( true ).toBe( true ); } ); } ); } )();
import React, { Component, PropTypes } from 'react'; import { ItemTypes } from './Constants'; import { DragSource } from 'react-dnd'; const dragbuttonSource = { beginDrag(props) { return { id: props.id }; }, endDrag(props, monitor) { const dropResult = monitor.getDropResult(); if (dropResult) { } } }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() } } class DragButton extends React.Component { render() { const { connectDragSource, isDragging } = this.props; return connectDragSource( <button style={{ opacity: isDragging ? 0.5 : 1, fontSize: 12, fontWeight: 'bold', cursor: 'move', border: '1px solid #CFD8DC', display: 'inline', backgroundColor: '#CFD8DC', verticalAlign: 'top' }}> <p style={{fontSize:'20', color:'#757575'}}>{this.props.text}</p> </button> ); } } /*PlayByPlay.propTypes = { connectDragSource: PropTypes.func.isRequired, isDragging: PropTypes.bool.isRequired };*/ export default DragSource(ItemTypes.MODULE, dragbuttonSource, collect)(DragButton);